From f45fb397549b8ad052324df65bddfd4fabff5ce5 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 5 Dec 2022 16:25:43 +0800 Subject: Develop secret api. v8 --- .../CrupestApi.Commons/Crud/CrudService.cs | 51 ++-------------------- 1 file changed, 4 insertions(+), 47 deletions(-) (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs') diff --git a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs index bc4ed50..63a247b 100644 --- a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs +++ b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs @@ -7,20 +7,17 @@ namespace CrupestApi.Commons.Crud; public class CrudService { + protected readonly TableInfo _table; protected readonly IOptionsSnapshot _crupestApiOptions; protected readonly ILogger> _logger; public CrudService(IOptionsSnapshot crupestApiOptions, ILogger> logger) { + _table = new TableInfo(typeof(TEntity)); _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"); @@ -40,57 +37,17 @@ public class CrudService return connection; } - public virtual async Task CheckDatabaseExist(SqliteConnection connection) - { - var tableName = GetTableName(); - var count = (await connection.QueryAsync( - @"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 connection.ExecuteAsync(_table.GenerateCreateTableSql(), transaction: transaction); await transaction.CommitAsync(); } public virtual async Task EnsureDatabase() { var connection = await CreateDbConnection(); - var exist = await CheckDatabaseExist(connection); + var exist = await _table.CheckExistence(connection); if (!exist) { await DoInitializeDatabase(connection); -- cgit v1.2.3