using System;
using System.Collections.Generic;
using System.Linq;
using NPoco;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Factories;
using Umbraco.Cms.Infrastructure.Scoping;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
///
/// Represents the NPoco implementation of .
///
internal class CacheInstructionRepository : ICacheInstructionRepository
{
private readonly IScopeAccessor _scopeAccessor;
public CacheInstructionRepository(IScopeAccessor scopeAccessor) => _scopeAccessor = scopeAccessor;
///
private IDatabaseScope? AmbientScope => _scopeAccessor.AmbientScope;
///
public int CountAll()
{
Sql? sql = AmbientScope?.SqlContext.Sql().Select("COUNT(*)")
.From();
return AmbientScope?.Database.ExecuteScalar(sql) ?? 0;
}
///
public int CountPendingInstructions(int lastId) =>
AmbientScope?.Database.ExecuteScalar("SELECT SUM(instructionCount) FROM umbracoCacheInstruction WHERE id > @lastId", new { lastId }) ?? 0;
///
public int GetMaxId() =>
AmbientScope?.Database.ExecuteScalar("SELECT MAX(id) FROM umbracoCacheInstruction") ?? 0;
///
public bool Exists(int id) => AmbientScope?.Database.Exists(id) ?? false;
///
public void Add(CacheInstruction cacheInstruction)
{
CacheInstructionDto dto = CacheInstructionFactory.BuildDto(cacheInstruction);
AmbientScope?.Database.Insert(dto);
}
///
public IEnumerable GetPendingInstructions(int lastId, int maxNumberToRetrieve)
{
Sql? sql = AmbientScope?.SqlContext.Sql().SelectAll()
.From()
.Where(dto => dto.Id > lastId)
.OrderBy(dto => dto.Id);
Sql? topSql = sql?.SelectTop(maxNumberToRetrieve);
return AmbientScope?.Database.Fetch(topSql).Select(CacheInstructionFactory.BuildEntity) ?? Array.Empty();
}
///
public void DeleteInstructionsOlderThan(DateTime pruneDate)
{
// Using 2 queries is faster than convoluted joins.
var maxId = AmbientScope?.Database.ExecuteScalar("SELECT MAX(id) FROM umbracoCacheInstruction;");
Sql deleteSql = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId", new { pruneDate, maxId });
AmbientScope?.Database.Execute(deleteSql);
}
}
}