From 3f5e7d236277c40aebab5154671953206e291e37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= <2270033969@qq.com> Date: Mon, 15 Jul 2024 23:23:19 +0800 Subject: [PATCH] =?UTF-8?q?style(=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90):?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../security/annotation/HasPermission.java | 14 +- .../PigResourceServerAutoConfiguration.java | 96 ++-- .../admin/controller/SysDictController.java | 399 ++++++++------- .../config/PigCodeGenDefaultProperties.java | 91 ++-- .../controller/GenGroupController.java | 181 ++++--- .../controller/GenTemplateController.java | 244 +++++---- .../controller/GeneratorController.java | 94 ++-- .../pig/codegen/entity/GenTemplateEntity.java | 136 +++--- .../pig/codegen/service/GenTableService.java | 76 ++- .../codegen/service/GenTemplateService.java | 22 +- .../impl/GenDatasourceConfServiceImpl.java | 232 +++++---- .../service/impl/GenTableServiceImpl.java | 372 +++++++------- .../service/impl/GenTemplateServiceImpl.java | 275 ++++++----- .../service/impl/GeneratorServiceImpl.java | 461 +++++++++--------- .../codegen/util/vo/GenTemplateFileVO.java | 45 +- 15 files changed, 1338 insertions(+), 1400 deletions(-) diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/HasPermission.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/HasPermission.java index 2a3b58828..67e314290 100644 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/HasPermission.java +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/HasPermission.java @@ -1,6 +1,5 @@ package com.pig4cloud.pig.common.security.annotation; - import org.springframework.security.access.prepost.PreAuthorize; import java.lang.annotation.ElementType; @@ -14,16 +13,15 @@ * @author lengleng * @date 2024/07/15 */ -@Target({ElementType.METHOD}) +@Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @PreAuthorize("@pms.hasPermission('{value}'.split(','))") public @interface HasPermission { - /** - * 权限字符串 - * - * @return {@link String[] } - */ - String[] value(); + /** + * 权限字符串 + * @return {@link String[] } + */ + String[] value(); } diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerAutoConfiguration.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerAutoConfiguration.java index 7be8d65c5..eb513b893 100644 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerAutoConfiguration.java +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerAutoConfiguration.java @@ -33,58 +33,54 @@ @EnableConfigurationProperties(PermitAllUrlProperties.class) public class PigResourceServerAutoConfiguration { - /** - * 鉴权具体的实现逻辑 - * - * @return (#pms.xxx) - */ - @Bean("pms") - public PermissionService permissionService() { - return new PermissionService(); - } + /** + * 鉴权具体的实现逻辑 + * @return (#pms.xxx) + */ + @Bean("pms") + public PermissionService permissionService() { + return new PermissionService(); + } - /** - * 请求令牌的抽取逻辑 - * - * @param urlProperties 对外暴露的接口列表 - * @return BearerTokenExtractor - */ - @Bean - public PigBearerTokenExtractor pigBearerTokenExtractor(PermitAllUrlProperties urlProperties) { - return new PigBearerTokenExtractor(urlProperties); - } + /** + * 请求令牌的抽取逻辑 + * @param urlProperties 对外暴露的接口列表 + * @return BearerTokenExtractor + */ + @Bean + public PigBearerTokenExtractor pigBearerTokenExtractor(PermitAllUrlProperties urlProperties) { + return new PigBearerTokenExtractor(urlProperties); + } - /** - * 资源服务器异常处理 - * - * @param objectMapper jackson 输出对象 - * @param securityMessageSource 自定义国际化处理器 - * @return ResourceAuthExceptionEntryPoint - */ - @Bean - public ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint(ObjectMapper objectMapper, - MessageSource securityMessageSource) { - return new ResourceAuthExceptionEntryPoint(objectMapper, securityMessageSource); - } + /** + * 资源服务器异常处理 + * @param objectMapper jackson 输出对象 + * @param securityMessageSource 自定义国际化处理器 + * @return ResourceAuthExceptionEntryPoint + */ + @Bean + public ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint(ObjectMapper objectMapper, + MessageSource securityMessageSource) { + return new ResourceAuthExceptionEntryPoint(objectMapper, securityMessageSource); + } - /** - * 资源服务器toke内省处理器 - * - * @param authorizationService token 存储实现 - * @return TokenIntrospector - */ - @Bean - public OpaqueTokenIntrospector opaqueTokenIntrospector(OAuth2AuthorizationService authorizationService) { - return new PigCustomOpaqueTokenIntrospector(authorizationService); - } + /** + * 资源服务器toke内省处理器 + * @param authorizationService token 存储实现 + * @return TokenIntrospector + */ + @Bean + public OpaqueTokenIntrospector opaqueTokenIntrospector(OAuth2AuthorizationService authorizationService) { + return new PigCustomOpaqueTokenIntrospector(authorizationService); + } + + /** + * 支持自定义权限表达式 + * @return {@link PrePostTemplateDefaults } + */ + @Bean + PrePostTemplateDefaults prePostTemplateDefaults() { + return new PrePostTemplateDefaults(); + } - /** - * 支持自定义权限表达式 - * - * @return {@link PrePostTemplateDefaults } - */ - @Bean - PrePostTemplateDefaults prePostTemplateDefaults() { - return new PrePostTemplateDefaults(); - } } diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysDictController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysDictController.java index 0231e6e14..bc95353c3 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysDictController.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysDictController.java @@ -60,213 +60,196 @@ @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class SysDictController { - private final SysDictService sysDictService; - - private final SysDictItemService sysDictItemService; - - /** - * 通过ID查询字典信息 - * - * @param id ID - * @return 字典信息 - */ - @GetMapping("/details/{id}") - public R getById(@PathVariable Long id) { - return R.ok(sysDictService.getById(id)); - } - - /** - * 查询字典信息 - * - * @param query 查询信息 - * @return 字典信息 - */ - @GetMapping("/details") - public R getDetails(@ParameterObject SysDict query) { - return R.ok(sysDictService.getOne(Wrappers.query(query), false)); - } - - /** - * 分页查询字典信息 - * - * @param page 分页对象 - * @return 分页对象 - */ - @GetMapping("/page") - public R getDictPage(@ParameterObject Page page, @ParameterObject SysDict sysDict) { - return R.ok(sysDictService.page(page, - Wrappers.lambdaQuery() - .eq(StrUtil.isNotBlank(sysDict.getSystemFlag()), SysDict::getSystemFlag, sysDict.getSystemFlag()) - .like(StrUtil.isNotBlank(sysDict.getDictType()), SysDict::getDictType, sysDict.getDictType()))); - } - - - /** - * 添加字典 - * - * @param sysDict 字典信息 - * @return success、false - */ - @SysLog("添加字典") - @PostMapping - @PreAuthorize("@pms.hasPermission('sys_dict_add')") - public R save(@Valid @RequestBody SysDict sysDict) { - sysDictService.save(sysDict); - return R.ok(sysDict); - } - - /** - * 删除字典,并且清除字典缓存 - * - * @param ids ID - * @return R - */ - @SysLog("删除字典") - @DeleteMapping - @PreAuthorize("@pms.hasPermission('sys_dict_del')") - @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) - public R removeById(@RequestBody Long[] ids) { - return R.ok(sysDictService.removeDictByIds(ids)); - } - - /** - * 修改字典 - * - * @param sysDict 字典信息 - * @return success/false - */ - @PutMapping - @SysLog("修改字典") - @PreAuthorize("@pms.hasPermission('sys_dict_edit')") - public R updateById(@Valid @RequestBody SysDict sysDict) { - return sysDictService.updateDict(sysDict); - } - - /** - * 分页查询 - * - * @param name 名称或者字典项 - * @return - */ - @GetMapping("/list") - public R getDictList(String name) { - return R.ok(sysDictService.list(Wrappers.lambdaQuery() - .like(StrUtil.isNotBlank(name), SysDict::getDictType, name) - .or() - .like(StrUtil.isNotBlank(name), SysDict::getDescription, name))); - } - - /** - * 分页查询 - * - * @param page 分页对象 - * @param sysDictItem 字典项 - * @return - */ - @GetMapping("/item/page") - public R getSysDictItemPage(Page page, SysDictItem sysDictItem) { - return R.ok(sysDictItemService.page(page, Wrappers.query(sysDictItem))); - } - - /** - * 通过id查询字典项 - * - * @param id id - * @return R - */ - @GetMapping("/item/details/{id}") - public R getDictItemById(@PathVariable("id") Long id) { - return R.ok(sysDictItemService.getById(id)); - } - - /** - * 查询字典项详情 - * - * @param query 查询条件 - * @return R - */ - @GetMapping("/item/details") - public R getDictItemDetails(SysDictItem query) { - return R.ok(sysDictItemService.getOne(Wrappers.query(query), false)); - } - - /** - * 新增字典项 - * - * @param sysDictItem 字典项 - * @return R - */ - @SysLog("新增字典项") - @PostMapping("/item") - @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) - public R save(@RequestBody SysDictItem sysDictItem) { - return R.ok(sysDictItemService.save(sysDictItem)); - } - - /** - * 修改字典项 - * - * @param sysDictItem 字典项 - * @return R - */ - @SysLog("修改字典项") - @PutMapping("/item") - public R updateById(@RequestBody SysDictItem sysDictItem) { - return sysDictItemService.updateDictItem(sysDictItem); - } - - /** - * 通过id删除字典项 - * - * @param id id - * @return R - */ - @SysLog("删除字典项") - @DeleteMapping("/item/{id}") - public R removeDictItemById(@PathVariable Long id) { - return sysDictItemService.removeDictItem(id); - } - - /** - * 同步缓存字典 - * - * @return R - */ - @SysLog("同步字典") - @PutMapping("/sync") - public R sync() { - return sysDictService.syncDictCache(); - } - - @ResponseExcel - @GetMapping("/export") - public List export(SysDictItem sysDictItem) { - return sysDictItemService.list(Wrappers.query(sysDictItem)); - } - - /** - * 通过字典类型查找字典 - * - * @param type 类型 - * @return 同类型字典 - */ - @GetMapping("/type/{type}") - @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()") - public R> getDictByType(@PathVariable String type) { - return R.ok(sysDictItemService.list(Wrappers.query().lambda().eq(SysDictItem::getDictType, type))); - } - - /** - * 通过字典类型查找字典 (针对feign调用) - * TODO: 兼容性方案,代码重复 - * @param type 类型 - * @return 同类型字典 - */ - @Inner - @GetMapping("/remote/type/{type}") - @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()") - public R> getRemoteDictByType(@PathVariable String type) { - return R.ok(sysDictItemService.list(Wrappers.query().lambda().eq(SysDictItem::getDictType, type))); - } + private final SysDictService sysDictService; + + private final SysDictItemService sysDictItemService; + + /** + * 通过ID查询字典信息 + * @param id ID + * @return 字典信息 + */ + @GetMapping("/details/{id}") + public R getById(@PathVariable Long id) { + return R.ok(sysDictService.getById(id)); + } + + /** + * 查询字典信息 + * @param query 查询信息 + * @return 字典信息 + */ + @GetMapping("/details") + public R getDetails(@ParameterObject SysDict query) { + return R.ok(sysDictService.getOne(Wrappers.query(query), false)); + } + + /** + * 分页查询字典信息 + * @param page 分页对象 + * @return 分页对象 + */ + @GetMapping("/page") + public R getDictPage(@ParameterObject Page page, @ParameterObject SysDict sysDict) { + return R.ok(sysDictService.page(page, + Wrappers.lambdaQuery() + .eq(StrUtil.isNotBlank(sysDict.getSystemFlag()), SysDict::getSystemFlag, sysDict.getSystemFlag()) + .like(StrUtil.isNotBlank(sysDict.getDictType()), SysDict::getDictType, sysDict.getDictType()))); + } + + /** + * 添加字典 + * @param sysDict 字典信息 + * @return success、false + */ + @SysLog("添加字典") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_dict_add')") + public R save(@Valid @RequestBody SysDict sysDict) { + sysDictService.save(sysDict); + return R.ok(sysDict); + } + + /** + * 删除字典,并且清除字典缓存 + * @param ids ID + * @return R + */ + @SysLog("删除字典") + @DeleteMapping + @PreAuthorize("@pms.hasPermission('sys_dict_del')") + @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) + public R removeById(@RequestBody Long[] ids) { + return R.ok(sysDictService.removeDictByIds(ids)); + } + + /** + * 修改字典 + * @param sysDict 字典信息 + * @return success/false + */ + @PutMapping + @SysLog("修改字典") + @PreAuthorize("@pms.hasPermission('sys_dict_edit')") + public R updateById(@Valid @RequestBody SysDict sysDict) { + return sysDictService.updateDict(sysDict); + } + + /** + * 分页查询 + * @param name 名称或者字典项 + * @return + */ + @GetMapping("/list") + public R getDictList(String name) { + return R.ok(sysDictService.list(Wrappers.lambdaQuery() + .like(StrUtil.isNotBlank(name), SysDict::getDictType, name) + .or() + .like(StrUtil.isNotBlank(name), SysDict::getDescription, name))); + } + + /** + * 分页查询 + * @param page 分页对象 + * @param sysDictItem 字典项 + * @return + */ + @GetMapping("/item/page") + public R getSysDictItemPage(Page page, SysDictItem sysDictItem) { + return R.ok(sysDictItemService.page(page, Wrappers.query(sysDictItem))); + } + + /** + * 通过id查询字典项 + * @param id id + * @return R + */ + @GetMapping("/item/details/{id}") + public R getDictItemById(@PathVariable("id") Long id) { + return R.ok(sysDictItemService.getById(id)); + } + + /** + * 查询字典项详情 + * @param query 查询条件 + * @return R + */ + @GetMapping("/item/details") + public R getDictItemDetails(SysDictItem query) { + return R.ok(sysDictItemService.getOne(Wrappers.query(query), false)); + } + + /** + * 新增字典项 + * @param sysDictItem 字典项 + * @return R + */ + @SysLog("新增字典项") + @PostMapping("/item") + @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) + public R save(@RequestBody SysDictItem sysDictItem) { + return R.ok(sysDictItemService.save(sysDictItem)); + } + + /** + * 修改字典项 + * @param sysDictItem 字典项 + * @return R + */ + @SysLog("修改字典项") + @PutMapping("/item") + public R updateById(@RequestBody SysDictItem sysDictItem) { + return sysDictItemService.updateDictItem(sysDictItem); + } + + /** + * 通过id删除字典项 + * @param id id + * @return R + */ + @SysLog("删除字典项") + @DeleteMapping("/item/{id}") + public R removeDictItemById(@PathVariable Long id) { + return sysDictItemService.removeDictItem(id); + } + + /** + * 同步缓存字典 + * @return R + */ + @SysLog("同步字典") + @PutMapping("/sync") + public R sync() { + return sysDictService.syncDictCache(); + } + + @ResponseExcel + @GetMapping("/export") + public List export(SysDictItem sysDictItem) { + return sysDictItemService.list(Wrappers.query(sysDictItem)); + } + + /** + * 通过字典类型查找字典 + * @param type 类型 + * @return 同类型字典 + */ + @GetMapping("/type/{type}") + @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()") + public R> getDictByType(@PathVariable String type) { + return R.ok(sysDictItemService.list(Wrappers.query().lambda().eq(SysDictItem::getDictType, type))); + } + + /** + * 通过字典类型查找字典 (针对feign调用) TODO: 兼容性方案,代码重复 + * @param type 类型 + * @return 同类型字典 + */ + @Inner + @GetMapping("/remote/type/{type}") + @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.data.isEmpty()") + public R> getRemoteDictByType(@PathVariable String type) { + return R.ok(sysDictItemService.list(Wrappers.query().lambda().eq(SysDictItem::getDictType, type))); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java index 5d0ad2605..0e8a48f50 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java @@ -16,60 +16,61 @@ @ConfigurationProperties(prefix = PigCodeGenDefaultProperties.PREFIX) public class PigCodeGenDefaultProperties { - public static final String PREFIX = "codegen"; + public static final String PREFIX = "codegen"; - /** - * 是否开启在线更新 - */ - private boolean autoCheckVersion = true; + /** + * 是否开启在线更新 + */ + private boolean autoCheckVersion = true; - /** - * 模板项目地址 - */ - private String onlineUrl = DefaultConstants.CGTM_URL; + /** + * 模板项目地址 + */ + private String onlineUrl = DefaultConstants.CGTM_URL; - /** - * 生成代码的包名 - */ - private String packageName = "com.pig4cloud.pig"; + /** + * 生成代码的包名 + */ + private String packageName = "com.pig4cloud.pig"; - /** - * 生成代码的版本 - */ - private String version = "1.0.0"; + /** + * 生成代码的版本 + */ + private String version = "1.0.0"; - /** - * 生成代码的模块名 - */ - private String moduleName = "admin"; + /** + * 生成代码的模块名 + */ + private String moduleName = "admin"; - /** - * 生成代码的后端路径 - */ - private String backendPath = "pig"; + /** + * 生成代码的后端路径 + */ + private String backendPath = "pig"; - /** - * 生成代码的前端路径 - */ - private String frontendPath = "pig-ui"; + /** + * 生成代码的前端路径 + */ + private String frontendPath = "pig-ui"; - /** - * 生成代码的作者 - */ - private String author = "pig"; + /** + * 生成代码的作者 + */ + private String author = "pig"; - /** - * 生成代码的邮箱 - */ - private String email = "sw@pigx.vip"; + /** + * 生成代码的邮箱 + */ + private String email = "sw@pigx.vip"; - /** - * 表单布局(一列、两列) - */ - private Integer formLayout = 2; + /** + * 表单布局(一列、两列) + */ + private Integer formLayout = 2; + + /** + * 下载方式 (0 文件下载、1写入目录) + */ + private String generatorType = "0"; - /** - * 下载方式 (0 文件下载、1写入目录) - */ - private String generatorType = "0"; } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java index 3d0b05995..39139b8cc 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java @@ -51,106 +51,99 @@ @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class GenGroupController { - private final GenGroupService genGroupService; + private final GenGroupService genGroupService; - /** - * 分页查询 - * - * @param page 分页对象 - * @param genGroup 模板分组 - * @return - */ - @Operation(summary = "分页查询", description = "分页查询") - @GetMapping("/page") - @HasPermission("codegen_group_view") - public R getgenGroupPage(Page page, GenGroupEntity genGroup) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() - .like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId()) - .like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName()); - return R.ok(genGroupService.page(page, wrapper)); - } + /** + * 分页查询 + * @param page 分页对象 + * @param genGroup 模板分组 + * @return + */ + @Operation(summary = "分页查询", description = "分页查询") + @GetMapping("/page") + @HasPermission("codegen_group_view") + public R getgenGroupPage(Page page, GenGroupEntity genGroup) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() + .like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId()) + .like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName()); + return R.ok(genGroupService.page(page, wrapper)); + } - /** - * 通过id查询模板分组 - * - * @param id id - * @return R - */ - @Operation(summary = "通过id查询", description = "通过id查询") - @GetMapping("/{id}") - @HasPermission("codegen_group_view") - public R getById(@PathVariable("id") Long id) { - return R.ok(genGroupService.getGroupVoById(id)); - } + /** + * 通过id查询模板分组 + * @param id id + * @return R + */ + @Operation(summary = "通过id查询", description = "通过id查询") + @GetMapping("/{id}") + @HasPermission("codegen_group_view") + public R getById(@PathVariable("id") Long id) { + return R.ok(genGroupService.getGroupVoById(id)); + } - /** - * 新增模板分组 - * - * @param genTemplateGroup 模板分组 - * @return R - */ - @Operation(summary = "新增模板分组", description = "新增模板分组") - @SysLog("新增模板分组") - @PostMapping - @HasPermission("codegen_group_add") - public R save(@RequestBody TemplateGroupDTO genTemplateGroup) { - genGroupService.saveGenGroup(genTemplateGroup); - return R.ok(); - } + /** + * 新增模板分组 + * @param genTemplateGroup 模板分组 + * @return R + */ + @Operation(summary = "新增模板分组", description = "新增模板分组") + @SysLog("新增模板分组") + @PostMapping + @HasPermission("codegen_group_add") + public R save(@RequestBody TemplateGroupDTO genTemplateGroup) { + genGroupService.saveGenGroup(genTemplateGroup); + return R.ok(); + } - /** - * 修改模板分组 - * - * @param groupVo 模板分组 - * @return R - */ - @Operation(summary = "修改模板分组", description = "修改模板分组") - @SysLog("修改模板分组") - @PutMapping - @HasPermission("codegen_group_edit") - public R updateById(@RequestBody GroupVO groupVo) { - genGroupService.updateGroupAndTemplateById(groupVo); - return R.ok(); - } + /** + * 修改模板分组 + * @param groupVo 模板分组 + * @return R + */ + @Operation(summary = "修改模板分组", description = "修改模板分组") + @SysLog("修改模板分组") + @PutMapping + @HasPermission("codegen_group_edit") + public R updateById(@RequestBody GroupVO groupVo) { + genGroupService.updateGroupAndTemplateById(groupVo); + return R.ok(); + } - /** - * 通过id删除模板分组 - * - * @param ids id列表 - * @return R - */ - @Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组") - @SysLog("通过id删除模板分组") - @DeleteMapping - @HasPermission("codegen_group_del") - public R removeById(@RequestBody Long[] ids) { - genGroupService.delGroupAndTemplate(ids); - return R.ok(); - } + /** + * 通过id删除模板分组 + * @param ids id列表 + * @return R + */ + @Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组") + @SysLog("通过id删除模板分组") + @DeleteMapping + @HasPermission("codegen_group_del") + public R removeById(@RequestBody Long[] ids) { + genGroupService.delGroupAndTemplate(ids); + return R.ok(); + } - /** - * 导出excel 表格 - * - * @param genGroup 查询条件 - * @return excel 文件流 - */ - @ResponseExcel - @GetMapping("/export") - @HasPermission("codegen_group_export") - public List export(GenGroupEntity genGroup) { - return genGroupService.list(Wrappers.query(genGroup)); - } + /** + * 导出excel 表格 + * @param genGroup 查询条件 + * @return excel 文件流 + */ + @ResponseExcel + @GetMapping("/export") + @HasPermission("codegen_group_export") + public List export(GenGroupEntity genGroup) { + return genGroupService.list(Wrappers.query(genGroup)); + } - - /** - * @return 响应信息主体 - */ - @GetMapping("/list") - @Operation(summary = "查询列表", description = "查询列表") - public R list() { - List list = genGroupService.list(Wrappers.lambdaQuery() - .orderByDesc(GenGroupEntity::getCreateTime)); - return R.ok(list); - } + /** + * @return 响应信息主体 + */ + @GetMapping("/list") + @Operation(summary = "查询列表", description = "查询列表") + public R list() { + List list = genGroupService + .list(Wrappers.lambdaQuery().orderByDesc(GenGroupEntity::getCreateTime)); + return R.ok(list); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java index 418ba2bb0..dadb5d194 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java @@ -51,132 +51,122 @@ @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class GenTemplateController { - private final GenTemplateService genTemplateService; + private final GenTemplateService genTemplateService; + + /** + * 分页查询 + * @param page 分页对象 + * @param genTemplate 模板 + * @return + */ + @Operation(summary = "分页查询", description = "分页查询") + @GetMapping("/page") + @HasPermission("codegen_template_view") + public R getGenTemplatePage(Page page, GenTemplateEntity genTemplate) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() + .like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId()) + .like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName, + genTemplate.getTemplateName()); + return R.ok(genTemplateService.page(page, wrapper)); + } + + /** + * 查询全部模板 + * @return + */ + @Operation(summary = "查询全部", description = "查询全部") + @GetMapping("/list") + @HasPermission("codegen_template_view") + public R list() { + return R.ok(genTemplateService + .list(Wrappers.lambdaQuery().orderByDesc(GenTemplateEntity::getCreateTime))); + } + + /** + * 通过id查询模板 + * @param id id + * @return R + */ + @Operation(summary = "通过id查询", description = "通过id查询") + @GetMapping("/{id}") + @HasPermission("codegen_template_view") + public R getById(@PathVariable("id") Long id) { + return R.ok(genTemplateService.getById(id)); + } + + /** + * 新增模板 + * @param genTemplate 模板 + * @return R + */ + @XssCleanIgnore + @Operation(summary = "新增模板", description = "新增模板") + @SysLog("新增模板") + @PostMapping + @HasPermission("codegen_template_add") + public R save(@RequestBody GenTemplateEntity genTemplate) { + return R.ok(genTemplateService.save(genTemplate)); + } + + /** + * 修改模板 + * @param genTemplate 模板 + * @return R + */ + @XssCleanIgnore + @Operation(summary = "修改模板", description = "修改模板") + @SysLog("修改模板") + @PutMapping + @HasPermission("codegen_template_edit") + public R updateById(@RequestBody GenTemplateEntity genTemplate) { + return R.ok(genTemplateService.updateById(genTemplate)); + } + + /** + * 通过id删除模板 + * @param ids id列表 + * @return R + */ + @Operation(summary = "通过id删除模板", description = "通过id删除模板") + @SysLog("通过id删除模板") + @DeleteMapping + @HasPermission("codegen_template_del") + public R removeById(@RequestBody Long[] ids) { + return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids))); + } + + /** + * 导出excel 表格 + * @param genTemplate 查询条件 + * @return excel 文件流 + */ + @ResponseExcel + @GetMapping("/export") + @HasPermission("codegen_template_export") + public List export(GenTemplateEntity genTemplate) { + return genTemplateService.list(Wrappers.query(genTemplate)); + } + + /** + * 在线更新模板 + * @return R + */ + @Operation(summary = "在线更新模板", description = "在线更新模板") + @GetMapping("/online") + @HasPermission("codegen_template_view") + public R online() { + return genTemplateService.onlineUpdate(); + } + + /** + * 检查版本 + * @return {@link R } + */ + @Operation(summary = "在线检查模板", description = "在线检查模板") + @GetMapping("/checkVersion") + @HasPermission("codegen_template_view") + public R checkVersion() { + return genTemplateService.checkVersion(); + } - /** - * 分页查询 - * - * @param page 分页对象 - * @param genTemplate 模板 - * @return - */ - @Operation(summary = "分页查询", description = "分页查询") - @GetMapping("/page") - @HasPermission("codegen_template_view") - public R getGenTemplatePage(Page page, GenTemplateEntity genTemplate) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() - .like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId()) - .like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName, - genTemplate.getTemplateName()); - return R.ok(genTemplateService.page(page, wrapper)); - } - - /** - * 查询全部模板 - * - * @return - */ - @Operation(summary = "查询全部", description = "查询全部") - @GetMapping("/list") - @HasPermission("codegen_template_view") - public R list() { - return R.ok(genTemplateService.list(Wrappers.lambdaQuery() - .orderByDesc(GenTemplateEntity::getCreateTime))); - } - - /** - * 通过id查询模板 - * - * @param id id - * @return R - */ - @Operation(summary = "通过id查询", description = "通过id查询") - @GetMapping("/{id}") - @HasPermission("codegen_template_view") - public R getById(@PathVariable("id") Long id) { - return R.ok(genTemplateService.getById(id)); - } - - /** - * 新增模板 - * - * @param genTemplate 模板 - * @return R - */ - @XssCleanIgnore - @Operation(summary = "新增模板", description = "新增模板") - @SysLog("新增模板") - @PostMapping - @HasPermission("codegen_template_add") - public R save(@RequestBody GenTemplateEntity genTemplate) { - return R.ok(genTemplateService.save(genTemplate)); - } - - /** - * 修改模板 - * - * @param genTemplate 模板 - * @return R - */ - @XssCleanIgnore - @Operation(summary = "修改模板", description = "修改模板") - @SysLog("修改模板") - @PutMapping - @HasPermission("codegen_template_edit") - public R updateById(@RequestBody GenTemplateEntity genTemplate) { - return R.ok(genTemplateService.updateById(genTemplate)); - } - - /** - * 通过id删除模板 - * - * @param ids id列表 - * @return R - */ - @Operation(summary = "通过id删除模板", description = "通过id删除模板") - @SysLog("通过id删除模板") - @DeleteMapping - @HasPermission("codegen_template_del") - public R removeById(@RequestBody Long[] ids) { - return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids))); - } - - /** - * 导出excel 表格 - * - * @param genTemplate 查询条件 - * @return excel 文件流 - */ - @ResponseExcel - @GetMapping("/export") - @HasPermission("codegen_template_export") - public List export(GenTemplateEntity genTemplate) { - return genTemplateService.list(Wrappers.query(genTemplate)); - } - - - /** - * 在线更新模板 - * - * @return R - */ - @Operation(summary = "在线更新模板", description = "在线更新模板") - @GetMapping("/online") - @HasPermission("codegen_template_view") - public R online() { - return genTemplateService.onlineUpdate(); - } - - - /** - * 检查版本 - * - * @return {@link R } - */ - @Operation(summary = "在线检查模板", description = "在线检查模板") - @GetMapping("/checkVersion") - @HasPermission("codegen_template_view") - public R checkVersion() { - return genTemplateService.checkVersion(); - } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java index 8b6cd4e89..cd1305c6c 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java @@ -46,61 +46,59 @@ @RequestMapping("/generator") public class GeneratorController { - private final GeneratorService generatorService; + private final GeneratorService generatorService; - /** - * ZIP 下载生成代码 - * - * @param tableIds 数据表ID - * @param response 流输出对象 - */ - @SneakyThrows - @GetMapping("/download") - public void download(String tableIds, HttpServletResponse response) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(outputStream); + /** + * ZIP 下载生成代码 + * @param tableIds 数据表ID + * @param response 流输出对象 + */ + @SneakyThrows + @GetMapping("/download") + public void download(String tableIds, HttpServletResponse response) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); - // 生成代码 - for (String tableId : tableIds.split(StrUtil.COMMA)) { - generatorService.downloadCode(Long.parseLong(tableId), zip); - } + // 生成代码 + for (String tableId : tableIds.split(StrUtil.COMMA)) { + generatorService.downloadCode(Long.parseLong(tableId), zip); + } - IoUtil.close(zip); + IoUtil.close(zip); - // zip压缩包数据 - byte[] data = outputStream.toByteArray(); + // zip压缩包数据 + byte[] data = outputStream.toByteArray(); - response.reset(); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds)); - response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); - response.setContentType("application/octet-stream; charset=UTF-8"); - IoUtil.write(response.getOutputStream(), false, data); - } + response.reset(); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds)); + response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); + response.setContentType("application/octet-stream; charset=UTF-8"); + IoUtil.write(response.getOutputStream(), false, data); + } - /** - * 目标目录生成代码 - */ - @ResponseBody - @GetMapping("/code") - public R code(String tableIds) throws Exception { - // 生成代码 - for (String tableId : tableIds.split(StrUtil.COMMA)) { - generatorService.generatorCode(Long.valueOf(tableId)); - } + /** + * 目标目录生成代码 + */ + @ResponseBody + @GetMapping("/code") + public R code(String tableIds) throws Exception { + // 生成代码 + for (String tableId : tableIds.split(StrUtil.COMMA)) { + generatorService.generatorCode(Long.valueOf(tableId)); + } - return R.ok(); - } + return R.ok(); + } - /** - * 预览代码 - * - * @param tableId 表ID - * @return - */ - @SneakyThrows - @GetMapping("/preview") - public List> preview(Long tableId) { - return generatorService.preview(tableId); - } + /** + * 预览代码 + * @param tableId 表ID + * @return + */ + @SneakyThrows + @GetMapping("/preview") + public List> preview(Long tableId) { + return generatorService.preview(tableId); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java index de36c9676..10b0f185a 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java @@ -37,73 +37,73 @@ @Schema(description = "模板") public class GenTemplateEntity extends Model { - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(type = IdType.ASSIGN_ID) - @Schema(description = "主键") - private Long id; - - /** - * 模板名称 - */ - @Schema(description = "模板名称") - private String templateName; - - /** - * 模板路径 - */ - @Schema(description = "模板路径") - private String generatorPath; - - /** - * 模板描述 - */ - @Schema(description = "模板描述") - private String templateDesc; - - /** - * 模板代码 - */ - @Schema(description = "模板代码") - private String templateCode; - - /** - * 创建人 - */ - @TableField(fill = FieldFill.INSERT) - @Schema(description = "创建人") - private String createBy; - - /** - * 修改人 - */ - @TableField(fill = FieldFill.UPDATE) - @Schema(description = "修改人") - private String updateBy; - - /** - * 创建时间 - */ - @Schema(description = "创建时间") - @TableField(fill = FieldFill.INSERT) - private LocalDateTime createTime; - - /** - * 修改时间 - */ - @Schema(description = "修改时间") - @TableField(fill = FieldFill.UPDATE) - private LocalDateTime updateTime; - - /** - * 删除标识(0-正常,1-删除) - */ - @TableLogic - @TableField(fill = FieldFill.INSERT) - @Schema(description = "删除标记,1:已删除,0:正常") - private String delFlag; + private static final long serialVersionUID = 1L; + + /** + * 主键 + */ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + /** + * 模板名称 + */ + @Schema(description = "模板名称") + private String templateName; + + /** + * 模板路径 + */ + @Schema(description = "模板路径") + private String generatorPath; + + /** + * 模板描述 + */ + @Schema(description = "模板描述") + private String templateDesc; + + /** + * 模板代码 + */ + @Schema(description = "模板代码") + private String templateCode; + + /** + * 创建人 + */ + @TableField(fill = FieldFill.INSERT) + @Schema(description = "创建人") + private String createBy; + + /** + * 修改人 + */ + @TableField(fill = FieldFill.UPDATE) + @Schema(description = "修改人") + private String updateBy; + + /** + * 创建时间 + */ + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + /** + * 修改时间 + */ + @Schema(description = "修改时间") + @TableField(fill = FieldFill.UPDATE) + private LocalDateTime updateTime; + + /** + * 删除标识(0-正常,1-删除) + */ + @TableLogic + @TableField(fill = FieldFill.INSERT) + @Schema(description = "删除标记,1:已删除,0:正常") + private String delFlag; } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java index 6430bbfad..84d8f1691 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java @@ -33,50 +33,44 @@ */ public interface GenTableService extends IService { + /** + * 查询对应数据源的表 + * @param page 分页信息 + * @param table 查询条件 + * @return 表 + */ + IPage queryTablePage(Page page, GenTable table); - /** - * 查询对应数据源的表 - * - * @param page 分页信息 - * @param table 查询条件 - * @return 表 - */ - IPage queryTablePage(Page
page, GenTable table); + /** + * 查询表信息(列),然后插入到中间表中 + * @param dsName 数据源 + * @param tableName 表名 + * @return GenTable + */ + GenTable queryOrBuildTable(String dsName, String tableName); - /** - * 查询表信息(列),然后插入到中间表中 - * - * @param dsName 数据源 - * @param tableName 表名 - * @return GenTable - */ - GenTable queryOrBuildTable(String dsName, String tableName); + /** + * 查询表ddl 语句 + * @param dsName 数据源名称 + * @param tableName 表名称 + * @return ddl 语句 + * @throws Exception + */ + String queryTableDdl(String dsName, String tableName) throws Exception; - /** - * 查询表ddl 语句 - * - * @param dsName 数据源名称 - * @param tableName 表名称 - * @return ddl 语句 - * @throws Exception - */ - String queryTableDdl(String dsName, String tableName) throws Exception; + /** + * 查询数据源里面的全部表 + * @param dsName 数据源名称 + * @return table + */ + List queryTableList(String dsName); - /** - * 查询数据源里面的全部表 - * - * @param dsName 数据源名称 - * @return table - */ - List queryTableList(String dsName); - - /** - * 查询表的全部字段 - * - * @param dsName 数据源 - * @param tableName 表名称 - * @return column - */ - List queryTableColumn(String dsName, String tableName); + /** + * 查询表的全部字段 + * @param dsName 数据源 + * @param tableName 表名称 + * @return column + */ + List queryTableColumn(String dsName, String tableName); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java index 644a662d0..0e0a137e6 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java @@ -29,18 +29,16 @@ */ public interface GenTemplateService extends IService { + /** + * 检查版本 + * @return {@link R } + */ + R checkVersion(); - /** - * 检查版本 - * - * @return {@link R } - */ - R checkVersion(); + /** + * 在线更新 + * @return {@link R } + */ + R onlineUpdate(); - /** - * 在线更新 - * - * @return {@link R } - */ - R onlineUpdate(); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java index 2077483c0..543f12a55 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java @@ -48,122 +48,120 @@ @Service @RequiredArgsConstructor public class GenDatasourceConfServiceImpl extends ServiceImpl - implements GenDatasourceConfService { - - private final StringEncryptor stringEncryptor; - - private final DataSourceCreator hikariDataSourceCreator; - - /** - * 保存数据源并且加密 - * - * @param conf - * @return - */ - @Override - public Boolean saveDsByEnc(GenDatasourceConf conf) { - // 校验配置合法性 - if (!checkDataSource(conf)) { - return Boolean.FALSE; - } - - // 添加动态数据源 - addDynamicDataSource(conf); - - // 更新数据库配置 - conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); - this.baseMapper.insert(conf); - return Boolean.TRUE; - } - - /** - * 更新数据源 - * - * @param conf 数据源信息 - * @return - */ - @Override - public Boolean updateDsByEnc(GenDatasourceConf conf) { - if (!checkDataSource(conf)) { - return Boolean.FALSE; - } - // 先移除 - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName()); - - // 再添加 - addDynamicDataSource(conf); - - // 更新数据库配置 - if (StrUtil.isNotBlank(conf.getPassword())) { - conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); - } - this.baseMapper.updateById(conf); - return Boolean.TRUE; - } - - /** - * 通过数据源名称删除 - * - * @param dsIds 数据源ID - * @return - */ - @Override - public Boolean removeByDsId(Long[] dsIds) { - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - this.baseMapper.selectBatchIds(CollUtil.toList(dsIds)) - .forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName())); - this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds)); - return Boolean.TRUE; - } - - /** - * 添加动态数据源 - * - * @param conf 数据源信息 - */ - @Override - public void addDynamicDataSource(GenDatasourceConf conf) { - DataSourceProperty dataSourceProperty = new DataSourceProperty(); - dataSourceProperty.setPoolName(conf.getName()); - dataSourceProperty.setUrl(conf.getUrl()); - dataSourceProperty.setUsername(conf.getUsername()); - dataSourceProperty.setPassword(conf.getPassword()); - DataSource dataSource = hikariDataSourceCreator.createDataSource(dataSourceProperty); - - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource); - } - - /** - * 校验数据源配置是否有效 - * - * @param conf 数据源信息 - * @return 有效/无效 - */ - @Override - public Boolean checkDataSource(GenDatasourceConf conf) { - String url; - // JDBC 配置形式 - if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) { - url = conf.getUrl(); - } else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) { - // 主机形式 sql server 特殊处理 - DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); - url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); - } else { - DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); - url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); - } - - conf.setUrl(url); - - try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) { - } catch (SQLException e) { - log.error("数据源配置 {} , 获取链接失败", conf.getName(), e); - throw new RuntimeException("数据库配置错误,链接失败"); - } - return Boolean.TRUE; - } + implements GenDatasourceConfService { + + private final StringEncryptor stringEncryptor; + + private final DataSourceCreator hikariDataSourceCreator; + + /** + * 保存数据源并且加密 + * @param conf + * @return + */ + @Override + public Boolean saveDsByEnc(GenDatasourceConf conf) { + // 校验配置合法性 + if (!checkDataSource(conf)) { + return Boolean.FALSE; + } + + // 添加动态数据源 + addDynamicDataSource(conf); + + // 更新数据库配置 + conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); + this.baseMapper.insert(conf); + return Boolean.TRUE; + } + + /** + * 更新数据源 + * @param conf 数据源信息 + * @return + */ + @Override + public Boolean updateDsByEnc(GenDatasourceConf conf) { + if (!checkDataSource(conf)) { + return Boolean.FALSE; + } + // 先移除 + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName()); + + // 再添加 + addDynamicDataSource(conf); + + // 更新数据库配置 + if (StrUtil.isNotBlank(conf.getPassword())) { + conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); + } + this.baseMapper.updateById(conf); + return Boolean.TRUE; + } + + /** + * 通过数据源名称删除 + * @param dsIds 数据源ID + * @return + */ + @Override + public Boolean removeByDsId(Long[] dsIds) { + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + this.baseMapper.selectBatchIds(CollUtil.toList(dsIds)) + .forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName())); + this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds)); + return Boolean.TRUE; + } + + /** + * 添加动态数据源 + * @param conf 数据源信息 + */ + @Override + public void addDynamicDataSource(GenDatasourceConf conf) { + DataSourceProperty dataSourceProperty = new DataSourceProperty(); + dataSourceProperty.setPoolName(conf.getName()); + dataSourceProperty.setUrl(conf.getUrl()); + dataSourceProperty.setUsername(conf.getUsername()); + dataSourceProperty.setPassword(conf.getPassword()); + DataSource dataSource = hikariDataSourceCreator.createDataSource(dataSourceProperty); + + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource); + } + + /** + * 校验数据源配置是否有效 + * @param conf 数据源信息 + * @return 有效/无效 + */ + @Override + public Boolean checkDataSource(GenDatasourceConf conf) { + String url; + // JDBC 配置形式 + if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) { + url = conf.getUrl(); + } + else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) { + // 主机形式 sql server 特殊处理 + DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); + url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); + } + else { + DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); + url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); + } + + conf.setUrl(url); + + try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) { + } + catch (SQLException e) { + log.error("数据源配置 {} , 获取链接失败", conf.getName(), e); + throw new RuntimeException("数据库配置错误,链接失败"); + } + return Boolean.TRUE; + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java index 706031b19..c89003e6b 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java @@ -63,194 +63,188 @@ @RequiredArgsConstructor public class GenTableServiceImpl extends ServiceImpl implements GenTableService { - private final PigCodeGenDefaultProperties configurationProperties; - - private final GenTableColumnService columnService; - - private final GenGroupService genGroupService; - - /** - * 查询表ddl 语句 - * - * @param dsName 数据源名称 - * @param tableName 表名称 - * @return ddl 语句 - * @throws Exception - */ - @Override - public String queryTableDdl(String dsName, String tableName) throws Exception { - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); - Table table = ServiceProxy.metadata().table(tableName); // 获取表结构 - table.execute(false);// 不执行SQL - ServiceProxy.ddl().create(table); - return table.getDdl();// 返回创建表的DDL - } - - /** - * 查询表的全部字段 - * - * @param dsName 数据源 - * @param tableName 表名称 - * @return column - */ - @Override - public List queryTableColumn(String dsName, String tableName) { - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); - return ServiceProxy.metadata().columns(tableName).values().stream().map(Column::getName).toList(); - } - - /** - * 查询对应数据源的表 - * - * @param page 分页信息 - * @param table 查询条件 - * @return 表 - */ - @Override - public IPage queryTablePage(Page
page, GenTable table) { - // 手动切换数据源 - DynamicDataSourceContextHolder.push(table.getDsName()); - List
tableList = ServiceProxy.metadata().tables().values().stream().filter(t -> { - if (StrUtil.isBlank(table.getTableName())) { - return true; - } - return StrUtil.containsIgnoreCase(t.getName(false), table.getTableName()); - }).toList(); - - // 根据 page 进行分页 - List
records = CollUtil.page((int) page.getCurrent() - 1, (int) page.getSize(), tableList); - page.setTotal(tableList.size()); - page.setRecords(records); - return page; - } - - /** - * 查询数据源里面的全部表 - * - * @param dsName 数据源名称 - * @return table - */ - @Override - public List queryTableList(String dsName) { - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); - return ServiceProxy.metadata().tables().values().stream().map(Table::getName).toList(); - } - - /** - * 查询表信息(列),然后插入到中间表中 - * - * @param dsName 数据源 - * @param tableName 表名 - * @return GenTable - */ - @Override - public GenTable queryOrBuildTable(String dsName, String tableName) { - GenTable genTable = baseMapper.selectOne( - Wrappers.lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName)); - // 如果 genTable 为空, 执行导入 - if (Objects.isNull(genTable)) { - genTable = this.tableImport(dsName, tableName); - } - - List fieldList = columnService.list(Wrappers.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, dsName) - .eq(GenTableColumnEntity::getTableName, tableName) - .orderByAsc(GenTableColumnEntity::getSort)); - genTable.setFieldList(fieldList); - - // 查询模板分组信息 - List groupEntities = genGroupService.list(); - genTable.setGroupList(groupEntities); - return genTable; - } - - @Transactional(rollbackFor = Exception.class) - protected GenTable tableImport(String dsName, String tableName) { - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); - - // 查询表是否存在 - GenTable table = new GenTable(); - // 从数据库获取表信息 - AnylineService service = ServiceProxy.service(); - Table tableMetadata = service.metadata().table(tableName); - Database database = service.metadata().database(); - // 获取默认表配置信息 () - - table.setPackageName(configurationProperties.getPackageName()); - table.setVersion(configurationProperties.getVersion()); - table.setBackendPath(configurationProperties.getBackendPath()); - table.setFrontendPath(configurationProperties.getFrontendPath()); - table.setAuthor(configurationProperties.getAuthor()); - table.setEmail(configurationProperties.getEmail()); - table.setTableName(tableName); - table.setDsName(dsName); - table.setTableComment(tableMetadata.getComment()); - - table.setDbType(database.getDatabase().title()); - table.setFormLayout(configurationProperties.getFormLayout()); - table.setGeneratorType(configurationProperties.getGeneratorType()); - table.setClassName(NamingCase.toPascalCase(tableName)); - // 模块名称默认为 admin - table.setModuleName(configurationProperties.getModuleName()); - table.setFunctionName(GenKit.getFunctionName(tableName)); - table.setCreateTime(LocalDateTime.now()); - - // 使用默认数据源 - DynamicDataSourceContextHolder.clear(); - this.save(table); - - // 获取原生字段数据 - List tableFieldList = getGenTableColumnEntities(dsName, tableName, tableMetadata); - - // 初始化字段数据 - columnService.initFieldList(tableFieldList); - // 保存列数据 - columnService.saveOrUpdateBatch(tableFieldList); - - table.setFieldList(tableFieldList); - return table; - } - - /** - * 获取表字段信息 - * - * @param dsName 数据源信息 - * @param tableName 表名称 - * @param tableMetadata 表的元数据 - * @return list - */ - private static @NotNull List getGenTableColumnEntities(String dsName, String tableName, - Table tableMetadata) { - List tableFieldList = new ArrayList<>(); - LinkedHashMap columns = tableMetadata.getColumns(); - columns.forEach((columnName, column) -> { - GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity(); - genTableColumnEntity.setTableName(tableName); - genTableColumnEntity.setDsName(dsName); - genTableColumnEntity.setFieldName(column.getName()); - genTableColumnEntity.setFieldComment(column.getComment()); - genTableColumnEntity.setFieldType(column.getTypeName()); - genTableColumnEntity.setPrimaryPk( - column.isPrimaryKey() == 1 ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue()); - genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name()); - genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue()); - genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue()); - - // 审计字段处理 - if (EnumUtil.contains(CommonColumnFiledEnum.class, column.getName())) { - CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(column.getName()); - genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem()); - genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem()); - genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill()); - genTableColumnEntity.setSort(commonColumnFiledEnum.getSort()); - } - tableFieldList.add(genTableColumnEntity); - }); - return tableFieldList; - } + private final PigCodeGenDefaultProperties configurationProperties; + + private final GenTableColumnService columnService; + + private final GenGroupService genGroupService; + + /** + * 查询表ddl 语句 + * @param dsName 数据源名称 + * @param tableName 表名称 + * @return ddl 语句 + * @throws Exception + */ + @Override + public String queryTableDdl(String dsName, String tableName) throws Exception { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + Table table = ServiceProxy.metadata().table(tableName); // 获取表结构 + table.execute(false);// 不执行SQL + ServiceProxy.ddl().create(table); + return table.getDdl();// 返回创建表的DDL + } + + /** + * 查询表的全部字段 + * @param dsName 数据源 + * @param tableName 表名称 + * @return column + */ + @Override + public List queryTableColumn(String dsName, String tableName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + return ServiceProxy.metadata().columns(tableName).values().stream().map(Column::getName).toList(); + } + + /** + * 查询对应数据源的表 + * @param page 分页信息 + * @param table 查询条件 + * @return 表 + */ + @Override + public IPage queryTablePage(Page
page, GenTable table) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(table.getDsName()); + List
tableList = ServiceProxy.metadata().tables().values().stream().filter(t -> { + if (StrUtil.isBlank(table.getTableName())) { + return true; + } + return StrUtil.containsIgnoreCase(t.getName(false), table.getTableName()); + }).toList(); + + // 根据 page 进行分页 + List
records = CollUtil.page((int) page.getCurrent() - 1, (int) page.getSize(), tableList); + page.setTotal(tableList.size()); + page.setRecords(records); + return page; + } + + /** + * 查询数据源里面的全部表 + * @param dsName 数据源名称 + * @return table + */ + @Override + public List queryTableList(String dsName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + return ServiceProxy.metadata().tables().values().stream().map(Table::getName).toList(); + } + + /** + * 查询表信息(列),然后插入到中间表中 + * @param dsName 数据源 + * @param tableName 表名 + * @return GenTable + */ + @Override + public GenTable queryOrBuildTable(String dsName, String tableName) { + GenTable genTable = baseMapper.selectOne( + Wrappers.lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName)); + // 如果 genTable 为空, 执行导入 + if (Objects.isNull(genTable)) { + genTable = this.tableImport(dsName, tableName); + } + + List fieldList = columnService.list(Wrappers.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, dsName) + .eq(GenTableColumnEntity::getTableName, tableName) + .orderByAsc(GenTableColumnEntity::getSort)); + genTable.setFieldList(fieldList); + + // 查询模板分组信息 + List groupEntities = genGroupService.list(); + genTable.setGroupList(groupEntities); + return genTable; + } + + @Transactional(rollbackFor = Exception.class) + protected GenTable tableImport(String dsName, String tableName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + + // 查询表是否存在 + GenTable table = new GenTable(); + // 从数据库获取表信息 + AnylineService service = ServiceProxy.service(); + Table tableMetadata = service.metadata().table(tableName); + Database database = service.metadata().database(); + // 获取默认表配置信息 () + + table.setPackageName(configurationProperties.getPackageName()); + table.setVersion(configurationProperties.getVersion()); + table.setBackendPath(configurationProperties.getBackendPath()); + table.setFrontendPath(configurationProperties.getFrontendPath()); + table.setAuthor(configurationProperties.getAuthor()); + table.setEmail(configurationProperties.getEmail()); + table.setTableName(tableName); + table.setDsName(dsName); + table.setTableComment(tableMetadata.getComment()); + + table.setDbType(database.getDatabase().title()); + table.setFormLayout(configurationProperties.getFormLayout()); + table.setGeneratorType(configurationProperties.getGeneratorType()); + table.setClassName(NamingCase.toPascalCase(tableName)); + // 模块名称默认为 admin + table.setModuleName(configurationProperties.getModuleName()); + table.setFunctionName(GenKit.getFunctionName(tableName)); + table.setCreateTime(LocalDateTime.now()); + + // 使用默认数据源 + DynamicDataSourceContextHolder.clear(); + this.save(table); + + // 获取原生字段数据 + List tableFieldList = getGenTableColumnEntities(dsName, tableName, tableMetadata); + + // 初始化字段数据 + columnService.initFieldList(tableFieldList); + // 保存列数据 + columnService.saveOrUpdateBatch(tableFieldList); + + table.setFieldList(tableFieldList); + return table; + } + + /** + * 获取表字段信息 + * @param dsName 数据源信息 + * @param tableName 表名称 + * @param tableMetadata 表的元数据 + * @return list + */ + private static @NotNull List getGenTableColumnEntities(String dsName, String tableName, + Table tableMetadata) { + List tableFieldList = new ArrayList<>(); + LinkedHashMap columns = tableMetadata.getColumns(); + columns.forEach((columnName, column) -> { + GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity(); + genTableColumnEntity.setTableName(tableName); + genTableColumnEntity.setDsName(dsName); + genTableColumnEntity.setFieldName(column.getName()); + genTableColumnEntity.setFieldComment(column.getComment()); + genTableColumnEntity.setFieldType(column.getTypeName()); + genTableColumnEntity.setPrimaryPk( + column.isPrimaryKey() == 1 ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue()); + genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name()); + genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue()); + genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue()); + + // 审计字段处理 + if (EnumUtil.contains(CommonColumnFiledEnum.class, column.getName())) { + CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(column.getName()); + genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem()); + genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem()); + genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill()); + genTableColumnEntity.setSort(commonColumnFiledEnum.getSort()); + } + tableFieldList.add(genTableColumnEntity); + }); + return tableFieldList; + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java index ad7604412..b92d28863 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java @@ -56,143 +56,140 @@ @Service @RequiredArgsConstructor public class GenTemplateServiceImpl extends ServiceImpl - implements GenTemplateService { - - private final GenTemplateGroupMapper genTemplateGroupMapper; - - private final GenGroupMapper genGroupMapper; - - private final PigCodeGenDefaultProperties defaultProperties; - - /** - * 在线更新 - * - * @return {@link R } - */ - @Override - @Transactional(rollbackFor = Exception.class) - public R onlineUpdate() { - // 获取 config.json 和 version 文件 - Map configAndVersion = getConfigAndVersion(); - JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); - String versionFile = (String) configAndVersion.get("versionFile"); - - // 查询出全部的模板组名称 - Set cgtmConfigGroupNames = configJsonObj.keySet(); - - String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); - // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 - boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() - .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); - - if (exists) { - return R.failed("已是最新版本,无需更新!"); - } - - // 插入新的模板组(名称 + VERSION), 再解析 config.json group 里面的所有模板 - insertTemplateFiles(versionFile, configJsonObj, cgtmConfigGroupName); - return R.ok("更新成功,版本号:" + versionFile); - } - - /** - * 检查版本 - * - * @return {@link R } - */ - public R checkVersion() { - // 关闭在线更新提示 - if (!defaultProperties.isAutoCheckVersion()) { - return R.ok(true); - } - - // 获取 config.json 和 version 文件 - Map configAndVersion = getConfigAndVersion(); - JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); - String versionFile = (String) configAndVersion.get("versionFile"); - - // 查询出全部的模板组名称 - Set cgtmConfigGroupNames = configJsonObj.keySet(); - - String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); - // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 - boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() - .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); - - return R.ok(exists); - } - - /** - * 获取配置和版本 - * - * @return {@link Map }<{@link String }, {@link Object }> - */ - private Map getConfigAndVersion() { - // 获取 config.json 和 version 文件 - String configFile = getCGTMFile("config.json"); - String versionFile = getCGTMFile("VERSION"); - - // 解析 config.json - JSONObject configJsonObj = JSONUtil.parseObj(configFile); - - // 将 configJsonObj 和 versionFile 放入 Map 中 - Map configAndVersion = new HashMap<>(); - configAndVersion.put("configJsonObj", configJsonObj); - configAndVersion.put("versionFile", versionFile); - - return configAndVersion; - } - - /** - * 插入模板文件 - * - * @param version 版本 - * @param configJsonObj config.json - * @param groupName 组名称 - */ - private void insertTemplateFiles(String version, JSONObject configJsonObj, String groupName) { - // 创建新的 group - GenGroupEntity genGroupEntity = new GenGroupEntity(); - genGroupEntity.setGroupName(groupName + version); - genGroupMapper.insert(genGroupEntity); - - // 解析json配置文件 - List templateFileVOList = configJsonObj.getBeanList(groupName, GenTemplateFileVO.class); - for (GenTemplateFileVO genTemplateFileVO : templateFileVOList) { - // 1. 获取模板文件 - String templateFile = getCGTMFile(genTemplateFileVO.getTemplateFile()); - - // 2. 插入模板文件 - GenTemplateEntity genTemplateEntity = new GenTemplateEntity(); - genTemplateEntity.setTemplateName(genTemplateFileVO.getTemplateName() + version); - genTemplateEntity.setTemplateDesc(genTemplateFileVO.getTemplateName() + version); - genTemplateEntity.setTemplateCode(templateFile); - genTemplateEntity.setGeneratorPath(genTemplateFileVO.getGeneratorPath()); - baseMapper.insert(genTemplateEntity); - - // 3. 插入模板组关联 - GenTemplateGroupEntity genTemplateGroupEntity = new GenTemplateGroupEntity(); - genTemplateGroupEntity.setTemplateId(genTemplateEntity.getId()); - genTemplateGroupEntity.setGroupId(genGroupEntity.getId()); - genTemplateGroupMapper.insert(genTemplateGroupEntity); - } - } - - - /** - * 获取 cgtmfile - * - * @param fileName 文件名 - * @return {@link String } - */ - private String getCGTMFile(String fileName) { - HttpResponse response = HttpRequest.get(String.format("%s/CGTM/raw/master/%s", DefaultConstants.CGTM_URL, fileName)) - .execute(); - - if (response.getStatus() == HttpStatus.HTTP_OK || StrUtil.isNotBlank(response.body())) { - return response.body(); - } else { - log.warn("在线更新模板失败:{} ,Http Code:{}", fileName, response.getStatus()); - throw new CheckedException("在线更新模板失败,任务终止!"); - } - } + implements GenTemplateService { + + private final GenTemplateGroupMapper genTemplateGroupMapper; + + private final GenGroupMapper genGroupMapper; + + private final PigCodeGenDefaultProperties defaultProperties; + + /** + * 在线更新 + * @return {@link R } + */ + @Override + @Transactional(rollbackFor = Exception.class) + public R onlineUpdate() { + // 获取 config.json 和 version 文件 + Map configAndVersion = getConfigAndVersion(); + JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); + String versionFile = (String) configAndVersion.get("versionFile"); + + // 查询出全部的模板组名称 + Set cgtmConfigGroupNames = configJsonObj.keySet(); + + String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); + // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 + boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() + .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); + + if (exists) { + return R.failed("已是最新版本,无需更新!"); + } + + // 插入新的模板组(名称 + VERSION), 再解析 config.json group 里面的所有模板 + insertTemplateFiles(versionFile, configJsonObj, cgtmConfigGroupName); + return R.ok("更新成功,版本号:" + versionFile); + } + + /** + * 检查版本 + * @return {@link R } + */ + public R checkVersion() { + // 关闭在线更新提示 + if (!defaultProperties.isAutoCheckVersion()) { + return R.ok(true); + } + + // 获取 config.json 和 version 文件 + Map configAndVersion = getConfigAndVersion(); + JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); + String versionFile = (String) configAndVersion.get("versionFile"); + + // 查询出全部的模板组名称 + Set cgtmConfigGroupNames = configJsonObj.keySet(); + + String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); + // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 + boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() + .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); + + return R.ok(exists); + } + + /** + * 获取配置和版本 + * @return {@link Map }<{@link String }, {@link Object }> + */ + private Map getConfigAndVersion() { + // 获取 config.json 和 version 文件 + String configFile = getCGTMFile("config.json"); + String versionFile = getCGTMFile("VERSION"); + + // 解析 config.json + JSONObject configJsonObj = JSONUtil.parseObj(configFile); + + // 将 configJsonObj 和 versionFile 放入 Map 中 + Map configAndVersion = new HashMap<>(); + configAndVersion.put("configJsonObj", configJsonObj); + configAndVersion.put("versionFile", versionFile); + + return configAndVersion; + } + + /** + * 插入模板文件 + * @param version 版本 + * @param configJsonObj config.json + * @param groupName 组名称 + */ + private void insertTemplateFiles(String version, JSONObject configJsonObj, String groupName) { + // 创建新的 group + GenGroupEntity genGroupEntity = new GenGroupEntity(); + genGroupEntity.setGroupName(groupName + version); + genGroupMapper.insert(genGroupEntity); + + // 解析json配置文件 + List templateFileVOList = configJsonObj.getBeanList(groupName, GenTemplateFileVO.class); + for (GenTemplateFileVO genTemplateFileVO : templateFileVOList) { + // 1. 获取模板文件 + String templateFile = getCGTMFile(genTemplateFileVO.getTemplateFile()); + + // 2. 插入模板文件 + GenTemplateEntity genTemplateEntity = new GenTemplateEntity(); + genTemplateEntity.setTemplateName(genTemplateFileVO.getTemplateName() + version); + genTemplateEntity.setTemplateDesc(genTemplateFileVO.getTemplateName() + version); + genTemplateEntity.setTemplateCode(templateFile); + genTemplateEntity.setGeneratorPath(genTemplateFileVO.getGeneratorPath()); + baseMapper.insert(genTemplateEntity); + + // 3. 插入模板组关联 + GenTemplateGroupEntity genTemplateGroupEntity = new GenTemplateGroupEntity(); + genTemplateGroupEntity.setTemplateId(genTemplateEntity.getId()); + genTemplateGroupEntity.setGroupId(genGroupEntity.getId()); + genTemplateGroupMapper.insert(genTemplateGroupEntity); + } + } + + /** + * 获取 cgtmfile + * @param fileName 文件名 + * @return {@link String } + */ + private String getCGTMFile(String fileName) { + HttpResponse response = HttpRequest + .get(String.format("%s/CGTM/raw/master/%s", DefaultConstants.CGTM_URL, fileName)) + .execute(); + + if (response.getStatus() == HttpStatus.HTTP_OK || StrUtil.isNotBlank(response.body())) { + return response.body(); + } + else { + log.warn("在线更新模板失败:{} ,Http Code:{}", fileName, response.getStatus()); + throw new CheckedException("在线更新模板失败,任务终止!"); + } + } + } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java index 3e1d7d112..aec0bac02 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java @@ -56,237 +56,234 @@ @RequiredArgsConstructor public class GeneratorServiceImpl implements GeneratorService { - private final PigCodeGenDefaultProperties configurationProperties; - - private final GenTableColumnService columnService; - - private final GenFieldTypeService fieldTypeService; - - private final GenTableService tableService; - - private final GenGroupService genGroupService; - - - /** - * 生成代码zip写出 - * - * @param tableId 表 - * @param zip 输出流 - */ - @Override - @SneakyThrows - public void downloadCode(Long tableId, ZipOutputStream zip) { - // 数据模型 - Map dataModel = getDataModel(tableId); - - Long style = (Long) dataModel.get("style"); - - GroupVO groupVo = genGroupService.getGroupVoById(style); - List templateList = groupVo.getTemplateList(); - - String frontendPath = configurationProperties.getFrontendPath(); - String backendPath = configurationProperties.getBackendPath(); - - for (GenTemplateEntity template : templateList) { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); - - dataModel.put("frontendPath", frontendPath); - dataModel.put("backendPath", backendPath); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); - - // 添加到zip - zip.putNextEntry(new ZipEntry(path)); - IoUtil.writeUtf8(zip, false, content); - zip.flush(); - zip.closeEntry(); - } - - } - - /** - * 表达式优化的预览代码方法 - * - * @param tableId 表 - * @return [{模板名称:渲染结果}] - */ - @Override - @SneakyThrows - public List> preview(Long tableId) { - // 数据模型 - Map dataModel = getDataModel(tableId); - - Long style = (Long) dataModel.get("style"); - - // 获取模板列表,Lambda 表达式简化代码 - List templateList = genGroupService.getGroupVoById(style).getTemplateList(); - - String frontendPath = configurationProperties.getFrontendPath(); - String backendPath = configurationProperties.getBackendPath(); - - return templateList.stream().map(template -> { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); - - // 预览模式下, 使用相对路径展示 - dataModel.put("frontendPath", frontendPath); - dataModel.put("backendPath", backendPath); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); - - // 使用 map 简化代码 - return new HashMap(4) { - { - put("code", content); - put("codePath", path); - } - }; - }).collect(Collectors.toList()); - } - - /** - * 目标目录写入渲染结果方法 - * - * @param tableId 表 - */ - @Override - public void generatorCode(Long tableId) { - // 数据模型 - Map dataModel = getDataModel(tableId); - Long style = (Long) dataModel.get("style"); - - // 获取模板列表,Lambda 表达式简化代码 - List templateList = genGroupService.getGroupVoById(style).getTemplateList(); - - templateList.forEach(template -> { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); - FileUtil.writeUtf8String(content, path); - }); - } - - - /** - * 通过 Lambda 表达式优化的获取数据模型方法 - * - * @param tableId 表格 ID - * @return 数据模型 Map 对象 - */ - private Map getDataModel(Long tableId) { - // 获取表格信息 - GenTable table = tableService.getById(tableId); - // 获取字段列表 - List fieldList = columnService.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, table.getDsName()) - .eq(GenTableColumnEntity::getTableName, table.getTableName()) - .orderByAsc(GenTableColumnEntity::getSort) - .list(); - - table.setFieldList(fieldList); - - // 创建数据模型对象 - Map dataModel = new HashMap<>(); - - // 填充数据模型 - dataModel.put("isSpringBoot3", isSpringBoot3()); - dataModel.put("dbType", table.getDbType()); - dataModel.put("package", table.getPackageName()); - dataModel.put("packagePath", table.getPackageName().replace(".", "/")); - dataModel.put("version", table.getVersion()); - dataModel.put("moduleName", table.getModuleName()); - dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName())); - dataModel.put("functionName", table.getFunctionName()); - dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName())); - dataModel.put("formLayout", table.getFormLayout()); - dataModel.put("style", table.getStyle()); - dataModel.put("author", table.getAuthor()); - dataModel.put("datetime", DateUtil.now()); - dataModel.put("date", DateUtil.today()); - setFieldTypeList(dataModel, table); - - // 获取导入的包列表 - Set importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName()); - dataModel.put("importList", importList); - dataModel.put("tableName", table.getTableName()); - dataModel.put("tableComment", table.getTableComment()); - dataModel.put("className", StrUtil.lowerFirst(table.getClassName())); - dataModel.put("ClassName", table.getClassName()); - dataModel.put("fieldList", table.getFieldList()); - - dataModel.put("backendPath", table.getBackendPath()); - dataModel.put("frontendPath", table.getFrontendPath()); - - // 设置子表 - String childTableName = table.getChildTableName(); - if (StrUtil.isNotBlank(childTableName)) { - List childFieldList = columnService.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, table.getDsName()) - .eq(GenTableColumnEntity::getTableName, table.getChildTableName()) - .list(); - dataModel.put("childFieldList", childFieldList); - dataModel.put("childTableName", childTableName); - dataModel.put("mainField", NamingCase.toCamelCase(table.getMainField())); - dataModel.put("childField", NamingCase.toCamelCase(table.getChildField())); - dataModel.put("ChildClassName", NamingCase.toPascalCase(childTableName)); - dataModel.put("childClassName", StrUtil.lowerFirst(NamingCase.toPascalCase(childTableName))); - // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) - childFieldList.stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) - .findFirst().ifPresent(columnEntity -> dataModel.put("isChildTenant", true)); - } - - // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) - table.getFieldList().stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) - .findFirst().ifPresent(columnEntity -> dataModel.put("isTenant", true)); - - return dataModel; - } - - /** - * 判断当前是否是 SpringBoot3 版本 - * - * @return true/fasle - */ - private boolean isSpringBoot3() { - return StrUtil.startWith(SpringBootVersion.getVersion(), "3"); - } - - /** - * 将表字段按照类型分组并存储到数据模型中 - * - * @param dataModel 存储数据的 Map 对象 - * @param table 表信息对象 - */ - private void setFieldTypeList(Map dataModel, GenTable table) { - // 按字段类型分组,使用 Map 存储不同类型的字段列表 - Map> typeMap = table.getFieldList() - .stream() - .collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk()))); - - // 从分组后的 Map 中获取不同类型的字段列表 - List primaryList = typeMap.get(true); - List formList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem())) - .collect(Collectors.toList()); - List gridList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem())) - .collect(Collectors.toList()); - List queryList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem())) - .collect(Collectors.toList()); - - if (CollUtil.isNotEmpty(primaryList)) { - dataModel.put("pk", primaryList.get(0)); - } - dataModel.put("primaryList", primaryList); - dataModel.put("formList", formList); - dataModel.put("gridList", gridList); - dataModel.put("queryList", queryList); - } + private final PigCodeGenDefaultProperties configurationProperties; + + private final GenTableColumnService columnService; + + private final GenFieldTypeService fieldTypeService; + + private final GenTableService tableService; + + private final GenGroupService genGroupService; + + /** + * 生成代码zip写出 + * @param tableId 表 + * @param zip 输出流 + */ + @Override + @SneakyThrows + public void downloadCode(Long tableId, ZipOutputStream zip) { + // 数据模型 + Map dataModel = getDataModel(tableId); + + Long style = (Long) dataModel.get("style"); + + GroupVO groupVo = genGroupService.getGroupVoById(style); + List templateList = groupVo.getTemplateList(); + + String frontendPath = configurationProperties.getFrontendPath(); + String backendPath = configurationProperties.getBackendPath(); + + for (GenTemplateEntity template : templateList) { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); + + dataModel.put("frontendPath", frontendPath); + dataModel.put("backendPath", backendPath); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); + + // 添加到zip + zip.putNextEntry(new ZipEntry(path)); + IoUtil.writeUtf8(zip, false, content); + zip.flush(); + zip.closeEntry(); + } + + } + + /** + * 表达式优化的预览代码方法 + * @param tableId 表 + * @return [{模板名称:渲染结果}] + */ + @Override + @SneakyThrows + public List> preview(Long tableId) { + // 数据模型 + Map dataModel = getDataModel(tableId); + + Long style = (Long) dataModel.get("style"); + + // 获取模板列表,Lambda 表达式简化代码 + List templateList = genGroupService.getGroupVoById(style).getTemplateList(); + + String frontendPath = configurationProperties.getFrontendPath(); + String backendPath = configurationProperties.getBackendPath(); + + return templateList.stream().map(template -> { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); + + // 预览模式下, 使用相对路径展示 + dataModel.put("frontendPath", frontendPath); + dataModel.put("backendPath", backendPath); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); + + // 使用 map 简化代码 + return new HashMap(4) { + { + put("code", content); + put("codePath", path); + } + }; + }).collect(Collectors.toList()); + } + + /** + * 目标目录写入渲染结果方法 + * @param tableId 表 + */ + @Override + public void generatorCode(Long tableId) { + // 数据模型 + Map dataModel = getDataModel(tableId); + Long style = (Long) dataModel.get("style"); + + // 获取模板列表,Lambda 表达式简化代码 + List templateList = genGroupService.getGroupVoById(style).getTemplateList(); + + templateList.forEach(template -> { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); + FileUtil.writeUtf8String(content, path); + }); + } + + /** + * 通过 Lambda 表达式优化的获取数据模型方法 + * @param tableId 表格 ID + * @return 数据模型 Map 对象 + */ + private Map getDataModel(Long tableId) { + // 获取表格信息 + GenTable table = tableService.getById(tableId); + // 获取字段列表 + List fieldList = columnService.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, table.getDsName()) + .eq(GenTableColumnEntity::getTableName, table.getTableName()) + .orderByAsc(GenTableColumnEntity::getSort) + .list(); + + table.setFieldList(fieldList); + + // 创建数据模型对象 + Map dataModel = new HashMap<>(); + + // 填充数据模型 + dataModel.put("isSpringBoot3", isSpringBoot3()); + dataModel.put("dbType", table.getDbType()); + dataModel.put("package", table.getPackageName()); + dataModel.put("packagePath", table.getPackageName().replace(".", "/")); + dataModel.put("version", table.getVersion()); + dataModel.put("moduleName", table.getModuleName()); + dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName())); + dataModel.put("functionName", table.getFunctionName()); + dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName())); + dataModel.put("formLayout", table.getFormLayout()); + dataModel.put("style", table.getStyle()); + dataModel.put("author", table.getAuthor()); + dataModel.put("datetime", DateUtil.now()); + dataModel.put("date", DateUtil.today()); + setFieldTypeList(dataModel, table); + + // 获取导入的包列表 + Set importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName()); + dataModel.put("importList", importList); + dataModel.put("tableName", table.getTableName()); + dataModel.put("tableComment", table.getTableComment()); + dataModel.put("className", StrUtil.lowerFirst(table.getClassName())); + dataModel.put("ClassName", table.getClassName()); + dataModel.put("fieldList", table.getFieldList()); + + dataModel.put("backendPath", table.getBackendPath()); + dataModel.put("frontendPath", table.getFrontendPath()); + + // 设置子表 + String childTableName = table.getChildTableName(); + if (StrUtil.isNotBlank(childTableName)) { + List childFieldList = columnService.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, table.getDsName()) + .eq(GenTableColumnEntity::getTableName, table.getChildTableName()) + .list(); + dataModel.put("childFieldList", childFieldList); + dataModel.put("childTableName", childTableName); + dataModel.put("mainField", NamingCase.toCamelCase(table.getMainField())); + dataModel.put("childField", NamingCase.toCamelCase(table.getChildField())); + dataModel.put("ChildClassName", NamingCase.toPascalCase(childTableName)); + dataModel.put("childClassName", StrUtil.lowerFirst(NamingCase.toPascalCase(childTableName))); + // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) + childFieldList.stream() + .filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) + .findFirst() + .ifPresent(columnEntity -> dataModel.put("isChildTenant", true)); + } + + // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) + table.getFieldList() + .stream() + .filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) + .findFirst() + .ifPresent(columnEntity -> dataModel.put("isTenant", true)); + + return dataModel; + } + + /** + * 判断当前是否是 SpringBoot3 版本 + * @return true/fasle + */ + private boolean isSpringBoot3() { + return StrUtil.startWith(SpringBootVersion.getVersion(), "3"); + } + + /** + * 将表字段按照类型分组并存储到数据模型中 + * @param dataModel 存储数据的 Map 对象 + * @param table 表信息对象 + */ + private void setFieldTypeList(Map dataModel, GenTable table) { + // 按字段类型分组,使用 Map 存储不同类型的字段列表 + Map> typeMap = table.getFieldList() + .stream() + .collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk()))); + + // 从分组后的 Map 中获取不同类型的字段列表 + List primaryList = typeMap.get(true); + List formList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem())) + .collect(Collectors.toList()); + List gridList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem())) + .collect(Collectors.toList()); + List queryList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem())) + .collect(Collectors.toList()); + + if (CollUtil.isNotEmpty(primaryList)) { + dataModel.put("pk", primaryList.get(0)); + } + dataModel.put("primaryList", primaryList); + dataModel.put("formList", formList); + dataModel.put("gridList", gridList); + dataModel.put("queryList", queryList); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java index 5eb4413c3..aff2918d2 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java @@ -8,30 +8,31 @@ *

* CGTM 文件路径 *

- * { - * "templateName": "Controller", - * "generatorPath": "${backendPath}/src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java", - * "templateDesc": "后台Controller", - * "templateFile": "temps/Controller" - * }, + * { "templateName": "Controller", "generatorPath": + * "${backendPath}/src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java", + * "templateDesc": "后台Controller", "templateFile": "temps/Controller" }, */ @Data public class GenTemplateFileVO { - /** - * 模板名称 - */ - private String templateName; - /** - * 路径 - */ - private String generatorPath; - /** - * 模板 desc - */ - private String templateDesc; - /** - * 模板文件 - */ - private String templateFile; + + /** + * 模板名称 + */ + private String templateName; + + /** + * 路径 + */ + private String generatorPath; + + /** + * 模板 desc + */ + private String templateDesc; + + /** + * 模板文件 + */ + private String templateFile; }