using System.Reflection;
using MasstransferInfrastructure.Database.DTO;
using Masuit.Tools;
using Masuit.Tools.Systems;
using SQLite;
namespace MasstransferInfrastructure.Database.Sqlite;
///
/// SQLite 数据库ORM工具类
///
public class SqliteHelper
{
// 默认的数据库密码
private const string Password = "88888888";
private readonly SQLiteConnection _db;
private static SqliteHelper? _instance;
private static readonly object Locker = new();
private SqliteHelper()
{
var profile = Environment.GetEnvironmentVariable("USERPROFILE");
var path = Path.Combine(profile, "masstransfer", "mass-transfer.db");
if (!Directory.Exists(Path.GetDirectoryName(path)!))
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
// 将文件复模板数据库复制到目标目录下
var template = Path.Combine(Environment.CurrentDirectory, "mass-transfer.db");
File.Copy(template, path);
}
_db = new SQLiteConnection(path);
_db.Execute($"PRAGMA key = '{Password}'");
}
public static SqliteHelper GetInstance()
{
lock (Locker)
{
// 如果类的实例不存在则创建,否则直接返回
_instance ??= new SqliteHelper();
}
return _instance;
}
///
/// 插入数据
///
/// 待插入的数据
/// 数据类型
public int Insert(T item)
{
CreateTable(item!.GetType());
var id = item?.GetType().GetProperty("Id");
if (id != null && id.CanWrite) id.SetValue(item, SnowFlakeNew.LongId.ToString());
var createTime = item?.GetType().GetProperty("CreateTime");
if (createTime != null && createTime.CanWrite) createTime.SetValue(item, DateTime.Now);
return _db.Insert(item);
}
///
/// 更新数据
///
/// 待更新的数据
/// 数据类型
public int Update(T item)
{
var updateTime = item?.GetType().GetProperty("UpdateTime");
if (updateTime != null && updateTime.CanWrite) updateTime.SetValue(item, DateTime.Now);
return _db.Update(item);
}
///
/// 删除数据
///
/// 待删除数据的ID
/// 数据类型
public int DeleteById(object id) where T : new()
{
var type = typeof(T);
var tableName = type.GetCustomAttribute()!.Name ?? type.Name;
return _db.Execute($"delete from {tableName} where id = {id}");
}
///
/// 删除数据
///
/// 待删除数据的对象
/// 数据类型
public int Delete(T item)
{
return _db.Delete(item);
}
///
/// 根据ID获取数据
///
/// 数据ID
/// 数据类型
public T GetById(object id) where T : new()
{
return _db.Get(id);
}
///
/// 查询数据
///
/// 查询语句
/// 查询参数
/// 数据类型
public List Query(string sql, params object[] args) where T : new()
{
return _db.Query(sql, args);
}
///
/// 查询所有数据
///
/// 数据类型
public List ListAll() where T : new()
{
return _db.Table().ToList();
}
public T SaveOrUpdate(T item) where T : new()
{
var id = item?.GetType().GetProperty("Id");
if (id != null && id.GetValue(item).IsNullOrEmpty())
// 插入
Insert(item);
else
// 否则是更新操作
Update(item);
return item;
}
///
/// 执行SQL语句
///
/// SQL语句
public int Execute(string sql)
{
return _db.Execute(sql);
}
///
/// 获取当前的表信息
///
///
///
public List GetTableInfo(string tableName)
{
return _db.GetTableInfo(tableName);
}
///
/// 创建表
///
///
public void CreateTable(Type entity)
{
_db.CreateTable(entity);
}
///
/// 分页查询结果
///
///
///
///
///
///
///
public Page Page(int page, int pageSize, string sql, params object[] args) where T : new()
{
var countSql = "select count(*) from ( " + sql + " ) as c";
var total = _db.ExecuteScalar(countSql, args);
var data = Query(sql + " limit " + (page - 1) * pageSize + "," + pageSize, args);
return new Page
{
CurrentPage = page,
PageSize = pageSize,
Total = total,
Pages = total / pageSize + (total % pageSize == 0 ? 0 : 1),
Data = data
};
}
///
/// 批量插入
///
///
///
///
public void BatchInsert(IEnumerable objects, bool runInTransaction = false) where T : new()
{
if (runInTransaction)
{
_db.RunInTransaction((Action)(() =>
{
foreach (object obj in objects)
Insert(obj);
}));
}
else
{
foreach (object obj in objects)
Insert(obj);
}
}
///
/// 更新指定字段
///
///
///
///
///
public void UpdateFieldById(object? id, string field, object? value) where T : new()
{
var type = typeof(T);
var tableName = type.GetCustomAttribute()!.Name ?? type.Name;
var sql = $"update {tableName} set {field} = ? where id = ?";
_db.Execute(sql, value, id);
}
}