using System; using System.Collections.Generic; using System.Linq; using NPoco; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Scoping; namespace Umbraco.Core.Persistence.Repositories.Implement { internal class KeyValueRepository : NPocoRepositoryBase, IKeyValueRepository { public KeyValueRepository(IScopeAccessor scopeAccessor, ILogger logger) : base(scopeAccessor, AppCaches.NoCache, logger) { } /// /// Gets a value directly from the database, no scope, nothing. /// /// Used by to determine the runtime state. internal static string GetValue(IUmbracoDatabase database, string key) { if (database is null) return null; var sql = database.SqlContext.Sql() .Select() .From() .Where(x => x.Key == key); return database.FirstOrDefault(sql)?.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 NPocoRepositoryBase protected override Guid NodeObjectTypeId => throw new NotImplementedException(); protected override Sql GetBaseQuery(bool isCount) { var sql = SqlContext.Sql(); sql = isCount ? sql.SelectCount() : sql.Select(); sql .From(); return sql; } protected override string GetBaseWhereClause() { return Constants.DatabaseSchema.Tables.KeyValue + ".key = @id"; } protected override IEnumerable GetDeleteClauses() { return new List(); } 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) { throw new NotImplementedException(); } protected override void PersistNewItem(IKeyValue entity) { var dto = Map(entity); Database.Insert(dto); } protected override void PersistUpdatedItem(IKeyValue entity) { var dto = Map(entity); 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 } }