aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Data
diff options
context:
space:
mode:
authorLuke <luke.pulverenti@gmail.com>2016-11-21 12:29:18 -0500
committerGitHub <noreply@github.com>2016-11-21 12:29:18 -0500
commitf80cc1bbd4145a682234d4d1d286c70f562f36bd (patch)
tree2ecc0e11aa1f394295f6269069da5ed6b9ed0667 /Emby.Server.Implementations/Data
parentb2ea3272e70a0f520133ee6a74d958e044d4392e (diff)
parent1acebd992229ee9bd6e7677f68174672fae53622 (diff)
Merge pull request #2299 from MediaBrowser/dev
Dev
Diffstat (limited to 'Emby.Server.Implementations/Data')
-rw-r--r--Emby.Server.Implementations/Data/BaseSqliteRepository.cs83
-rw-r--r--Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs25
-rw-r--r--Emby.Server.Implementations/Data/SqliteExtensions.cs10
-rw-r--r--Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs7
-rw-r--r--Emby.Server.Implementations/Data/SqliteItemRepository.cs885
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserDataRepository.cs98
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserRepository.cs19
7 files changed, 618 insertions, 509 deletions
diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
index c506411d4..d4226ec25 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,9 @@ namespace Emby.Server.Implementations.Data
private static bool _versionLogged;
- protected virtual SQLiteDatabaseConnection CreateConnection(bool isReadOnly = false)
+ private string _defaultWal;
+
+ protected SQLiteDatabaseConnection CreateConnection(bool isReadOnly = false, Action<SQLiteDatabaseConnection> onConnect = null)
{
if (!_versionLogged)
{
@@ -56,60 +53,73 @@ namespace Emby.Server.Implementations.Data
ConnectionFlags connectionFlags;
- //isReadOnly = false;
-
if (isReadOnly)
{
- connectionFlags = ConnectionFlags.ReadOnly;
- //connectionFlags = ConnectionFlags.Create;
- //connectionFlags |= ConnectionFlags.ReadWrite;
+ //Logger.Info("Opening read connection");
}
else
{
- connectionFlags = ConnectionFlags.Create;
- connectionFlags |= ConnectionFlags.ReadWrite;
+ //Logger.Info("Opening write connection");
}
- if (EnableConnectionPooling)
+ isReadOnly = false;
+
+ if (isReadOnly)
{
- connectionFlags |= ConnectionFlags.SharedCached;
+ connectionFlags = ConnectionFlags.ReadOnly;
+ //connectionFlags = ConnectionFlags.Create;
+ //connectionFlags |= ConnectionFlags.ReadWrite;
}
else
{
- connectionFlags |= ConnectionFlags.PrivateCache;
+ connectionFlags = ConnectionFlags.Create;
+ connectionFlags |= ConnectionFlags.ReadWrite;
}
+ connectionFlags |= ConnectionFlags.SharedCached;
connectionFlags |= ConnectionFlags.NoMutex;
var db = SQLite3.Open(DbFilePath, connectionFlags, null);
+ if (string.IsNullOrWhiteSpace(_defaultWal))
+ {
+ _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
+ }
+
var queries = new List<string>
{
- "pragma default_temp_store = memory",
- "PRAGMA page_size=4096",
- "PRAGMA journal_mode=WAL",
- "PRAGMA temp_store=memory",
- "PRAGMA synchronous=Normal",
+ "PRAGMA default_temp_store=memory",
+ "pragma temp_store = memory",
+ "PRAGMA journal_mode=WAL"
//"PRAGMA cache size=-10000"
};
- var cacheSize = CacheSize;
- if (cacheSize.HasValue)
- {
+ //var cacheSize = CacheSize;
+ //if (cacheSize.HasValue)
+ //{
- }
+ //}
- if (EnableExclusiveMode)
- {
- queries.Add("PRAGMA locking_mode=EXCLUSIVE");
- }
+ ////foreach (var query in queries)
+ ////{
+ //// db.Execute(query);
+ ////}
- //foreach (var query in queries)
- //{
- // db.Execute(query);
- //}
+ //Logger.Info("synchronous: " + db.Query("PRAGMA synchronous").SelectScalarString().First());
+ //Logger.Info("temp_store: " + db.Query("PRAGMA temp_store").SelectScalarString().First());
- db.ExecuteAll(string.Join(";", queries.ToArray()));
+ //if (!string.Equals(_defaultWal, "wal", StringComparison.OrdinalIgnoreCase) || onConnect != null)
+ {
+ using (WriteLock.Write())
+ {
+ db.ExecuteAll(string.Join(";", queries.ToArray()));
+
+ if (onConnect != null)
+ {
+ onConnect(db);
+ }
+ }
+ }
return db;
}
@@ -122,11 +132,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..17afbcfa9 100644
--- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
@@ -54,9 +54,16 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
+ connection.ExecuteAll(string.Join(";", new[]
+ {
+ "PRAGMA page_size=4096",
+ "pragma default_temp_store = memory",
+ "pragma temp_store = memory"
+ }));
+
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 +93,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 +137,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 +169,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 +203,9 @@ namespace Emby.Server.Implementations.Data
{
var list = new List<DisplayPreferences>();
- 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<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)
diff --git a/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs b/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs
index 96edc5d0d..efc0ee2ed 100644
--- a/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs
@@ -31,6 +31,13 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
+ connection.ExecuteAll(string.Join(";", new[]
+ {
+ "PRAGMA page_size=4096",
+ "pragma default_temp_store = memory",
+ "pragma temp_store = memory"
+ }));
+
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..bc1eca06a 100644
--- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
@@ -29,6 +29,7 @@ using MediaBrowser.Server.Implementations.Devices;
using MediaBrowser.Server.Implementations.Playlists;
using MediaBrowser.Model.Reflection;
using SQLitePCL.pretty;
+using MediaBrowser.Model.System;
namespace Emby.Server.Implementations.Data
{
@@ -66,14 +67,14 @@ namespace Emby.Server.Implementations.Data
private readonly string _criticReviewsPath;
- public const int LatestSchemaVersion = 109;
private readonly IMemoryStreamFactory _memoryStreamProvider;
private readonly IFileSystem _fileSystem;
+ private readonly IEnvironmentInfo _environmentInfo;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
/// </summary>
- public SqliteItemRepository(IServerConfigurationManager config, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamFactory memoryStreamProvider, IAssemblyInfo assemblyInfo, IFileSystem fileSystem)
+ public SqliteItemRepository(IServerConfigurationManager config, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamFactory memoryStreamProvider, IAssemblyInfo assemblyInfo, IFileSystem fileSystem, IEnvironmentInfo environmentInfo)
: base(logger)
{
if (config == null)
@@ -89,6 +90,7 @@ namespace Emby.Server.Implementations.Data
_jsonSerializer = jsonSerializer;
_memoryStreamProvider = memoryStreamProvider;
_fileSystem = fileSystem;
+ _environmentInfo = environmentInfo;
_typeMapper = new TypeMapper(assemblyInfo);
_criticReviewsPath = Path.Combine(_config.ApplicationPaths.DataPath, "critic-reviews");
@@ -127,10 +129,18 @@ namespace Emby.Server.Implementations.Data
{
_connection = CreateConnection(false);
+ _connection.ExecuteAll(string.Join(";", new[]
+ {
+ "PRAGMA page_size=4096",
+ "PRAGMA default_temp_store=memory",
+ "PRAGMA temp_store=memory"
+ }));
+
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)",
@@ -184,7 +194,6 @@ namespace Emby.Server.Implementations.Data
AddColumn(db, "TypedBaseItems", "ProductionYear", "INT", existingColumnNames);
AddColumn(db, "TypedBaseItems", "ParentId", "GUID", existingColumnNames);
AddColumn(db, "TypedBaseItems", "Genres", "Text", existingColumnNames);
- AddColumn(db, "TypedBaseItems", "SchemaVersion", "INT", existingColumnNames);
AddColumn(db, "TypedBaseItems", "SortName", "Text", existingColumnNames);
AddColumn(db, "TypedBaseItems", "RunTimeTicks", "BIGINT", existingColumnNames);
@@ -196,7 +205,6 @@ namespace Emby.Server.Implementations.Data
AddColumn(db, "TypedBaseItems", "DateModified", "DATETIME", existingColumnNames);
AddColumn(db, "TypedBaseItems", "ForcedSortName", "Text", existingColumnNames);
- AddColumn(db, "TypedBaseItems", "IsOffline", "BIT", existingColumnNames);
AddColumn(db, "TypedBaseItems", "LocationType", "Text", existingColumnNames);
AddColumn(db, "TypedBaseItems", "IsSeries", "BIT", existingColumnNames);
@@ -344,25 +352,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<SQLiteDatabaseConnection> 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 =
@@ -371,7 +380,6 @@ namespace Emby.Server.Implementations.Data
"data",
"StartDate",
"EndDate",
- "IsOffline",
"ChannelId",
"IsMovie",
"IsSports",
@@ -519,7 +527,6 @@ namespace Emby.Server.Implementations.Data
"ParentId",
"Genres",
"InheritedParentalRatingValue",
- "SchemaVersion",
"SortName",
"RunTimeTicks",
"OfficialRatingDescription",
@@ -529,7 +536,6 @@ namespace Emby.Server.Implementations.Data
"DateCreated",
"DateModified",
"ForcedSortName",
- "IsOffline",
"LocationType",
"PreferredMetadataLanguage",
"PreferredMetadataCountryCode",
@@ -635,12 +641,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);
+ });
+ }
}
}
@@ -777,7 +786,6 @@ namespace Emby.Server.Implementations.Data
}
saveItemStatement.TryBind("@InheritedParentalRatingValue", item.GetInheritedParentalRatingValue() ?? 0);
- saveItemStatement.TryBind("@SchemaVersion", LatestSchemaVersion);
saveItemStatement.TryBind("@SortName", item.SortName);
saveItemStatement.TryBind("@RunTimeTicks", item.RunTimeTicks);
@@ -790,7 +798,6 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.TryBind("@DateModified", item.DateModified);
saveItemStatement.TryBind("@ForcedSortName", item.ForcedSortName);
- saveItemStatement.TryBind("@IsOffline", item.IsOffline);
saveItemStatement.TryBind("@LocationType", item.LocationType.ToString());
saveItemStatement.TryBind("@PreferredMetadataLanguage", item.PreferredMetadataLanguage);
@@ -1169,16 +1176,19 @@ namespace Emby.Server.Implementations.Data
}
CheckDisposed();
-
- using (WriteLock.Write())
+ //Logger.Info("Retrieving item {0}", id.ToString("N"));
+ 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);
+ }
}
}
}
@@ -1353,64 +1363,72 @@ namespace Emby.Server.Implementations.Data
if (!reader.IsDBNull(4))
{
- item.IsOffline = reader.GetBoolean(4);
+ item.ChannelId = reader.GetString(4);
}
- if (!reader.IsDBNull(5))
- {
- item.ChannelId = reader.GetString(5);
- }
+ var index = 5;
var hasProgramAttributes = item as IHasProgramAttributes;
if (hasProgramAttributes != null)
{
- if (!reader.IsDBNull(6))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsMovie = reader.GetBoolean(6);
+ hasProgramAttributes.IsMovie = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(7))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsSports = reader.GetBoolean(7);
+ hasProgramAttributes.IsSports = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(8))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsKids = reader.GetBoolean(8);
+ hasProgramAttributes.IsKids = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(9))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsSeries = reader.GetBoolean(9);
+ hasProgramAttributes.IsSeries = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(10))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsLive = reader.GetBoolean(10);
+ hasProgramAttributes.IsLive = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(11))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsNews = reader.GetBoolean(11);
+ hasProgramAttributes.IsNews = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(12))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsPremiere = reader.GetBoolean(12);
+ hasProgramAttributes.IsPremiere = reader.GetBoolean(index);
}
+ index++;
- if (!reader.IsDBNull(13))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.EpisodeTitle = reader.GetString(13);
+ hasProgramAttributes.EpisodeTitle = reader.GetString(index);
}
+ index++;
- if (!reader.IsDBNull(14))
+ if (!reader.IsDBNull(index))
{
- hasProgramAttributes.IsRepeat = reader.GetBoolean(14);
+ hasProgramAttributes.IsRepeat = reader.GetBoolean(index);
}
+ index++;
+ }
+ else
+ {
+ index += 9;
}
-
- var index = 15;
if (!reader.IsDBNull(index))
{
@@ -1976,15 +1994,18 @@ 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())
{
- 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 +2028,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 +2109,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.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();
+ saveChapterStatement.MoveNext();
- index++;
+ index++;
+ }
}
- }
- });
+ });
+ }
}
}
@@ -2343,6 +2370,8 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
+ //Logger.Info("GetItemList: " + _environmentInfo.StackTrace);
+
var now = DateTime.UtcNow;
var list = new List<BaseItem>();
@@ -2383,31 +2412,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);
- }
+ if (EnableJoinUserData(query))
+ {
+ statement.TryBind("@UserId", query.User.Id);
+ }
- BindSimilarParams(query, statement);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(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)
+ foreach (var row in statement.ExecuteQuery())
{
- list.Add(item);
+ 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
@@ -2505,6 +2537,7 @@ namespace Emby.Server.Implementations.Data
TotalRecordCount = returnList.Count
};
}
+ //Logger.Info("GetItems: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -2548,72 +2581,75 @@ 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)
{
- 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);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(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)
+ foreach (var row in statement.ExecuteQuery())
{
- list.Add(item);
+ var item = GetItem(row, query);
+ if (item != null)
+ {
+ list.Add(item);
+ }
}
}
}
- }
- commandText = string.Empty;
+ commandText = string.Empty;
- if (EnableGroupByPresentationUniqueKey(query))
- {
- commandText += " select count (distinct PresentationUniqueKey)" + GetFromText();
- }
- else
- {
- commandText += " select count (guid)" + GetFromText();
- }
+ if (EnableGroupByPresentationUniqueKey(query))
+ {
+ commandText += " select count (distinct PresentationUniqueKey)" + GetFromText();
+ }
+ else
+ {
+ commandText += " select count (guid)" + GetFromText();
+ }
- commandText += GetJoinUserDataText(query);
- commandText += whereTextWithoutPaging;
+ commandText += GetJoinUserDataText(query);
+ commandText += whereTextWithoutPaging;
- using (var statement = _connection.PrepareStatement(commandText))
- {
- 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);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
+ totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ }
- LogQueryTime("GetItems", commandText, now);
+ LogQueryTime("GetItems", commandText, now);
- return new QueryResult<BaseItem>()
- {
- Items = list.ToArray(),
- TotalRecordCount = totalRecordCount
- };
+ return new QueryResult<BaseItem>()
+ {
+ Items = list.ToArray(),
+ TotalRecordCount = totalRecordCount
+ };
+ }
}
}
@@ -2739,6 +2775,7 @@ namespace Emby.Server.Implementations.Data
}
CheckDisposed();
+ //Logger.Info("GetItemIdsList: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -2774,29 +2811,32 @@ 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())
{
- 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);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(row[0].ReadGuid());
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(row[0].ReadGuid());
+ }
}
- }
- LogQueryTime("GetItemList", commandText, now);
+ LogQueryTime("GetItemList", commandText, now);
- return list;
+ return list;
+ }
}
}
@@ -2842,34 +2882,37 @@ 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())
{
- 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);
+ if (EnableJoinUserData(query))
+ {
+ statement.TryBind("@UserId", query.User.Id);
+ }
- foreach (var row in statement.ExecuteQuery())
- {
- var id = row.GetGuid(0);
- string path = null;
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- if (!row.IsDBNull(1))
+ foreach (var row in statement.ExecuteQuery())
{
- path = row.GetString(1);
+ var id = row.GetGuid(0);
+ string path = null;
+
+ if (!row.IsDBNull(1))
+ {
+ path = row.GetString(1);
+ }
+ list.Add(new Tuple<Guid, string>(id, path));
}
- list.Add(new Tuple<Guid, string>(id, path));
}
- }
- LogQueryTime("GetItemIdsWithPath", commandText, now);
+ LogQueryTime("GetItemIdsWithPath", commandText, now);
- return list;
+ return list;
+ }
}
}
@@ -2891,6 +2934,7 @@ namespace Emby.Server.Implementations.Data
TotalRecordCount = returnList.Count
};
}
+ //Logger.Info("GetItemIds: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -2928,64 +2972,67 @@ namespace Emby.Server.Implementations.Data
var list = new List<Guid>();
- 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);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(row[0].ReadGuid());
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(row[0].ReadGuid());
+ }
}
- }
- commandText = string.Empty;
+ commandText = string.Empty;
- if (EnableGroupByPresentationUniqueKey(query))
- {
- commandText += " select count (distinct PresentationUniqueKey)" + GetFromText();
- }
- else
- {
- commandText += " select count (guid)" + GetFromText();
- }
+ if (EnableGroupByPresentationUniqueKey(query))
+ {
+ commandText += " select count (distinct PresentationUniqueKey)" + GetFromText();
+ }
+ else
+ {
+ commandText += " select count (guid)" + GetFromText();
+ }
- commandText += GetJoinUserDataText(query);
- commandText += whereTextWithoutPaging;
+ commandText += GetJoinUserDataText(query);
+ commandText += whereTextWithoutPaging;
- using (var statement = _connection.PrepareStatement(commandText))
- {
- 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);
+ BindSimilarParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
+ totalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ }
- LogQueryTime("GetItemIds", commandText, now);
+ LogQueryTime("GetItemIds", commandText, now);
- return new QueryResult<Guid>()
- {
- Items = list.ToArray(),
- TotalRecordCount = totalRecordCount
- };
+ return new QueryResult<Guid>()
+ {
+ Items = list.ToArray(),
+ TotalRecordCount = totalRecordCount
+ };
+ }
}
}
@@ -3013,14 +3060,6 @@ namespace Emby.Server.Implementations.Data
statement.TryBind("@IsLocked", query.IsLocked);
}
}
- if (query.IsOffline.HasValue)
- {
- whereClauses.Add("IsOffline=@IsOffline");
- if (statement != null)
- {
- statement.TryBind("@IsOffline", query.IsOffline);
- }
- }
var exclusiveProgramAttribtues = !(query.IsMovie ?? true) ||
!(query.IsSports ?? true) ||
@@ -4289,33 +4328,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);
+ foreach (var row in connection.Query(commandText))
+ {
+ var id = row.GetGuid(0);
+ string value = row.IsDBNull(2) ? null : row.GetString(2);
- newValues.Add(new Tuple<Guid, string>(id, value));
- }
+ newValues.Add(new Tuple<Guid, string>(id, value));
+ }
- Logger.Debug("UpdateInheritedTags - {0} rows", newValues.Count);
- if (newValues.Count == 0)
- {
- return;
- }
+ 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)
+ // write lock here
+ using (var statement = connection.PrepareStatement("Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid"))
{
- var paramList = new List<object>();
+ foreach (var item in newValues)
+ {
+ var paramList = new List<object>();
- paramList.Add(item.Item1);
- paramList.Add(item.Item2);
+ paramList.Add(item.Item1);
+ paramList.Add(item.Item2);
- statement.Execute(paramList.ToArray());
+ statement.Execute(paramList.ToArray());
+ }
}
}
}
@@ -4360,28 +4402,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 +4462,22 @@ 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())
{
- // 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 +4503,19 @@ 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())
{
- // 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 +4718,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.Read())
{
- 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));
+ }
}
}
}
@@ -4695,6 +4749,7 @@ namespace Emby.Server.Implementations.Data
}
CheckDisposed();
+ //Logger.Info("GetItemValues: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -4825,67 +4880,70 @@ 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)))
{
- 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);
- }
+ 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);
+ 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)
+ foreach (var row in statement.ExecuteQuery())
{
- var countStartColumn = columns.Count - 1;
+ var item = GetItem(row);
+ if (item != null)
+ {
+ var countStartColumn = columns.Count - 1;
- list.Add(new Tuple<BaseItem, ItemCounts>(item, GetItemCounts(row, countStartColumn, typesToCount)));
+ list.Add(new Tuple<BaseItem, ItemCounts>(item, GetItemCounts(row, countStartColumn, typesToCount)));
+ }
}
- }
- LogQueryTime("GetItemValues", commandText, now);
+ LogQueryTime("GetItemValues", commandText, now);
+ }
}
- }
- if (query.EnableTotalRecordCount)
- {
- commandText = "select count (distinct PresentationUniqueKey)" + GetFromText();
+ if (query.EnableTotalRecordCount)
+ {
+ commandText = "select count (distinct PresentationUniqueKey)" + GetFromText();
- commandText += GetJoinUserDataText(query);
- commandText += whereText;
+ commandText += GetJoinUserDataText(query);
+ commandText += whereText;
- using (var statement = _connection.PrepareStatement(commandText))
- {
- statement.TryBind("@SelectType", returnType);
- if (EnableJoinUserData(query))
+ 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);
+ if (typeSubQuery != null)
+ {
+ GetWhereClauses(typeSubQuery, null, "itemTypes");
+ }
+ BindSimilarParams(query, statement);
+ GetWhereClauses(innerQuery, statement);
+ GetWhereClauses(outerQuery, statement);
- count = statement.ExecuteQuery().SelectScalarInt().First();
+ count = statement.ExecuteQuery().SelectScalarInt().First();
- LogQueryTime("GetItemValues", commandText, now);
+ 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.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.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<object>();
-
- 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.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.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);
-
- statement.Execute(paramList.ToArray());
+ foreach (var stream in streams)
+ {
+ var paramList = new List<object>();
+
+ 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.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.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);
+
+ statement.Execute(paramList.ToArray());
+ }
}
}
}
diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
index a66536179..9f7cce13b 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; }
- }
-
/// <summary>
/// Gets the name of the repository
/// </summary>
@@ -43,13 +36,23 @@ 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;
- string[] queries = {
+ using (var connection = CreateConnection())
+ {
+ connection.ExecuteAll(string.Join(";", new[]
+ {
+ "PRAGMA page_size=4096",
+ "pragma default_temp_store = memory",
+ "pragma temp_store = memory"
+ }));
+
+ 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 +72,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);
+ });
+ }
}
/// <summary>
@@ -139,18 +143,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 +214,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 +251,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 +304,18 @@ 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())
{
- 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..f902d981f 100644
--- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
@@ -50,6 +50,13 @@ namespace Emby.Server.Implementations.Data
{
using (var connection = CreateConnection())
{
+ connection.ExecuteAll(string.Join(";", new[]
+ {
+ "PRAGMA page_size=4096",
+ "pragma default_temp_store = memory",
+ "pragma temp_store = memory"
+ }));
+
string[] queries = {
"create table if not exists users (guid GUID primary key, data BLOB)",
@@ -83,9 +90,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 +115,9 @@ namespace Emby.Server.Implementations.Data
{
var list = new List<User>();
- 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 +153,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 =>
{