update connections

This commit is contained in:
Luke Pulverenti 2016-11-20 22:52:58 -05:00
parent 985c9111cf
commit 1dc080df8b
12 changed files with 693 additions and 557 deletions

View File

@ -27,6 +27,14 @@ namespace Emby.Server.Implementations.Activity
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists ActivityLogEntries (Id GUID PRIMARY KEY, Name TEXT, Overview TEXT, ShortOverview TEXT, Type TEXT, ItemId TEXT, UserId TEXT, DateCreated DATETIME, LogSeverity TEXT)",
@ -51,9 +59,9 @@ namespace Emby.Server.Implementations.Activity
throw new ArgumentNullException("entry");
}
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -78,10 +86,10 @@ namespace Emby.Server.Implementations.Activity
}
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit)
{
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = BaseActivitySelectText;
var whereClauses = new List<string>();

View File

@ -30,11 +30,6 @@ namespace Emby.Server.Implementations.Data
get { return false; }
}
protected virtual bool EnableConnectionPooling
{
get { return true; }
}
static BaseSqliteRepository()
{
SQLite3.EnableSharedCache = false;
@ -45,7 +40,7 @@ namespace Emby.Server.Implementations.Data
private static bool _versionLogged;
protected virtual SQLiteDatabaseConnection CreateConnection(bool isReadOnly = false)
protected SQLiteDatabaseConnection CreateConnection(bool isReadOnly = false, Action<SQLiteDatabaseConnection> onConnect = null)
{
if (!_versionLogged)
{
@ -56,7 +51,7 @@ namespace Emby.Server.Implementations.Data
ConnectionFlags connectionFlags;
//isReadOnly = false;
isReadOnly = false;
if (isReadOnly)
{
@ -70,47 +65,41 @@ namespace Emby.Server.Implementations.Data
connectionFlags |= ConnectionFlags.ReadWrite;
}
if (EnableConnectionPooling)
{
connectionFlags |= ConnectionFlags.SharedCached;
}
else
{
connectionFlags |= ConnectionFlags.PrivateCache;
}
connectionFlags |= ConnectionFlags.NoMutex;
var db = SQLite3.Open(DbFilePath, connectionFlags, null);
var queries = new List<string>
{
"pragma default_temp_store = memory",
"pragma temp_store = memory",
"PRAGMA page_size=4096",
"PRAGMA journal_mode=WAL",
"PRAGMA temp_store=memory",
"PRAGMA synchronous=Normal",
"pragma synchronous=Normal",
//"PRAGMA cache size=-10000"
};
var cacheSize = CacheSize;
if (cacheSize.HasValue)
{
}
if (EnableExclusiveMode)
{
queries.Add("PRAGMA locking_mode=EXCLUSIVE");
}
//foreach (var query in queries)
//var cacheSize = CacheSize;
//if (cacheSize.HasValue)
//{
// db.Execute(query);
//}
////foreach (var query in queries)
////{
//// db.Execute(query);
////}
using (WriteLock.Write())
{
db.ExecuteAll(string.Join(";", queries.ToArray()));
if (onConnect != null)
{
onConnect(db);
}
}
return db;
}
@ -122,11 +111,6 @@ namespace Emby.Server.Implementations.Data
}
}
protected virtual bool EnableExclusiveMode
{
get { return false; }
}
internal static void CheckOk(int rc)
{
string msg = "";

View File

@ -54,6 +54,14 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists userdisplaypreferences (id GUID, userId GUID, client text, data BLOB)",
@ -86,9 +94,9 @@ namespace Emby.Server.Implementations.Data
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -130,9 +138,9 @@ namespace Emby.Server.Implementations.Data
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -162,9 +170,9 @@ namespace Emby.Server.Implementations.Data
var guidId = displayPreferencesId.GetMD5();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where id = @id and userId=@userId and client=@client"))
{
@ -196,9 +204,9 @@ namespace Emby.Server.Implementations.Data
{
var list = new List<DisplayPreferences>();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId"))
{

View File

@ -131,11 +131,13 @@ namespace Emby.Server.Implementations.Data
public static void Attach(IDatabaseConnection db, string path, string alias)
{
var commandText = string.Format("attach ? as {0};", alias);
var paramList = new List<object>();
paramList.Add(path);
var commandText = string.Format("attach @path as {0};", alias);
db.Execute(commandText, paramList.ToArray());
using (var statement = db.PrepareStatement(commandText))
{
statement.TryBind("@path", path);
statement.MoveNext();
}
}
public static bool IsDBNull(this IReadOnlyList<IResultSetValue> result, int index)

View File

@ -31,6 +31,14 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists FileOrganizerResults (ResultId GUID PRIMARY KEY, OriginalPath TEXT, TargetPath TEXT, FileLength INT, OrganizationDate datetime, Status TEXT, OrganizationType TEXT, StatusMessage TEXT, ExtractedName TEXT, ExtractedYear int null, ExtractedSeasonNumber int null, ExtractedEpisodeNumber int null, ExtractedEndingEpisodeNumber, DuplicatePaths TEXT int null)",

View File

@ -127,10 +127,19 @@ namespace Emby.Server.Implementations.Data
{
_connection = CreateConnection(false);
_connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
var createMediaStreamsTableCommand
= "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, CodecTag TEXT NULL, Comment TEXT NULL, NalLengthSize TEXT NULL, IsAvc BIT NULL, Title TEXT NULL, TimeBase TEXT NULL, CodecTimeBase TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))";
string[] queries = {
"PRAGMA locking_mode=NORMAL",
"create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
@ -344,25 +353,26 @@ namespace Emby.Server.Implementations.Data
_connection.RunQueries(postQueries);
SqliteExtensions.Attach(_connection, Path.Combine(_config.ApplicationPaths.DataPath, "userdata_v2.db"), "UserDataDb");
userDataRepo.Initialize(_connection, WriteLock);
//SqliteExtensions.Attach(_connection, Path.Combine(_config.ApplicationPaths.DataPath, "userdata_v2.db"), "UserDataDb");
userDataRepo.Initialize(WriteLock);
//await Vacuum(_connection).ConfigureAwait(false);
}
protected override bool EnableConnectionPooling
private SQLiteDatabaseConnection CreateConnection(bool readOnly, bool attachUserdata)
{
get
Action<SQLiteDatabaseConnection> onConnect = null;
if (attachUserdata)
{
return false;
}
onConnect =
c => SqliteExtensions.Attach(c, Path.Combine(_config.ApplicationPaths.DataPath, "userdata_v2.db"),
"UserDataDb");
}
protected override bool EnableExclusiveMode
{
get
{
return true;
}
var conn = CreateConnection(readOnly, onConnect);
return conn;
}
private readonly string[] _retriveItemColumns =
@ -635,14 +645,17 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
_connection.RunInTransaction(db =>
connection.RunInTransaction(db =>
{
SaveItemsInTranscation(db, items);
});
}
}
}
private void SaveItemsInTranscation(IDatabaseConnection db, List<BaseItem> items)
{
@ -1170,9 +1183,11 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement("select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid = @guid"))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid = @guid"))
{
statement.TryBind("@guid", id);
@ -1182,6 +1197,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return null;
}
@ -1976,9 +1992,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<ChapterInfo>();
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc"))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc"))
{
statement.TryBind("@ItemId", id);
@ -1988,6 +2006,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return list;
}
@ -2007,9 +2026,11 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException("id");
}
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex"))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex"))
{
statement.TryBind("@ItemId", id);
statement.TryBind("@ChapterIndex", index);
@ -2020,6 +2041,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return null;
}
@ -2085,12 +2107,14 @@ namespace Emby.Server.Implementations.Data
var index = 0;
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
_connection.RunInTransaction(db =>
connection.RunInTransaction(db =>
{
// First delete chapters
_connection.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", id.ToGuidParamValue());
db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", id.ToGuidParamValue());
using (var saveChapterStatement = db.PrepareStatement("replace into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath, ImageDateModified) values (@ItemId, @ChapterIndex, @StartPositionTicks, @Name, @ImagePath, @ImageDateModified)"))
{
@ -2116,6 +2140,7 @@ namespace Emby.Server.Implementations.Data
});
}
}
}
protected override void CloseConnection()
{
@ -2383,9 +2408,11 @@ namespace Emby.Server.Implementations.Data
}
}
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (var statement = _connection.PrepareStatement(commandText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2409,6 +2436,7 @@ namespace Emby.Server.Implementations.Data
LogQueryTime("GetItemList", commandText, now);
}
}
// Hack for right now since we currently don't support filtering out these duplicates within a query
if (query.EnableGroupByMetadataKey)
@ -2548,14 +2576,16 @@ namespace Emby.Server.Implementations.Data
}
}
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (WriteLock.Read())
{
var totalRecordCount = 0;
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
if (!isReturningZeroItems)
{
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2592,7 +2622,7 @@ namespace Emby.Server.Implementations.Data
commandText += GetJoinUserDataText(query);
commandText += whereTextWithoutPaging;
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2616,6 +2646,7 @@ namespace Emby.Server.Implementations.Data
};
}
}
}
private string GetOrderByText(InternalItemsQuery query)
{
@ -2774,9 +2805,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<Guid>();
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (var statement = _connection.PrepareStatement(commandText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2799,6 +2832,7 @@ namespace Emby.Server.Implementations.Data
return list;
}
}
}
public List<Tuple<Guid, string>> GetItemIdsWithPath(InternalItemsQuery query)
{
@ -2842,9 +2876,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<Tuple<Guid, string>>();
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (var statement = _connection.PrepareStatement(commandText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2872,6 +2908,7 @@ namespace Emby.Server.Implementations.Data
return list;
}
}
}
public QueryResult<Guid> GetItemIds(InternalItemsQuery query)
{
@ -2928,11 +2965,13 @@ namespace Emby.Server.Implementations.Data
var list = new List<Guid>();
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (WriteLock.Read())
{
var totalRecordCount = 0;
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2964,7 +3003,7 @@ namespace Emby.Server.Implementations.Data
commandText += GetJoinUserDataText(query);
commandText += whereTextWithoutPaging;
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
if (EnableJoinUserData(query))
{
@ -2988,6 +3027,7 @@ namespace Emby.Server.Implementations.Data
};
}
}
}
private List<string> GetWhereClauses(InternalItemsQuery query, IStatement statement, string paramSuffix = "")
{
@ -4289,9 +4329,11 @@ namespace Emby.Server.Implementations.Data
var commandText = "select Guid,InheritedTags,(select group_concat(Tags, '|') from TypedBaseItems where (guid=outer.guid) OR (guid in (Select AncestorId from AncestorIds where ItemId=Outer.guid))) as NewInheritedTags from typedbaseitems as Outer where NewInheritedTags <> InheritedTags";
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
foreach (var row in _connection.Query(commandText))
foreach (var row in connection.Query(commandText))
{
var id = row.GetGuid(0);
string value = row.IsDBNull(2) ? null : row.GetString(2);
@ -4306,7 +4348,7 @@ namespace Emby.Server.Implementations.Data
}
// write lock here
using (var statement = _connection.PrepareStatement("Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid"))
using (var statement = connection.PrepareStatement("Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid"))
{
foreach (var item in newValues)
{
@ -4320,6 +4362,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
private static Dictionary<string, string[]> GetTypeMapDictionary()
{
@ -4360,9 +4403,11 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
_connection.RunInTransaction(db =>
connection.RunInTransaction(db =>
{
// Delete people
ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", id.ToGuidParamValue());
@ -4384,6 +4429,7 @@ namespace Emby.Server.Implementations.Data
});
}
}
}
private void ExecuteWithSingleParam(IDatabaseConnection db, string query, byte[] value)
{
@ -4417,9 +4463,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<string>();
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement(commandText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
// Run this again to bind the params
GetPeopleWhereClauses(query, statement);
@ -4432,6 +4480,7 @@ namespace Emby.Server.Implementations.Data
return list;
}
}
}
public List<PersonInfo> GetPeople(InternalPeopleQuery query)
{
@ -4455,9 +4504,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<PersonInfo>();
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement(commandText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
// Run this again to bind the params
GetPeopleWhereClauses(query, statement);
@ -4468,6 +4519,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return list;
}
@ -4667,9 +4719,11 @@ namespace Emby.Server.Implementations.Data
commandText += " Group By CleanValue";
using (var connection = CreateConnection(true))
{
using (WriteLock.Write())
{
foreach (var row in _connection.Query(commandText))
foreach (var row in connection.Query(commandText))
{
if (!row.IsDBNull(0))
{
@ -4677,6 +4731,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
LogQueryTime("GetItemValueNames", commandText, now);
return list;
@ -4825,11 +4880,13 @@ namespace Emby.Server.Implementations.Data
var list = new List<Tuple<BaseItem, ItemCounts>>();
var count = 0;
using (WriteLock.Write())
using (var connection = CreateConnection(true, EnableJoinUserData(query)))
{
using (WriteLock.Read())
{
if (!isReturningZeroItems)
{
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
statement.TryBind("@SelectType", returnType);
if (EnableJoinUserData(query))
@ -4867,7 +4924,7 @@ namespace Emby.Server.Implementations.Data
commandText += GetJoinUserDataText(query);
commandText += whereText;
using (var statement = _connection.PrepareStatement(commandText))
using (var statement = connection.PrepareStatement(commandText))
{
statement.TryBind("@SelectType", returnType);
if (EnableJoinUserData(query))
@ -4889,6 +4946,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
if (count == 0)
{
@ -5043,15 +5101,16 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
using (WriteLock.Write())
using (var connection = CreateConnection())
{
// First delete
using (WriteLock.Write())
{ // First delete
// "delete from People where ItemId=?"
_connection.Execute("delete from People where ItemId=?", itemId.ToGuidParamValue());
connection.Execute("delete from People where ItemId=?", itemId.ToGuidParamValue());
var listIndex = 0;
using (var statement = _connection.PrepareStatement(
using (var statement = connection.PrepareStatement(
"insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values (@ItemId, @Name, @Role, @PersonType, @SortOrder, @ListOrder)"))
{
foreach (var person in people)
@ -5074,6 +5133,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
private PersonInfo GetPerson(IReadOnlyList<IResultSetValue> reader)
{
@ -5127,9 +5187,11 @@ namespace Emby.Server.Implementations.Data
cmdText += " order by StreamIndex ASC";
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement(cmdText))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(cmdText))
{
statement.TryBind("@ItemId", query.ItemId.ToGuidParamValue());
@ -5149,6 +5211,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return list;
}
@ -5169,12 +5232,13 @@ namespace Emby.Server.Implementations.Data
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
using (var connection = CreateConnection())
{
// First delete chapters
_connection.Execute("delete from mediastreams where ItemId=@ItemId", id.ToGuidParamValue());
using (WriteLock.Write())
{ // First delete chapters
connection.Execute("delete from mediastreams where ItemId=@ItemId", id.ToGuidParamValue());
using (var statement = _connection.PrepareStatement(string.Format("replace into mediastreams ({0}) values ({1})",
using (var statement = connection.PrepareStatement(string.Format("replace into mediastreams ({0}) values ({1})",
string.Join(",", _mediaStreamSaveColumns),
string.Join(",", _mediaStreamSaveColumns.Select(i => "@" + i).ToArray()))))
{
@ -5225,6 +5289,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
/// <summary>
/// Gets the chapter.

View File

@ -14,19 +14,12 @@ namespace Emby.Server.Implementations.Data
{
public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository
{
private SQLiteDatabaseConnection _connection;
public SqliteUserDataRepository(ILogger logger, IApplicationPaths appPaths)
: base(logger)
{
DbFilePath = Path.Combine(appPaths.DataPath, "userdata_v2.db");
}
protected override bool EnableConnectionPooling
{
get { return false; }
}
/// <summary>
/// Gets the name of the repository
/// </summary>
@ -43,14 +36,25 @@ namespace Emby.Server.Implementations.Data
/// Opens the connection to the database
/// </summary>
/// <returns>Task.</returns>
public void Initialize(SQLiteDatabaseConnection connection, ReaderWriterLockSlim writeLock)
public void Initialize(ReaderWriterLockSlim writeLock)
{
WriteLock.Dispose();
WriteLock = writeLock;
_connection = connection;
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"PRAGMA locking_mode=NORMAL",
"create table if not exists UserDataDb.userdata (key nvarchar, userId GUID, rating float null, played bit, playCount int, isFavorite bit, playbackPositionTicks bigint, lastPlayedDate datetime null)",
"drop index if exists UserDataDb.idx_userdata",
@ -69,7 +73,7 @@ namespace Emby.Server.Implementations.Data
"pragma shrink_memory"
};
_connection.RunQueries(queries);
connection.RunQueries(queries);
connection.RunInTransaction(db =>
{
@ -79,6 +83,7 @@ namespace Emby.Server.Implementations.Data
AddColumn(db, "userdata", "SubtitleStreamIndex", "int", existingColumnNames);
});
}
}
/// <summary>
/// Saves the user data.
@ -139,18 +144,21 @@ namespace Emby.Server.Implementations.Data
{
cancellationToken.ThrowIfCancellationRequested();
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
_connection.RunInTransaction(db =>
connection.RunInTransaction(db =>
{
SaveUserData(db, userId, key, userData);
});
}
}
}
private void SaveUserData(IDatabaseConnection db, Guid userId, string key, UserItemData userData)
{
using (var statement = _connection.PrepareStatement("replace into userdata (key, userId, rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex) values (@key, @userId, @rating,@played,@playCount,@isFavorite,@playbackPositionTicks,@lastPlayedDate,@AudioStreamIndex,@SubtitleStreamIndex)"))
using (var statement = db.PrepareStatement("replace into userdata (key, userId, rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex) values (@key, @userId, @rating,@played,@playCount,@isFavorite,@playbackPositionTicks,@lastPlayedDate,@AudioStreamIndex,@SubtitleStreamIndex)"))
{
statement.TryBind("@UserId", userId.ToGuidParamValue());
statement.TryBind("@Key", key);
@ -207,9 +215,11 @@ namespace Emby.Server.Implementations.Data
{
cancellationToken.ThrowIfCancellationRequested();
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
_connection.RunInTransaction(db =>
connection.RunInTransaction(db =>
{
foreach (var userItemData in userDataList)
{
@ -218,6 +228,7 @@ namespace Emby.Server.Implementations.Data
});
}
}
}
/// <summary>
/// Gets the user data.
@ -241,9 +252,11 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException("key");
}
using (WriteLock.Write())
using (var connection = CreateConnection(true))
{
using (var statement = _connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where key =@Key and userId=@UserId"))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where key =@Key and userId=@UserId"))
{
statement.TryBind("@UserId", userId.ToGuidParamValue());
statement.TryBind("@Key", key);
@ -254,6 +267,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return null;
}
@ -291,9 +305,11 @@ namespace Emby.Server.Implementations.Data
var list = new List<UserItemData>();
using (WriteLock.Write())
using (var connection = CreateConnection())
{
using (var statement = _connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where userId=@UserId"))
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where userId=@UserId"))
{
statement.TryBind("@UserId", userId.ToGuidParamValue());
@ -303,6 +319,7 @@ namespace Emby.Server.Implementations.Data
}
}
}
}
return list;
}

View File

@ -50,6 +50,14 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists users (guid GUID primary key, data BLOB)",
@ -83,9 +91,9 @@ namespace Emby.Server.Implementations.Data
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -108,9 +116,9 @@ namespace Emby.Server.Implementations.Data
{
var list = new List<User>();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
foreach (var row in connection.Query("select guid,data from users"))
{
@ -146,9 +154,9 @@ namespace Emby.Server.Implementations.Data
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{

View File

@ -29,7 +29,16 @@ namespace Emby.Server.Implementations.Notifications
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT NULL, Url TEXT NULL, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT NULL, PRIMARY KEY (Id, UserId))",
"create index if not exists idx_Notifications1 on Notifications(Id)",
"create index if not exists idx_Notifications2 on Notifications(UserId)"
@ -103,9 +112,9 @@ namespace Emby.Server.Implementations.Notifications
{
var result = new NotificationsSummary();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement("select Level from Notifications where UserId=@UserId and IsRead=@IsRead"))
{
@ -220,9 +229,9 @@ namespace Emby.Server.Implementations.Notifications
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(conn =>
{
@ -283,9 +292,9 @@ namespace Emby.Server.Implementations.Notifications
{
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(conn =>
{
@ -305,9 +314,9 @@ namespace Emby.Server.Implementations.Notifications
{
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(conn =>
{

View File

@ -30,6 +30,14 @@ namespace Emby.Server.Implementations.Security
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists AccessTokens (Id GUID PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT, AppName TEXT, AppVersion TEXT, DeviceName TEXT, UserId TEXT, IsActive BIT, DateCreated DATETIME NOT NULL, DateRevoked DATETIME)",
@ -63,9 +71,9 @@ namespace Emby.Server.Implementations.Security
cancellationToken.ThrowIfCancellationRequested();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -200,6 +208,8 @@ namespace Emby.Server.Implementations.Security
var list = new List<AuthenticationInfo>();
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
BindAuthenticationQueryParams(query, statement);
@ -226,6 +236,7 @@ namespace Emby.Server.Implementations.Security
}
}
}
}
public AuthenticationInfo Get(string id)
{
@ -234,9 +245,9 @@ namespace Emby.Server.Implementations.Security
throw new ArgumentNullException("id");
}
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = BaseSelectText + " where Id=@Id";

View File

@ -27,6 +27,14 @@ namespace Emby.Server.Implementations.Social
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists Shares (Id GUID, ItemId TEXT, UserId TEXT, ExpirationDate DateTime, PRIMARY KEY (Id))",
@ -50,9 +58,9 @@ namespace Emby.Server.Implementations.Social
throw new ArgumentNullException("info.Id");
}
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(db =>
{
@ -75,9 +83,9 @@ namespace Emby.Server.Implementations.Social
throw new ArgumentNullException("id");
}
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = ?";

View File

@ -43,6 +43,14 @@ namespace Emby.Server.Implementations.Sync
{
using (var connection = CreateConnection())
{
connection.ExecuteAll(string.Join(";", new[]
{
"pragma default_temp_store = memory",
"pragma default_synchronous=Normal",
"pragma temp_store = memory",
"pragma synchronous=Normal",
}));
string[] queries = {
"create table if not exists SyncJobs (Id GUID PRIMARY KEY, TargetId TEXT NOT NULL, Name TEXT NOT NULL, Profile TEXT, Quality TEXT, Bitrate INT, Status TEXT NOT NULL, Progress FLOAT, UserId TEXT NOT NULL, ItemIds TEXT NOT NULL, Category TEXT, ParentId TEXT, UnwatchedOnly BIT, ItemLimit INT, SyncNewContent BIT, DateCreated DateTime, DateLastModified DateTime, ItemCount int)",
@ -95,9 +103,9 @@ namespace Emby.Server.Implementations.Sync
throw new ArgumentNullException("id");
}
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = BaseJobSelectText + " where Id=?";
var paramList = new List<object>();
@ -206,9 +214,9 @@ namespace Emby.Server.Implementations.Sync
CheckDisposed();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
string commandText;
var paramList = new List<object>();
@ -259,9 +267,9 @@ namespace Emby.Server.Implementations.Sync
CheckDisposed();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
connection.RunInTransaction(conn =>
{
@ -281,9 +289,9 @@ namespace Emby.Server.Implementations.Sync
CheckDisposed();
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = BaseJobSelectText;
var paramList = new List<object>();
@ -379,11 +387,11 @@ namespace Emby.Server.Implementations.Sync
CheckDisposed();
using (WriteLock.Read())
{
var guid = new Guid(id);
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = BaseJobItemSelectText + " where Id=?";
var paramList = new List<object>();
@ -407,9 +415,9 @@ namespace Emby.Server.Implementations.Sync
throw new ArgumentNullException("query");
}
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
using (WriteLock.Read())
{
var commandText = baseSelectText;
var paramList = new List<object>();
@ -487,8 +495,6 @@ namespace Emby.Server.Implementations.Sync
var now = DateTime.UtcNow;
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
{
var commandText = "select ItemId,Status,Progress from SyncJobItems";
@ -511,6 +517,8 @@ namespace Emby.Server.Implementations.Sync
commandText += " where " + string.Join(" AND ", whereClauses.ToArray());
}
using (WriteLock.Read())
{
using (var statement = connection.PrepareStatement(commandText))
{
if (!string.IsNullOrWhiteSpace(query.TargetId))
@ -664,9 +672,9 @@ namespace Emby.Server.Implementations.Sync
CheckDisposed();
using (WriteLock.Write())
{
using (var connection = CreateConnection())
{
using (WriteLock.Write())
{
string commandText;