blob: 63a247b786e24847b0c3ca34f797596d457d2d17 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
using System.Data;
using Dapper;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;
namespace CrupestApi.Commons.Crud;
public class CrudService<TEntity>
{
protected readonly TableInfo _table;
protected readonly IOptionsSnapshot<CrupestApiConfig> _crupestApiOptions;
protected readonly ILogger<CrudService<TEntity>> _logger;
public CrudService(IOptionsSnapshot<CrupestApiConfig> crupestApiOptions, ILogger<CrudService<TEntity>> logger)
{
_table = new TableInfo(typeof(TEntity));
_crupestApiOptions = crupestApiOptions;
_logger = logger;
}
public virtual string GetDbConnectionString()
{
var fileName = Path.Combine(_crupestApiOptions.Value.DataDir, "crupest-api.db");
return new SqliteConnectionStringBuilder()
{
DataSource = fileName,
Mode = SqliteOpenMode.ReadWriteCreate
}.ToString();
}
public async Task<SqliteConnection> CreateDbConnection()
{
var connection = new SqliteConnection(GetDbConnectionString());
await connection.OpenAsync();
return connection;
}
public virtual async Task DoInitializeDatabase(SqliteConnection connection)
{
await using var transaction = await connection.BeginTransactionAsync();
await connection.ExecuteAsync(_table.GenerateCreateTableSql(), transaction: transaction);
await transaction.CommitAsync();
}
public virtual async Task<SqliteConnection> EnsureDatabase()
{
var connection = await CreateDbConnection();
var exist = await _table.CheckExistence(connection);
if (!exist)
{
await DoInitializeDatabase(connection);
}
return connection;
}
}
|