From 093be9500e54c70efd086fa89a1feeb3465b22d1 Mon Sep 17 00:00:00 2001 From: yubaolee Date: Mon, 17 Mar 2025 13:52:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90=E5=8A=A0?= =?UTF-8?q?=E4=B8=8A=E5=A4=96=E9=83=A8=E6=95=B0=E6=8D=AE=E6=BA=90=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenAuth.App/BuilderTable/BuilderTableApp.cs | 185 +++++++++--------- .../BuilderTable/BuilderTableColumnApp.cs | 60 +++--- .../Request/AddOrUpdateBuilderTableReq.cs | 5 + .../BuilderTable/Request/SyncStructureReq.cs | 9 +- OpenAuth.App/DbExtension.cs | 18 ++ OpenAuth.Repository/Domain/BuilderTable.cs | 6 + 6 files changed, 155 insertions(+), 128 deletions(-) diff --git a/OpenAuth.App/BuilderTable/BuilderTableApp.cs b/OpenAuth.App/BuilderTable/BuilderTableApp.cs index b627cc69..9fa4b98e 100644 --- a/OpenAuth.App/BuilderTable/BuilderTableApp.cs +++ b/OpenAuth.App/BuilderTable/BuilderTableApp.cs @@ -25,7 +25,7 @@ using OpenAuth.Repository.Interface; namespace OpenAuth.App { - public class BuilderTableApp : BaseStringApp + public class BuilderTableApp : BaseStringApp { private BuilderTableColumnApp _builderTableColumnApp; private CategoryApp _categoryApp; @@ -34,7 +34,7 @@ namespace OpenAuth.App private string _startName = ""; private IOptions _appConfiguration; - public BuilderTableApp(IUnitWork unitWork, IRepository repository, + public BuilderTableApp(IUnitWork unitWork, IRepository repository, RevelanceManagerApp app, IAuth auth, DbExtension dbExtension, BuilderTableColumnApp builderTableColumnApp, IOptions appConfiguration, CategoryApp categoryApp) : base(unitWork, repository, auth) { @@ -93,10 +93,10 @@ namespace OpenAuth.App objs = objs.Where(u => u.Id.Contains(request.key)); } - result.data =await objs.OrderBy(u => u.Id) + result.data = await objs.OrderBy(u => u.Id) .Skip((request.page - 1) * request.limit) .Take(request.limit).ToListAsync(); - result.count =await objs.CountAsync(); + result.count = await objs.CountAsync(); return result; } @@ -111,14 +111,14 @@ namespace OpenAuth.App { throw new Exception("模块名称不能为空"); } - + if (string.IsNullOrEmpty(req.Namespace)) { throw new Exception("命名空间不能为空"); } - + var obj = AddTableAndColumns(req.MapTo()); - + UnitWork.Save(); return obj.Id; } @@ -192,7 +192,8 @@ namespace OpenAuth.App ParentTableId = obj.ParentTableId, UpdateTime = DateTime.Now, UpdateUserId = user.Id, - UpdateUserName = user.Name + UpdateUserName = user.Name, + ExternalDataSourceId = obj.ExternalDataSourceId //外部数据源ID }); } @@ -228,8 +229,8 @@ namespace OpenAuth.App CreateEntityModel(tableColumns, sysTableInfo); } - - + + /// /// 创建业务逻辑层 /// @@ -243,12 +244,12 @@ namespace OpenAuth.App || mainColumns.Count == 0) throw new Exception("未能找到正确的模版信息"); - //生成应用层 + //生成应用层 GenerateApp(sysTableInfo, mainColumns); //生成应用层的请求参数 GenerateAppReq(sysTableInfo, mainColumns); - + //生成WebApI接口 GenerateWebApi(sysTableInfo, mainColumns); } @@ -278,48 +279,48 @@ namespace OpenAuth.App { domainContent = FileHelper.ReadFile(@"Template\\SingleTable\\BuildApp.html"); } - domainContent = domainContent - .Replace("{TableName}", sysTableInfo.TableName) - .Replace("{ModuleCode}", sysTableInfo.ModuleCode) - .Replace("{ModuleName}", sysTableInfo.ModuleName) - .Replace("{ClassName}", sysTableInfo.ClassName) - .Replace("{StartName}", StratName); + domainContent = domainContent + .Replace("{TableName}", sysTableInfo.TableName) + .Replace("{ModuleCode}", sysTableInfo.ModuleCode) + .Replace("{ModuleName}", sysTableInfo.ModuleName) + .Replace("{ClassName}", sysTableInfo.ClassName) + .Replace("{StartName}", StratName); - if (!string.IsNullOrEmpty(sysTableInfo.ForeignKey)) - { //替换外键模版 - var foreignTemplate = $"objs = objs.Where(u => u.{sysTableInfo.ForeignKey} == request.{sysTableInfo.ForeignKey});"; - domainContent = domainContent - .Replace("{ForeignKeyTemplate}", foreignTemplate); - } - else + if (!string.IsNullOrEmpty(sysTableInfo.ForeignKey)) + { //替换外键模版 + var foreignTemplate = $"objs = objs.Where(u => u.{sysTableInfo.ForeignKey} == request.{sysTableInfo.ForeignKey});"; + domainContent = domainContent + .Replace("{ForeignKeyTemplate}", foreignTemplate); + } + else + { + domainContent = domainContent + .Replace("{ForeignKeyTemplate}", ""); + } + + var primarykey = sysColumns.FirstOrDefault(u => u.IsKey); + if (primarykey == null) + { + throw new Exception($"未能找到表{sysTableInfo.TableName}的主键字段"); + } + if (primarykey.ColumnType == "decimal" || primarykey.ColumnType == "numeric") //是否为数字 + { + if (primarykey.IsIncrement) //是否自增 { - domainContent = domainContent - .Replace("{ForeignKeyTemplate}", ""); + domainContent = domainContent.Replace("{BaseAppName}", "BaseIntAutoGenApp"); } - - var primarykey = sysColumns.FirstOrDefault(u => u.IsKey); - if (primarykey == null) + else //普通的雪花算法生成id { - throw new Exception($"未能找到表{sysTableInfo.TableName}的主键字段"); - } - if (primarykey.ColumnType == "decimal" || primarykey.ColumnType == "numeric") //是否为数字 - { - if(primarykey.IsIncrement) //是否自增 - { - domainContent = domainContent.Replace("{BaseAppName}", "BaseIntAutoGenApp"); - } - else //普通的雪花算法生成id - { - domainContent = domainContent.Replace("{BaseAppName}", "BaseLongApp"); - } - } - else - { - domainContent = domainContent.Replace("{BaseAppName}", "BaseStringApp"); + domainContent = domainContent.Replace("{BaseAppName}", "BaseLongApp"); } + } + else + { + domainContent = domainContent.Replace("{BaseAppName}", "BaseStringApp"); + } FileHelper.WriteFile($"{appRootPath}\\{sysTableInfo.ModuleCode}", $"{sysTableInfo.ModuleCode}.cs", domainContent); } - + /// /// 生成APP层的请求参数 /// @@ -420,30 +421,30 @@ namespace OpenAuth.App .Replace("{ModuleName}", sysTableInfo.ModuleName) .Replace("{ClassName}", sysTableInfo.ClassName) .Replace("{StartName}", StratName); - - var primarykey = sysColumns.FirstOrDefault(u => u.IsKey); - if (primarykey == null) + + var primarykey = sysColumns.FirstOrDefault(u => u.IsKey); + if (primarykey == null) + { + throw new Exception($"未能找到表{sysTableInfo.TableName}的主键字段"); + } + if (primarykey.ColumnType == "decimal" || primarykey.ColumnType == "numeric") //是否为数字 + { + if (primarykey.IsIncrement) //是否自增 { - throw new Exception($"未能找到表{sysTableInfo.TableName}的主键字段"); + domainContent = domainContent.Replace("{KeyTypeName}", "int"); } - if (primarykey.ColumnType == "decimal" || primarykey.ColumnType == "numeric") //是否为数字 + else //普通的雪花算法生成id { - if(primarykey.IsIncrement) //是否自增 - { - domainContent = domainContent.Replace("{KeyTypeName}", "int"); - } - else //普通的雪花算法生成id - { - domainContent = domainContent.Replace("{KeyTypeName}", "decimal"); - } - } - else - { - domainContent = domainContent.Replace("{KeyTypeName}", "string"); + domainContent = domainContent.Replace("{KeyTypeName}", "decimal"); } + } + else + { + domainContent = domainContent.Replace("{KeyTypeName}", "string"); + } FileHelper.WriteFile(controllerPath, controllerName + ".cs", domainContent); } - + /// /// 创建实体 /// @@ -467,8 +468,8 @@ namespace OpenAuth.App attributeBuilder.Append("\r\n"); attributeBuilder.Append(" /// "); attributeBuilder.Append("\r\n"); - - attributeBuilder.Append(" [Description(\""+ column.Remark +"\")]"); + + attributeBuilder.Append(" [Description(\"" + column.Remark + "\")]"); attributeBuilder.Append("\r\n"); string entityType = column.EntityType; @@ -481,7 +482,7 @@ namespace OpenAuth.App attributeBuilder.Append("\r\n\r\n "); constructionBuilder.Append(" this." + column.EntityName - + "=" + (GetDefault(column.EntityType)??"\"\"") + + "=" + (GetDefault(column.EntityType) ?? "\"\"") + ";\r\n"); } @@ -500,7 +501,7 @@ namespace OpenAuth.App } if (primarykey.ColumnType == "decimal" || primarykey.ColumnType == "numeric") //是否为数字 { - if(primarykey.IsIncrement) //是否自增 + if (primarykey.IsIncrement) //是否自增 { domainContent = domainContent.Replace("{BaseEntityName}", "IntAutoGenEntity"); } @@ -509,7 +510,7 @@ namespace OpenAuth.App domainContent = domainContent.Replace("{BaseEntityName}", "LongEntity"); } } - else + else { domainContent = domainContent.Replace("{BaseEntityName}", "StringEntity"); } @@ -571,7 +572,7 @@ namespace OpenAuth.App return null; } - + /// /// 校验模块是否已经存在 @@ -594,7 +595,7 @@ namespace OpenAuth.App && x.BaseType == typeof(StringEntity)); foreach (var entity in types) { - if (entity.Name == moduleCode ) + if (entity.Name == moduleCode) throw new Exception($"实际表名【{moduleCode}】已创建实体,不能创建实体"); if (entity.Name != moduleCode) @@ -626,7 +627,7 @@ namespace OpenAuth.App if (!string.IsNullOrEmpty(sysTableInfo.ParentTableId)) { return; - // throw new Exception("子表不能直接生成vue,请使用该表对应的父表生成vue或删除该表的父表"); + // throw new Exception("子表不能直接生成vue,请使用该表对应的父表生成vue或删除该表的父表"); } var tableColumns = _builderTableColumnApp.Find(req.Id); @@ -639,12 +640,12 @@ namespace OpenAuth.App //查找是否存在子表额情况 var subTable = Repository.FirstOrDefault(u => u.ParentTableId == req.Id); - + if (subTable == null) //如果子表不存在,则用单模版生成 { if (req.Version == "vue3") { - if (sysTableInfo.IsDynamicHeader) + if (sysTableInfo.IsDynamicHeader) { domainContent = FileHelper.ReadFile(@"Template\\SingleTable\\BuildVue3WithDynamicHeader.html"); } @@ -655,7 +656,7 @@ namespace OpenAuth.App } else { - if (sysTableInfo.IsDynamicHeader) + if (sysTableInfo.IsDynamicHeader) { domainContent = FileHelper.ReadFile(@"Template\\SingleTable\\BuildVueWithDynamicHeader.html"); } @@ -664,18 +665,18 @@ namespace OpenAuth.App domainContent = FileHelper.ReadFile(@"Template\\SingleTable\\BuildVue.html"); } } - - domainContent = domainContent.Replace("{ClassName}", sysTableInfo.ClassName) - .Replace("{TableName}", sysTableInfo.ClassName.ToCamelCase()) - .Replace("{HeaderList}", BuilderHeader(tableColumns).ToString()); + + domainContent = domainContent.Replace("{ClassName}", sysTableInfo.ClassName) + .Replace("{TableName}", sysTableInfo.ClassName.ToCamelCase()) + .Replace("{HeaderList}", BuilderHeader(tableColumns).ToString()); } else //如果存在子表,则使用主从表生成 { var subTableColumns = _builderTableColumnApp.Find(subTable.Id); if (subTableColumns.Count == 0) throw new Exception($"未找到子表{subTable.ClassName}的字段定义"); - + if (req.Version == "vue3") { if (sysTableInfo.IsDynamicHeader) @@ -699,7 +700,7 @@ namespace OpenAuth.App } } - + domainContent = domainContent.Replace("{ParentTableId}", subTable.ForeignKey.ToCamelCase()) .Replace("{FirstTableName}", sysTableInfo.ClassName.ToCamelCase()) @@ -711,8 +712,8 @@ namespace OpenAuth.App - - FileHelper.WriteFile(Path.Combine(req.VueProjRootPath, $"src/views/{sysTableInfo.ClassName.ToLower()}s/"), + + FileHelper.WriteFile(Path.Combine(req.VueProjRootPath, $"src/views/{sysTableInfo.ClassName.ToLower()}s/"), $"index.vue", domainContent); } @@ -759,15 +760,15 @@ namespace OpenAuth.App || tableColumns == null || tableColumns.Count == 0) throw new Exception("未能找到正确的模版信息"); - + var domainContent = FileHelper.ReadFile(@"Template\\BuildVueApi.html"); domainContent = domainContent.Replace("{TableName}", sysTableInfo.ClassName.ToCamelCase()); - - FileHelper.WriteFile(Path.Combine(req.VueProjRootPath, $"src/api/"),$"{sysTableInfo.ClassName.ToCamelCase()}s.js", + + FileHelper.WriteFile(Path.Combine(req.VueProjRootPath, $"src/api/"), $"{sysTableInfo.ClassName.ToCamelCase()}s.js", domainContent); } - + /// /// 加载所有的主表(parentId为空的) /// @@ -775,14 +776,14 @@ namespace OpenAuth.App public async Task AllMain() { var result = new TableData(); - var objs = UnitWork.Find(u =>string.IsNullOrEmpty(u.ParentTableId)).Select(u=>new + var objs = UnitWork.Find(u => string.IsNullOrEmpty(u.ParentTableId)).Select(u => new { - Id= u.Id, + Id = u.Id, Name = u.TableName }); - result.data =await objs.OrderBy(u => u.Id).ToListAsync(); - result.count =await objs.CountAsync(); + result.data = await objs.OrderBy(u => u.Id).ToListAsync(); + result.count = await objs.CountAsync(); return result; } } diff --git a/OpenAuth.App/BuilderTable/BuilderTableColumnApp.cs b/OpenAuth.App/BuilderTable/BuilderTableColumnApp.cs index e8dde248..f5ba8695 100644 --- a/OpenAuth.App/BuilderTable/BuilderTableColumnApp.cs +++ b/OpenAuth.App/BuilderTable/BuilderTableColumnApp.cs @@ -7,23 +7,17 @@ using Microsoft.EntityFrameworkCore; using OpenAuth.App.Interface; using OpenAuth.App.Request; using OpenAuth.App.Response; -using OpenAuth.Repository; using OpenAuth.Repository.Domain; -using OpenAuth.Repository.Interface; - - +using SqlSugar; namespace OpenAuth.App { - public class BuilderTableColumnApp : BaseStringApp + public class BuilderTableColumnApp : SqlSugarBaseApp { - private DbExtension _dbExtension; - public BuilderTableColumnApp(IUnitWork unitWork, IRepository repository, - IAuth auth, DbExtension dbExtension) : base(unitWork, repository,auth) + public BuilderTableColumnApp(ISqlSugarClient client, IAuth auth, DbExtension dbExtension) : base(client, auth) { _dbExtension = dbExtension; } - /// /// 加载列表 /// @@ -34,25 +28,23 @@ namespace OpenAuth.App throw new Exception($"缺少必要的参数BuilderTableId"); } var result = new TableResp(); - var objs = UnitWork.Find(u =>u.TableId == request.BuilderTableId); + var objs = Repository.AsQueryable().Where(u => u.TableId == request.BuilderTableId); if (!string.IsNullOrEmpty(request.key)) { objs = objs.Where(u => u.ColumnName.Contains(request.key)); } - - result.data =await objs.OrderByDescending(u => u.IsList) - .ThenBy(u=>u.Sort) - .ThenBy(u =>u.ColumnName) + result.data = await objs.OrderByDescending(u => u.IsList) + .OrderBy(u => u.Sort) + .OrderBy(u => u.ColumnName) .Skip((request.page - 1) * request.limit) .Take(request.limit).ToListAsync(); - result.count =await objs.CountAsync(); + result.count = await objs.CountAsync(); return result; } - public void Update(AddOrUpdateBuilderTableColumnReq obj) { var user = _auth.GetCurrentUser().User; - UnitWork.Update(u => u.Id == obj.Id, u => new BuilderTableColumn + Repository.Update(u => new BuilderTableColumn { TableId = obj.TableId, TableName = obj.TableName, @@ -82,28 +74,34 @@ namespace OpenAuth.App UpdateTime = DateTime.Now, UpdateUserId = user.Id, UpdateUserName = user.Name - //todo:补充或调整自己需要的字段 - }); - + }, u => u.Id == obj.Id); } - /// /// 同步数据结构 /// 读取数据库结构与当前结构的差异,如果数据库有新增的字段,则自动加入 /// public void Sync(SyncStructureReq req) { + var builderTable = SugarClient.Queryable().First(u => u.Id == req.BuilderTableId); + if (builderTable != null) + { + //如果代码生成器配置了外部数据库连接,则使用外部数据库连接 + var connection = SugarClient.Queryable().First(u => u.Id == builderTable.ExternalDataSourceId); + if (connection != null) + { + var dbType = connection.Dbtype; + _dbExtension.SetConnection(connection.Connectionstring, dbType); + } + } var columns = _dbExtension.GetDbTableStructure(req.TableName); if (!columns.Any()) { throw new Exception($"未能找到{req.TableName}表结构定义"); } - - var exists = Find(req.Id).Select(u=>u.ColumnName); - + var exists = Find(req.Id).Select(u => u.ColumnName.ToLower()); foreach (var column in columns) { - if(exists.Contains(column.ColumnName)) continue; + if (exists.Contains(column.ColumnName.ToLower())) continue; //列名转化为小写对比 var builderColumn = new BuilderTableColumn { ColumnName = column.ColumnName, @@ -111,7 +109,6 @@ namespace OpenAuth.App ColumnType = column.ColumnType, EntityType = column.EntityType, EntityName = column.ColumnName, - IsKey = column.IsKey == 1, IsRequired = column.IsNull != 1, IsEdit = true, @@ -120,21 +117,14 @@ namespace OpenAuth.App MaxLength = column.MaxLength, TableName = req.TableName, TableId = req.Id, - CreateTime = DateTime.Now }; - UnitWork.Add(builderColumn); + Repository.Insert(builderColumn); } - UnitWork.Save(); } - - - - - public List Find(string tableId) { - return Repository.Find(u => u.TableId == tableId).ToList(); + return Repository.AsQueryable().Where(u => u.TableId == tableId).ToList(); } } } \ No newline at end of file diff --git a/OpenAuth.App/BuilderTable/Request/AddOrUpdateBuilderTableReq.cs b/OpenAuth.App/BuilderTable/Request/AddOrUpdateBuilderTableReq.cs index 712e4bd4..4ce20693 100644 --- a/OpenAuth.App/BuilderTable/Request/AddOrUpdateBuilderTableReq.cs +++ b/OpenAuth.App/BuilderTable/Request/AddOrUpdateBuilderTableReq.cs @@ -83,5 +83,10 @@ namespace OpenAuth.App.Request /// 子表外键 /// public string ForeignKey { get; set; } + + /// + /// 外部数据源ID + /// + public string ExternalDataSourceId { get; set; } } } \ No newline at end of file diff --git a/OpenAuth.App/BuilderTable/Request/SyncStructureReq.cs b/OpenAuth.App/BuilderTable/Request/SyncStructureReq.cs index 60ab53d1..6d506edd 100644 --- a/OpenAuth.App/BuilderTable/Request/SyncStructureReq.cs +++ b/OpenAuth.App/BuilderTable/Request/SyncStructureReq.cs @@ -16,9 +16,16 @@ namespace OpenAuth.App.Request public class SyncStructureReq { /// - /// Id为空则为添加 + /// 列ID + /// Id为空则为添加 /// public string Id { get; set; } + + + /// + /// 代码生成器主表ID + /// + public string BuilderTableId { get; set; } /// /// 表英文全称 diff --git a/OpenAuth.App/DbExtension.cs b/OpenAuth.App/DbExtension.cs index b53369c8..af8c4ecc 100644 --- a/OpenAuth.App/DbExtension.cs +++ b/OpenAuth.App/DbExtension.cs @@ -408,5 +408,23 @@ namespace OpenAuth.App } return new List(); } + + /// + /// 设置数据库连接 + /// + /// 数据库连接字符串 + /// 数据库类型 + public void SetConnection(string connectionString, int? dbType) + { + var config = new ConnectionConfig + { + ConnectionString = connectionString, + IsAutoCloseConnection = true, + DbType = (SqlSugar.DbType)dbType + }; + // 创建新的SqlSugarClient实例 + SugarClient = new SqlSugarClient(config); + + } } } \ No newline at end of file diff --git a/OpenAuth.Repository/Domain/BuilderTable.cs b/OpenAuth.Repository/Domain/BuilderTable.cs index bae1a2c3..ce1eb6f7 100644 --- a/OpenAuth.Repository/Domain/BuilderTable.cs +++ b/OpenAuth.Repository/Domain/BuilderTable.cs @@ -157,5 +157,11 @@ namespace OpenAuth.Repository.Domain /// [Description("主表ID,如果为空表示为主表")] public string ParentTableId { get; set; } + + /// + /// 外部数据源ID + /// + [Description("外部数据源ID")] + public string ExternalDataSourceId { get; set; } } } \ No newline at end of file