├── .vscode └── extensions.json ├── public └── favicon.ico ├── doc └── assets │ ├── main.png │ ├── invokeTree.png │ ├── complex-example.png │ └── complex-example-result.png ├── tsconfig.node.json ├── src ├── main.ts ├── main.js ├── examples │ ├── index.ts │ ├── init.json │ └── complex.json ├── env.d.ts ├── main.js.map ├── generator │ ├── type.d.ts │ └── index.ts ├── components │ └── SearchableTree.vue └── App.vue ├── Dockerfile ├── vite.config.ts ├── .gitignore ├── .eslintrc.js ├── tsconfig.json ├── index.html ├── package.json ├── README.md └── LICENSE /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["Vue.volar"] 3 | } 4 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyupi/sql-generator/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /doc/assets/main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyupi/sql-generator/HEAD/doc/assets/main.png -------------------------------------------------------------------------------- /doc/assets/invokeTree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyupi/sql-generator/HEAD/doc/assets/invokeTree.png -------------------------------------------------------------------------------- /doc/assets/complex-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyupi/sql-generator/HEAD/doc/assets/complex-example.png -------------------------------------------------------------------------------- /doc/assets/complex-example-result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyupi/sql-generator/HEAD/doc/assets/complex-example-result.png -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "module": "esnext", 5 | "moduleResolution": "node" 6 | }, 7 | "include": [ 8 | "vite.config.ts" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { createApp } from "vue"; 2 | import App from "./App.vue"; 3 | import Antd from "ant-design-vue"; 4 | import "ant-design-vue/dist/antd.css"; 5 | 6 | const app = createApp(App); 7 | app.use(Antd).mount("#app"); 8 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18-buster-slim 2 | 3 | RUN npm install -g http-server 4 | 5 | WORKDIR /src 6 | 7 | COPY . . 8 | 9 | RUN npm install 10 | 11 | RUN npm run build 12 | 13 | EXPOSE 8080 14 | CMD [ "http-server", "dist" ] -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vite"; 2 | import vue from "@vitejs/plugin-vue"; 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | server: { 7 | open: true, 8 | hmr: true, 9 | }, 10 | plugins: [vue()], 11 | }); 12 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue'; 2 | import TDesign from 'tdesign-vue-next'; 3 | import App from './app.vue'; 4 | // 引入组件库全局样式资源 5 | import 'tdesign-vue-next/es/style/index.css'; 6 | const app = createApp(App); 7 | app.use(TDesign); 8 | app.mount('#app'); 9 | //# sourceMappingURL=main.js.map -------------------------------------------------------------------------------- /src/examples/index.ts: -------------------------------------------------------------------------------- 1 | import init from "./init.json"; 2 | import complex from "./complex.json"; 3 | 4 | const exampleMap: Record = { 5 | init, 6 | complex, 7 | }; 8 | 9 | export const importExample = (key: string) => { 10 | return JSON.stringify(exampleMap[key]); 11 | }; 12 | -------------------------------------------------------------------------------- /src/examples/init.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "必填, 代码从这里开始生成, 用 @规则名() 引用其他语句", 3 | "规则名": "可以编写任意 SQL 语句 @规则名2() @动态传参(a = 求给 ||| b = star)", 4 | "规则名2": { 5 | "sql": "用 #{参数名} 指定可被替换的值", 6 | "params": { 7 | "参数名": "在 params 中指定静态参数, 会优先被替换" 8 | } 9 | }, 10 | "动态传参": "#{a}鱼皮#{b}" 11 | } -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module "*.vue" { 4 | import type { DefineComponent } from "vue"; 5 | // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types 6 | const component: DefineComponent<{}, {}, any>; 7 | export default component; 8 | } 9 | -------------------------------------------------------------------------------- /src/main.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAChC,OAAO,OAAO,MAAM,kBAAkB,CAAC;AACvC,OAAO,GAAG,MAAM,WAAW,CAAC;AAE5B,cAAc;AACd,OAAO,qCAAqC,CAAC;AAE7C,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;AAC3B,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACjB,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC"} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | package-lock.json 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* 8 | pnpm-debug.log* 9 | lerna-debug.log* 10 | 11 | node_modules 12 | dist 13 | dist-ssr 14 | *.local 15 | 16 | # Editor directories and files 17 | .vscode/* 18 | !.vscode/extensions.json 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | node: true, 6 | }, 7 | extends: ["plugin:vue/vue3-recommended", "plugin:prettier/recommended"], 8 | parserOptions: { 9 | ecmaVersion: "latest", 10 | parser: "@typescript-eslint/parser", 11 | sourceType: "module", 12 | }, 13 | plugins: ["vue", "@typescript-eslint", "prettier"], 14 | rules: { 15 | "prettier/prettier": "error", 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /src/generator/type.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 输入 JSON Value 3 | */ 4 | interface InputJSONValue { 5 | // sql 语句 6 | sql: string; 7 | // 静态参数 8 | params?: Record; 9 | } 10 | 11 | /** 12 | * 调用树节点 13 | */ 14 | interface InvokeTreeNode { 15 | title: string; 16 | sql: string; 17 | key?: string; 18 | params?: Record; 19 | resultSQL?: string; 20 | children?: InvokeTreeNode[]; 21 | } 22 | 23 | /** 24 | * 调用树 25 | */ 26 | type InvokeTree = InvokeTreeNode[]; 27 | 28 | /** 29 | * 输入 JSON 30 | */ 31 | interface InputJSON extends Record { 32 | // 入口文件 33 | main: InputJSONValue; 34 | } 35 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "useDefineForClassFields": true, 5 | "module": "esnext", 6 | "moduleResolution": "node", 7 | "strict": true, 8 | "jsx": "preserve", 9 | "sourceMap": true, 10 | "resolveJsonModule": true, 11 | "isolatedModules": true, 12 | "esModuleInterop": true, 13 | "lib": [ 14 | "esnext", 15 | "dom" 16 | ], 17 | "skipLibCheck": true 18 | }, 19 | "include": [ 20 | "src/**/*.ts", 21 | "src/**/*.d.ts", 22 | "src/**/*.tsx", 23 | "src/**/*.vue" 24 | ], 25 | "references": [ 26 | { 27 | "path": "./tsconfig.node.json" 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 结构化 SQL 生成器 - by 鱼皮 8 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sql-generator", 3 | "private": true, 4 | "version": "0.0.1", 5 | "scripts": { 6 | "dev": "vite", 7 | "build": "vue-tsc --noEmit && vite build", 8 | "preview": "vite preview" 9 | }, 10 | "dependencies": { 11 | "@ant-design/icons-vue": "^6.1.0", 12 | "ant-design-vue": "^3.2.3", 13 | "monaco-editor": "^0.33.0", 14 | "sql-formatter": "^4.0.2", 15 | "vue": "^3.2.25" 16 | }, 17 | "devDependencies": { 18 | "@typescript-eslint/eslint-plugin": "^5.23.0", 19 | "@typescript-eslint/parser": "^5.23.0", 20 | "@vitejs/plugin-vue": "^2.3.1", 21 | "eslint": "^8.15.0", 22 | "eslint-config-prettier": "^8.5.0", 23 | "eslint-config-standard": "^17.0.0", 24 | "eslint-plugin-import": "^2.26.0", 25 | "eslint-plugin-n": "^15.2.0", 26 | "eslint-plugin-prettier": "^4.0.0", 27 | "eslint-plugin-promise": "^6.0.0", 28 | "eslint-plugin-vue": "^8.7.1", 29 | "prettier": "2.6.2", 30 | "typescript": "^4.5.4", 31 | "vite": "^2.9.7", 32 | "vue-tsc": "^0.34.7" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/examples/complex.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "select (a / b - 1) from (@查整体(date = 今天)) a, (@查整体(date = 昨天)) b", 3 | "查整体": "@查年级() union @查1班() union @查2班() where date = #{date}", 4 | "查年级": "@查汇总_性别汇总() union @查汇总_性别分组() union @查汇总_爱好汇总() union @查汇总_爱好分组() union @查汇总_电脑类别汇总() union @查汇总_电脑类别分组()", 5 | "查汇总_性别汇总": "@查除电脑关联表()", 6 | "查汇总_性别分组": "@查除电脑关联表() group by 性别", 7 | "查汇总_爱好汇总": "@查除电脑关联表()", 8 | "查汇总_爱好分组": "@查除电脑关联表() where 爱好 in (xx) group by 爱好", 9 | "查汇总_电脑类别汇总": "@查除三连和学习表()", 10 | "查汇总_电脑类别分组": "@查除三连和学习表() group by 电脑类别", 11 | "查1班": "@查1班_性别汇总() union @查1班_性别分组() union @查1班_爱好汇总() union @查1班_爱好分组() union @查1班_电脑类别汇总() union @查汇总_电脑类别分组()", 12 | "查1班_性别汇总": "@查除电脑关联表() where 1班", 13 | "查1班_性别分组": "@查除电脑关联表() where 1班 group by 性别", 14 | "查1班_爱好汇总": "@查除电脑关联表() where 1班", 15 | "查1班_爱好分组": "@查除电脑关联表() where 1班 and 爱好 in (xx) group by 爱好", 16 | "查1班_电脑类别汇总": "@查除三连和学习表() where 1班", 17 | "查1班_电脑类别分组": "@查除三连和学习表() where 1班 group by 电脑类别", 18 | "查2班": "@查2班_性别汇总() union @查2班_性别分组() union @查2班_电脑类别汇总() union @查2班_电脑类别分组()", 19 | "查2班_性别汇总": "@查除电脑关联表() where 2班", 20 | "查2班_性别分组": "@查除电脑关联表() where 2班 group by 性别", 21 | "查2班_电脑类别汇总": "@查除三连和学习表() where 2班", 22 | "查2班_电脑类别分组": "@查除三连和学习表() where 2班 group by 电脑类别", 23 | "查所有关联表": "@查信息表() left join (@查三连表()) left join (@查学习表()) left join (@查电脑表()) left join (@查全校信息())", 24 | "查除电脑关联表": "@查信息表() left join (@查三连表()) left join (@查学习表()) left join (@查全校信息())", 25 | "查除三连和学习表": "@查信息表() left join (@查电脑表()) left join (@查全校信息())", 26 | "查信息表": "select 字段 from 信息表 where 年级 = 1", 27 | "查三连表": "select 字段 from 三连表 where 年级 = 1", 28 | "查学习表": "select 字段 from 学习表 where 年级 = 1", 29 | "查电脑表": "select 字段 from 电脑表 where 年级 = 1", 30 | "查全校信息": "select 字段 from 信息表" 31 | } -------------------------------------------------------------------------------- /src/components/SearchableTree.vue: -------------------------------------------------------------------------------- 1 | 51 | 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 结构化 SQL 生成器 2 | 3 | > 用 JSON 来轻松生成复杂的 SQL,大幅提高写 SQL 的效率! 4 | > 5 | > by 程序员鱼皮 6 | 7 | 在线使用:http://sql.yupi.icu 8 | 9 | 项目介绍视频:https://www.bilibili.com/video/BV1qa411J7vh/ 10 | 11 | ![工具截图](./doc/assets/main.png) 12 | 13 | ## 项目作用 14 | 15 | 1. 将 SQL 的编写逻辑 `结构化` ,像写文章大纲一样编写和阅读 SQL 16 | 2. 重复的 SQL 只需编写一次 ,SQL 变动时修改一处即可 17 | 3. 可以针对某部分 SQL 进行传参和调试 18 | 4. 查看 SQL 语句的引用树和替换过程,便于分析理解 SQL 19 | 20 | ![查看调用树和替换过程](./doc/assets/invokeTree.png) 21 | 22 | ## 应用场景 23 | 24 | 如果你要写一句复杂的 SQL,且 SQL 中很多代码是 **相似** 但又不相同的。那么推荐使用该工具,可以不用重复编写 SQL,更有利于修改、维护和理解。 25 | 26 | 尤其是在大数据分析场景下,经常会有编写复杂 SQL 的需求。 27 | 28 | > 之所以会有这个轮子,也正是因为鱼皮在工作中要写一句长达 3000 行的 SQL 来离线分析数据,手写真的人要疯了! 29 | 30 | 当然,你也完全可以把它当做一个 `重复代码生成器` ~ 31 | 32 | ## 示例 33 | 34 | 需求:计算 id = 1 和 id = 2 的两位同学的身高差 35 | 36 | SQL 大概是这样的: 37 | 38 | ```sql 39 | select (s1.height - s2.height) as 身高差 40 | from 41 | (select * from student where id = 1) s1, 42 | (select * from student where id = 2) s2 43 | ``` 44 | 45 | 显然,上述 SQL 中学生表查询了 2 次,而且除了查询的 id 不同外,查询逻辑完全一致! 46 | 47 | 如果后面查询学生的逻辑发生修改,那么以上 2 个子查询都要同时修改,不利于维护。 48 | 49 | 而使用本工具,只需编写如下 JSON,就能自动生成完整的 SQL 了: 50 | 51 | ```json 52 | { 53 | "main": "select @身高差() from (@学生表(id = 1)) s1, (@学生表(id = 2)) s2", 54 | "身高差": "(s1.height - s2.height) as 身高差", 55 | "学生表": "select * from student where id = #{id}" 56 | } 57 | ``` 58 | 59 | 通过类似 `函数调用 + 传参` 的方式,我们无需重复编写 SQL,而且整个 SQL 的逻辑更清晰! 60 | 61 | 当然,以上只是一个示例,真实大数据离线分析的场景下,SQL 可比这复杂 N 倍! 62 | 63 | 如果感兴趣的话,欢迎往下看文档,还有更复杂的示例~ 64 | 65 | ## 优势 66 | 67 | 1. 支持在线编辑 JSON 和 SQL,支持代码高亮、语法校验、一键格式化、查找和替换、代码块折叠等,体验良好 68 | 2. 支持一键生成 SQL 69 | 3. 支持参数透传,比如 @a(xx = #{yy}),yy 变量可传递给 @a 公式 70 | 4. 支持嵌套传参(将子查询作为参数),比如 @a(xx = @b(yy = 1)) 71 | 5. 不限制用户在 JSON 中编写的内容,因此该工具也可以作为重复代码生成器来使用 72 | 6. 支持查看 SQL 语句的调用树和替换详情,便于分析引用关系 73 | 74 | ## 文档 75 | 76 | 可以把下面的代码放到生成器中试试,一下就明白如何使用啦~ 77 | 78 | ```json 79 | { 80 | "main": "必填, 代码从这里开始生成, 用 @规则名() 引用其他语句", 81 | "规则名": "可以编写任意 SQL 语句 @规则名2() @动态传参(a = 求给 ||| b = star)", 82 | "规则名2": { 83 | "sql": "用 #{参数名} 指定可被替换的值", 84 | "params": { 85 | "参数名": "在 params 中指定静态参数, 会优先被替换" 86 | } 87 | }, 88 | "动态传参": "#{a}鱼皮#{b}" 89 | } 90 | ``` 91 | 92 | ### 补充说明 93 | 94 | `对象键`:定义 SQL 生成规则名称,main 表示入口 SQL,从该 SQL 语句开始生成。 95 | 96 | `对象值`:定义具体生成规则。可以是 SQL 字符串或者对象。 97 | 98 | `sql`:定义模板 SQL 语句,可以是任意字符串,比如一组字段、一段查询条件、一段计算逻辑、完整 SQL 等。 99 | 100 | `params`:静态参数,解析器会优先将该变量替换到当前语句的 #{变量名} 中 101 | 102 | `#{xxx}`:定义可被替换的变量,优先用当前层级 params 替换,否则由外层传递 103 | 104 | `@xxx(yy = 1 ||| zz = #{变量})`:引用其他 SQL,可传参,参数可再用变量来表示,使用 |||(三个竖线)来分隔参数。 105 | 106 | ## 复杂示例 107 | 108 | 需求:用一句 SQL 查询出以下表格 109 | 110 | ![](./doc/assets/complex-example.png) 111 | 112 | 这个表格的难点在哪? 113 | 114 | 1. 查汇总和查明细的粒度不同,不能用 group by 区分,只能用 union(红色) 115 | 2. 分类列中不同行的数据有交叉,不能用 group by 区分,只能用 union 116 | 3. 每一列由多张表共同 join 而成,且不同分类可关联的表不同,须进行区分(灰色表示无法关联),并将缺失的字段补齐(否则无法 union) 117 | 4. 不同行的同一列计算公式可能不同(蓝色) 118 | 5. 不同列的过滤条件不同(比如最后两列墨绿色是要查全校,其余列只查 1 年级) 119 | 6. 要查询同环比,只能用 2 份完整的数据去 join 然后错位计算来得出 120 | 121 | 显然,这个表中很多查询逻辑是重复但又不同的。 122 | 123 | 这么算下来,最后这个 SQL 中到底会包含多少个基础表的 select 呢?每个基础表查询要重复编写多少遍呢? 124 | 125 | 然而,这个表格也只是鱼皮对实际需求简化后才得来的,实际需求比这还复杂几倍! 126 | 127 | 可想而知,人工写有多恶心?! 128 | 129 | 但是使用本工具,只需编写如下结构化的 JSON: 130 | 131 | ```json 132 | { 133 | "main": "select (a / b - 1) from (@查整体(date = 今天)) a, (@查整体(date = 昨天)) b", 134 | "查整体": "@查年级() union @查1班() union @查2班() where date = #{date}", 135 | "查年级": "@查汇总_性别汇总() union @查汇总_性别分组() union @查汇总_爱好汇总() union @查汇总_爱好分组() union @查汇总_电脑类别汇总() union @查汇总_电脑类别分组()", 136 | "查汇总_性别汇总": "@查除电脑关联表()", 137 | "查汇总_性别分组": "@查除电脑关联表() group by 性别", 138 | "查汇总_爱好汇总": "@查除电脑关联表()", 139 | "查汇总_爱好分组": "@查除电脑关联表() where 爱好 in (xx) group by 爱好", 140 | "查汇总_电脑类别汇总": "@查除三连和学习表()", 141 | "查汇总_电脑类别分组": "@查除三连和学习表() group by 电脑类别", 142 | 143 | "查1班": "@查1班_性别汇总() union @查1班_性别分组() union @查1班_爱好汇总() union @查1班_爱好分组() union @查1班_电脑类别汇总() union @查汇总_电脑类别分组()", 144 | "查1班_性别汇总": "@查除电脑关联表() where 1班", 145 | "查1班_性别分组": "@查除电脑关联表() where 1班 group by 性别", 146 | "查1班_爱好汇总": "@查除电脑关联表() where 1班", 147 | "查1班_爱好分组": "@查除电脑关联表() where 1班 and 爱好 in (xx) group by 爱好", 148 | "查1班_电脑类别汇总": "@查除三连和学习表() where 1班", 149 | "查1班_电脑类别分组": "@查除三连和学习表() where 1班 group by 电脑类别", 150 | 151 | "查2班": "@查2班_性别汇总() union @查2班_性别分组() union @查2班_电脑类别汇总() union @查2班_电脑类别分组()", 152 | "查2班_性别汇总": "@查除电脑关联表() where 2班", 153 | "查2班_性别分组": "@查除电脑关联表() where 2班 group by 性别", 154 | "查2班_电脑类别汇总": "@查除三连和学习表() where 2班", 155 | "查2班_电脑类别分组": "@查除三连和学习表() where 2班 group by 电脑类别", 156 | 157 | "查所有关联表": "@查信息表() left join (@查三连表()) left join (@查学习表()) left join (@查电脑表()) left join (@查全校信息())", 158 | "查除电脑关联表": "@查信息表() left join (@查三连表()) left join (@查学习表()) left join (@查全校信息())", 159 | "查除三连和学习表": "@查信息表() left join (@查电脑表()) left join (@查全校信息())", 160 | "查信息表": "select 字段 from 信息表 where 年级 = 1", 161 | "查三连表": "select 字段 from 三连表 where 年级 = 1", 162 | "查学习表": "select 字段 from 学习表 where 年级 = 1", 163 | "查电脑表": "select 字段 from 电脑表 where 年级 = 1", 164 | "查全校信息": "select 字段 from 信息表" 165 | } 166 | ``` 167 | 168 | 就能自动生成 SQL 了,还可以查看调用关系,非常清晰: 169 | 170 | ![](./doc/assets/complex-example-result.png) 171 | 172 | 173 | ## 实现 174 | 175 | 使用和 JSON 相性最好的 JavaScript 来实现,编写一份逻辑 JS 文件,可同时应用于 browser 和 server 端。 176 | 177 | 功能比较轻量,因此选择优先在纯 browser 端实现。 178 | 179 | 前端使用 `Vue3 + Vite + Ant Design Vue` 开发界面,选用 `Monaco Editor` 实现代码编辑、高亮、格式化等功能,使用 `TypeScript + ESLint` 保证代码规范。 180 | 181 | SQL 生成逻辑如下: 182 | 183 | 1. JSON 字符串转对象 184 | 2. 从入口开始,先替换 params 静态参数,得到当前层解析 185 | 3. 对 @xxx 语法进行递归解析,递归解析时,优先替换静态参数,再替换外层传来的调用参数 186 | 4. 得到最终 SQL 187 | 188 | 解析器原本采用正则非贪婪替换方式实现,但无法实现嵌套调用,比如 @a(xx = @b()),会被识别为 @a(xx = @b(),匹配到了最近的右括号。 189 | 因此针对括号嵌套的情况对子查询替换算法做了优化,已支持包含括号语句的嵌套调用。 190 | 191 | -------------------------------------------------------------------------------- /src/generator/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 生成 SQL 入口函数 3 | * @param json 4 | */ 5 | export function doGenerateSQL(json: InputJSON) { 6 | // 缺失入口 7 | if (!json?.main) { 8 | return null; 9 | } 10 | const sql = json.main.sql ?? json.main; 11 | if (!sql) { 12 | return null; 13 | } 14 | const initTreeNode = { 15 | title: "main", 16 | sql, 17 | children: [], 18 | }; 19 | const rootInvokeTreeNode = { ...initTreeNode }; 20 | const context = json; 21 | const resultSQL = generateSQL( 22 | "main", 23 | context, 24 | context.main?.params, 25 | rootInvokeTreeNode 26 | ); 27 | return { 28 | resultSQL, 29 | invokeTree: rootInvokeTreeNode.children[0], // 取第一个作为根节点 30 | }; 31 | } 32 | 33 | /** 34 | * 递归生成 SQL 35 | * @param key 36 | * @param context 37 | * @param params 38 | * @param invokeTreeNode 39 | */ 40 | function generateSQL( 41 | key: string, 42 | context: InputJSON, 43 | params?: Record, 44 | invokeTreeNode?: InvokeTreeNode 45 | ): string { 46 | const currentNode = context[key]; 47 | if (!currentNode) { 48 | return ""; 49 | } 50 | let childInvokeTreeNode: InvokeTreeNode | undefined; 51 | if (invokeTreeNode) { 52 | childInvokeTreeNode = { 53 | title: key, 54 | sql: currentNode.sql ?? currentNode, 55 | params, 56 | children: [], 57 | }; 58 | invokeTreeNode.children?.push(childInvokeTreeNode); 59 | } 60 | const result = replaceParams( 61 | currentNode, 62 | context, 63 | params, 64 | childInvokeTreeNode 65 | ); 66 | const resultSQL = replaceSubSql(result, context, childInvokeTreeNode); 67 | if (childInvokeTreeNode) { 68 | childInvokeTreeNode.resultSQL = resultSQL; 69 | } 70 | return resultSQL; 71 | } 72 | 73 | /** 74 | * 参数替换(params) 75 | * @param currentNode 76 | * @param context 77 | * @param params 动态参数 78 | * @param invokeTreeNode 79 | */ 80 | function replaceParams( 81 | currentNode: InputJSONValue, 82 | context: InputJSON, 83 | params?: Record, 84 | invokeTreeNode?: InvokeTreeNode 85 | ): string { 86 | if (currentNode == null) { 87 | return ""; 88 | } 89 | const sql = currentNode.sql ?? currentNode; 90 | if (!sql) { 91 | return ""; 92 | } 93 | // 动态、静态参数结合,且优先用静态参数 94 | params = { ...(params ?? {}), ...currentNode.params }; 95 | if (invokeTreeNode) { 96 | invokeTreeNode.params = params; 97 | } 98 | // 无需替换 99 | if (!params || Object.keys(params).length < 1) { 100 | return sql; 101 | } 102 | let result = sql; 103 | for (const paramsKey in params) { 104 | const replacedKey = `#{${paramsKey}}`; 105 | // 递归解析 106 | // const replacement = replaceSubSql( 107 | // params[paramsKey], 108 | // context, 109 | // invokeTreeNode 110 | // ); 111 | const replacement = params[paramsKey]; 112 | // find and replace 113 | result = result.replaceAll(replacedKey, replacement); 114 | } 115 | return result; 116 | } 117 | 118 | /** 119 | * 替换子 SQL(@xxx) 120 | * @param sql 121 | * @param context 122 | * @param invokeTreeNode 123 | */ 124 | function replaceSubSql( 125 | sql: string, 126 | context: InputJSON, 127 | invokeTreeNode?: InvokeTreeNode 128 | ): string { 129 | if (!sql) { 130 | return ""; 131 | } 132 | let result = sql; 133 | result = String(result); 134 | let regExpMatchArray = matchSubQuery(result); 135 | // 依次替换 136 | while (regExpMatchArray && regExpMatchArray.length > 2) { 137 | // 找到结果 138 | const subKey = regExpMatchArray[1]; 139 | // 可用来替换的节点 140 | const replacementNode = context[subKey]; 141 | // 没有可替换的节点 142 | if (!replacementNode) { 143 | const errorMsg = `${subKey} 不存在`; 144 | alert(errorMsg); 145 | throw new Error(errorMsg); 146 | } 147 | // 获取要传递的动态参数 148 | // e.g. "a = b, c = d" 149 | let paramsStr = regExpMatchArray[2]; 150 | if (paramsStr) { 151 | paramsStr = paramsStr.trim(); 152 | } 153 | // e.g. ["a = b", "c = d"] 154 | const singleParamsStrArray = paramsStr.split("|||"); 155 | // string => object 156 | const params: Record = {}; 157 | for (const singleParamsStr of singleParamsStrArray) { 158 | // 必须分成 2 段 159 | const keyValueArray = singleParamsStr.split("=", 2); 160 | if (keyValueArray.length < 2) { 161 | continue; 162 | } 163 | const key = keyValueArray[0].trim(); 164 | params[key] = keyValueArray[1].trim(); 165 | } 166 | // 递归解析被替换节点 167 | const replacement = generateSQL(subKey, context, params, invokeTreeNode); 168 | result = result.replace(regExpMatchArray[0], replacement); 169 | regExpMatchArray = matchSubQuery(result); 170 | } 171 | return result; 172 | } 173 | 174 | /** 175 | * 匹配子查询 176 | * @param str 177 | */ 178 | function matchSubQuery(str: string) { 179 | if (!str) { 180 | return null; 181 | } 182 | const regExp = /@([\u4e00-\u9fa5_a-zA-Z0-9]+)\((.*?)\)/; 183 | let regExpMatchArray = str.match(regExp); 184 | if (!regExpMatchArray || regExpMatchArray.index === undefined) { 185 | return null; 186 | } 187 | // @ 开始位置 188 | let startPos = regExpMatchArray.index; 189 | // 左括号右侧 190 | let leftParenthesisPos = startPos + regExpMatchArray[1].length + 2; 191 | // 遍历游标 192 | let currPos = leftParenthesisPos; 193 | // 默认匹配结束位置,需要对此结果进行修正 194 | let endPos = startPos + regExpMatchArray[0].length; 195 | // 剩余待匹配左括号数量 196 | let leftCount = 1; 197 | while (currPos < str.length) { 198 | const currentChar = str.charAt(currPos); 199 | if (currentChar === "(") { 200 | leftCount++; 201 | } else if (currentChar === ")") { 202 | leftCount--; 203 | } 204 | // 匹配结束 205 | if (leftCount == 0) { 206 | endPos = currPos + 1; 207 | break; 208 | } 209 | currPos++; 210 | } 211 | return [ 212 | str.slice(startPos, endPos), 213 | regExpMatchArray[1], 214 | str.slice(leftParenthesisPos, endPos - 1), 215 | ]; 216 | } 217 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 119 | 120 | 180 | 181 | 190 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------