diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index d730e420a..8a7573d66 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -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 (var connection = CreateConnection()) + using (WriteLock.Write()) { connection.RunInTransaction(db => { @@ -79,9 +87,9 @@ namespace Emby.Server.Implementations.Activity public QueryResult GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit) { - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = BaseActivitySelectText; var whereClauses = new List(); diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index c506411d4..382c7f245 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -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 onConnect = null) { if (!_versionLogged) { @@ -56,7 +51,7 @@ namespace Emby.Server.Implementations.Data ConnectionFlags connectionFlags; - //isReadOnly = false; + isReadOnly = false; if (isReadOnly) { @@ -70,46 +65,40 @@ namespace Emby.Server.Implementations.Data connectionFlags |= ConnectionFlags.ReadWrite; } - if (EnableConnectionPooling) - { - connectionFlags |= ConnectionFlags.SharedCached; - } - else - { - connectionFlags |= ConnectionFlags.PrivateCache; - } - + connectionFlags |= ConnectionFlags.SharedCached; connectionFlags |= ConnectionFlags.NoMutex; var db = SQLite3.Open(DbFilePath, connectionFlags, null); var queries = new List { - "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); + //} - db.ExecuteAll(string.Join(";", queries.ToArray())); + ////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 = ""; diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 184caa4d4..ab927ce86 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -54,9 +54,17 @@ 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)", + "create table if not exists userdisplaypreferences (id GUID, userId GUID, client text, data BLOB)", "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)" }; @@ -86,9 +94,9 @@ namespace Emby.Server.Implementations.Data cancellationToken.ThrowIfCancellationRequested(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - 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 (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 (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(); - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + using (WriteLock.Read()) { using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId")) { diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index e4e91626d..5b2549087 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -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(); - 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 result, int index) diff --git a/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs b/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs index 96edc5d0d..a71682329 100644 --- a/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs @@ -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)", diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index c720a8d89..754af9640 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -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 - { - get - { - return false; - } - } - protected override bool EnableExclusiveMode + private SQLiteDatabaseConnection CreateConnection(bool readOnly, bool attachUserdata) { - get + Action onConnect = null; + + if (attachUserdata) { - return true; + onConnect = + c => SqliteExtensions.Attach(c, Path.Combine(_config.ApplicationPaths.DataPath, "userdata_v2.db"), + "UserDataDb"); } + + var conn = CreateConnection(readOnly, onConnect); + + return conn; } private readonly string[] _retriveItemColumns = @@ -635,12 +645,15 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - _connection.RunInTransaction(db => + using (WriteLock.Write()) { - SaveItemsInTranscation(db, items); - }); + connection.RunInTransaction(db => + { + SaveItemsInTranscation(db, items); + }); + } } } @@ -1170,15 +1183,18 @@ 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()) { - statement.TryBind("@guid", id); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement("select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid = @guid")) { - return GetItem(row); + statement.TryBind("@guid", id); + + foreach (var row in statement.ExecuteQuery()) + { + return GetItem(row); + } } } } @@ -1976,15 +1992,18 @@ namespace Emby.Server.Implementations.Data var list = new List(); - 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()) { - statement.TryBind("@ItemId", id); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc")) { - list.Add(GetChapter(row)); + statement.TryBind("@ItemId", id); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetChapter(row)); + } } } } @@ -2007,16 +2026,19 @@ 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()) { - statement.TryBind("@ItemId", id); - statement.TryBind("@ChapterIndex", index); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement("select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex")) { - return GetChapter(row); + statement.TryBind("@ItemId", id); + statement.TryBind("@ChapterIndex", index); + + foreach (var row in statement.ExecuteQuery()) + { + return GetChapter(row); + } } } } @@ -2085,35 +2107,38 @@ namespace Emby.Server.Implementations.Data var index = 0; - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - _connection.RunInTransaction(db => + using (WriteLock.Write()) { - // First delete chapters - _connection.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)")) + connection.RunInTransaction(db => { - foreach (var chapter in chapters) + // First delete chapters + 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)")) { - if (index > 0) + foreach (var chapter in chapters) { - saveChapterStatement.Reset(); + if (index > 0) + { + saveChapterStatement.Reset(); + } + + saveChapterStatement.TryBind("@ItemId", id.ToGuidParamValue()); + saveChapterStatement.TryBind("@ChapterIndex", index); + saveChapterStatement.TryBind("@StartPositionTicks", chapter.StartPositionTicks); + saveChapterStatement.TryBind("@Name", chapter.Name); + saveChapterStatement.TryBind("@ImagePath", chapter.ImagePath); + saveChapterStatement.TryBind("@ImageDateModified", chapter.ImageDateModified); + + saveChapterStatement.MoveNext(); + + index++; } - - saveChapterStatement.TryBind("@ItemId", id.ToGuidParamValue()); - saveChapterStatement.TryBind("@ChapterIndex", index); - saveChapterStatement.TryBind("@StartPositionTicks", chapter.StartPositionTicks); - saveChapterStatement.TryBind("@Name", chapter.Name); - saveChapterStatement.TryBind("@ImagePath", chapter.ImagePath); - saveChapterStatement.TryBind("@ImageDateModified", chapter.ImageDateModified); - - saveChapterStatement.MoveNext(); - - index++; } - } - }); + }); + } } } @@ -2383,31 +2408,34 @@ namespace Emby.Server.Implementations.Data } } - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - if (EnableJoinUserData(query)) + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); - } - - BindSimilarParams(query, statement); - - // Running this again will bind the params - GetWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) - { - var item = GetItem(row, query); - if (item != null) + if (EnableJoinUserData(query)) { - list.Add(item); + statement.TryBind("@UserId", query.User.Id); + } + + BindSimilarParams(query, statement); + + // Running this again will bind the params + GetWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + var item = GetItem(row, query); + if (item != null) + { + list.Add(item); + } } } - } - LogQueryTime("GetItemList", commandText, now); + LogQueryTime("GetItemList", commandText, now); + } } // Hack for right now since we currently don't support filtering out these duplicates within a query @@ -2548,14 +2576,53 @@ namespace Emby.Server.Implementations.Data } } - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - var totalRecordCount = 0; - var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; - - if (!isReturningZeroItems) + using (WriteLock.Read()) { - using (var statement = _connection.PrepareStatement(commandText)) + var totalRecordCount = 0; + var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; + + if (!isReturningZeroItems) + { + using (var statement = connection.PrepareStatement(commandText)) + { + if (EnableJoinUserData(query)) + { + statement.TryBind("@UserId", query.User.Id); + } + + BindSimilarParams(query, statement); + + // Running this again will bind the params + GetWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + var item = GetItem(row, query); + if (item != null) + { + list.Add(item); + } + } + } + } + + commandText = string.Empty; + + if (EnableGroupByPresentationUniqueKey(query)) + { + commandText += " select count (distinct PresentationUniqueKey)" + GetFromText(); + } + else + { + commandText += " select count (guid)" + GetFromText(); + } + + commandText += GetJoinUserDataText(query); + commandText += whereTextWithoutPaging; + + using (var statement = connection.PrepareStatement(commandText)) { if (EnableJoinUserData(query)) { @@ -2567,53 +2634,17 @@ namespace Emby.Server.Implementations.Data // Running this again will bind the params GetWhereClauses(query, statement); - foreach (var row in statement.ExecuteQuery()) - { - var item = GetItem(row, query); - if (item != null) - { - list.Add(item); - } - } + totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); } - } - commandText = string.Empty; + LogQueryTime("GetItems", commandText, now); - if (EnableGroupByPresentationUniqueKey(query)) - { - commandText += " select count (distinct PresentationUniqueKey)" + GetFromText(); - } - else - { - commandText += " select count (guid)" + GetFromText(); - } - - commandText += GetJoinUserDataText(query); - commandText += whereTextWithoutPaging; - - using (var statement = _connection.PrepareStatement(commandText)) - { - if (EnableJoinUserData(query)) + return new QueryResult() { - statement.TryBind("@UserId", query.User.Id); - } - - BindSimilarParams(query, statement); - - // Running this again will bind the params - GetWhereClauses(query, statement); - - totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + Items = list.ToArray(), + TotalRecordCount = totalRecordCount + }; } - - LogQueryTime("GetItems", commandText, now); - - return new QueryResult() - { - Items = list.ToArray(), - TotalRecordCount = totalRecordCount - }; } } @@ -2774,29 +2805,32 @@ namespace Emby.Server.Implementations.Data var list = new List(); - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - if (EnableJoinUserData(query)) + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); + if (EnableJoinUserData(query)) + { + statement.TryBind("@UserId", query.User.Id); + } + + BindSimilarParams(query, statement); + + // Running this again will bind the params + GetWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(row[0].ReadGuid()); + } } - BindSimilarParams(query, statement); + LogQueryTime("GetItemList", commandText, now); - // Running this again will bind the params - GetWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) - { - list.Add(row[0].ReadGuid()); - } + return list; } - - LogQueryTime("GetItemList", commandText, now); - - return list; } } @@ -2842,34 +2876,37 @@ namespace Emby.Server.Implementations.Data var list = new List>(); - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - if (EnableJoinUserData(query)) + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); - } - - // Running this again will bind the params - GetWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) - { - var id = row.GetGuid(0); - string path = null; - - if (!row.IsDBNull(1)) + if (EnableJoinUserData(query)) { - path = row.GetString(1); + statement.TryBind("@UserId", query.User.Id); + } + + // Running this again will bind the params + GetWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + var id = row.GetGuid(0); + string path = null; + + if (!row.IsDBNull(1)) + { + path = row.GetString(1); + } + list.Add(new Tuple(id, path)); } - list.Add(new Tuple(id, path)); } + + LogQueryTime("GetItemIdsWithPath", commandText, now); + + return list; } - - LogQueryTime("GetItemIdsWithPath", commandText, now); - - return list; } } @@ -2928,64 +2965,67 @@ namespace Emby.Server.Implementations.Data var list = new List(); - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - var totalRecordCount = 0; - - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - if (EnableJoinUserData(query)) + var totalRecordCount = 0; + + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); + if (EnableJoinUserData(query)) + { + statement.TryBind("@UserId", query.User.Id); + } + + BindSimilarParams(query, statement); + + // Running this again will bind the params + GetWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(row[0].ReadGuid()); + } } - BindSimilarParams(query, statement); + commandText = string.Empty; - // Running this again will bind the params - GetWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) + if (EnableGroupByPresentationUniqueKey(query)) { - list.Add(row[0].ReadGuid()); + commandText += " select count (distinct PresentationUniqueKey)" + GetFromText(); } - } - - commandText = string.Empty; - - if (EnableGroupByPresentationUniqueKey(query)) - { - commandText += " select count (distinct PresentationUniqueKey)" + GetFromText(); - } - else - { - commandText += " select count (guid)" + GetFromText(); - } - - commandText += GetJoinUserDataText(query); - commandText += whereTextWithoutPaging; - - using (var statement = _connection.PrepareStatement(commandText)) - { - if (EnableJoinUserData(query)) + else { - statement.TryBind("@UserId", query.User.Id); + commandText += " select count (guid)" + GetFromText(); } - BindSimilarParams(query, statement); + commandText += GetJoinUserDataText(query); + commandText += whereTextWithoutPaging; - // Running this again will bind the params - GetWhereClauses(query, statement); + using (var statement = connection.PrepareStatement(commandText)) + { + if (EnableJoinUserData(query)) + { + statement.TryBind("@UserId", query.User.Id); + } - totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + BindSimilarParams(query, statement); + + // Running this again will bind the params + GetWhereClauses(query, statement); + + totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + } + + LogQueryTime("GetItemIds", commandText, now); + + return new QueryResult() + { + Items = list.ToArray(), + TotalRecordCount = totalRecordCount + }; } - - LogQueryTime("GetItemIds", commandText, now); - - return new QueryResult() - { - Items = list.ToArray(), - TotalRecordCount = totalRecordCount - }; } } @@ -4289,33 +4329,36 @@ 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 (WriteLock.Write()) + using (var connection = CreateConnection()) { - foreach (var row in _connection.Query(commandText)) + using (WriteLock.Write()) { - var id = row.GetGuid(0); - string value = row.IsDBNull(2) ? null : row.GetString(2); - - newValues.Add(new Tuple(id, value)); - } - - Logger.Debug("UpdateInheritedTags - {0} rows", newValues.Count); - if (newValues.Count == 0) - { - return; - } - - // write lock here - using (var statement = _connection.PrepareStatement("Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid")) - { - foreach (var item in newValues) + foreach (var row in connection.Query(commandText)) { - var paramList = new List(); + var id = row.GetGuid(0); + string value = row.IsDBNull(2) ? null : row.GetString(2); - paramList.Add(item.Item1); - paramList.Add(item.Item2); + newValues.Add(new Tuple(id, value)); + } - statement.Execute(paramList.ToArray()); + Logger.Debug("UpdateInheritedTags - {0} rows", newValues.Count); + if (newValues.Count == 0) + { + return; + } + + // write lock here + using (var statement = connection.PrepareStatement("Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid")) + { + foreach (var item in newValues) + { + var paramList = new List(); + + paramList.Add(item.Item1); + paramList.Add(item.Item2); + + statement.Execute(paramList.ToArray()); + } } } } @@ -4360,28 +4403,31 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - _connection.RunInTransaction(db => + using (WriteLock.Write()) { - // Delete people - ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", id.ToGuidParamValue()); + connection.RunInTransaction(db => + { + // Delete people + ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", id.ToGuidParamValue()); - // Delete chapters - ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", id.ToGuidParamValue()); + // Delete chapters + ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", id.ToGuidParamValue()); - // Delete media streams - ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", id.ToGuidParamValue()); + // Delete media streams + ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", id.ToGuidParamValue()); - // Delete ancestors - ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", id.ToGuidParamValue()); + // Delete ancestors + ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", id.ToGuidParamValue()); - // Delete item values - ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", id.ToGuidParamValue()); + // Delete item values + ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", id.ToGuidParamValue()); - // Delete the item - ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", id.ToGuidParamValue()); - }); + // Delete the item + ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", id.ToGuidParamValue()); + }); + } } } @@ -4417,19 +4463,22 @@ namespace Emby.Server.Implementations.Data var list = new List(); - using (WriteLock.Write()) + using (var connection = CreateConnection(true)) { - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - // Run this again to bind the params - GetPeopleWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement(commandText)) { - list.Add(row.GetString(0)); + // Run this again to bind the params + GetPeopleWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(row.GetString(0)); + } } + return list; } - return list; } } @@ -4455,16 +4504,19 @@ namespace Emby.Server.Implementations.Data var list = new List(); - using (WriteLock.Write()) + using (var connection = CreateConnection(true)) { - using (var statement = _connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - // Run this again to bind the params - GetPeopleWhereClauses(query, statement); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement(commandText)) { - list.Add(GetPerson(row)); + // Run this again to bind the params + GetPeopleWhereClauses(query, statement); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetPerson(row)); + } } } } @@ -4667,13 +4719,16 @@ namespace Emby.Server.Implementations.Data commandText += " Group By CleanValue"; - using (WriteLock.Write()) + using (var connection = CreateConnection(true)) { - foreach (var row in _connection.Query(commandText)) + using (WriteLock.Write()) { - if (!row.IsDBNull(0)) + foreach (var row in connection.Query(commandText)) { - list.Add(row.GetString(0)); + if (!row.IsDBNull(0)) + { + list.Add(row.GetString(0)); + } } } } @@ -4825,67 +4880,70 @@ namespace Emby.Server.Implementations.Data var list = new List>(); var count = 0; - using (WriteLock.Write()) + using (var connection = CreateConnection(true, EnableJoinUserData(query))) { - if (!isReturningZeroItems) + using (WriteLock.Read()) { - using (var statement = _connection.PrepareStatement(commandText)) + if (!isReturningZeroItems) { - statement.TryBind("@SelectType", returnType); - if (EnableJoinUserData(query)) + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); - } - - if (typeSubQuery != null) - { - GetWhereClauses(typeSubQuery, null, "itemTypes"); - } - BindSimilarParams(query, statement); - GetWhereClauses(innerQuery, statement); - GetWhereClauses(outerQuery, statement); - - foreach (var row in statement.ExecuteQuery()) - { - var item = GetItem(row); - if (item != null) + statement.TryBind("@SelectType", returnType); + if (EnableJoinUserData(query)) { - var countStartColumn = columns.Count - 1; - - list.Add(new Tuple(item, GetItemCounts(row, countStartColumn, typesToCount))); + statement.TryBind("@UserId", query.User.Id); } - } - LogQueryTime("GetItemValues", commandText, now); + if (typeSubQuery != null) + { + GetWhereClauses(typeSubQuery, null, "itemTypes"); + } + BindSimilarParams(query, statement); + GetWhereClauses(innerQuery, statement); + GetWhereClauses(outerQuery, statement); + + foreach (var row in statement.ExecuteQuery()) + { + var item = GetItem(row); + if (item != null) + { + var countStartColumn = columns.Count - 1; + + list.Add(new Tuple(item, GetItemCounts(row, countStartColumn, typesToCount))); + } + } + + LogQueryTime("GetItemValues", commandText, now); + } } - } - if (query.EnableTotalRecordCount) - { - commandText = "select count (distinct PresentationUniqueKey)" + GetFromText(); - - commandText += GetJoinUserDataText(query); - commandText += whereText; - - using (var statement = _connection.PrepareStatement(commandText)) + if (query.EnableTotalRecordCount) { - statement.TryBind("@SelectType", returnType); - if (EnableJoinUserData(query)) + commandText = "select count (distinct PresentationUniqueKey)" + GetFromText(); + + commandText += GetJoinUserDataText(query); + commandText += whereText; + + using (var statement = connection.PrepareStatement(commandText)) { - statement.TryBind("@UserId", query.User.Id); + statement.TryBind("@SelectType", returnType); + if (EnableJoinUserData(query)) + { + statement.TryBind("@UserId", query.User.Id); + } + + if (typeSubQuery != null) + { + GetWhereClauses(typeSubQuery, null, "itemTypes"); + } + BindSimilarParams(query, statement); + GetWhereClauses(innerQuery, statement); + GetWhereClauses(outerQuery, statement); + + count = statement.ExecuteQuery().SelectScalarInt().First(); + + LogQueryTime("GetItemValues", commandText, now); } - - if (typeSubQuery != null) - { - GetWhereClauses(typeSubQuery, null, "itemTypes"); - } - BindSimilarParams(query, statement); - GetWhereClauses(innerQuery, statement); - GetWhereClauses(outerQuery, statement); - - count = statement.ExecuteQuery().SelectScalarInt().First(); - - LogQueryTime("GetItemValues", commandText, now); } } } @@ -5043,33 +5101,35 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - // First delete - // "delete from People where ItemId=?" - _connection.Execute("delete from People where ItemId=?", itemId.ToGuidParamValue()); + using (WriteLock.Write()) + { // First delete + // "delete from People where ItemId=?" + connection.Execute("delete from People where ItemId=?", itemId.ToGuidParamValue()); - var listIndex = 0; + var listIndex = 0; - 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) + using (var statement = connection.PrepareStatement( + "insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values (@ItemId, @Name, @Role, @PersonType, @SortOrder, @ListOrder)")) { - if (listIndex > 0) + foreach (var person in people) { - statement.Reset(); + if (listIndex > 0) + { + statement.Reset(); + } + + statement.TryBind("@ItemId", itemId.ToGuidParamValue()); + statement.TryBind("@Name", person.Name); + statement.TryBind("@Role", person.Role); + statement.TryBind("@PersonType", person.Type); + statement.TryBind("@SortOrder", person.SortOrder); + statement.TryBind("@ListOrder", listIndex); + + statement.MoveNext(); + listIndex++; } - - statement.TryBind("@ItemId", itemId.ToGuidParamValue()); - statement.TryBind("@Name", person.Name); - statement.TryBind("@Role", person.Role); - statement.TryBind("@PersonType", person.Type); - statement.TryBind("@SortOrder", person.SortOrder); - statement.TryBind("@ListOrder", listIndex); - - statement.MoveNext(); - listIndex++; } } } @@ -5127,25 +5187,28 @@ 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()) { - statement.TryBind("@ItemId", query.ItemId.ToGuidParamValue()); - - if (query.Type.HasValue) + using (var statement = connection.PrepareStatement(cmdText)) { - statement.TryBind("@StreamType", query.Type.Value.ToString()); - } + statement.TryBind("@ItemId", query.ItemId.ToGuidParamValue()); - if (query.Index.HasValue) - { - statement.TryBind("@StreamIndex", query.Index.Value); - } + if (query.Type.HasValue) + { + statement.TryBind("@StreamType", query.Type.Value.ToString()); + } - foreach (var row in statement.ExecuteQuery()) - { - list.Add(GetMediaStream(row)); + if (query.Index.HasValue) + { + statement.TryBind("@StreamIndex", query.Index.Value); + } + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetMediaStream(row)); + } } } } @@ -5169,58 +5232,60 @@ 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})", - string.Join(",", _mediaStreamSaveColumns), - string.Join(",", _mediaStreamSaveColumns.Select(i => "@" + i).ToArray())))) - { - foreach (var stream in streams) + using (var statement = connection.PrepareStatement(string.Format("replace into mediastreams ({0}) values ({1})", + string.Join(",", _mediaStreamSaveColumns), + string.Join(",", _mediaStreamSaveColumns.Select(i => "@" + i).ToArray())))) { - var paramList = new List(); + foreach (var stream in streams) + { + var paramList = new List(); - paramList.Add(id.ToGuidParamValue()); - paramList.Add(stream.Index); - paramList.Add(stream.Type.ToString()); - paramList.Add(stream.Codec); - paramList.Add(stream.Language); - paramList.Add(stream.ChannelLayout); - paramList.Add(stream.Profile); - paramList.Add(stream.AspectRatio); - paramList.Add(stream.Path); + paramList.Add(id.ToGuidParamValue()); + paramList.Add(stream.Index); + paramList.Add(stream.Type.ToString()); + paramList.Add(stream.Codec); + paramList.Add(stream.Language); + paramList.Add(stream.ChannelLayout); + paramList.Add(stream.Profile); + paramList.Add(stream.AspectRatio); + paramList.Add(stream.Path); - paramList.Add(stream.IsInterlaced); - paramList.Add(stream.BitRate); - paramList.Add(stream.Channels); - paramList.Add(stream.SampleRate); + paramList.Add(stream.IsInterlaced); + paramList.Add(stream.BitRate); + paramList.Add(stream.Channels); + paramList.Add(stream.SampleRate); - paramList.Add(stream.IsDefault); - paramList.Add(stream.IsForced); - paramList.Add(stream.IsExternal); + paramList.Add(stream.IsDefault); + paramList.Add(stream.IsForced); + paramList.Add(stream.IsExternal); - paramList.Add(stream.Width); - paramList.Add(stream.Height); - paramList.Add(stream.AverageFrameRate); - paramList.Add(stream.RealFrameRate); - paramList.Add(stream.Level); - paramList.Add(stream.PixelFormat); - paramList.Add(stream.BitDepth); - paramList.Add(stream.IsExternal); - paramList.Add(stream.RefFrames); + paramList.Add(stream.Width); + paramList.Add(stream.Height); + paramList.Add(stream.AverageFrameRate); + paramList.Add(stream.RealFrameRate); + paramList.Add(stream.Level); + paramList.Add(stream.PixelFormat); + paramList.Add(stream.BitDepth); + paramList.Add(stream.IsExternal); + paramList.Add(stream.RefFrames); - paramList.Add(stream.CodecTag); - paramList.Add(stream.Comment); - paramList.Add(stream.NalLengthSize); - paramList.Add(stream.IsAVC); - paramList.Add(stream.Title); + paramList.Add(stream.CodecTag); + paramList.Add(stream.Comment); + paramList.Add(stream.NalLengthSize); + paramList.Add(stream.IsAVC); + paramList.Add(stream.Title); - paramList.Add(stream.TimeBase); - paramList.Add(stream.CodecTimeBase); + paramList.Add(stream.TimeBase); + paramList.Add(stream.CodecTimeBase); - statement.Execute(paramList.ToArray()); + statement.Execute(paramList.ToArray()); + } } } } diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index a66536179..0b4768c14 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -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; } - } - /// /// Gets the name of the repository /// @@ -43,13 +36,24 @@ namespace Emby.Server.Implementations.Data /// Opens the connection to the database /// /// Task. - public void Initialize(SQLiteDatabaseConnection connection, ReaderWriterLockSlim writeLock) + public void Initialize(ReaderWriterLockSlim writeLock) { WriteLock.Dispose(); WriteLock = writeLock; - _connection = connection; - string[] queries = { + 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)", @@ -69,15 +73,16 @@ namespace Emby.Server.Implementations.Data "pragma shrink_memory" }; - _connection.RunQueries(queries); + connection.RunQueries(queries); - connection.RunInTransaction(db => - { - var existingColumnNames = GetColumnNames(db, "userdata"); + connection.RunInTransaction(db => + { + var existingColumnNames = GetColumnNames(db, "userdata"); - AddColumn(db, "userdata", "AudioStreamIndex", "int", existingColumnNames); - AddColumn(db, "userdata", "SubtitleStreamIndex", "int", existingColumnNames); - }); + AddColumn(db, "userdata", "AudioStreamIndex", "int", existingColumnNames); + AddColumn(db, "userdata", "SubtitleStreamIndex", "int", existingColumnNames); + }); + } } /// @@ -139,18 +144,21 @@ namespace Emby.Server.Implementations.Data { cancellationToken.ThrowIfCancellationRequested(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - _connection.RunInTransaction(db => + using (WriteLock.Write()) { - SaveUserData(db, userId, key, userData); - }); + 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,15 +215,18 @@ namespace Emby.Server.Implementations.Data { cancellationToken.ThrowIfCancellationRequested(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - _connection.RunInTransaction(db => + using (WriteLock.Write()) { - foreach (var userItemData in userDataList) + connection.RunInTransaction(db => { - SaveUserData(db, userId, userItemData.Key, userItemData); - } - }); + foreach (var userItemData in userDataList) + { + SaveUserData(db, userId, userItemData.Key, userItemData); + } + }); + } } } @@ -241,16 +252,19 @@ 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()) { - statement.TryBind("@UserId", userId.ToGuidParamValue()); - statement.TryBind("@Key", key); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where key =@Key and userId=@UserId")) { - return ReadRow(row); + statement.TryBind("@UserId", userId.ToGuidParamValue()); + statement.TryBind("@Key", key); + + foreach (var row in statement.ExecuteQuery()) + { + return ReadRow(row); + } } } } @@ -291,15 +305,18 @@ namespace Emby.Server.Implementations.Data var list = new List(); - 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()) { - statement.TryBind("@UserId", userId.ToGuidParamValue()); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from userdata where userId=@UserId")) { - list.Add(ReadRow(row)); + statement.TryBind("@UserId", userId.ToGuidParamValue()); + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(ReadRow(row)); + } } } } diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index 5e148d95a..0a2f9e7cd 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -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 (var connection = CreateConnection()) + using (WriteLock.Write()) { connection.RunInTransaction(db => { @@ -108,9 +116,9 @@ namespace Emby.Server.Implementations.Data { var list = new List(); - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - 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 (var connection = CreateConnection()) + using (WriteLock.Write()) { connection.RunInTransaction(db => { diff --git a/Emby.Server.Implementations/Notifications/SqliteNotificationsRepository.cs b/Emby.Server.Implementations/Notifications/SqliteNotificationsRepository.cs index 5a3b64dbb..5fc691527 100644 --- a/Emby.Server.Implementations/Notifications/SqliteNotificationsRepository.cs +++ b/Emby.Server.Implementations/Notifications/SqliteNotificationsRepository.cs @@ -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 (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 (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 (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 (var connection = CreateConnection()) + using (WriteLock.Write()) { connection.RunInTransaction(conn => { diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index a9141f153..0a598e9a7 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -30,9 +30,17 @@ 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)", + "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)", "create index if not exists idx_AccessTokens on AccessTokens(Id)" }; @@ -63,9 +71,9 @@ namespace Emby.Server.Implementations.Security cancellationToken.ThrowIfCancellationRequested(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + using (WriteLock.Write()) { connection.RunInTransaction(db => { @@ -200,28 +208,31 @@ namespace Emby.Server.Implementations.Security var list = new List(); - using (var statement = connection.PrepareStatement(commandText)) + using (WriteLock.Read()) { - BindAuthenticationQueryParams(query, statement); - - foreach (var row in statement.ExecuteQuery()) + using (var statement = connection.PrepareStatement(commandText)) { - list.Add(Get(row)); - } + BindAuthenticationQueryParams(query, statement); - using (var totalCountStatement = connection.PrepareStatement("select count (Id) from AccessTokens" + whereTextWithoutPaging)) - { - BindAuthenticationQueryParams(query, totalCountStatement); - - var count = totalCountStatement.ExecuteQuery() - .SelectScalarInt() - .First(); - - return new QueryResult() + foreach (var row in statement.ExecuteQuery()) { - Items = list.ToArray(), - TotalRecordCount = count - }; + list.Add(Get(row)); + } + + using (var totalCountStatement = connection.PrepareStatement("select count (Id) from AccessTokens" + whereTextWithoutPaging)) + { + BindAuthenticationQueryParams(query, totalCountStatement); + + var count = totalCountStatement.ExecuteQuery() + .SelectScalarInt() + .First(); + + return new QueryResult() + { + Items = list.ToArray(), + TotalRecordCount = count + }; + } } } } @@ -234,9 +245,9 @@ namespace Emby.Server.Implementations.Security throw new ArgumentNullException("id"); } - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = BaseSelectText + " where Id=@Id"; diff --git a/Emby.Server.Implementations/Social/SharingRepository.cs b/Emby.Server.Implementations/Social/SharingRepository.cs index 9065ee108..e0ee62780 100644 --- a/Emby.Server.Implementations/Social/SharingRepository.cs +++ b/Emby.Server.Implementations/Social/SharingRepository.cs @@ -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 (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 (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = ?"; diff --git a/Emby.Server.Implementations/Sync/SyncRepository.cs b/Emby.Server.Implementations/Sync/SyncRepository.cs index 6fb918f15..36558142b 100644 --- a/Emby.Server.Implementations/Sync/SyncRepository.cs +++ b/Emby.Server.Implementations/Sync/SyncRepository.cs @@ -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 (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = BaseJobSelectText + " where Id=?"; var paramList = new List(); @@ -206,9 +214,9 @@ namespace Emby.Server.Implementations.Sync CheckDisposed(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + using (WriteLock.Write()) { string commandText; var paramList = new List(); @@ -259,9 +267,9 @@ namespace Emby.Server.Implementations.Sync CheckDisposed(); - using (WriteLock.Write()) + using (var connection = CreateConnection()) { - 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 (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = BaseJobSelectText; var paramList = new List(); @@ -379,11 +387,11 @@ namespace Emby.Server.Implementations.Sync CheckDisposed(); - using (WriteLock.Read()) - { - var guid = new Guid(id); + var guid = new Guid(id); - using (var connection = CreateConnection(true)) + using (var connection = CreateConnection(true)) + { + using (WriteLock.Read()) { var commandText = BaseJobItemSelectText + " where Id=?"; var paramList = new List(); @@ -407,9 +415,9 @@ namespace Emby.Server.Implementations.Sync throw new ArgumentNullException("query"); } - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + using (WriteLock.Read()) { var commandText = baseSelectText; var paramList = new List(); @@ -487,30 +495,30 @@ namespace Emby.Server.Implementations.Sync var now = DateTime.UtcNow; - using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + var commandText = "select ItemId,Status,Progress from SyncJobItems"; + var whereClauses = new List(); + + if (!string.IsNullOrWhiteSpace(query.TargetId)) { - var commandText = "select ItemId,Status,Progress from SyncJobItems"; - var whereClauses = new List(); + whereClauses.Add("TargetId=@TargetId"); + } - if (!string.IsNullOrWhiteSpace(query.TargetId)) - { - whereClauses.Add("TargetId=@TargetId"); - } + if (query.Statuses.Length > 0) + { + var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray()); - if (query.Statuses.Length > 0) - { - var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray()); + whereClauses.Add(string.Format("Status in ({0})", statuses)); + } - whereClauses.Add(string.Format("Status in ({0})", statuses)); - } - - if (whereClauses.Count > 0) - { - commandText += " where " + string.Join(" AND ", whereClauses.ToArray()); - } + if (whereClauses.Count > 0) + { + 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 (var connection = CreateConnection()) + using (WriteLock.Write()) { string commandText;