Merge pull request #1646 from Bond-009/lock

Return DB lock immediately
pull/1665/head
Joshua M. Boniface 5 years ago committed by GitHub
commit dc1782d049
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -154,8 +154,6 @@ namespace Emby.Server.Implementations.Activity
} }
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
{
using (var connection = GetConnection(true))
{ {
var commandText = BaseActivitySelectText; var commandText = BaseActivitySelectText;
var whereClauses = new List<string>(); var whereClauses = new List<string>();
@ -186,9 +184,12 @@ namespace Emby.Server.Implementations.Activity
string.Empty : string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray()); " where " + string.Join(" AND ", whereClauses.ToArray());
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", whereClauses.Add(
string.Format(
CultureInfo.InvariantCulture,
"Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
pagingWhereText, pagingWhereText,
startIndex.Value.ToString(_usCulture))); startIndex.Value));
} }
var whereText = whereClauses.Count == 0 ? var whereText = whereClauses.Count == 0 ?
@ -204,15 +205,20 @@ namespace Emby.Server.Implementations.Activity
commandText += " LIMIT " + limit.Value.ToString(_usCulture); commandText += " LIMIT " + limit.Value.ToString(_usCulture);
} }
var statementTexts = new List<string>(); var statementTexts = new[]
statementTexts.Add(commandText);
statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
return connection.RunInTransaction(db =>
{ {
commandText,
"select count (Id) from ActivityLog" + whereTextWithoutPaging
};
var list = new List<ActivityLogEntry>(); var list = new List<ActivityLogEntry>();
var result = new QueryResult<ActivityLogEntry>(); var result = new QueryResult<ActivityLogEntry>();
using (var connection = GetConnection(true))
{
connection.RunInTransaction(
db =>
{
var statements = PrepareAll(db, statementTexts).ToList(); var statements = PrepareAll(db, statementTexts).ToList();
using (var statement = statements[0]) using (var statement = statements[0])
@ -237,12 +243,12 @@ namespace Emby.Server.Implementations.Activity
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
} }
},
ReadTransactionMode);
}
result.Items = list.ToArray(); result.Items = list.ToArray();
return result; return result;
}, ReadTransactionMode);
}
} }
private static ActivityLogEntry GetEntry(IReadOnlyList<IResultSetValue> reader) private static ActivityLogEntry GetEntry(IReadOnlyList<IResultSetValue> reader)

@ -62,14 +62,14 @@ namespace Emby.Server.Implementations.Data
/// <returns>Task.</returns> /// <returns>Task.</returns>
private void InitializeInternal() private void InitializeInternal()
{ {
using (var connection = GetConnection()) string[] queries =
{ {
string[] queries = {
"create table if not exists userdisplaypreferences (id GUID NOT NULL, userId GUID NOT NULL, client text NOT NULL, data BLOB NOT NULL)", "create table if not exists userdisplaypreferences (id GUID NOT NULL, userId GUID NOT NULL, client text NOT NULL, data BLOB NOT NULL)",
"create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)" "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)"
}; };
using (var connection = GetConnection())
{
connection.RunQueries(queries); connection.RunQueries(queries);
} }
} }
@ -81,7 +81,6 @@ namespace Emby.Server.Implementations.Data
/// <param name="userId">The user id.</param> /// <param name="userId">The user id.</param>
/// <param name="client">The client.</param> /// <param name="client">The client.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="ArgumentNullException">item</exception> /// <exception cref="ArgumentNullException">item</exception>
public void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken) public void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
{ {
@ -99,10 +98,9 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection()) using (var connection = GetConnection())
{ {
connection.RunInTransaction(db => connection.RunInTransaction(
{ db => SaveDisplayPreferences(displayPreferences, userId, client, db),
SaveDisplayPreferences(displayPreferences, userId, client, db); TransactionMode);
}, TransactionMode);
} }
} }
@ -127,7 +125,6 @@ namespace Emby.Server.Implementations.Data
/// <param name="displayPreferences">The display preferences.</param> /// <param name="displayPreferences">The display preferences.</param>
/// <param name="userId">The user id.</param> /// <param name="userId">The user id.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="ArgumentNullException">item</exception> /// <exception cref="ArgumentNullException">item</exception>
public void SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId, CancellationToken cancellationToken) public void SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId, CancellationToken cancellationToken)
{ {
@ -140,13 +137,15 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection()) using (var connection = GetConnection())
{ {
connection.RunInTransaction(db => connection.RunInTransaction(
db =>
{ {
foreach (var displayPreference in displayPreferences) foreach (var displayPreference in displayPreferences)
{ {
SaveDisplayPreferences(displayPreference, userId, displayPreference.Client, db); SaveDisplayPreferences(displayPreference, userId, displayPreference.Client, db);
} }
}, TransactionMode); },
TransactionMode);
} }
} }
@ -180,13 +179,13 @@ namespace Emby.Server.Implementations.Data
return Get(row); return Get(row);
} }
} }
}
return new DisplayPreferences return new DisplayPreferences
{ {
Id = guidId.ToString("N", CultureInfo.InvariantCulture) Id = guidId.ToString("N", CultureInfo.InvariantCulture)
}; };
} }
}
/// <summary> /// <summary>
/// Gets all display preferences for the given user. /// Gets all display preferences for the given user.
@ -218,13 +217,9 @@ namespace Emby.Server.Implementations.Data
=> _jsonSerializer.DeserializeFromString<DisplayPreferences>(row.GetString(0)); => _jsonSerializer.DeserializeFromString<DisplayPreferences>(row.GetString(0));
public void SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken) public void SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken)
{ => SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken);
SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken);
}
public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client) public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client)
{ => GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
}
} }
} }

@ -99,12 +99,11 @@ namespace Emby.Server.Implementations.Data
/// </summary> /// </summary>
public void Initialize(SqliteUserDataRepository userDataRepo, IUserManager userManager) public void Initialize(SqliteUserDataRepository userDataRepo, IUserManager userManager)
{ {
using (var connection = GetConnection()) const string CreateMediaStreamsTableCommand
{
const string 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, ColorPrimaries TEXT NULL, ColorSpace TEXT NULL, ColorTransfer 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, ColorPrimaries TEXT NULL, ColorSpace TEXT NULL, ColorTransfer TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))";
string[] queries = { string[] queries =
{
"PRAGMA locking_mode=EXCLUSIVE", "PRAGMA locking_mode=EXCLUSIVE",
"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)", "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)",
@ -123,11 +122,91 @@ namespace Emby.Server.Implementations.Data
"create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))", "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
createMediaStreamsTableCommand, CreateMediaStreamsTableCommand,
"pragma shrink_memory" "pragma shrink_memory"
}; };
string[] postQueries =
{
// obsolete
"drop index if exists idx_TypedBaseItems",
"drop index if exists idx_mediastreams",
"drop index if exists idx_mediastreams1",
"drop index if exists idx_"+ChaptersTableName,
"drop index if exists idx_UserDataKeys1",
"drop index if exists idx_UserDataKeys2",
"drop index if exists idx_TypeTopParentId3",
"drop index if exists idx_TypeTopParentId2",
"drop index if exists idx_TypeTopParentId4",
"drop index if exists idx_Type",
"drop index if exists idx_TypeTopParentId",
"drop index if exists idx_GuidType",
"drop index if exists idx_TopParentId",
"drop index if exists idx_TypeTopParentId6",
"drop index if exists idx_ItemValues2",
"drop index if exists Idx_ProviderIds",
"drop index if exists idx_ItemValues3",
"drop index if exists idx_ItemValues4",
"drop index if exists idx_ItemValues5",
"drop index if exists idx_UserDataKeys3",
"drop table if exists UserDataKeys",
"drop table if exists ProviderIds",
"drop index if exists Idx_ProviderIds1",
"drop table if exists Images",
"drop index if exists idx_Images",
"drop index if exists idx_TypeSeriesPresentationUniqueKey",
"drop index if exists idx_SeriesPresentationUniqueKey",
"drop index if exists idx_TypeSeriesPresentationUniqueKey2",
"drop index if exists idx_AncestorIds3",
"drop index if exists idx_AncestorIds4",
"drop index if exists idx_AncestorIds2",
"create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
"create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
"create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
"create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
"create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
// covering index
"create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
// series
"create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
// series counts
// seriesdateplayed sort order
"create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
// live tv programs
"create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
// covering index for getitemvalues
"create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
// used by movie suggestions
"create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
"create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
// latest items
"create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
"create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
// resume
"create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
// items by name
"create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
"create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
// Used to update inherited tags
"create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
};
using (var connection = GetConnection())
{
connection.RunQueries(queries); connection.RunQueries(queries);
connection.RunInTransaction(db => connection.RunInTransaction(db =>
@ -235,83 +314,6 @@ namespace Emby.Server.Implementations.Data
}, TransactionMode); }, TransactionMode);
string[] postQueries =
{
// obsolete
"drop index if exists idx_TypedBaseItems",
"drop index if exists idx_mediastreams",
"drop index if exists idx_mediastreams1",
"drop index if exists idx_"+ChaptersTableName,
"drop index if exists idx_UserDataKeys1",
"drop index if exists idx_UserDataKeys2",
"drop index if exists idx_TypeTopParentId3",
"drop index if exists idx_TypeTopParentId2",
"drop index if exists idx_TypeTopParentId4",
"drop index if exists idx_Type",
"drop index if exists idx_TypeTopParentId",
"drop index if exists idx_GuidType",
"drop index if exists idx_TopParentId",
"drop index if exists idx_TypeTopParentId6",
"drop index if exists idx_ItemValues2",
"drop index if exists Idx_ProviderIds",
"drop index if exists idx_ItemValues3",
"drop index if exists idx_ItemValues4",
"drop index if exists idx_ItemValues5",
"drop index if exists idx_UserDataKeys3",
"drop table if exists UserDataKeys",
"drop table if exists ProviderIds",
"drop index if exists Idx_ProviderIds1",
"drop table if exists Images",
"drop index if exists idx_Images",
"drop index if exists idx_TypeSeriesPresentationUniqueKey",
"drop index if exists idx_SeriesPresentationUniqueKey",
"drop index if exists idx_TypeSeriesPresentationUniqueKey2",
"drop index if exists idx_AncestorIds3",
"drop index if exists idx_AncestorIds4",
"drop index if exists idx_AncestorIds2",
"create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
"create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
"create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
"create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
"create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
// covering index
"create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
// series
"create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
// series counts
// seriesdateplayed sort order
"create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
// live tv programs
"create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
// covering index for getitemvalues
"create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
// used by movie suggestions
"create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
"create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
// latest items
"create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
"create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
// resume
"create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
// items by name
"create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
"create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
// Used to update inherited tags
"create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
};
connection.RunQueries(postQueries); connection.RunQueries(postQueries);
} }
@ -1994,12 +1996,12 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(chapters)); throw new ArgumentNullException(nameof(chapters));
} }
var idBlob = id.ToGuidBlob();
using (var connection = GetConnection()) using (var connection = GetConnection())
{ {
connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var idBlob = id.ToGuidBlob();
// First delete chapters // First delete chapters
db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob); db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
@ -2530,6 +2532,7 @@ namespace Emby.Server.Implementations.Data
commandText += " where " + string.Join(" AND ", whereClauses); commandText += " where " + string.Join(" AND ", whereClauses);
} }
int count;
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
using (var statement = PrepareStatement(connection, commandText)) using (var statement = PrepareStatement(connection, commandText))
@ -2545,11 +2548,12 @@ namespace Emby.Server.Implementations.Data
// Running this again will bind the params // Running this again will bind the params
GetWhereClauses(query, statement); GetWhereClauses(query, statement);
var count = statement.ExecuteQuery().SelectScalarInt().First(); count = statement.ExecuteQuery().SelectScalarInt().First();
LogQueryTime("GetCount", commandText, now);
return count;
} }
} }
LogQueryTime("GetCount", commandText, now);
return count;
} }
public List<BaseItem> GetItemList(InternalItemsQuery query) public List<BaseItem> GetItemList(InternalItemsQuery query)
@ -2599,10 +2603,9 @@ namespace Emby.Server.Implementations.Data
} }
} }
var items = new List<BaseItem>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
var items = new List<BaseItem>();
using (var statement = PrepareStatement(connection, commandText)) using (var statement = PrepareStatement(connection, commandText))
{ {
if (EnableJoinUserData(query)) if (EnableJoinUserData(query))
@ -2653,12 +2656,12 @@ namespace Emby.Server.Implementations.Data
items = newList; items = newList;
} }
}
LogQueryTime("GetItemList", commandText, now); LogQueryTime("GetItemList", commandText, now);
return items; return items;
} }
}
private string FixUnicodeChars(string buffer) private string FixUnicodeChars(string buffer)
{ {
@ -2750,8 +2753,6 @@ namespace Emby.Server.Implementations.Data
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
var list = new List<BaseItem>();
// Hack for right now since we currently don't support filtering out these duplicates within a query // Hack for right now since we currently don't support filtering out these duplicates within a query
if (query.Limit.HasValue && query.EnableGroupByMetadataKey) if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
{ {
@ -2817,11 +2818,13 @@ namespace Emby.Server.Implementations.Data
statementTexts.Add(commandText); statementTexts.Add(commandText);
} }
var list = new List<BaseItem>();
var result = new QueryResult<BaseItem>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
return connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var result = new QueryResult<BaseItem>();
var statements = PrepareAll(db, statementTexts).ToList(); var statements = PrepareAll(db, statementTexts).ToList();
if (!isReturningZeroItems) if (!isReturningZeroItems)
@ -2876,14 +2879,12 @@ namespace Emby.Server.Implementations.Data
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
} }
} }
}, ReadTransactionMode);
}
LogQueryTime("GetItems", commandText, now); LogQueryTime("GetItems", commandText, now);
result.Items = list.ToArray(); result.Items = list.ToArray();
return result; return result;
}, ReadTransactionMode);
}
} }
private string GetOrderByText(InternalItemsQuery query) private string GetOrderByText(InternalItemsQuery query)
@ -3049,10 +3050,9 @@ namespace Emby.Server.Implementations.Data
} }
} }
var list = new List<Guid>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
var list = new List<Guid>();
using (var statement = PrepareStatement(connection, commandText)) using (var statement = PrepareStatement(connection, commandText))
{ {
if (EnableJoinUserData(query)) if (EnableJoinUserData(query))
@ -3071,12 +3071,11 @@ namespace Emby.Server.Implementations.Data
list.Add(row[0].ReadGuidFromBlob()); list.Add(row[0].ReadGuidFromBlob());
} }
} }
}
LogQueryTime("GetItemList", commandText, now); LogQueryTime("GetItemList", commandText, now);
return list; return list;
} }
}
public List<Tuple<Guid, string>> GetItemIdsWithPath(InternalItemsQuery query) public List<Tuple<Guid, string>> GetItemIdsWithPath(InternalItemsQuery query)
{ {
@ -3137,6 +3136,7 @@ namespace Emby.Server.Implementations.Data
{ {
path = row.GetString(1); path = row.GetString(1);
} }
list.Add(new Tuple<Guid, string>(id, path)); list.Add(new Tuple<Guid, string>(id, path));
} }
} }
@ -3198,7 +3198,7 @@ namespace Emby.Server.Implementations.Data
} }
} }
var list = new List<Guid>();
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
var statementTexts = new List<string>(); var statementTexts = new List<string>();
@ -3228,12 +3228,12 @@ namespace Emby.Server.Implementations.Data
statementTexts.Add(commandText); statementTexts.Add(commandText);
} }
var list = new List<Guid>();
var result = new QueryResult<Guid>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
return connection.RunInTransaction(db => connection.RunInTransaction(db =>
{ {
var result = new QueryResult<Guid>();
var statements = PrepareAll(db, statementTexts).ToList(); var statements = PrepareAll(db, statementTexts).ToList();
if (!isReturningZeroItems) if (!isReturningZeroItems)
@ -3276,14 +3276,13 @@ namespace Emby.Server.Implementations.Data
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
} }
} }
}, ReadTransactionMode);
}
LogQueryTime("GetItemIds", commandText, now); LogQueryTime("GetItemIds", commandText, now);
result.Items = list.ToArray(); result.Items = list.ToArray();
return result; return result;
}, ReadTransactionMode);
}
} }
private bool IsAlphaNumeric(string str) private bool IsAlphaNumeric(string str)
@ -4859,11 +4858,9 @@ namespace Emby.Server.Implementations.Data
private void UpdateInheritedTags(CancellationToken cancellationToken) private void UpdateInheritedTags(CancellationToken cancellationToken)
{ {
using (var connection = GetConnection()) string sql = string.Join(
{ ";",
connection.RunInTransaction(db => new string[]
{
connection.ExecuteAll(string.Join(";", new string[]
{ {
"delete from itemvalues where type = 6", "delete from itemvalues where type = 6",
@ -4873,8 +4870,13 @@ namespace Emby.Server.Implementations.Data
FROM AncestorIds FROM AncestorIds
LEFT JOIN ItemValues ON (AncestorIds.AncestorId = ItemValues.ItemId) LEFT JOIN ItemValues ON (AncestorIds.AncestorId = ItemValues.ItemId)
where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type = 4 " where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type = 4 "
});
})); using (var connection = GetConnection())
{
connection.RunInTransaction(db =>
{
connection.ExecuteAll(sql);
}, TransactionMode); }, TransactionMode);
} }
@ -4992,6 +4994,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
list.Add(row.GetString(0)); list.Add(row.GetString(0));
} }
} }
return list; return list;
} }
} }
@ -5242,10 +5245,9 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
commandText += " Group By CleanValue"; commandText += " Group By CleanValue";
var list = new List<string>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
var list = new List<string>();
using (var statement = PrepareStatement(connection, commandText)) using (var statement = PrepareStatement(connection, commandText))
{ {
foreach (var row in statement.ExecuteQuery()) foreach (var row in statement.ExecuteQuery())
@ -5257,11 +5259,11 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
} }
} }
LogQueryTime("GetItemValueNames", commandText, now); }
LogQueryTime("GetItemValueNames", commandText, now);
return list; return list;
} }
}
private QueryResult<(BaseItem, ItemCounts)> GetItemValues(InternalItemsQuery query, int[] itemValueTypes, string returnType) private QueryResult<(BaseItem, ItemCounts)> GetItemValues(InternalItemsQuery query, int[] itemValueTypes, string returnType)
{ {
@ -5417,6 +5419,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{ {
statementTexts.Add(commandText); statementTexts.Add(commandText);
} }
if (query.EnableTotalRecordCount) if (query.EnableTotalRecordCount)
{ {
var countText = "select " var countText = "select "
@ -5428,13 +5431,13 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
statementTexts.Add(countText); statementTexts.Add(countText);
} }
var list = new List<(BaseItem, ItemCounts)>();
var result = new QueryResult<(BaseItem, ItemCounts)>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
return connection.RunInTransaction(db => connection.RunInTransaction(
db =>
{ {
var list = new List<(BaseItem, ItemCounts)>();
var result = new QueryResult<(BaseItem, ItemCounts)>();
var statements = PrepareAll(db, statementTexts).ToList(); var statements = PrepareAll(db, statementTexts).ToList();
if (!isReturningZeroItems) if (!isReturningZeroItems)
@ -5451,6 +5454,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{ {
GetWhereClauses(typeSubQuery, null); GetWhereClauses(typeSubQuery, null);
} }
BindSimilarParams(query, statement); BindSimilarParams(query, statement);
BindSearchParams(query, statement); BindSearchParams(query, statement);
GetWhereClauses(innerQuery, statement); GetWhereClauses(innerQuery, statement);
@ -5474,8 +5478,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
list.Add((item, GetItemCounts(row, countStartColumn, typesToCount))); list.Add((item, GetItemCounts(row, countStartColumn, typesToCount)));
} }
} }
LogQueryTime("GetItemValues", commandText, now);
} }
} }
@ -5505,21 +5507,22 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
GetWhereClauses(outerQuery, statement); GetWhereClauses(outerQuery, statement);
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
LogQueryTime("GetItemValues", commandText, now);
} }
} }
},
ReadTransactionMode);
}
LogQueryTime("GetItemValues", commandText, now);
if (result.TotalRecordCount == 0) if (result.TotalRecordCount == 0)
{ {
result.TotalRecordCount = list.Count; result.TotalRecordCount = list.Count;
} }
result.Items = list.ToArray(); result.Items = list.ToArray();
return result; return result;
}, ReadTransactionMode);
}
} }
private ItemCounts GetItemCounts(IReadOnlyList<IResultSetValue> reader, int countStartColumn, string[] typesToCount) private ItemCounts GetItemCounts(IReadOnlyList<IResultSetValue> reader, int countStartColumn, string[] typesToCount)

@ -23,23 +23,23 @@ namespace Emby.Server.Implementations.Security
public void Initialize() public void Initialize()
{ {
using (var connection = GetConnection()) string[] queries =
{ {
var tableNewlyCreated = !TableExists(connection, "Tokens");
string[] queries = {
"create table if not exists Tokens (Id INTEGER PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT NOT NULL, AppName TEXT NOT NULL, AppVersion TEXT NOT NULL, DeviceName TEXT NOT NULL, UserId TEXT, UserName TEXT, IsActive BIT NOT NULL, DateCreated DATETIME NOT NULL, DateLastActivity DATETIME NOT NULL)", "create table if not exists Tokens (Id INTEGER PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT NOT NULL, AppName TEXT NOT NULL, AppVersion TEXT NOT NULL, DeviceName TEXT NOT NULL, UserId TEXT, UserName TEXT, IsActive BIT NOT NULL, DateCreated DATETIME NOT NULL, DateLastActivity DATETIME NOT NULL)",
"create table if not exists Devices (Id TEXT NOT NULL PRIMARY KEY, CustomName TEXT, Capabilities TEXT)", "create table if not exists Devices (Id TEXT NOT NULL PRIMARY KEY, CustomName TEXT, Capabilities TEXT)",
"drop index if exists idx_AccessTokens", "drop index if exists idx_AccessTokens",
"drop index if exists Tokens1", "drop index if exists Tokens1",
"drop index if exists Tokens2", "drop index if exists Tokens2",
"create index if not exists Tokens3 on Tokens (AccessToken, DateLastActivity)", "create index if not exists Tokens3 on Tokens (AccessToken, DateLastActivity)",
"create index if not exists Tokens4 on Tokens (Id, DateLastActivity)", "create index if not exists Tokens4 on Tokens (Id, DateLastActivity)",
"create index if not exists Devices1 on Devices (Id)" "create index if not exists Devices1 on Devices (Id)"
}; };
using (var connection = GetConnection())
{
var tableNewlyCreated = !TableExists(connection, "Tokens");
connection.RunQueries(queries); connection.RunQueries(queries);
TryMigrate(connection, tableNewlyCreated); TryMigrate(connection, tableNewlyCreated);
@ -244,18 +244,19 @@ namespace Emby.Server.Implementations.Security
} }
} }
var list = new List<AuthenticationInfo>(); var statementTexts = new[]
{
commandText,
"select count (Id) from Tokens" + whereTextWithoutPaging
};
var list = new List<AuthenticationInfo>();
var result = new QueryResult<AuthenticationInfo>();
using (var connection = GetConnection(true)) using (var connection = GetConnection(true))
{ {
return connection.RunInTransaction(db => connection.RunInTransaction(
db =>
{ {
var result = new QueryResult<AuthenticationInfo>();
var statementTexts = new List<string>();
statementTexts.Add(commandText);
statementTexts.Add("select count (Id) from Tokens" + whereTextWithoutPaging);
var statements = PrepareAll(db, statementTexts) var statements = PrepareAll(db, statementTexts)
.ToList(); .ToList();
@ -277,12 +278,12 @@ namespace Emby.Server.Implementations.Security
.First(); .First();
} }
} }
},
ReadTransactionMode);
}
result.Items = list.ToArray(); result.Items = list.ToArray();
return result; return result;
}, ReadTransactionMode);
}
} }
private static AuthenticationInfo Get(IReadOnlyList<IResultSetValue> reader) private static AuthenticationInfo Get(IReadOnlyList<IResultSetValue> reader)

Loading…
Cancel
Save