using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Querying; using Umbraco.Cms.Infrastructure.Scoping; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement { internal class KeyValueRepository : EntityRepositoryBase, IKeyValueRepository { public KeyValueRepository(IScopeAccessor scopeAccessor, ILogger logger) : base(scopeAccessor, AppCaches.NoCache, logger) { } /// public IReadOnlyDictionary? FindByKeyPrefix(string keyPrefix) => Get(Query().Where(entity => entity.Identifier!.StartsWith(keyPrefix)))? .ToDictionary(x => x.Identifier!, x => x.Value); #region Overrides of IReadWriteQueryRepository public override void Save(IKeyValue entity) { if (Get(entity.Identifier) == null) PersistNewItem(entity); else PersistUpdatedItem(entity); } #endregion #region Overrides of EntityRepositoryBase protected override Sql GetBaseQuery(bool isCount) { var sql = SqlContext.Sql(); sql = isCount ? sql.SelectCount() : sql.Select(); sql .From(); return sql; } protected override string GetBaseWhereClause() => Core.Constants.DatabaseSchema.Tables.KeyValue + ".key = @id"; protected override IEnumerable GetDeleteClauses() => Enumerable.Empty(); protected override IKeyValue? PerformGet(string? id) { var sql = GetBaseQuery(false).Where(x => x.Key == id); var dto = Database.Fetch(sql).FirstOrDefault(); return dto == null ? null : Map(dto); } protected override IEnumerable? PerformGetAll(params string[]? ids) { var sql = GetBaseQuery(false).WhereIn(x => x.Key, ids); var dtos = Database.Fetch(sql); return dtos?.WhereNotNull().Select(Map)!; } protected override IEnumerable PerformGetByQuery(IQuery query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator(sqlClause, query); var sql = translator.Translate(); return Database.Fetch(sql).Select(Map).WhereNotNull(); } protected override void PersistNewItem(IKeyValue entity) { var dto = Map(entity); Database.Insert(dto); } protected override void PersistUpdatedItem(IKeyValue entity) { var dto = Map(entity); if (dto is not null) { Database.Update(dto); } } private static KeyValueDto? Map(IKeyValue keyValue) { if (keyValue == null) return null; return new KeyValueDto { Key = keyValue.Identifier, Value = keyValue.Value, UpdateDate = keyValue.UpdateDate, }; } private static IKeyValue? Map(KeyValueDto dto) { if (dto == null) return null; return new KeyValue { Identifier = dto.Key, Value = dto.Value, UpdateDate = dto.UpdateDate, }; } #endregion } }