blob: bc4ed50e6072bd40f45ec3217cf800e7664e399c (
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
using System.Data;
using Dapper;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;
namespace CrupestApi.Commons.Crud;
public class CrudService<TEntity>
{
protected readonly IOptionsSnapshot<CrupestApiConfig> _crupestApiOptions;
protected readonly ILogger<CrudService<TEntity>> _logger;
public CrudService(IOptionsSnapshot<CrupestApiConfig> crupestApiOptions, ILogger<CrudService<TEntity>> logger)
{
_crupestApiOptions = crupestApiOptions;
_logger = logger;
}
public virtual string GetTableName()
{
return typeof(TEntity).Name;
}
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<bool> CheckDatabaseExist(SqliteConnection connection)
{
var tableName = GetTableName();
var count = (await connection.QueryAsync<int>(
@"SELECT count(*) FROM sqlite_schema WHERE type = 'table' AND tbl_name = @TableName;",
new { TableName = tableName })).Single();
if (count == 0)
{
return false;
}
else if (count > 1)
{
throw new DatabaseInternalException($"More than 1 table has name {tableName}. What happened?");
}
else
{
return true;
}
}
public string GetSqlType(Type type)
{
return ColumnTypeInfoRegistry.Singleton.GetSqlType(type);
}
public string GetCreateTableColumnSql()
{
var properties = typeof(TEntity).GetProperties();
var sql = string.Join(", ", properties.Select(p => $"{p.Name} {GetSqlType(p.PropertyType)}"));
return sql;
}
public virtual async Task DoInitializeDatabase(SqliteConnection connection)
{
await using var transaction = await connection.BeginTransactionAsync();
var tableName = GetTableName();
var columnSql = GetCreateTableColumnSql();
var sql = $@"
CREATE TABLE {tableName}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
{columnSql}
);
";
await connection.ExecuteAsync(sql, transaction: transaction);
await transaction.CommitAsync();
}
public virtual async Task<SqliteConnection> EnsureDatabase()
{
var connection = await CreateDbConnection();
var exist = await CheckDatabaseExist(connection);
if (!exist)
{
await DoInitializeDatabase(connection);
}
return connection;
}
}
|