Files
annotations/Azaion.Common/Database/DbFactory.cs
T
Alex Bezdieniezhnykh 5fa18aa514 queue + local sqlite WIP
2024-12-17 18:46:33 +02:00

66 lines
1.7 KiB
C#

using System.Diagnostics;
using Azaion.Common.DTO;
using Azaion.Common.DTO.Config;
using LinqToDB;
using LinqToDB.Mapping;
using Microsoft.Extensions.Options;
namespace Azaion.Common.Database;
public interface IDbFactory
{
Task<T> Run<T>(Func<AnnotationsDb, Task<T>> func);
Task Run(Func<AnnotationsDb, Task> func);
}
public class DbFactory : IDbFactory
{
private readonly DataOptions _dataOptions;
public DbFactory(IOptions<AnnotationConfig> annConfig)
{
_dataOptions = LoadOptions(annConfig.Value.AnnotationsDbFile);
}
private DataOptions LoadOptions(string dbFile)
{
if (string.IsNullOrEmpty(dbFile))
throw new ArgumentException($"Empty AnnotationsDbFile in config!");
var dataOptions = new DataOptions()
.UseSQLiteOfficial($"Data Source={dbFile}")
.UseMappingSchema(AnnotationsDbSchemaHolder.MappingSchema);
_ = dataOptions.UseTracing(TraceLevel.Info, t => Console.WriteLine(t.SqlText));
return dataOptions;
}
public async Task<T> Run<T>(Func<AnnotationsDb, Task<T>> func)
{
await using var db = new AnnotationsDb(_dataOptions);
return await func(db);
}
public async Task Run(Func<AnnotationsDb, Task> func)
{
await using var db = new AnnotationsDb(_dataOptions);
await func(db);
}
}
public static class AnnotationsDbSchemaHolder
{
public static readonly MappingSchema MappingSchema;
static AnnotationsDbSchemaHolder()
{
MappingSchema = new MappingSchema();
var builder = new FluentMappingBuilder(MappingSchema);
builder.Entity<AnnotationName>().HasTableName("annotations_queue");
builder.Build();
}
}