use individual connections

This commit is contained in:
Luke Pulverenti 2016-06-11 11:55:05 -04:00
parent 682edf5abd
commit 4c7f292ba8
12 changed files with 1196 additions and 1281 deletions

View File

@ -15,29 +15,19 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository
{ {
private IDbConnection _connection; public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector dbConnector) : base(logManager, dbConnector)
private readonly IServerApplicationPaths _appPaths; {
DbFilePath = Path.Combine(appPaths.DataPath, "notifications.db");
}
public event EventHandler<NotificationUpdateEventArgs> NotificationAdded; public event EventHandler<NotificationUpdateEventArgs> NotificationAdded;
public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead; public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead;
public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated; public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
private IDbCommand _replaceNotificationCommand; public async Task Initialize()
private IDbCommand _markReadCommand;
private IDbCommand _markAllReadCommand;
public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths)
: base(logManager)
{ {
_appPaths = appPaths; using (var connection = await CreateConnection().ConfigureAwait(false))
}
public async Task Initialize(IDbConnector dbConnector)
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "notifications.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { 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, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))", "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))",
@ -50,39 +40,8 @@ namespace MediaBrowser.Server.Implementations.Notifications
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
PrepareStatements();
} }
private void PrepareStatements()
{
_replaceNotificationCommand = _connection.CreateCommand();
_replaceNotificationCommand.CommandText = "replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)";
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Date");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Name");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Description");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Url");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Level");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Category");
_replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@RelatedId");
_markReadCommand = _connection.CreateCommand();
_markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId";
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
_markReadCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
_markAllReadCommand = _connection.CreateCommand();
_markAllReadCommand.CommandText = "update Notifications set IsRead=@IsRead where UserId=@UserId";
_markAllReadCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
_markAllReadCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
} }
/// <summary> /// <summary>
@ -94,7 +53,9 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
var result = new NotificationResult(); var result = new NotificationResult();
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
var clauses = new List<string>(); var clauses = new List<string>();
@ -139,12 +100,15 @@ namespace MediaBrowser.Server.Implementations.Notifications
return result; return result;
} }
} }
}
public NotificationsSummary GetNotificationsSummary(string userId) public NotificationsSummary GetNotificationsSummary(string userId)
{ {
var result = new NotificationsSummary(); var result = new NotificationsSummary();
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "select Level from Notifications where UserId=@UserId and IsRead=@IsRead"; cmd.CommandText = "select Level from Notifications where UserId=@UserId and IsRead=@IsRead";
@ -171,6 +135,7 @@ namespace MediaBrowser.Server.Implementations.Notifications
return result; return result;
} }
} }
}
/// <summary> /// <summary>
/// Gets the notifications. /// Gets the notifications.
@ -179,10 +144,14 @@ namespace MediaBrowser.Server.Implementations.Notifications
/// <returns>IEnumerable{Notification}.</returns> /// <returns>IEnumerable{Notification}.</returns>
private IEnumerable<Notification> GetNotifications(IDataReader reader) private IEnumerable<Notification> GetNotifications(IDataReader reader)
{ {
var list = new List<Notification>();
while (reader.Read()) while (reader.Read())
{ {
yield return GetNotification(reader); list.Add(GetNotification(reader));
} }
return list;
} }
private Notification GetNotification(IDataReader reader) private Notification GetNotification(IDataReader reader)
@ -273,28 +242,43 @@ namespace MediaBrowser.Server.Implementations.Notifications
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var replaceNotificationCommand = connection.CreateCommand())
{
replaceNotificationCommand.CommandText = "replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)";
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Id");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@UserId");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Date");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Name");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Description");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Url");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Level");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@IsRead");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@Category");
replaceNotificationCommand.Parameters.Add(replaceNotificationCommand, "@RelatedId");
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
_replaceNotificationCommand.GetParameter(0).Value = new Guid(notification.Id); replaceNotificationCommand.GetParameter(0).Value = new Guid(notification.Id);
_replaceNotificationCommand.GetParameter(1).Value = new Guid(notification.UserId); replaceNotificationCommand.GetParameter(1).Value = new Guid(notification.UserId);
_replaceNotificationCommand.GetParameter(2).Value = notification.Date.ToUniversalTime(); replaceNotificationCommand.GetParameter(2).Value = notification.Date.ToUniversalTime();
_replaceNotificationCommand.GetParameter(3).Value = notification.Name; replaceNotificationCommand.GetParameter(3).Value = notification.Name;
_replaceNotificationCommand.GetParameter(4).Value = notification.Description; replaceNotificationCommand.GetParameter(4).Value = notification.Description;
_replaceNotificationCommand.GetParameter(5).Value = notification.Url; replaceNotificationCommand.GetParameter(5).Value = notification.Url;
_replaceNotificationCommand.GetParameter(6).Value = notification.Level.ToString(); replaceNotificationCommand.GetParameter(6).Value = notification.Level.ToString();
_replaceNotificationCommand.GetParameter(7).Value = notification.IsRead; replaceNotificationCommand.GetParameter(7).Value = notification.IsRead;
_replaceNotificationCommand.GetParameter(8).Value = string.Empty; replaceNotificationCommand.GetParameter(8).Value = string.Empty;
_replaceNotificationCommand.GetParameter(9).Value = string.Empty; replaceNotificationCommand.GetParameter(9).Value = string.Empty;
_replaceNotificationCommand.Transaction = transaction; replaceNotificationCommand.Transaction = transaction;
_replaceNotificationCommand.ExecuteNonQuery(); replaceNotificationCommand.ExecuteNonQuery();
transaction.Commit(); transaction.Commit();
} }
@ -324,8 +308,8 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -366,7 +350,14 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var markAllReadCommand = connection.CreateCommand())
{
markAllReadCommand.CommandText = "update Notifications set IsRead=@IsRead where UserId=@UserId";
markAllReadCommand.Parameters.Add(markAllReadCommand, "@UserId");
markAllReadCommand.Parameters.Add(markAllReadCommand, "@IsRead");
IDbTransaction transaction = null; IDbTransaction transaction = null;
@ -374,12 +365,12 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
_markAllReadCommand.GetParameter(0).Value = new Guid(userId); markAllReadCommand.GetParameter(0).Value = new Guid(userId);
_markAllReadCommand.GetParameter(1).Value = isRead; markAllReadCommand.GetParameter(1).Value = isRead;
_markAllReadCommand.ExecuteNonQuery(); markAllReadCommand.ExecuteNonQuery();
transaction.Commit(); transaction.Commit();
} }
@ -409,8 +400,8 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -418,7 +409,15 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var markReadCommand = connection.CreateCommand())
{
markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId";
markReadCommand.Parameters.Add(markReadCommand, "@UserId");
markReadCommand.Parameters.Add(markReadCommand, "@IsRead");
markReadCommand.Parameters.Add(markReadCommand, "@Id");
IDbTransaction transaction = null; IDbTransaction transaction = null;
@ -426,18 +425,18 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
_markReadCommand.GetParameter(0).Value = new Guid(userId); markReadCommand.GetParameter(0).Value = new Guid(userId);
_markReadCommand.GetParameter(1).Value = isRead; markReadCommand.GetParameter(1).Value = isRead;
foreach (var id in notificationIdList) foreach (var id in notificationIdList)
{ {
_markReadCommand.GetParameter(2).Value = id; markReadCommand.GetParameter(2).Value = id;
_markReadCommand.Transaction = transaction; markReadCommand.Transaction = transaction;
_markReadCommand.ExecuteNonQuery(); markReadCommand.ExecuteNonQuery();
} }
transaction.Commit(); transaction.Commit();
@ -468,22 +467,8 @@ namespace MediaBrowser.Server.Implementations.Notifications
{ {
transaction.Dispose(); transaction.Dispose();
} }
WriteLock.Release();
} }
} }
protected override void CloseConnection()
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
} }
} }
} }

View File

@ -9,13 +9,22 @@ namespace MediaBrowser.Server.Implementations.Persistence
public abstract class BaseSqliteRepository : IDisposable public abstract class BaseSqliteRepository : IDisposable
{ {
protected readonly SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1); protected readonly SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1);
protected readonly IDbConnector DbConnector;
protected ILogger Logger; protected ILogger Logger;
protected BaseSqliteRepository(ILogManager logManager) protected string DbFilePath { get; set; }
protected BaseSqliteRepository(ILogManager logManager, IDbConnector dbConnector)
{ {
DbConnector = dbConnector;
Logger = logManager.GetLogger(GetType().Name); Logger = logManager.GetLogger(GetType().Name);
} }
protected Task<IDbConnection> CreateConnection(bool isReadOnly = false)
{
return DbConnector.Connect(DbFilePath, false, true);
}
private bool _disposed; private bool _disposed;
protected void CheckDisposed() protected void CheckDisposed()
{ {
@ -84,6 +93,9 @@ namespace MediaBrowser.Server.Implementations.Persistence
} }
} }
protected abstract void CloseConnection(); protected virtual void CloseConnection()
{
}
} }
} }

View File

@ -5,6 +5,6 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
public interface IDbConnector public interface IDbConnector
{ {
Task<IDbConnection> Connect(string dbPath, int? cacheSize = null); Task<IDbConnection> Connect(string dbPath, bool isReadOnly, bool enablePooling = false, int? cacheSize = null);
} }
} }

View File

@ -18,12 +18,11 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// </summary> /// </summary>
public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository
{ {
private IDbConnection _connection; public SqliteDisplayPreferencesRepository(ILogManager logManager, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IDbConnector dbConnector)
: base(logManager, dbConnector)
public SqliteDisplayPreferencesRepository(ILogManager logManager, IJsonSerializer jsonSerializer, IApplicationPaths appPaths) : base(logManager)
{ {
_jsonSerializer = jsonSerializer; _jsonSerializer = jsonSerializer;
_appPaths = appPaths; DbFilePath = Path.Combine(appPaths.DataPath, "displaypreferences.db");
} }
/// <summary> /// <summary>
@ -43,21 +42,14 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// </summary> /// </summary>
private readonly IJsonSerializer _jsonSerializer; private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// The _app paths
/// </summary>
private readonly IApplicationPaths _appPaths;
/// <summary> /// <summary>
/// Opens the connection to the database /// Opens the connection to the database
/// </summary> /// </summary>
/// <returns>Task.</returns> /// <returns>Task.</returns>
public async Task Initialize(IDbConnector dbConnector) public async Task Initialize()
{
using (var connection = await CreateConnection().ConfigureAwait(false))
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { 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)",
@ -69,7 +61,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
}
} }
/// <summary> /// <summary>
@ -96,15 +89,15 @@ namespace MediaBrowser.Server.Implementations.Persistence
var serialized = _jsonSerializer.SerializeToBytes(displayPreferences); var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
using (var cmd = _connection.CreateCommand()) using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)"; cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
@ -146,8 +139,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release();
} }
} }
@ -168,20 +160,20 @@ namespace MediaBrowser.Server.Implementations.Persistence
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
foreach (var displayPreference in displayPreferences) foreach (var displayPreference in displayPreferences)
{ {
var serialized = _jsonSerializer.SerializeToBytes(displayPreference); var serialized = _jsonSerializer.SerializeToBytes(displayPreference);
using (var cmd = _connection.CreateCommand()) using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)"; cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
@ -224,8 +216,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release();
} }
} }
@ -246,7 +237,10 @@ namespace MediaBrowser.Server.Implementations.Persistence
var guidId = displayPreferencesId.GetMD5(); var guidId = displayPreferencesId.GetMD5();
var cmd = _connection.CreateCommand(); using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client"; cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client";
cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = guidId; cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = guidId;
@ -269,6 +263,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
Id = guidId.ToString("N") Id = guidId.ToString("N")
}; };
} }
}
}
/// <summary> /// <summary>
/// Gets all display preferences for the given user. /// Gets all display preferences for the given user.
@ -278,8 +274,12 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <exception cref="System.ArgumentNullException">item</exception> /// <exception cref="System.ArgumentNullException">item</exception>
public IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId) public IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId)
{ {
var list = new List<DisplayPreferences>();
var cmd = _connection.CreateCommand(); using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "select data from userdisplaypreferences where userId=@userId"; cmd.CommandText = "select data from userdisplaypreferences where userId=@userId";
cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId; cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId;
@ -290,24 +290,14 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
using (var stream = reader.GetMemoryStream(0)) using (var stream = reader.GetMemoryStream(0))
{ {
yield return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream); list.Add(_jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream));
}
} }
} }
} }
} }
protected override void CloseConnection() return list;
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
} }
public Task SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken) public Task SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken)

View File

@ -19,11 +19,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <summary> /// <summary>
/// Connects to db. /// Connects to db.
/// </summary> /// </summary>
/// <param name="dbPath">The db path.</param> public static async Task<IDbConnection> ConnectToDb(string dbPath, bool isReadOnly, bool enablePooling, int? cacheSize, ILogger logger)
/// <param name="logger">The logger.</param>
/// <returns>Task{IDbConnection}.</returns>
/// <exception cref="System.ArgumentNullException">dbPath</exception>
public static async Task<IDbConnection> ConnectToDb(string dbPath, int? cacheSize, ILogger logger)
{ {
if (string.IsNullOrEmpty(dbPath)) if (string.IsNullOrEmpty(dbPath))
{ {
@ -38,7 +34,9 @@ namespace MediaBrowser.Server.Implementations.Persistence
CacheSize = cacheSize ?? 2000, CacheSize = cacheSize ?? 2000,
SyncMode = SynchronizationModes.Normal, SyncMode = SynchronizationModes.Normal,
DataSource = dbPath, DataSource = dbPath,
JournalMode = SQLiteJournalModeEnum.Wal JournalMode = SQLiteJournalModeEnum.Wal,
Pooling = enablePooling,
ReadOnly = isReadOnly
}; };
var connection = new SQLiteConnection(connectionstr.ConnectionString); var connection = new SQLiteConnection(connectionstr.ConnectionString);
@ -47,15 +45,5 @@ namespace MediaBrowser.Server.Implementations.Persistence
return connection; return connection;
} }
public static void BindFunction(this SQLiteConnection connection, SQLiteFunction function)
{
var attributes = function.GetType().GetCustomAttributes(typeof(SQLiteFunctionAttribute), true).Cast<SQLiteFunctionAttribute>().ToArray();
if (attributes.Length == 0)
{
throw new InvalidOperationException("SQLiteFunction doesn't have SQLiteFunctionAttribute");
}
connection.BindFunction(attributes[0], function);
}
} }
} }

View File

@ -26,7 +26,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
private IDbCommand _deleteResultCommand; private IDbCommand _deleteResultCommand;
private IDbCommand _deleteAllCommand; private IDbCommand _deleteAllCommand;
public SqliteFileOrganizationRepository(ILogManager logManager, IServerApplicationPaths appPaths) : base(logManager) public SqliteFileOrganizationRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector connector) : base(logManager, connector)
{ {
_appPaths = appPaths; _appPaths = appPaths;
} }
@ -39,7 +39,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "fileorganization.db"); var dbFile = Path.Combine(_appPaths.DataPath, "fileorganization.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false); _connection = await dbConnector.Connect(dbFile, false).ConfigureAwait(false);
string[] queries = { string[] queries = {

View File

@ -99,8 +99,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SqliteItemRepository"/> class. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
/// </summary> /// </summary>
public SqliteItemRepository(IServerConfigurationManager config, IJsonSerializer jsonSerializer, ILogManager logManager) public SqliteItemRepository(IServerConfigurationManager config, IJsonSerializer jsonSerializer, ILogManager logManager, IDbConnector connector)
: base(logManager) : base(logManager, connector)
{ {
if (config == null) if (config == null)
{ {
@ -127,7 +127,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
var dbFile = Path.Combine(_config.ApplicationPaths.DataPath, "library.db"); var dbFile = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
_connection = await dbConnector.Connect(dbFile, 6000).ConfigureAwait(false); _connection = await dbConnector.Connect(dbFile, false, false, 6000).ConfigureAwait(false);
var createMediaStreamsTableCommand 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))"; = "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))";

View File

@ -18,7 +18,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
private IDbConnection _connection; private IDbConnection _connection;
private readonly IApplicationPaths _appPaths; private readonly IApplicationPaths _appPaths;
public SqliteUserDataRepository(ILogManager logManager, IApplicationPaths appPaths) : base(logManager) public SqliteUserDataRepository(ILogManager logManager, IApplicationPaths appPaths, IDbConnector connector) : base(logManager, connector)
{ {
_appPaths = appPaths; _appPaths = appPaths;
} }
@ -43,7 +43,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "userdata_v2.db"); var dbFile = Path.Combine(_appPaths.DataPath, "userdata_v2.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false); _connection = await dbConnector.Connect(dbFile, false).ConfigureAwait(false);
string[] queries = { string[] queries = {

View File

@ -17,14 +17,13 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// </summary> /// </summary>
public class SqliteUserRepository : BaseSqliteRepository, IUserRepository public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
{ {
private IDbConnection _connection;
private readonly IServerApplicationPaths _appPaths;
private readonly IJsonSerializer _jsonSerializer; private readonly IJsonSerializer _jsonSerializer;
public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer) : base(logManager) public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer, IDbConnector dbConnector) : base(logManager, dbConnector)
{ {
_appPaths = appPaths;
_jsonSerializer = jsonSerializer; _jsonSerializer = jsonSerializer;
DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
} }
/// <summary> /// <summary>
@ -43,12 +42,10 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// Opens the connection to the database /// Opens the connection to the database
/// </summary> /// </summary>
/// <returns>Task.</returns> /// <returns>Task.</returns>
public async Task Initialize(IDbConnector dbConnector) public async Task Initialize()
{
using (var connection = await CreateConnection().ConfigureAwait(false))
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { string[] queries = {
"create table if not exists users (guid GUID primary key, data BLOB)", "create table if not exists users (guid GUID primary key, data BLOB)",
@ -61,7 +58,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
}
} }
/// <summary> /// <summary>
@ -84,15 +82,15 @@ namespace MediaBrowser.Server.Implementations.Persistence
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
using (var cmd = _connection.CreateCommand()) using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "replace into users (guid, data) values (@1, @2)"; cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id; cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id;
@ -131,8 +129,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release();
} }
} }
@ -142,7 +139,11 @@ namespace MediaBrowser.Server.Implementations.Persistence
/// <returns>IEnumerable{User}.</returns> /// <returns>IEnumerable{User}.</returns>
public IEnumerable<User> RetrieveAllUsers() public IEnumerable<User> RetrieveAllUsers()
{ {
using (var cmd = _connection.CreateCommand()) var list = new List<User>();
using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "select guid,data from users"; cmd.CommandText = "select guid,data from users";
@ -156,13 +157,16 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
var user = _jsonSerializer.DeserializeFromStream<User>(stream); var user = _jsonSerializer.DeserializeFromStream<User>(stream);
user.Id = id; user.Id = id;
yield return user; list.Add(user);
} }
} }
} }
} }
} }
return list;
}
/// <summary> /// <summary>
/// Deletes the user. /// Deletes the user.
/// </summary> /// </summary>
@ -179,15 +183,15 @@ namespace MediaBrowser.Server.Implementations.Persistence
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
using (var cmd = _connection.CreateCommand()) using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = "delete from users where guid=@guid"; cmd.CommandText = "delete from users where guid=@guid";
@ -226,23 +230,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
{ {
transaction.Dispose(); transaction.Dispose();
} }
WriteLock.Release();
} }
} }
protected override void CloseConnection()
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
} }
} }
} }

View File

@ -15,24 +15,20 @@ namespace MediaBrowser.Server.Implementations.Security
{ {
public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository
{ {
private IDbConnection _connection;
private readonly IServerApplicationPaths _appPaths; private readonly IServerApplicationPaths _appPaths;
private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private IDbCommand _saveInfoCommand; public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths, IDbConnector connector)
: base(logManager, connector)
public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths)
: base(logManager)
{ {
_appPaths = appPaths; _appPaths = appPaths;
DbFilePath = Path.Combine(appPaths.DataPath, "authentication.db");
} }
public async Task Initialize(IDbConnector dbConnector) public async Task Initialize()
{
using (var connection = await CreateConnection().ConfigureAwait(false))
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "authentication.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { 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)",
@ -44,28 +40,10 @@ namespace MediaBrowser.Server.Implementations.Security
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
_connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT"); connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT");
PrepareStatements();
} }
private void PrepareStatements()
{
_saveInfoCommand = _connection.CreateCommand();
_saveInfoCommand.CommandText = "replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)";
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@Id");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AccessToken");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DeviceId");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AppName");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@AppVersion");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DeviceName");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@UserId");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@IsActive");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DateCreated");
_saveInfoCommand.Parameters.Add(_saveInfoCommand, "@DateRevoked");
} }
public Task Create(AuthenticationInfo info, CancellationToken cancellationToken) public Task Create(AuthenticationInfo info, CancellationToken cancellationToken)
@ -84,30 +62,45 @@ namespace MediaBrowser.Server.Implementations.Security
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var saveInfoCommand = connection.CreateCommand())
{
saveInfoCommand.CommandText = "replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)";
saveInfoCommand.Parameters.Add(saveInfoCommand, "@Id");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AccessToken");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceId");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppName");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@AppVersion");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DeviceName");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@UserId");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@IsActive");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateCreated");
saveInfoCommand.Parameters.Add(saveInfoCommand, "@DateRevoked");
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
var index = 0; var index = 0;
_saveInfoCommand.GetParameter(index++).Value = new Guid(info.Id); saveInfoCommand.GetParameter(index++).Value = new Guid(info.Id);
_saveInfoCommand.GetParameter(index++).Value = info.AccessToken; saveInfoCommand.GetParameter(index++).Value = info.AccessToken;
_saveInfoCommand.GetParameter(index++).Value = info.DeviceId; saveInfoCommand.GetParameter(index++).Value = info.DeviceId;
_saveInfoCommand.GetParameter(index++).Value = info.AppName; saveInfoCommand.GetParameter(index++).Value = info.AppName;
_saveInfoCommand.GetParameter(index++).Value = info.AppVersion; saveInfoCommand.GetParameter(index++).Value = info.AppVersion;
_saveInfoCommand.GetParameter(index++).Value = info.DeviceName; saveInfoCommand.GetParameter(index++).Value = info.DeviceName;
_saveInfoCommand.GetParameter(index++).Value = info.UserId; saveInfoCommand.GetParameter(index++).Value = info.UserId;
_saveInfoCommand.GetParameter(index++).Value = info.IsActive; saveInfoCommand.GetParameter(index++).Value = info.IsActive;
_saveInfoCommand.GetParameter(index++).Value = info.DateCreated; saveInfoCommand.GetParameter(index++).Value = info.DateCreated;
_saveInfoCommand.GetParameter(index++).Value = info.DateRevoked; saveInfoCommand.GetParameter(index++).Value = info.DateRevoked;
_saveInfoCommand.Transaction = transaction; saveInfoCommand.Transaction = transaction;
_saveInfoCommand.ExecuteNonQuery(); saveInfoCommand.ExecuteNonQuery();
transaction.Commit(); transaction.Commit();
} }
@ -137,8 +130,8 @@ namespace MediaBrowser.Server.Implementations.Security
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -151,7 +144,9 @@ namespace MediaBrowser.Server.Implementations.Security
throw new ArgumentNullException("query"); throw new ArgumentNullException("query");
} }
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = BaseSelectText; cmd.CommandText = BaseSelectText;
@ -248,6 +243,7 @@ namespace MediaBrowser.Server.Implementations.Security
}; };
} }
} }
}
public AuthenticationInfo Get(string id) public AuthenticationInfo Get(string id)
{ {
@ -256,9 +252,11 @@ namespace MediaBrowser.Server.Implementations.Security
throw new ArgumentNullException("id"); throw new ArgumentNullException("id");
} }
using (var connection = CreateConnection(true).Result)
{
var guid = new Guid(id); var guid = new Guid(id);
using (var cmd = _connection.CreateCommand()) using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = BaseSelectText + " where Id=@Id"; cmd.CommandText = BaseSelectText + " where Id=@Id";
@ -275,6 +273,7 @@ namespace MediaBrowser.Server.Implementations.Security
return null; return null;
} }
}
private AuthenticationInfo Get(IDataReader reader) private AuthenticationInfo Get(IDataReader reader)
{ {
@ -319,19 +318,5 @@ namespace MediaBrowser.Server.Implementations.Security
return info; return info;
} }
protected override void CloseConnection()
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
}
} }
} }

View File

@ -12,26 +12,20 @@ namespace MediaBrowser.Server.Implementations.Social
{ {
public class SharingRepository : BaseSqliteRepository public class SharingRepository : BaseSqliteRepository
{ {
private IDbConnection _connection; public SharingRepository(ILogManager logManager, IApplicationPaths appPaths, IDbConnector dbConnector)
private IDbCommand _saveShareCommand; : base(logManager, dbConnector)
private readonly IApplicationPaths _appPaths;
public SharingRepository(ILogManager logManager, IApplicationPaths appPaths)
: base(logManager)
{ {
_appPaths = appPaths; DbFilePath = Path.Combine(appPaths.DataPath, "shares.db");
} }
/// <summary> /// <summary>
/// Opens the connection to the database /// Opens the connection to the database
/// </summary> /// </summary>
/// <returns>Task.</returns> /// <returns>Task.</returns>
public async Task Initialize(IDbConnector dbConnector) public async Task Initialize()
{
using (var connection = await CreateConnection().ConfigureAwait(false))
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "shares.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { string[] queries = {
"create table if not exists Shares (Id GUID, ItemId TEXT, UserId TEXT, ExpirationDate DateTime, PRIMARY KEY (Id))", "create table if not exists Shares (Id GUID, ItemId TEXT, UserId TEXT, ExpirationDate DateTime, PRIMARY KEY (Id))",
@ -43,23 +37,8 @@ namespace MediaBrowser.Server.Implementations.Social
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
PrepareStatements();
} }
/// <summary>
/// Prepares the statements.
/// </summary>
private void PrepareStatements()
{
_saveShareCommand = _connection.CreateCommand();
_saveShareCommand.CommandText = "replace into Shares (Id, ItemId, UserId, ExpirationDate) values (@Id, @ItemId, @UserId, @ExpirationDate)";
_saveShareCommand.Parameters.Add(_saveShareCommand, "@Id");
_saveShareCommand.Parameters.Add(_saveShareCommand, "@ItemId");
_saveShareCommand.Parameters.Add(_saveShareCommand, "@UserId");
_saveShareCommand.Parameters.Add(_saveShareCommand, "@ExpirationDate");
} }
public async Task CreateShare(SocialShareInfo info) public async Task CreateShare(SocialShareInfo info)
@ -77,22 +56,31 @@ namespace MediaBrowser.Server.Implementations.Social
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var saveShareCommand = connection.CreateCommand())
{
saveShareCommand.CommandText = "replace into Shares (Id, ItemId, UserId, ExpirationDate) values (@Id, @ItemId, @UserId, @ExpirationDate)";
saveShareCommand.Parameters.Add(saveShareCommand, "@Id");
saveShareCommand.Parameters.Add(saveShareCommand, "@ItemId");
saveShareCommand.Parameters.Add(saveShareCommand, "@UserId");
saveShareCommand.Parameters.Add(saveShareCommand, "@ExpirationDate");
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
_saveShareCommand.GetParameter(0).Value = new Guid(info.Id); saveShareCommand.GetParameter(0).Value = new Guid(info.Id);
_saveShareCommand.GetParameter(1).Value = info.ItemId; saveShareCommand.GetParameter(1).Value = info.ItemId;
_saveShareCommand.GetParameter(2).Value = info.UserId; saveShareCommand.GetParameter(2).Value = info.UserId;
_saveShareCommand.GetParameter(3).Value = info.ExpirationDate; saveShareCommand.GetParameter(3).Value = info.ExpirationDate;
_saveShareCommand.Transaction = transaction; saveShareCommand.Transaction = transaction;
_saveShareCommand.ExecuteNonQuery(); saveShareCommand.ExecuteNonQuery();
transaction.Commit(); transaction.Commit();
} }
@ -122,8 +110,8 @@ namespace MediaBrowser.Server.Implementations.Social
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -134,7 +122,9 @@ namespace MediaBrowser.Server.Implementations.Social
throw new ArgumentNullException("id"); throw new ArgumentNullException("id");
} }
var cmd = _connection.CreateCommand(); using (var connection = CreateConnection(true).Result)
{
var cmd = connection.CreateCommand();
cmd.CommandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = @id"; cmd.CommandText = "select Id, ItemId, UserId, ExpirationDate from Shares where id = @id";
cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = new Guid(id); cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = new Guid(id);
@ -149,6 +139,7 @@ namespace MediaBrowser.Server.Implementations.Social
return null; return null;
} }
}
private SocialShareInfo GetSocialShareInfo(IDataReader reader) private SocialShareInfo GetSocialShareInfo(IDataReader reader)
{ {
@ -166,19 +157,5 @@ namespace MediaBrowser.Server.Implementations.Social
{ {
} }
protected override void CloseConnection()
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
}
} }
} }

View File

@ -18,33 +18,21 @@ namespace MediaBrowser.Server.Implementations.Sync
{ {
public class SyncRepository : BaseSqliteRepository, ISyncRepository public class SyncRepository : BaseSqliteRepository, ISyncRepository
{ {
private IDbConnection _connection;
private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private IDbCommand _insertJobCommand;
private IDbCommand _updateJobCommand;
private IDbCommand _deleteJobCommand;
private IDbCommand _deleteJobItemsCommand;
private IDbCommand _insertJobItemCommand;
private IDbCommand _updateJobItemCommand;
private readonly IJsonSerializer _json; private readonly IJsonSerializer _json;
private readonly IServerApplicationPaths _appPaths;
public SyncRepository(ILogManager logManager, IJsonSerializer json, IServerApplicationPaths appPaths) public SyncRepository(ILogManager logManager, IJsonSerializer json, IServerApplicationPaths appPaths, IDbConnector connector)
: base(logManager) : base(logManager, connector)
{ {
_json = json; _json = json;
_appPaths = appPaths; DbFilePath = Path.Combine(appPaths.DataPath, "sync14.db");
} }
public async Task Initialize(IDbConnector dbConnector) public async Task Initialize()
{
using (var connection = await CreateConnection().ConfigureAwait(false))
{ {
var dbFile = Path.Combine(_appPaths.DataPath, "sync14.db");
_connection = await dbConnector.Connect(dbFile).ConfigureAwait(false);
string[] queries = { 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)", "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)",
@ -61,114 +49,12 @@ namespace MediaBrowser.Server.Implementations.Sync
"pragma shrink_memory" "pragma shrink_memory"
}; };
_connection.RunQueries(queries, Logger); connection.RunQueries(queries, Logger);
_connection.AddColumn(Logger, "SyncJobs", "Profile", "TEXT"); connection.AddColumn(Logger, "SyncJobs", "Profile", "TEXT");
_connection.AddColumn(Logger, "SyncJobs", "Bitrate", "INT"); connection.AddColumn(Logger, "SyncJobs", "Bitrate", "INT");
_connection.AddColumn(Logger, "SyncJobItems", "ItemDateModifiedTicks", "BIGINT"); connection.AddColumn(Logger, "SyncJobItems", "ItemDateModifiedTicks", "BIGINT");
PrepareStatements();
} }
private void PrepareStatements()
{
// _deleteJobCommand
_deleteJobCommand = _connection.CreateCommand();
_deleteJobCommand.CommandText = "delete from SyncJobs where Id=@Id";
_deleteJobCommand.Parameters.Add(_deleteJobCommand, "@Id");
// _deleteJobItemsCommand
_deleteJobItemsCommand = _connection.CreateCommand();
_deleteJobItemsCommand.CommandText = "delete from SyncJobItems where JobId=@JobId";
_deleteJobItemsCommand.Parameters.Add(_deleteJobItemsCommand, "@JobId");
// _insertJobCommand
_insertJobCommand = _connection.CreateCommand();
_insertJobCommand.CommandText = "insert into SyncJobs (Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount) values (@Id, @TargetId, @Name, @Profile, @Quality, @Bitrate, @Status, @Progress, @UserId, @ItemIds, @Category, @ParentId, @UnwatchedOnly, @ItemLimit, @SyncNewContent, @DateCreated, @DateLastModified, @ItemCount)";
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Id");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@TargetId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Name");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Profile");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Quality");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Bitrate");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Status");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Progress");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@UserId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemIds");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Category");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ParentId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@UnwatchedOnly");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemLimit");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@SyncNewContent");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@DateCreated");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@DateLastModified");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemCount");
// _updateJobCommand
_updateJobCommand = _connection.CreateCommand();
_updateJobCommand.CommandText = "update SyncJobs set TargetId=@TargetId,Name=@Name,Profile=@Profile,Quality=@Quality,Bitrate=@Bitrate,Status=@Status,Progress=@Progress,UserId=@UserId,ItemIds=@ItemIds,Category=@Category,ParentId=@ParentId,UnwatchedOnly=@UnwatchedOnly,ItemLimit=@ItemLimit,SyncNewContent=@SyncNewContent,DateCreated=@DateCreated,DateLastModified=@DateLastModified,ItemCount=@ItemCount where Id=@Id";
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Id");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@TargetId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Name");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Profile");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Quality");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Bitrate");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Status");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Progress");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@UserId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemIds");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Category");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ParentId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@UnwatchedOnly");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemLimit");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@SyncNewContent");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@DateCreated");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@DateLastModified");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemCount");
// _insertJobItemCommand
_insertJobItemCommand = _connection.CreateCommand();
_insertJobItemCommand.CommandText = "insert into SyncJobItems (Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex, ItemDateModifiedTicks) values (@Id, @ItemId, @ItemName, @MediaSourceId, @JobId, @TemporaryPath, @OutputPath, @Status, @TargetId, @DateCreated, @Progress, @AdditionalFiles, @MediaSource, @IsMarkedForRemoval, @JobItemIndex, @ItemDateModifiedTicks)";
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Id");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@ItemId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@ItemName");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@MediaSourceId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@JobId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@TemporaryPath");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@OutputPath");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Status");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@TargetId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@DateCreated");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Progress");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@AdditionalFiles");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@MediaSource");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@IsMarkedForRemoval");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@JobItemIndex");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@ItemDateModifiedTicks");
// _updateJobItemCommand
_updateJobItemCommand = _connection.CreateCommand();
_updateJobItemCommand.CommandText = "update SyncJobItems set ItemId=@ItemId,ItemName=@ItemName,MediaSourceId=@MediaSourceId,JobId=@JobId,TemporaryPath=@TemporaryPath,OutputPath=@OutputPath,Status=@Status,TargetId=@TargetId,DateCreated=@DateCreated,Progress=@Progress,AdditionalFiles=@AdditionalFiles,MediaSource=@MediaSource,IsMarkedForRemoval=@IsMarkedForRemoval,JobItemIndex=@JobItemIndex,ItemDateModifiedTicks=@ItemDateModifiedTicks where Id=@Id";
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Id");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@ItemId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@ItemName");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@MediaSourceId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@JobId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@TemporaryPath");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@OutputPath");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Status");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@TargetId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@DateCreated");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Progress");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@AdditionalFiles");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@MediaSource");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@IsMarkedForRemoval");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@JobItemIndex");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@ItemDateModifiedTicks");
} }
private const string BaseJobSelectText = "select Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount from SyncJobs"; private const string BaseJobSelectText = "select Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount from SyncJobs";
@ -190,7 +76,9 @@ namespace MediaBrowser.Server.Implementations.Sync
throw new ArgumentNullException("id"); throw new ArgumentNullException("id");
} }
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = BaseJobSelectText + " where Id=@Id"; cmd.CommandText = BaseJobSelectText + " where Id=@Id";
@ -207,6 +95,7 @@ namespace MediaBrowser.Server.Implementations.Sync
return null; return null;
} }
}
private SyncJob GetJob(IDataReader reader) private SyncJob GetJob(IDataReader reader)
{ {
@ -283,15 +172,15 @@ namespace MediaBrowser.Server.Implementations.Sync
public Task Create(SyncJob job) public Task Create(SyncJob job)
{ {
return InsertOrUpdate(job, _insertJobCommand); return InsertOrUpdate(job, true);
} }
public Task Update(SyncJob job) public Task Update(SyncJob job)
{ {
return InsertOrUpdate(job, _updateJobCommand); return InsertOrUpdate(job, false);
} }
private async Task InsertOrUpdate(SyncJob job, IDbCommand cmd) private async Task InsertOrUpdate(SyncJob job, bool insert)
{ {
if (job == null) if (job == null)
{ {
@ -300,13 +189,62 @@ namespace MediaBrowser.Server.Implementations.Sync
CheckDisposed(); CheckDisposed();
await WriteLock.WaitAsync().ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var cmd = connection.CreateCommand())
{
if (insert)
{
cmd.CommandText = "insert into SyncJobs (Id, TargetId, Name, Profile, Quality, Bitrate, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount) values (@Id, @TargetId, @Name, @Profile, @Quality, @Bitrate, @Status, @Progress, @UserId, @ItemIds, @Category, @ParentId, @UnwatchedOnly, @ItemLimit, @SyncNewContent, @DateCreated, @DateLastModified, @ItemCount)";
cmd.Parameters.Add(cmd, "@Id");
cmd.Parameters.Add(cmd, "@TargetId");
cmd.Parameters.Add(cmd, "@Name");
cmd.Parameters.Add(cmd, "@Profile");
cmd.Parameters.Add(cmd, "@Quality");
cmd.Parameters.Add(cmd, "@Bitrate");
cmd.Parameters.Add(cmd, "@Status");
cmd.Parameters.Add(cmd, "@Progress");
cmd.Parameters.Add(cmd, "@UserId");
cmd.Parameters.Add(cmd, "@ItemIds");
cmd.Parameters.Add(cmd, "@Category");
cmd.Parameters.Add(cmd, "@ParentId");
cmd.Parameters.Add(cmd, "@UnwatchedOnly");
cmd.Parameters.Add(cmd, "@ItemLimit");
cmd.Parameters.Add(cmd, "@SyncNewContent");
cmd.Parameters.Add(cmd, "@DateCreated");
cmd.Parameters.Add(cmd, "@DateLastModified");
cmd.Parameters.Add(cmd, "@ItemCount");
}
else
{
cmd.CommandText = "update SyncJobs set TargetId=@TargetId,Name=@Name,Profile=@Profile,Quality=@Quality,Bitrate=@Bitrate,Status=@Status,Progress=@Progress,UserId=@UserId,ItemIds=@ItemIds,Category=@Category,ParentId=@ParentId,UnwatchedOnly=@UnwatchedOnly,ItemLimit=@ItemLimit,SyncNewContent=@SyncNewContent,DateCreated=@DateCreated,DateLastModified=@DateLastModified,ItemCount=@ItemCount where Id=@Id";
cmd.Parameters.Add(cmd, "@Id");
cmd.Parameters.Add(cmd, "@TargetId");
cmd.Parameters.Add(cmd, "@Name");
cmd.Parameters.Add(cmd, "@Profile");
cmd.Parameters.Add(cmd, "@Quality");
cmd.Parameters.Add(cmd, "@Bitrate");
cmd.Parameters.Add(cmd, "@Status");
cmd.Parameters.Add(cmd, "@Progress");
cmd.Parameters.Add(cmd, "@UserId");
cmd.Parameters.Add(cmd, "@ItemIds");
cmd.Parameters.Add(cmd, "@Category");
cmd.Parameters.Add(cmd, "@ParentId");
cmd.Parameters.Add(cmd, "@UnwatchedOnly");
cmd.Parameters.Add(cmd, "@ItemLimit");
cmd.Parameters.Add(cmd, "@SyncNewContent");
cmd.Parameters.Add(cmd, "@DateCreated");
cmd.Parameters.Add(cmd, "@DateLastModified");
cmd.Parameters.Add(cmd, "@ItemCount");
}
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
var index = 0; var index = 0;
@ -361,8 +299,8 @@ namespace MediaBrowser.Server.Implementations.Sync
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -375,24 +313,33 @@ namespace MediaBrowser.Server.Implementations.Sync
CheckDisposed(); CheckDisposed();
await WriteLock.WaitAsync().ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var deleteJobCommand = connection.CreateCommand())
{
using (var deleteJobItemsCommand = connection.CreateCommand())
{
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); // _deleteJobCommand
deleteJobCommand.CommandText = "delete from SyncJobs where Id=@Id";
deleteJobCommand.Parameters.Add(deleteJobCommand, "@Id");
var index = 0; transaction = connection.BeginTransaction();
_deleteJobCommand.GetParameter(index++).Value = new Guid(id); deleteJobCommand.GetParameter(0).Value = new Guid(id);
_deleteJobCommand.Transaction = transaction; deleteJobCommand.Transaction = transaction;
_deleteJobCommand.ExecuteNonQuery(); deleteJobCommand.ExecuteNonQuery();
index = 0; // _deleteJobItemsCommand
_deleteJobItemsCommand.GetParameter(index++).Value = id; deleteJobItemsCommand.CommandText = "delete from SyncJobItems where JobId=@JobId";
_deleteJobItemsCommand.Transaction = transaction; deleteJobItemsCommand.Parameters.Add(deleteJobItemsCommand, "@JobId");
_deleteJobItemsCommand.ExecuteNonQuery();
deleteJobItemsCommand.GetParameter(0).Value = id;
deleteJobItemsCommand.Transaction = transaction;
deleteJobItemsCommand.ExecuteNonQuery();
transaction.Commit(); transaction.Commit();
} }
@ -422,8 +369,9 @@ namespace MediaBrowser.Server.Implementations.Sync
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
}
} }
} }
@ -436,7 +384,9 @@ namespace MediaBrowser.Server.Implementations.Sync
CheckDisposed(); CheckDisposed();
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = BaseJobSelectText; cmd.CommandText = BaseJobSelectText;
@ -514,6 +464,7 @@ namespace MediaBrowser.Server.Implementations.Sync
}; };
} }
} }
}
public SyncJobItem GetJobItem(string id) public SyncJobItem GetJobItem(string id)
{ {
@ -526,7 +477,9 @@ namespace MediaBrowser.Server.Implementations.Sync
var guid = new Guid(id); var guid = new Guid(id);
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = BaseJobItemSelectText + " where Id=@Id"; cmd.CommandText = BaseJobItemSelectText + " where Id=@Id";
@ -543,6 +496,7 @@ namespace MediaBrowser.Server.Implementations.Sync
return null; return null;
} }
}
private QueryResult<T> GetJobItemReader<T>(SyncJobItemQuery query, string baseSelectText, Func<IDataReader, T> itemFactory) private QueryResult<T> GetJobItemReader<T>(SyncJobItemQuery query, string baseSelectText, Func<IDataReader, T> itemFactory)
{ {
@ -551,7 +505,9 @@ namespace MediaBrowser.Server.Implementations.Sync
throw new ArgumentNullException("query"); throw new ArgumentNullException("query");
} }
using (var cmd = _connection.CreateCommand()) using (var connection = CreateConnection(true).Result)
{
using (var cmd = connection.CreateCommand())
{ {
cmd.CommandText = baseSelectText; cmd.CommandText = baseSelectText;
@ -628,6 +584,7 @@ namespace MediaBrowser.Server.Implementations.Sync
}; };
} }
} }
}
public QueryResult<SyncedItemProgress> GetSyncedItemProgresses(SyncJobItemQuery query) public QueryResult<SyncedItemProgress> GetSyncedItemProgresses(SyncJobItemQuery query)
{ {
@ -641,15 +598,15 @@ namespace MediaBrowser.Server.Implementations.Sync
public Task Create(SyncJobItem jobItem) public Task Create(SyncJobItem jobItem)
{ {
return InsertOrUpdate(jobItem, _insertJobItemCommand); return InsertOrUpdate(jobItem, true);
} }
public Task Update(SyncJobItem jobItem) public Task Update(SyncJobItem jobItem)
{ {
return InsertOrUpdate(jobItem, _updateJobItemCommand); return InsertOrUpdate(jobItem, false);
} }
private async Task InsertOrUpdate(SyncJobItem jobItem, IDbCommand cmd) private async Task InsertOrUpdate(SyncJobItem jobItem, bool insert)
{ {
if (jobItem == null) if (jobItem == null)
{ {
@ -658,13 +615,59 @@ namespace MediaBrowser.Server.Implementations.Sync
CheckDisposed(); CheckDisposed();
await WriteLock.WaitAsync().ConfigureAwait(false); using (var connection = await CreateConnection().ConfigureAwait(false))
{
using (var cmd = connection.CreateCommand())
{
if (insert)
{
cmd.CommandText = "insert into SyncJobItems (Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex, ItemDateModifiedTicks) values (@Id, @ItemId, @ItemName, @MediaSourceId, @JobId, @TemporaryPath, @OutputPath, @Status, @TargetId, @DateCreated, @Progress, @AdditionalFiles, @MediaSource, @IsMarkedForRemoval, @JobItemIndex, @ItemDateModifiedTicks)";
cmd.Parameters.Add(cmd, "@Id");
cmd.Parameters.Add(cmd, "@ItemId");
cmd.Parameters.Add(cmd, "@ItemName");
cmd.Parameters.Add(cmd, "@MediaSourceId");
cmd.Parameters.Add(cmd, "@JobId");
cmd.Parameters.Add(cmd, "@TemporaryPath");
cmd.Parameters.Add(cmd, "@OutputPath");
cmd.Parameters.Add(cmd, "@Status");
cmd.Parameters.Add(cmd, "@TargetId");
cmd.Parameters.Add(cmd, "@DateCreated");
cmd.Parameters.Add(cmd, "@Progress");
cmd.Parameters.Add(cmd, "@AdditionalFiles");
cmd.Parameters.Add(cmd, "@MediaSource");
cmd.Parameters.Add(cmd, "@IsMarkedForRemoval");
cmd.Parameters.Add(cmd, "@JobItemIndex");
cmd.Parameters.Add(cmd, "@ItemDateModifiedTicks");
}
else
{
// cmd
cmd.CommandText = "update SyncJobItems set ItemId=@ItemId,ItemName=@ItemName,MediaSourceId=@MediaSourceId,JobId=@JobId,TemporaryPath=@TemporaryPath,OutputPath=@OutputPath,Status=@Status,TargetId=@TargetId,DateCreated=@DateCreated,Progress=@Progress,AdditionalFiles=@AdditionalFiles,MediaSource=@MediaSource,IsMarkedForRemoval=@IsMarkedForRemoval,JobItemIndex=@JobItemIndex,ItemDateModifiedTicks=@ItemDateModifiedTicks where Id=@Id";
cmd.Parameters.Add(cmd, "@Id");
cmd.Parameters.Add(cmd, "@ItemId");
cmd.Parameters.Add(cmd, "@ItemName");
cmd.Parameters.Add(cmd, "@MediaSourceId");
cmd.Parameters.Add(cmd, "@JobId");
cmd.Parameters.Add(cmd, "@TemporaryPath");
cmd.Parameters.Add(cmd, "@OutputPath");
cmd.Parameters.Add(cmd, "@Status");
cmd.Parameters.Add(cmd, "@TargetId");
cmd.Parameters.Add(cmd, "@DateCreated");
cmd.Parameters.Add(cmd, "@Progress");
cmd.Parameters.Add(cmd, "@AdditionalFiles");
cmd.Parameters.Add(cmd, "@MediaSource");
cmd.Parameters.Add(cmd, "@IsMarkedForRemoval");
cmd.Parameters.Add(cmd, "@JobItemIndex");
cmd.Parameters.Add(cmd, "@ItemDateModifiedTicks");
}
IDbTransaction transaction = null; IDbTransaction transaction = null;
try try
{ {
transaction = _connection.BeginTransaction(); transaction = connection.BeginTransaction();
var index = 0; var index = 0;
@ -717,8 +720,8 @@ namespace MediaBrowser.Server.Implementations.Sync
{ {
transaction.Dispose(); transaction.Dispose();
} }
}
WriteLock.Release(); }
} }
} }
@ -809,19 +812,5 @@ namespace MediaBrowser.Server.Implementations.Sync
return item; return item;
} }
protected override void CloseConnection()
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
}
} }
} }