1098 lines
37 KiB
C#
1098 lines
37 KiB
C#
using SqlSugar;
|
||
using System.Text.Json;
|
||
using WinFormsApp.Utils;
|
||
|
||
namespace guoke
|
||
{
|
||
/// <summary>
|
||
/// 数据库服务
|
||
/// </summary>
|
||
public class DatabaseService
|
||
{
|
||
LogService log;
|
||
/// <summary>
|
||
/// 数据库配置字典
|
||
/// </summary>
|
||
static Dictionary<string, DatabaseConfig> dbConf=new Dictionary<string, DatabaseConfig>();
|
||
public DatabaseService(LogService logService)
|
||
{
|
||
//StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser);
|
||
log = logService;
|
||
List<DatabaseConfig> configs = ConfigReader.GetObject<List<DatabaseConfig>>("DB");
|
||
foreach (DatabaseConfig config in configs) {
|
||
dbConf.Add(config.Name, config);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 单例模式对象字段
|
||
/// </summary>
|
||
static Dictionary<string, SqlSugarScope> SugarScope = new Dictionary<string, SqlSugarScope>();
|
||
/// <summary>
|
||
/// 获取单例模式对象 可以跨线程
|
||
/// </summary>
|
||
/// <param name="dbName"></param>
|
||
/// <returns></returns>
|
||
public SqlSugarScope GetScope(string dbName)
|
||
{
|
||
if (dbConf.TryGetValue(dbName, out var conf))
|
||
{
|
||
if (SugarScope.ContainsKey(dbName))//单例模式以创建
|
||
{
|
||
return SugarScope[dbName];
|
||
}
|
||
else //创建在返回
|
||
{
|
||
SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
|
||
{
|
||
ConfigId = conf.Name,
|
||
ConnectionString = conf.Connection,
|
||
DbType = conf.Type,
|
||
IsAutoCloseConnection = true,
|
||
},
|
||
db =>
|
||
{
|
||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||
{
|
||
if (conf.Print)
|
||
{
|
||
var currentDbName = db.CurrentConnectionConfig.ConfigId;
|
||
log.Debug($"数据库{currentDbName}", $"sql:{sql}");
|
||
}
|
||
};
|
||
});
|
||
db.Ado.CommandTimeOut = 1;//单位秒
|
||
SugarScope.Add(dbName, db);//添加到单例字典
|
||
return db;
|
||
}
|
||
}
|
||
else
|
||
log.Warn("数据库", $"没有{dbName}对应的数据库");
|
||
return null;
|
||
}
|
||
/// <summary>
|
||
/// 获取仓库对象 单例模式 可以跨线程
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="dbName"></param>
|
||
/// <param name="checkTable"></param>
|
||
/// <returns></returns>
|
||
public WarehouseScope<T> GetWarehouseScope<T>(string dbName, bool checkTable = false) where T : class, IBaseTableModel, new()
|
||
{
|
||
return new WarehouseScope<T>(log, GetScope(dbName), checkTable);
|
||
}
|
||
/// <summary>
|
||
/// 获取客户端对象 不可以跨线程
|
||
/// </summary>
|
||
/// <param name="dbName">数据库名称</param>
|
||
/// <returns></returns>
|
||
public SqlSugarClient GetClient(string dbName)
|
||
{
|
||
if (dbConf.TryGetValue(dbName, out var conf))
|
||
{
|
||
SqlSugarClient db= new SqlSugarClient(new ConnectionConfig()
|
||
{
|
||
ConfigId = conf.Name,
|
||
ConnectionString = conf.Connection,
|
||
DbType = conf.Type,
|
||
IsAutoCloseConnection = true,
|
||
},
|
||
db =>
|
||
{
|
||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||
{
|
||
if (conf.Print)
|
||
{
|
||
var currentDbName = db.CurrentConnectionConfig.ConfigId;
|
||
log.Debug($"数据库{currentDbName}", $"sql:{sql}");
|
||
}
|
||
};
|
||
});
|
||
db.Ado.CommandTimeOut = 1;//单位秒
|
||
return db;
|
||
}
|
||
else
|
||
log.Warn("数据库", $"没有{dbName}对应的数据库");
|
||
return null;
|
||
}
|
||
/// <summary>
|
||
/// 获取仓库客户端对象 不可以跨线程
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="dbName"></param>
|
||
/// <param name="checkTable"></param>
|
||
/// <returns></returns>
|
||
public WarehouseClient<T> GetWarehouseClient<T>(string dbName, bool checkTable = false) where T : class, IBaseTableModel, new()
|
||
{
|
||
return new WarehouseClient<T>(log, GetClient(dbName));
|
||
}
|
||
/// <summary>
|
||
/// 获取仓库
|
||
/// </summary>
|
||
/// <typeparam name="T">模型类型</typeparam>
|
||
/// <param name="db">数据库连接对象</param>
|
||
/// <returns></returns>
|
||
public Repository<T> GetWarehouse<T>(ISqlSugarClient db, bool checkTable = false) where T : class, IBaseTableModel, new()
|
||
{
|
||
return new Repository<T>(db, checkTable);
|
||
}
|
||
/// <summary>
|
||
/// 获取仓库
|
||
/// </summary>
|
||
/// <typeparam name="T">模型类型</typeparam>
|
||
/// <param name="dbName">数据库名称</param>
|
||
/// <returns></returns>
|
||
public Repository<T> GetWarehouse<T>(string dbName, bool checkTable = false) where T : class, IBaseTableModel, new()
|
||
{
|
||
ISqlSugarClient db = GetClient(dbName);
|
||
return new Repository<T>(db, checkTable);
|
||
}
|
||
/// <summary>
|
||
/// 只是方法名称不一样 主要为了用在反射中唯一性
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="dbName"></param>
|
||
/// <param name="checkTable"></param>
|
||
/// <returns></returns>
|
||
public Repository<T> GetWarehouseRef<T>(string dbName, bool checkTable = false) where T : class, IBaseTableModel, new()
|
||
{
|
||
ISqlSugarClient db = GetClient(dbName);
|
||
return new Repository<T>(db, checkTable);
|
||
}
|
||
/// <summary>
|
||
/// 获取数据库配置
|
||
/// </summary>
|
||
/// <param name="name"></param>
|
||
/// <returns></returns>
|
||
public DatabaseConfig GetConfig(string name)
|
||
{
|
||
if (dbConf.TryGetValue(name, out var conf))
|
||
{ return conf; }
|
||
else
|
||
log.Warn("数据库", $"没有{name}对应的数据库配置");
|
||
return null;
|
||
}
|
||
/// <summary>
|
||
/// 根据类型获取表名
|
||
/// </summary>
|
||
/// <param name="type">模型类型</param>
|
||
/// <returns></returns>
|
||
public string GetTableName(Type type)
|
||
{
|
||
object[] attributes = type.GetCustomAttributes(typeof(SugarTable), false);
|
||
if (attributes.Length > 0)
|
||
{
|
||
SugarTable sugarTable = (SugarTable)attributes[0];
|
||
return sugarTable.TableName;
|
||
}
|
||
return type.Name;
|
||
}
|
||
}
|
||
/// <summary>
|
||
|
||
public class WarehouseBase<T> where T : class, IBaseTableModel, new()
|
||
{
|
||
//var db = Mode ? (dynamic)Scope : Client;
|
||
/// <summary>
|
||
/// 获取雪花ID
|
||
/// </summary>
|
||
public long NextId { get { return SnowFlakeSingle.Instance.NextId(); } }
|
||
/// <summary>
|
||
/// 模式 true=单例模式 false=客户端模式
|
||
/// </summary>
|
||
protected bool Mode { get; set; }
|
||
/// <summary>
|
||
/// 日志服务
|
||
/// </summary>
|
||
public LogService log { get; set; }
|
||
/// <summary>
|
||
/// 单例模式实例
|
||
/// </summary>
|
||
protected SqlSugarScope Scope { get; set; }
|
||
/// <summary>
|
||
/// 客户端实例
|
||
/// </summary>
|
||
protected SqlSugarClient Client { get; set; }
|
||
/// <summary>
|
||
/// 仓储表名
|
||
/// </summary>
|
||
public string TableName { get; set; }
|
||
/// <summary>
|
||
/// 连接状态
|
||
/// </summary>
|
||
public bool ConnStatus{ get {
|
||
var db = Mode ? (dynamic)Scope : Client;
|
||
return db.Ado.IsValidConnection();
|
||
}}
|
||
/// <summary>
|
||
/// 数据库安全性检查
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public bool DatabaseSecurityCheck()
|
||
{
|
||
var db = Mode ? (dynamic)Scope : Client;
|
||
if (db == null)
|
||
{
|
||
LogService.Log.Warn("数据库", "数据库连接对象空");
|
||
return true;
|
||
}
|
||
if (!db.Ado.IsValidConnection())
|
||
{
|
||
LogService.Log.Warn("数据库", "数据库连接断开");
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
#region 表相关
|
||
/// <summary>
|
||
/// 检查表
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public bool CheckTable<T>()
|
||
{
|
||
string tableName = GetTableName(typeof(T));// typeof(T).Name;
|
||
if (Mode)
|
||
{
|
||
return Scope.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
else
|
||
{
|
||
return Client.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
|
||
}
|
||
/// <summary>
|
||
/// 检查表
|
||
/// </summary>
|
||
/// <param name="tableName"></param>
|
||
public bool CheckTable(string tableName)
|
||
{
|
||
if (Mode)
|
||
{
|
||
return Scope.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
else
|
||
{
|
||
return Client.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 检查并创建
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public bool CheckToCreate<T>()
|
||
{
|
||
try
|
||
{
|
||
string tableName = GetTableName(typeof(T));//获取表名
|
||
|
||
if (!CheckTable(tableName))
|
||
{
|
||
if (Mode)
|
||
{
|
||
if (Scope.MappingTables == null)
|
||
{
|
||
Scope.MappingTables = new MappingTableList();
|
||
}
|
||
Scope.MappingTables.Add(typeof(T).Name, tableName); // 类名 表名
|
||
Scope.CodeFirst.InitTables(typeof(T)); //创建表
|
||
}
|
||
else
|
||
{
|
||
if (Client.MappingTables == null)
|
||
{
|
||
Client.MappingTables = new MappingTableList();
|
||
}
|
||
Client.MappingTables.Add(typeof(T).Name, tableName); // 类名 表名
|
||
Client.CodeFirst.InitTables(typeof(T)); //创建表
|
||
}
|
||
log.Info("仓库", $"创建表:{tableName},模型:{typeof(T).Name}");
|
||
}
|
||
return true;
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
log.Error("数据库", $"检查创建表错误:{e.Message}");
|
||
return false;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 根据类型获取表名
|
||
/// </summary>
|
||
/// <param name="type">模型类型</param>
|
||
/// <returns></returns>
|
||
public string GetTableName(Type type)
|
||
{
|
||
object[] attributes = type.GetCustomAttributes(typeof(SugarTable), false);
|
||
if (attributes.Length > 0)
|
||
{
|
||
SugarTable sugarTable = (SugarTable)attributes[0];
|
||
return sugarTable.TableName;
|
||
}
|
||
return type.Name;
|
||
}
|
||
#endregion
|
||
|
||
}
|
||
/// <summary>
|
||
/// 仓储单例模式 可以跨线程
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public class WarehouseScope<T>: WarehouseBase<T> where T : class, IBaseTableModel, new()
|
||
{
|
||
/// <summary>
|
||
/// 数据库对象
|
||
/// </summary>
|
||
public SqlSugarScope Db{ get;}
|
||
/// <summary>
|
||
/// 构建仓储
|
||
/// </summary>
|
||
/// <param name="logService"></param>
|
||
/// <param name="db"></param>
|
||
/// <param name="checkTable"></param>
|
||
public WarehouseScope (LogService logService, SqlSugarScope db, bool checkTable = false)
|
||
{
|
||
base.Mode = true;
|
||
base.Scope = db;
|
||
base.log = logService;
|
||
this.Db= db;
|
||
this.TableName = GetTableName(typeof(T));//获取表名
|
||
if (checkTable)
|
||
{
|
||
CheckToCreate<T>();
|
||
}
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 仓储客户端模式 不能跨线程
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public class WarehouseClient<T>: WarehouseBase<T> where T : class, IBaseTableModel, new()
|
||
{
|
||
/// <summary>
|
||
/// 数据库对象
|
||
/// </summary>
|
||
public SqlSugarClient Db { get; }
|
||
/// <summary>
|
||
/// 构建仓储
|
||
/// </summary>
|
||
/// <param name="logService"></param>
|
||
/// <param name="db"></param>
|
||
/// <param name="checkTable"></param>
|
||
public WarehouseClient(LogService logService, SqlSugarClient db, bool checkTable = false)
|
||
{
|
||
base.Mode = false;
|
||
base.Client = db;
|
||
base.log = logService;
|
||
this.Db = db;
|
||
this.TableName = GetTableName(typeof(T));//获取表名
|
||
if (checkTable)
|
||
{
|
||
CheckToCreate<T>();
|
||
}
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 创建仓库
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public class Repository<T> : SimpleClient<T> where T : class, IBaseTableModel,new()
|
||
{
|
||
/// <summary>
|
||
/// 获取雪花ID
|
||
/// </summary>
|
||
public long NextId { get { return SnowFlakeSingle.Instance.NextId(); } }
|
||
/// <summary>
|
||
///
|
||
/// </summary>
|
||
private ISqlSugarClient db;
|
||
/// <summary>
|
||
/// 数据库连接对象
|
||
/// </summary>
|
||
public ISqlSugarClient Db { get => db;}
|
||
/// <summary>
|
||
/// 空表名
|
||
/// </summary>
|
||
private string tableName = "空表名";
|
||
/// <summary>
|
||
/// 日志
|
||
/// </summary>
|
||
LogService log;
|
||
/// <summary>
|
||
/// 创建仓库
|
||
/// </summary>
|
||
/// <param name="dbClient">数据库连接实例</param>
|
||
/// <param name="checkTable">是否创建表</param>
|
||
public Repository(ISqlSugarClient dbClient,bool checkTable=false)
|
||
{
|
||
log = LogService.Log;
|
||
base.Context = dbClient;//赋值给基类
|
||
db = dbClient;
|
||
tableName = GetTableName(typeof(T));//获取表名
|
||
if (db.Ado.IsValidConnection())
|
||
{
|
||
if (checkTable)
|
||
{
|
||
CheckToCreate<T>();
|
||
}
|
||
}
|
||
else
|
||
{
|
||
log.Error("仓储", $"{typeof(T).Name}数据库连接不成功");
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 数据库连接状态
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public bool Connection()
|
||
{
|
||
return db.Ado.IsValidConnection();
|
||
}
|
||
#region 工具方法
|
||
/// <summary>
|
||
/// 从json字符串中对象中获取所有属性的key
|
||
/// </summary>
|
||
/// <param name="jsonString">key的数据</param>
|
||
/// <returns></returns>
|
||
public List<string> GetKeysFromJson(string jsonString)
|
||
{
|
||
// 将 JSON 字符串解析为字典
|
||
var dictionary = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
|
||
|
||
// 获取所有的键并转换为列表
|
||
List<string> keys = new List<string>(dictionary.Keys);
|
||
|
||
return keys;
|
||
}
|
||
#endregion
|
||
#region 表相关
|
||
/// <summary>
|
||
/// 检查表
|
||
/// </summary>
|
||
/// <param name="tableName"></param>
|
||
public bool CheckTable(string tableName)
|
||
{
|
||
return Db.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
/// <summary>
|
||
/// 检查表
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public bool CheckTable<T>()
|
||
{
|
||
string tableName = GetTableName(typeof(T));// typeof(T).Name;
|
||
return Db.DbMaintenance.IsAnyTable(tableName);//判断状态表是否存在
|
||
}
|
||
/// <summary>
|
||
/// 检查并创建
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public bool CheckToCreate<T>()
|
||
{
|
||
try
|
||
{
|
||
string tableName = GetTableName(typeof(T));//获取表名
|
||
if (!Db.DbMaintenance.IsAnyTable(tableName))//判断状态表是否存在
|
||
{
|
||
if (Db.MappingTables == null)
|
||
{
|
||
Db.MappingTables = new MappingTableList();
|
||
}
|
||
Db.MappingTables.Add(typeof(T).Name, tableName); // 类名 表名
|
||
Db.CodeFirst.InitTables(typeof(T)); //创建表
|
||
log.Info("仓库", $"创建表:{tableName},模型:{typeof(T).Name}");
|
||
}
|
||
return true;
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 根据类型获取表名
|
||
/// </summary>
|
||
/// <param name="type">模型类型</param>
|
||
/// <returns></returns>
|
||
string GetTableName(Type type)
|
||
{
|
||
object[] attributes = type.GetCustomAttributes(typeof(SugarTable), false);
|
||
if (attributes.Length > 0)
|
||
{
|
||
SugarTable sugarTable = (SugarTable)attributes[0];
|
||
return sugarTable.TableName;
|
||
}
|
||
return type.Name;
|
||
}
|
||
#endregion
|
||
#region 增
|
||
/// <summary>
|
||
/// 增加数据
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <returns></returns>
|
||
public int Insert( List<T> data)
|
||
{
|
||
return Db.Insertable(data).ExecuteCommand();
|
||
}
|
||
#endregion
|
||
#region 插入更新
|
||
/// <summary>
|
||
/// 存在数据库更新 不存在插入 (默认是主键)
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <returns></returns>
|
||
public int InsertUpdate(T data)
|
||
{
|
||
return db.Storageable(data).ExecuteCommand();
|
||
}
|
||
#endregion
|
||
#region 删
|
||
/// <summary>
|
||
/// 删除指定时间之前的数据
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="hours"></param>
|
||
/// <returns></returns>
|
||
public int DeleteDataByHours(int hours)
|
||
{
|
||
DateTime targetTime = DateTime.Now.AddHours(-hours);// 计算要删除数据的时间点
|
||
return db.Deleteable<T>().Where(it => it.CreateTime < targetTime).ExecuteCommand();
|
||
}
|
||
/// <summary>
|
||
/// 删除当前时间指定天数之前的数据
|
||
/// </summary>
|
||
/// <param name="day"></param>
|
||
/// <returns></returns>
|
||
public int DeleteDataByDay(int day)
|
||
{
|
||
DateTime targetTime = DateTime.Now.AddDays(-day);// 计算要删除数据的时间点
|
||
return db.Deleteable<T>().Where(it => it.CreateTime < targetTime).ExecuteCommand();
|
||
}
|
||
/// <summary>
|
||
/// 已创建时间保留最新N条数据 其余删除
|
||
/// </summary>
|
||
/// <param name="N"></param>
|
||
/// <returns></returns>
|
||
public int ClearTheLatestNItems(int N)
|
||
{
|
||
return db.Deleteable<T>().In(it => it.Id,db.Queryable<T>().Skip(10).OrderByDescending(it => it.CreateTime)//Take(10)最新10条2个有区别
|
||
.Select(it => it.Id)).ExecuteCommand();
|
||
}
|
||
|
||
#endregion
|
||
#region 改
|
||
/// <summary>
|
||
/// 设置同步状态
|
||
/// </summary>
|
||
/// <param name="id"></param>
|
||
/// <returns></returns>
|
||
public int SetSyncStatus(T data)
|
||
{
|
||
data.SyncStatus = 1;
|
||
return db.Updateable(data).UpdateColumns(it => new { it.SyncStatus}).ExecuteCommand();
|
||
}
|
||
#endregion
|
||
#region 查
|
||
/// <summary>
|
||
/// 查询记录是否存在
|
||
/// </summary>
|
||
/// <param name="fieldName">字段名称</param>
|
||
/// <param name="fieldValue">字段值</param>
|
||
/// <param name="conditionalType">条件类型 默认==等于</param>
|
||
/// <returns></returns>
|
||
public bool Queryable(string fieldName,object fieldValue, string conditionalType="==")
|
||
{
|
||
return db.Queryable<T>().Where( fieldName, conditionalType, fieldValue).Any();
|
||
}
|
||
/// <summary>
|
||
/// 分页查询
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="pageNumber"></param>
|
||
/// <param name="pageSize"></param>
|
||
/// <param name="totalNumber"></param>
|
||
/// <param name="totalPage"></param>
|
||
/// <returns></returns>
|
||
public List<T> QueryPage<T>(int pageNumber, int pageSize, ref int totalNumber, ref int totalPage)
|
||
{
|
||
return db.Queryable<T>().ToPageList(pageNumber, pageSize, ref totalNumber, ref totalPage);
|
||
}
|
||
/// <summary>
|
||
/// 获取未同步的数据10条
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public List<T> GetUnsynchronizedData()
|
||
{
|
||
return db.Queryable<T>().Take(10).Where(it=>it.SyncStatus==0).ToList();
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
/// <summary>
|
||
/// 数据库配置模型
|
||
/// </summary>
|
||
public class DatabaseConfig
|
||
{
|
||
// 数据库名称
|
||
public string Name { get; set; }
|
||
|
||
// 数据库是否使能
|
||
public bool Enabled { get; set; }=false;
|
||
|
||
// 数据库类型,例如 "SQLServer", "MySQL", "PostgreSQL" 等
|
||
public DbType Type { get; set; } = DbType.Sqlite;
|
||
|
||
// 数据库连接字符串
|
||
public string Connection { get; set; }
|
||
|
||
// 数据库配置备注
|
||
public string Remarks { get; set; } = "";
|
||
|
||
// 是否打印日志等相关信息
|
||
public bool Print { get; set; } = false;
|
||
|
||
}
|
||
/// <summary>
|
||
/// 数据库基类接口
|
||
/// </summary>
|
||
public interface IBaseTableModel
|
||
{
|
||
int Id { get; set; }
|
||
DateTime CreateTime { get; set; }
|
||
DateTime UpdateTime { get; set; }
|
||
string Remarks { get; set; }
|
||
int SyncStatus { get; set; }
|
||
}
|
||
/// <summary>
|
||
/// 数据模型基类
|
||
/// </summary>
|
||
public class BaseTableModel: IBaseTableModel
|
||
{
|
||
// 主键 ID
|
||
[SugarColumn(IsIdentity = true, IsPrimaryKey = true, ColumnDescription = "主键")]//主键标识 自增标识
|
||
public int Id { get; set; }
|
||
|
||
// 创建时间
|
||
[SugarColumn(ColumnDescription = "创建时间")]
|
||
public DateTime CreateTime { get; set; }= DateTime.Now;
|
||
|
||
// 更新时间
|
||
[SugarColumn(ColumnDescription = "更新时间")]
|
||
public DateTime UpdateTime { get; set; } = DateTime.Now;
|
||
|
||
// 同步状态
|
||
[SugarColumn(ColumnDescription = "同步状态")]
|
||
public int SyncStatus { get; set; } = 0;
|
||
|
||
// 备注信息
|
||
[SugarColumn(ColumnDescription = "备注信息", IsNullable = true)]
|
||
public string Remarks { get; set; } = "";
|
||
}
|
||
/// <summary>
|
||
/// 数据库同步特性
|
||
/// </summary>
|
||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||
public class DatabaseSyncAttribute : Attribute
|
||
{
|
||
/// <summary>
|
||
/// 源数据库
|
||
/// </summary>
|
||
public string Source { get; }
|
||
/// <summary>
|
||
/// 目标数据库
|
||
/// </summary>
|
||
public string Target { get; }
|
||
/// <summary>
|
||
/// 清理使能
|
||
/// </summary>
|
||
public bool CleanupEnabled { get; set; } = false; // 默认不清理
|
||
/// <summary>
|
||
/// 清理模式 false 默认保留天数
|
||
/// </summary>
|
||
public bool CleanupMode { get; set; } = false;
|
||
/// <summary>
|
||
/// 保留数 CleanupMode=true (保留条数) =false (保留天数) 默认保留30天
|
||
/// </summary>
|
||
public int RetentionCount { get; set; } = 30;
|
||
|
||
/// <summary>
|
||
/// 数据库同步特性
|
||
/// </summary>
|
||
/// <param name="source">源数据库</param>
|
||
/// <param name="target">目标数据库</param>
|
||
/// <param name="cleanupEnabled">源表清理使能</param>
|
||
/// <param name="cleanupMode">清理模式 =true保留条数 =false 默认保留天数 </param>
|
||
/// <param name="retentionCount">保留数 CleanupMode=true (保留条数) =false (保留天数) 默认保留30天</param>
|
||
public DatabaseSyncAttribute(string source, string target,bool cleanupEnabled=false,bool cleanupMode=false,int retentionCount=30)
|
||
{
|
||
Source = source;
|
||
Target = target;
|
||
CleanupEnabled = cleanupEnabled;
|
||
CleanupMode = cleanupMode;
|
||
RetentionCount = retentionCount;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// SqlSugar条件构建器,用于简化条件查询的构建
|
||
/// </summary>
|
||
public class ConditionBuilder
|
||
{
|
||
private List<IConditionalModel> _conditions = new List<IConditionalModel>();
|
||
private Dictionary<string, GroupConditionBuilder> _namedGroups = new Dictionary<string, GroupConditionBuilder>();
|
||
|
||
/// <summary>
|
||
/// 获取构建的条件列表
|
||
/// </summary>
|
||
public List<IConditionalModel> Build()
|
||
{
|
||
var result = new List<IConditionalModel>(_conditions);
|
||
// 添加所有命名条件组
|
||
foreach (var group in _namedGroups.Values)
|
||
{
|
||
result.Add(group.Build());
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加简单条件
|
||
/// </summary>
|
||
/// <param name="fieldName">字段名</param>
|
||
/// <param name="conditionalType">条件类型</param>
|
||
/// <param name="fieldValue">字段值</param>
|
||
/// <returns>当前构建器实例</returns>
|
||
public ConditionBuilder Where(string fieldName, CondType conditionalType, object fieldValue, string cSharpTypeName=null)
|
||
{
|
||
_conditions.Add(new ConditionalModel
|
||
{
|
||
FieldName = fieldName,
|
||
ConditionalType =(ConditionalType)conditionalType,
|
||
FieldValue = fieldValue?.ToString(),
|
||
CSharpTypeName = cSharpTypeName
|
||
});
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加等于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.Equal, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加不等于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereNotEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.NoEqual, fieldValue);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加大于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereGreaterThan(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.GreaterThan, fieldValue);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加大于等于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereGreaterThanOrEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.GreaterThanOrEqual, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加小于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereLessThan(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.LessThan, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加小于等于条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereLessThanOrEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.LessThanOrEqual, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加Like条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereLike(string fieldName, string fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(fieldName, CondType.Like, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加In条件
|
||
/// </summary>
|
||
public ConditionBuilder WhereIn(string fieldName, params object[] values)
|
||
{
|
||
return Where(fieldName, CondType.In, string.Join(",", values));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加复杂条件组
|
||
/// </summary>
|
||
/// <param name="builderAction">条件组构建器委托</param>
|
||
/// <returns>当前构建器实例</returns>
|
||
public ConditionBuilder WhereGroup(Action<GroupConditionBuilder> builderAction)
|
||
{
|
||
var groupBuilder = new GroupConditionBuilder();
|
||
builderAction(groupBuilder);
|
||
_conditions.Add(groupBuilder.Build());
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加命名的复杂条件组,可以在后续代码中继续添加条件
|
||
/// </summary>
|
||
/// <param name="groupName">条件组名称</param>
|
||
/// <param name="builderAction">条件组构建器委托</param>
|
||
/// <returns>当前构建器实例</returns>
|
||
public ConditionBuilder WhereGroup(string groupName, Action<GroupConditionBuilder> builderAction)
|
||
{
|
||
if (!_namedGroups.TryGetValue(groupName, out var groupBuilder))
|
||
{
|
||
groupBuilder = new GroupConditionBuilder();
|
||
_namedGroups.Add(groupName, groupBuilder);
|
||
}
|
||
|
||
builderAction(groupBuilder);
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取已命名的条件组构建器
|
||
/// </summary>
|
||
/// <param name="groupName">条件组名称</param>
|
||
/// <returns>条件组构建器</returns>
|
||
public GroupConditionBuilder GetGroup(string groupName)
|
||
{
|
||
if (!_namedGroups.TryGetValue(groupName, out var groupBuilder))
|
||
{
|
||
groupBuilder = new GroupConditionBuilder();
|
||
_namedGroups.Add(groupName, groupBuilder);
|
||
}
|
||
return groupBuilder;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 条件组构建器,用于构建复杂的条件组
|
||
/// </summary>
|
||
public class GroupConditionBuilder
|
||
{
|
||
private List<KeyValuePair<WhereType, ConditionalModel>> _conditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>();
|
||
private WhereType _defaultWhereType = WhereType.And;
|
||
|
||
/// <summary>
|
||
/// 设置默认的连接类型(And/Or)
|
||
/// </summary>
|
||
public GroupConditionBuilder SetDefaultWhereType(WhereType whereType)
|
||
{
|
||
_defaultWhereType = whereType;
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 构建条件集合
|
||
/// </summary>
|
||
public ConditionalCollections Build()
|
||
{
|
||
return new ConditionalCollections
|
||
{
|
||
ConditionalList = _conditionalList
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加条件(使用默认连接类型)
|
||
/// </summary>
|
||
public GroupConditionBuilder Where(string fieldName, CondType conditionalType, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(_defaultWhereType, fieldName,conditionalType, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加条件(指定连接类型)
|
||
/// </summary>
|
||
public GroupConditionBuilder Where(WhereType whereType, string fieldName, CondType conditionalType, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
_conditionalList.Add(new KeyValuePair<WhereType, ConditionalModel>(
|
||
whereType,
|
||
new ConditionalModel
|
||
{
|
||
FieldName = fieldName,
|
||
ConditionalType = (ConditionalType)conditionalType,
|
||
FieldValue = fieldValue?.ToString(),
|
||
CSharpTypeName = cSharpTypeName
|
||
}
|
||
));
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加And连接的条件
|
||
/// </summary>
|
||
public GroupConditionBuilder And(string fieldName, CondType conditionalType, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(WhereType.And, fieldName, conditionalType, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加Or连接的条件
|
||
/// </summary>
|
||
public GroupConditionBuilder Or(string fieldName, CondType conditionalType, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Where(WhereType.Or, fieldName, conditionalType, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加And连接的等于条件
|
||
/// </summary>
|
||
public GroupConditionBuilder AndEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return And(fieldName, CondType.Equal, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加Or连接的等于条件
|
||
/// </summary>
|
||
public GroupConditionBuilder OrEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Or(fieldName, CondType.Equal, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加And连接的不等于条件
|
||
/// </summary>
|
||
public GroupConditionBuilder AndNotEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return And(fieldName, CondType.NoEqual, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加Or连接的不等于条件
|
||
/// </summary>
|
||
public GroupConditionBuilder OrNotEqual(string fieldName, object fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Or(fieldName, CondType.NoEqual, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加And连接的Like条件
|
||
/// </summary>
|
||
public GroupConditionBuilder AndLike(string fieldName, string fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return And(fieldName, CondType.Like, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加Or连接的Like条件
|
||
/// </summary>
|
||
public GroupConditionBuilder OrLike(string fieldName, string fieldValue, string cSharpTypeName = null)
|
||
{
|
||
return Or(fieldName, CondType.Like, fieldValue, cSharpTypeName);
|
||
}
|
||
|
||
// 可以根据需要添加更多便捷方法
|
||
}
|
||
/// <summary>
|
||
/// 条件类型枚举
|
||
/// </summary>
|
||
public enum CondType
|
||
{
|
||
/// <summary>
|
||
/// 等于条件,用于判断字段值是否等于指定值
|
||
/// </summary>
|
||
Equal,
|
||
|
||
/// <summary>
|
||
/// 模糊匹配,相当于 SQL 中的 LIKE '%value%'
|
||
/// </summary>
|
||
Like,
|
||
|
||
/// <summary>
|
||
/// 大于条件,相当于 SQL 中的 >
|
||
/// </summary>
|
||
GreaterThan,
|
||
|
||
/// <summary>
|
||
/// 大于等于条件,相当于 SQL 中的 >=
|
||
/// </summary>
|
||
GreaterThanOrEqual,
|
||
|
||
/// <summary>
|
||
/// 小于条件,相当于 SQL 中的 <
|
||
/// </summary>
|
||
LessThan,
|
||
|
||
/// <summary>
|
||
/// 小于等于条件,相当于 SQL 中的 <=
|
||
/// </summary>
|
||
LessThanOrEqual,
|
||
|
||
/// <summary>
|
||
/// 包含条件,相当于 SQL 中的 IN
|
||
/// </summary>
|
||
In,
|
||
|
||
/// <summary>
|
||
/// 不包含条件,相当于 SQL 中的 NOT IN
|
||
/// </summary>
|
||
NotIn,
|
||
|
||
/// <summary>
|
||
/// 左模糊匹配,相当于 SQL 中的 LIKE '%value'
|
||
/// </summary>
|
||
LikeLeft,
|
||
|
||
/// <summary>
|
||
/// 右模糊匹配,相当于 SQL 中的 LIKE 'value%'
|
||
/// </summary>
|
||
LikeRight,
|
||
|
||
/// <summary>
|
||
/// 不等于条件,相当于 SQL 中的 != 或 <>
|
||
/// </summary>
|
||
NoEqual,
|
||
/// <summary>
|
||
/// 判断字段是否为 null 或空
|
||
/// </summary>
|
||
IsNullOrEmpty,
|
||
|
||
/// <summary>
|
||
/// 不是条件,用于否定判断
|
||
/// </summary>
|
||
IsNot,
|
||
|
||
/// <summary>
|
||
/// 不包含,相当于 SQL 中的 NOT LIKE
|
||
/// </summary>
|
||
NoLike,
|
||
|
||
/// <summary>
|
||
/// 等于 null 条件
|
||
/// </summary>
|
||
EqualNull,
|
||
|
||
/// <summary>
|
||
/// 包含模糊匹配,可以进行多个值的模糊查询
|
||
/// </summary>
|
||
InLike,
|
||
|
||
/// <summary>
|
||
/// 范围查询,用于指定一个值的范围
|
||
/// </summary>
|
||
Range
|
||
}
|
||
}
|