update queries

This commit is contained in:
Luke Pulverenti 2016-11-20 00:59:36 -05:00
parent b06d1851da
commit 64d15be839
9 changed files with 253 additions and 125 deletions

View File

@ -679,7 +679,7 @@ namespace Emby.Server.Core.Data
throw new ArgumentNullException("item"); throw new ArgumentNullException("item");
} }
return SaveItems(new[] { item }, cancellationToken); return SaveItems(new List<BaseItem> { item }, cancellationToken);
} }
/// <summary> /// <summary>
@ -693,7 +693,7 @@ namespace Emby.Server.Core.Data
/// or /// or
/// cancellationToken /// cancellationToken
/// </exception> /// </exception>
public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken) public async Task SaveItems(List<BaseItem> items, CancellationToken cancellationToken)
{ {
if (items == null) if (items == null)
{ {

View File

@ -57,18 +57,21 @@ namespace Emby.Server.Implementations.Activity
{ {
connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var commandText = "replace into ActivityLogEntries (Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"; using (var statement = db.PrepareStatement("replace into ActivityLogEntries (Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Id, @Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"))
{
statement.BindParameters.TryBind("@Id", entry.Id.ToGuidParamValue());
statement.BindParameters.TryBind("@Name", entry.Name);
db.Execute(commandText, statement.BindParameters.TryBind("@Overview", entry.Overview);
entry.Id.ToGuidParamValue(), statement.BindParameters.TryBind("@ShortOverview", entry.ShortOverview);
entry.Name, statement.BindParameters.TryBind("@Type", entry.Type);
entry.Overview, statement.BindParameters.TryBind("@ItemId", entry.ItemId);
entry.ShortOverview, statement.BindParameters.TryBind("@UserId", entry.UserId);
entry.Type, statement.BindParameters.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
entry.ItemId, statement.BindParameters.TryBind("@LogSeverity", entry.Severity.ToString());
entry.UserId,
entry.Date.ToDateTimeParamValue(), statement.MoveNext();
entry.Severity.ToString()); }
}); });
} }
} }

View File

@ -100,14 +100,17 @@ namespace Emby.Server.Implementations.Data
private void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, IDatabaseConnection connection) private void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, IDatabaseConnection connection)
{ {
var commandText = "replace into userdisplaypreferences (id, userid, client, data) values (?, ?, ?, ?)"; using (var statement = connection.PrepareStatement("replace into userdisplaypreferences (id, userid, client, data) values (@id, @userid, @client, @data)"))
var serialized = _jsonSerializer.SerializeToBytes(displayPreferences, _memoryStreamProvider); {
var serialized = _jsonSerializer.SerializeToBytes(displayPreferences, _memoryStreamProvider);
connection.Execute(commandText, statement.BindParameters.TryBind("@id", displayPreferences.Id.ToGuidParamValue());
displayPreferences.Id.ToGuidParamValue(), statement.BindParameters.TryBind("@userId", userId.ToGuidParamValue());
userId.ToGuidParamValue(), statement.BindParameters.TryBind("@client", client);
client, statement.BindParameters.TryBind("@data", serialized);
serialized);
statement.MoveNext();
}
} }
/// <summary> /// <summary>
@ -163,16 +166,16 @@ namespace Emby.Server.Implementations.Data
{ {
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
var commandText = "select data from userdisplaypreferences where id = ? and userId=? and client=?"; using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where id = @id and userId=@userId and client=@client"))
var paramList = new List<object>();
paramList.Add(guidId.ToGuidParamValue());
paramList.Add(userId.ToGuidParamValue());
paramList.Add(client);
foreach (var row in connection.Query(commandText, paramList.ToArray()))
{ {
return Get(row); statement.BindParameters.TryBind("@id", guidId.ToGuidParamValue());
statement.BindParameters.TryBind("@userId", userId.ToGuidParamValue());
statement.BindParameters.TryBind("@client", client);
foreach (var row in statement.ExecuteQuery())
{
return Get(row);
}
} }
return new DisplayPreferences return new DisplayPreferences
@ -197,14 +200,14 @@ namespace Emby.Server.Implementations.Data
{ {
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
var commandText = "select data from userdisplaypreferences where userId=?"; using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId"))
var paramList = new List<object>();
paramList.Add(userId.ToGuidParamValue());
foreach (var row in connection.Query(commandText, paramList.ToArray()))
{ {
list.Add(Get(row)); statement.BindParameters.TryBind("@userId", userId.ToGuidParamValue());
foreach (var row in statement.ExecuteQuery())
{
list.Add(Get(row));
}
} }
} }
} }

View File

@ -168,14 +168,54 @@ namespace Emby.Server.Implementations.Data
return result[index].ToFloat(); return result[index].ToFloat();
} }
public static DateTime GetDateTime(this IReadOnlyList<IResultSetValue> result, int index)
{
return result[index].ReadDateTime();
}
public static Guid GetGuid(this IReadOnlyList<IResultSetValue> result, int index) public static Guid GetGuid(this IReadOnlyList<IResultSetValue> result, int index)
{ {
return result[index].ReadGuid(); return result[index].ReadGuid();
} }
public static void TryBind(this IReadOnlyDictionary<string, IBindParameter> bindParameters, string name, string value)
{
IBindParameter bindParam;
if (bindParameters.TryGetValue(name, out bindParam))
{
bindParam.Bind(value);
}
}
public static void TryBind(this IReadOnlyDictionary<string, IBindParameter> bindParameters, string name, bool value)
{
IBindParameter bindParam;
if (bindParameters.TryGetValue(name, out bindParam))
{
bindParam.Bind(value);
}
}
public static void TryBind(this IReadOnlyDictionary<string, IBindParameter> bindParameters, string name, byte[] value)
{
IBindParameter bindParam;
if (bindParameters.TryGetValue(name, out bindParam))
{
bindParam.Bind(value);
}
}
public static void TryBindNull(this IReadOnlyDictionary<string, IBindParameter> bindParameters, string name)
{
IBindParameter bindParam;
if (bindParameters.TryGetValue(name, out bindParam))
{
bindParam.BindNull();
}
}
public static IEnumerable<IReadOnlyList<IResultSetValue>> ExecuteQuery(
this IStatement This)
{
while (This.MoveNext())
{
yield return This.Current;
}
}
} }
} }

View File

@ -89,11 +89,12 @@ namespace Emby.Server.Implementations.Data
{ {
connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var commandText = "replace into users (guid, data) values (?, ?)"; using (var statement = db.PrepareStatement("replace into users (guid, data) values (@guid, @data)"))
{
db.Execute(commandText, statement.BindParameters.TryBind("@guid", user.Id.ToGuidParamValue());
user.Id.ToGuidParamValue(), statement.BindParameters.TryBind("@data", serialized);
serialized); statement.MoveNext();
}
}); });
} }
} }
@ -151,10 +152,11 @@ namespace Emby.Server.Implementations.Data
{ {
connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var commandText = "delete from users where guid=?"; using (var statement = db.PrepareStatement("delete from users where guid=@id"))
{
db.Execute(commandText, statement.BindParameters.TryBind("@id", user.Id.ToGuidParamValue());
user.Id.ToGuidParamValue()); statement.MoveNext();
}
}); });
} }
} }

View File

@ -107,17 +107,23 @@ namespace Emby.Server.Implementations.Notifications
{ {
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
foreach (var row in connection.Query("select Level from Notifications where UserId=? and IsRead=?", userId.ToGuidParamValue(), false)) using (var statement = connection.PrepareStatement("select Level from Notifications where UserId=@UserId and IsRead=@IsRead"))
{ {
var levels = new List<NotificationLevel>(); statement.BindParameters.TryBind("@IsRead", false);
statement.BindParameters.TryBind("@UserId", userId.ToGuidParamValue());
levels.Add(GetLevel(row, 0)); foreach (var row in statement.ExecuteQuery())
result.UnreadCount = levels.Count;
if (levels.Count > 0)
{ {
result.MaxUnreadNotificationLevel = levels.Max(); var levels = new List<NotificationLevel>();
levels.Add(GetLevel(row, 0));
result.UnreadCount = levels.Count;
if (levels.Count > 0)
{
result.MaxUnreadNotificationLevel = levels.Max();
}
} }
} }
@ -220,17 +226,21 @@ namespace Emby.Server.Implementations.Notifications
{ {
connection.RunInTransaction(conn => connection.RunInTransaction(conn =>
{ {
conn.Execute("replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", using (var statement = conn.PrepareStatement("replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)"))
notification.Id.ToGuidParamValue(), {
notification.UserId.ToGuidParamValue(), statement.BindParameters.TryBind("@Id", notification.Id.ToGuidParamValue());
notification.Date.ToDateTimeParamValue(), statement.BindParameters.TryBind("@UserId", notification.UserId.ToGuidParamValue());
notification.Name, statement.BindParameters.TryBind("@Date", notification.Date.ToDateTimeParamValue());
notification.Description, statement.BindParameters.TryBind("@Name", notification.Name);
notification.Url, statement.BindParameters.TryBind("@Description", notification.Description);
notification.Level.ToString(), statement.BindParameters.TryBind("@Url", notification.Url);
notification.IsRead, statement.BindParameters.TryBind("@Level", notification.Level.ToString());
string.Empty, statement.BindParameters.TryBind("@IsRead", notification.IsRead);
string.Empty); statement.BindParameters.TryBind("@Category", string.Empty);
statement.BindParameters.TryBind("@RelatedId", string.Empty);
statement.MoveNext();
}
}); });
} }
} }
@ -279,7 +289,13 @@ namespace Emby.Server.Implementations.Notifications
{ {
connection.RunInTransaction(conn => connection.RunInTransaction(conn =>
{ {
conn.Execute("update Notifications set IsRead=? where UserId=?", isRead, userId.ToGuidParamValue()); using (var statement = conn.PrepareStatement("update Notifications set IsRead=@IsRead where UserId=@UserId"))
{
statement.BindParameters.TryBind("@IsRead", isRead);
statement.BindParameters.TryBind("@UserId", userId.ToGuidParamValue());
statement.MoveNext();
}
}); });
} }
} }
@ -295,12 +311,21 @@ namespace Emby.Server.Implementations.Notifications
{ {
connection.RunInTransaction(conn => connection.RunInTransaction(conn =>
{ {
var userIdParam = userId.ToGuidParamValue(); using (var statement = conn.PrepareStatement("update Notifications set IsRead=@IsRead where UserId=@UserId and Id=@Id"))
foreach (var id in notificationIdList)
{ {
conn.Execute("update Notifications set IsRead=? where UserId=? and Id=?", isRead, userIdParam, id); statement.BindParameters.TryBind("@IsRead", isRead);
statement.BindParameters.TryBind("@UserId", userId.ToGuidParamValue());
foreach (var id in notificationIdList)
{
statement.Reset();
statement.BindParameters.TryBind("@Id", id.ToGuidParamValue());
statement.MoveNext();
}
} }
}); });
} }
} }

View File

@ -69,19 +69,30 @@ namespace Emby.Server.Implementations.Security
{ {
connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var commandText = "replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; using (var statement = db.PrepareStatement("replace into AccessTokens (Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked) values (@Id, @AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @IsActive, @DateCreated, @DateRevoked)"))
{
statement.BindParameters.TryBind("@Id", info.Id.ToGuidParamValue());
statement.BindParameters.TryBind("@AccessToken", info.AccessToken);
db.Execute(commandText, statement.BindParameters.TryBind("@DeviceId", info.DeviceId);
info.Id.ToGuidParamValue(), statement.BindParameters.TryBind("@AppName", info.AppName);
info.AccessToken, statement.BindParameters.TryBind("@AppVersion", info.AppVersion);
info.DeviceId, statement.BindParameters.TryBind("@DeviceName", info.DeviceName);
info.AppName, statement.BindParameters.TryBind("@UserId", info.UserId);
info.AppVersion, statement.BindParameters.TryBind("@IsActive", info.IsActive);
info.DeviceName, statement.BindParameters.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
info.UserId,
info.IsActive, if (info.DateRevoked.HasValue)
info.DateCreated.ToDateTimeParamValue(), {
info.DateRevoked.HasValue ? info.DateRevoked.Value.ToDateTimeParamValue() : null); statement.BindParameters.TryBind("@DateRevoked", info.DateRevoked.Value.ToDateTimeParamValue());
}
else
{
statement.BindParameters.TryBindNull("@DateRevoked");
}
statement.MoveNext();
}
}); });
} }
} }
@ -89,6 +100,29 @@ namespace Emby.Server.Implementations.Security
private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens"; private const string BaseSelectText = "select Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, IsActive, DateCreated, DateRevoked from AccessTokens";
private void BindAuthenticationQueryParams(AuthenticationInfoQuery query, IStatement statement)
{
if (!string.IsNullOrWhiteSpace(query.AccessToken))
{
statement.BindParameters.TryBind("@AccessToken", query.AccessToken);
}
if (!string.IsNullOrWhiteSpace(query.UserId))
{
statement.BindParameters.TryBind("@UserId", query.UserId);
}
if (!string.IsNullOrWhiteSpace(query.DeviceId))
{
statement.BindParameters.TryBind("@DeviceId", query.DeviceId);
}
if (query.IsActive.HasValue)
{
statement.BindParameters.TryBind("@IsActive", query.IsActive.Value);
}
}
public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query) public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query)
{ {
if (query == null) if (query == null)
@ -99,7 +133,6 @@ namespace Emby.Server.Implementations.Security
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
var commandText = BaseSelectText; var commandText = BaseSelectText;
var paramList = new List<object>();
var whereClauses = new List<string>(); var whereClauses = new List<string>();
@ -107,26 +140,22 @@ namespace Emby.Server.Implementations.Security
if (!string.IsNullOrWhiteSpace(query.AccessToken)) if (!string.IsNullOrWhiteSpace(query.AccessToken))
{ {
whereClauses.Add("AccessToken=?"); whereClauses.Add("AccessToken=@AccessToken");
paramList.Add(query.AccessToken);
} }
if (!string.IsNullOrWhiteSpace(query.UserId)) if (!string.IsNullOrWhiteSpace(query.UserId))
{ {
whereClauses.Add("UserId=?"); whereClauses.Add("UserId=@UserId");
paramList.Add(query.UserId);
} }
if (!string.IsNullOrWhiteSpace(query.DeviceId)) if (!string.IsNullOrWhiteSpace(query.DeviceId))
{ {
whereClauses.Add("DeviceId=?"); whereClauses.Add("DeviceId=@DeviceId");
paramList.Add(query.DeviceId);
} }
if (query.IsActive.HasValue) if (query.IsActive.HasValue)
{ {
whereClauses.Add("IsActive=?"); whereClauses.Add("IsActive=@IsActive");
paramList.Add(query.IsActive.Value);
} }
if (query.HasUser.HasValue) if (query.HasUser.HasValue)
@ -171,20 +200,30 @@ namespace Emby.Server.Implementations.Security
var list = new List<AuthenticationInfo>(); var list = new List<AuthenticationInfo>();
foreach (var row in connection.Query(commandText, paramList.ToArray())) using (var statement = connection.PrepareStatement(commandText))
{ {
list.Add(Get(row)); BindAuthenticationQueryParams(query, statement);
foreach (var row in statement.ExecuteQuery())
{
list.Add(Get(row));
}
using (var totalCountStatement = connection.PrepareStatement("select count (Id) from AccessTokens" + whereTextWithoutPaging))
{
BindAuthenticationQueryParams(query, totalCountStatement);
var count = totalCountStatement.ExecuteQuery()
.SelectScalarInt()
.First();
return new QueryResult<AuthenticationInfo>()
{
Items = list.ToArray(),
TotalRecordCount = count
};
}
} }
var count = connection.Query("select count (Id) from AccessTokens" + whereTextWithoutPaging, paramList.ToArray())
.SelectScalarInt()
.First();
return new QueryResult<AuthenticationInfo>()
{
Items = list.ToArray(),
TotalRecordCount = count
};
} }
} }
@ -199,16 +238,18 @@ namespace Emby.Server.Implementations.Security
{ {
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
var commandText = BaseSelectText + " where Id=?"; var commandText = BaseSelectText + " where Id=@Id";
var paramList = new List<object>();
paramList.Add(id.ToGuidParamValue()); using (var statement = connection.PrepareStatement(commandText))
foreach (var row in connection.Query(commandText, paramList.ToArray()))
{ {
return Get(row); statement.BindParameters["@Id"].Bind(id.ToGuidParamValue());
foreach (var row in statement.ExecuteQuery())
{
return Get(row);
}
return null;
} }
return null;
} }
} }
} }

View File

@ -492,14 +492,11 @@ namespace Emby.Server.Implementations.Sync
using (var connection = CreateConnection(true)) using (var connection = CreateConnection(true))
{ {
var commandText = "select ItemId,Status,Progress from SyncJobItems"; var commandText = "select ItemId,Status,Progress from SyncJobItems";
var whereClauses = new List<string>(); var whereClauses = new List<string>();
var paramList = new List<object>();
if (!string.IsNullOrWhiteSpace(query.TargetId)) if (!string.IsNullOrWhiteSpace(query.TargetId))
{ {
whereClauses.Add("TargetId=?"); whereClauses.Add("TargetId=@TargetId");
paramList.Add(query.TargetId);
} }
if (query.Statuses.Length > 0) if (query.Statuses.Length > 0)
@ -514,22 +511,39 @@ namespace Emby.Server.Implementations.Sync
commandText += " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += " where " + string.Join(" AND ", whereClauses.ToArray());
} }
foreach (var row in connection.Query(commandText, paramList.ToArray())) using (var statement = connection.PrepareStatement(commandText))
{ {
AddStatusResult(row, result, false); if (!string.IsNullOrWhiteSpace(query.TargetId))
{
statement.BindParameters.TryBind("@TargetId", query.TargetId);
}
foreach (var row in statement.ExecuteQuery())
{
AddStatusResult(row, result, false);
}
LogQueryTime("GetSyncedItemProgresses", commandText, now);
} }
LogQueryTime("GetSyncedItemProgresses", commandText, now);
commandText = commandText commandText = commandText
.Replace("select ItemId,Status,Progress from SyncJobItems", "select ItemIds,Status,Progress from SyncJobs") .Replace("select ItemId,Status,Progress from SyncJobItems", "select ItemIds,Status,Progress from SyncJobs")
.Replace("'Synced'", "'Completed','CompletedWithError'"); .Replace("'Synced'", "'Completed','CompletedWithError'");
now = DateTime.UtcNow; now = DateTime.UtcNow;
foreach (var row in connection.Query(commandText, paramList.ToArray()))
using (var statement = connection.PrepareStatement(commandText))
{ {
AddStatusResult(row, result, true); if (!string.IsNullOrWhiteSpace(query.TargetId))
{
statement.BindParameters.TryBind("@TargetId", query.TargetId);
}
foreach (var row in statement.ExecuteQuery())
{
AddStatusResult(row, result, true);
}
LogQueryTime("GetSyncedItemProgresses", commandText, now);
} }
LogQueryTime("GetSyncedItemProgresses", commandText, now);
} }
} }

View File

@ -51,7 +51,7 @@ namespace MediaBrowser.Controller.Persistence
/// <param name="items">The items.</param> /// <param name="items">The items.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken); Task SaveItems(List<BaseItem> items, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Retrieves the item. /// Retrieves the item.