@zenorm/generate 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,15 +1,21 @@
1
- # Changelog
2
-
3
- ## [1.1.1] - 2023-3-24
4
- - fix: 生成格式少个空格和空行
5
- - update: bindQuery 增加 count 和 exists
6
- - 补充注释说明
7
-
8
- ## [1.1.0] - 2023-3-24
9
- - 新增: 绑定静态 Query
10
-
11
- ## [1.0.0] - 2023-3-23
12
- - 完善
13
-
14
- ## [0.0.1] - 2023-3-23
15
- - zenorm@3.25.0 分离为独立项目
1
+ # Changelog
2
+
3
+ ## [1.3.0] - 2023-3-25
4
+ - update: bindQuery 增加 save, update, delete
5
+
6
+ ## [1.2.0] - 2023-3-24
7
+ - update: bindQuery 改为函数形式
8
+
9
+ ## [1.1.1] - 2023-3-24
10
+ - fix: 生成格式少个空格和空行
11
+ - update: bindQuery 增加 count 和 exists
12
+ - 补充注释说明
13
+
14
+ ## [1.1.0] - 2023-3-24
15
+ - 新增: 绑定静态 Query
16
+
17
+ ## [1.0.0] - 2023-3-23
18
+ - 完善
19
+
20
+ ## [0.0.1] - 2023-3-23
21
+ - 从 zenorm@3.25.0 分离为独立项目
package/README.md CHANGED
@@ -1,24 +1,24 @@
1
- # ZenORM Generate
2
-
3
- [ZenORM](https://www.npmjs.com/package/zenorm) Table Structure Code Generation Tool
4
-
5
- 表结构代码生成工具
6
-
7
- ## Generate Config - 代码生成配置
8
-
9
- | 配置项 | 类型 | 默认值 | 说明
10
- | ----- | --- | ----- | ----
11
- | host | `string` | 无 | 目标数据库地址
12
- | port | `number` | 无 | 数据库端口
13
- | user | `string` | 无 | 数据库用户名
14
- | password | `string` | 无 | 数据库密码
15
- | database | `string` | 无 | 数据库名
16
- | outputDir | `string` | `'./src/model'` | 代码输出目录
17
- | tablesFilename | `string` | `'_tables'` | 生成数据库表结构文件名
18
- | repositoriesFilename | `string` | `'_repositories'` | 生成 repositories 文件名
19
- | globalFilename | `string` | 无 | 全局文件名 - 如果设置所有表将继承于此 - 例如设置为:'_global' - 如果文件不存在则自动创建
20
- | bindQuery | `string` | | 绑定 Query 对象 - 设置 query 源,格式: 'QueryParam@filename' 例如: 'pool@../db'
21
- | generateRepositories | `boolean` | `false` | 是否生成 Repositories 类 - 通常用于多租户模式做数据库前置绑定 `Query` 对象
22
- | declareRepositoriesToModules | `string[]` | 无 | 是否需将 Repositories 实例定义到目标模块中 - 例如: `["@zenweb/core.Core.repositories"]`
23
- | filter | `string` | 无 | 表过滤规则正则
24
- | include | `string` | 无 | 表包含规则正则
1
+ # ZenORM Generate
2
+
3
+ [ZenORM](https://www.npmjs.com/package/zenorm) Table Structure Code Generation Tool
4
+
5
+ 表结构代码生成工具
6
+
7
+ ## Generate Config - 代码生成配置
8
+
9
+ | 配置项 | 类型 | 默认值 | 说明
10
+ | ----- | --- | ----- | ----
11
+ | host | `string` | 无 | 目标数据库地址
12
+ | port | `number` | 无 | 数据库端口
13
+ | user | `string` | 无 | 数据库用户名
14
+ | password | `string` | 无 | 数据库密码
15
+ | database | `string` | 无 | 数据库名
16
+ | outputDir | `string` | `'./src/model'` | 代码输出目录
17
+ | tablesFilename | `string` | `'_tables'` | 生成数据库表结构文件名
18
+ | repositoriesFilename | `string` | `'_repositories'` | 生成 repositories 文件名
19
+ | globalFilename | `string` | 无 | 全局文件名 - 如果设置所有表将继承于此 - 例如设置为:'_global' - 如果文件不存在则自动创建
20
+ | bindQuery | `boolean` | `false` | repositories 文件生成 bindQuery(query: QueryParam) 方法用于设置模型的 Query - 并生成模型的静态 Repository 方法
21
+ | generateRepositories | `boolean` | `false` | 是否生成 Repositories 类 - 通常用于多租户模式做数据库前置绑定 `Query` 对象
22
+ | declareRepositoriesToModules | `string[]` | 无 | 是否需将 Repositories 实例定义到目标模块中 - 例如: `["@zenweb/core.Core.repositories"]`
23
+ | filter | `string` | 无 | 表过滤规则正则
24
+ | include | `string` | 无 | 表包含规则正则
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env node
2
- export {};
1
+ #!/usr/bin/env node
2
+ export {};
@@ -1,27 +1,27 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const path = require("path");
5
- const generate_1 = require("../generate");
6
- function getConfig(filename) {
7
- const configFile = path.join(process.cwd(), filename);
8
- const config = require(configFile);
9
- return Object.assign({
10
- backend: '@zenorm/generate-mysql',
11
- }, config);
12
- }
13
- async function main(configFilename) {
14
- const config = await getConfig(configFilename);
15
- const call = require(config.backend).default;
16
- await (0, generate_1.generate)(call()(config), config);
17
- }
18
- if (!process.argv[2]) {
19
- console.log('zenorm-generate config.json');
20
- process.exit(1);
21
- }
22
- else {
23
- main(process.argv[2]).then(() => process.exit(), e => {
24
- console.error(e);
25
- process.exit(1);
26
- });
27
- }
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const path = require("path");
5
+ const generate_1 = require("../generate");
6
+ function getConfig(filename) {
7
+ const configFile = path.join(process.cwd(), filename);
8
+ const config = require(configFile);
9
+ return Object.assign({
10
+ backend: '@zenorm/generate-mysql',
11
+ }, config);
12
+ }
13
+ async function main(configFilename) {
14
+ const config = await getConfig(configFilename);
15
+ const call = require(config.backend).default;
16
+ await (0, generate_1.generate)(call()(config), config);
17
+ }
18
+ if (!process.argv[2]) {
19
+ console.log('zenorm-generate config.json');
20
+ process.exit(1);
21
+ }
22
+ else {
23
+ main(process.argv[2]).then(() => process.exit(), e => {
24
+ console.error(e);
25
+ process.exit(1);
26
+ });
27
+ }
@@ -1,2 +1,2 @@
1
- import { GenerateConfig, TabelDescribe } from './types';
2
- export declare function generate(tables: AsyncGenerator<TabelDescribe>, cfg?: GenerateConfig): Promise<void>;
1
+ import { GenerateConfig, TabelDescribe } from './types';
2
+ export declare function generate(tables: AsyncGenerator<TabelDescribe>, cfg?: GenerateConfig): Promise<void>;
package/dist/generate.js CHANGED
@@ -1,164 +1,166 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generate = void 0;
4
- const fs_1 = require("fs");
5
- const path = require("path");
6
- const pascal_case_1 = require("pascal-case");
7
- const snake_case_1 = require("snake-case");
8
- const utils_1 = require("./utils");
9
- const zenormName = process.env.ZENORM_NAME || 'zenorm';
10
- async function generate(tables, cfg) {
11
- console.log('generate models...');
12
- const config = Object.assign({
13
- outputDir: './src/model',
14
- tablesFilename: '_tables',
15
- repositoriesFilename: '_repositories',
16
- }, cfg);
17
- const outputDir = (0, utils_1.cwdPath)(config.outputDir);
18
- await (0, utils_1.checkFileDir)(outputDir);
19
- console.log('database:', config.database);
20
- const remark = [
21
- '// zenorm 自动生成文件',
22
- '// 请不要修改此文件,因为此文件在每次重新生成数据库结构时会被覆盖',
23
- `// create at: ${(0, utils_1.currentDatetime)()}`,
24
- `// create by: ${process.env.USER || process.env.USERNAME || '-'}@${process.env.COMPUTERNAME || '-'}`,
25
- `// database: ${config.database}`,
26
- ];
27
- const structs = [
28
- ...remark,
29
- config.globalFilename ? `import _Global from './${config.globalFilename}';` : null,
30
- '',
31
- ];
32
- const models = [];
33
- const filterRegExp = config.filter ? new RegExp(config.filter) : null;
34
- const includeRegExp = config.include ? new RegExp(config.include) : null;
35
- for await (const t of tables) {
36
- const tableName = t.name;
37
- if ((filterRegExp && filterRegExp.test(tableName))
38
- || (includeRegExp && !includeRegExp.test(tableName))) {
39
- // console.log('table:', tableName, 'ignore');
40
- continue;
41
- }
42
- const className = (0, pascal_case_1.pascalCase)(tableName);
43
- const name = (0, snake_case_1.snakeCase)(tableName);
44
- const outputFilename = path.join(outputDir, name + '.ts');
45
- console.log('table:', tableName);
46
- let pk = 'id';
47
- let pkType = 'number';
48
- const props = [];
49
- const columns = [];
50
- for (const c of t.columns) {
51
- if (c.pk) {
52
- pk = c.name;
53
- pkType = c.type;
54
- }
55
- if (c.comment && c.comment.length) {
56
- props.push(` /**`);
57
- for (const line of c.comment) {
58
- props.push(` * ${line}`);
59
- }
60
- props.push(` */`);
61
- }
62
- props.push(` ${c.name}${c.required ? '!' : '?'}: ${c.type};`);
63
- columns.push(c.name);
64
- }
65
- structs.push(`export class ${className}Table${config.globalFilename ? ' extends _Global' : ''} {`);
66
- structs.push(` static columns = ${JSON.stringify(columns)};`);
67
- structs.push(...props);
68
- structs.push('}');
69
- structs.push('');
70
- // model class
71
- await (0, utils_1.notExistsPut)(outputFilename, () => {
72
- return [
73
- `import { model } from '${zenormName}';`,
74
- `import { ${className}Table } from './${config.tablesFilename}';`,
75
- '',
76
- `@model({`,
77
- ` pk: '${pk}',`,
78
- name != tableName ? ` name: '${name}',` : null,
79
- ` table: '${tableName}',`,
80
- `})`,
81
- `export default class ${className} extends ${className}Table {`,
82
- `}`,
83
- '',
84
- ].filter(i => i !== null).join('\n');
85
- });
86
- models.push({ name, className, pkType });
87
- }
88
- const tablesFilename = path.join(outputDir, config.tablesFilename + '.ts');
89
- console.log(`write tables file: ${tablesFilename}`);
90
- await fs_1.promises.writeFile(tablesFilename, structs.filter(i => i !== null).join('\n'));
91
- const repositories = [
92
- ...remark,
93
- `import { ${config.generateRepositories ? `QueryParam, ` : ''}createRepositoryQuery } from '${zenormName}';`,
94
- ...models.map(({ name, className }) => `import _${className} from './${name}';`),
95
- ];
96
- // 绑定静态 Query
97
- if (config.bindQuery) {
98
- const [v, p] = config.bindQuery.split('@', 2);
99
- repositories.push(`import { ${v} as _query } from '${p}';`);
100
- }
101
- // static
102
- models.forEach(({ className, pkType }) => {
103
- repositories.push('', `export class ${className} extends _${className} {`, ` /** 使用指定 Query 对象查询 ${className}Repository */`, ` static query = createRepositoryQuery<${className}, ${pkType}>(${className});`);
104
- if (config.bindQuery) {
105
- repositories.push(` /** Query 绑定的 ${className}Repository */`);
106
- repositories.push(` static repository = ${className}.query(_query);`);
107
- repositories.push(...[
108
- 'of',
109
- 'find',
110
- 'findByPk',
111
- 'getByPk',
112
- 'count',
113
- 'exists',
114
- 'create',
115
- 'createAndGet',
116
- ].map(i => ` static ${i}: typeof ${className}.repository.${i} = ${className}.repository.${i}.bind(${className}.repository);`));
117
- // 实例方法
118
- repositories.push(` /** 保存当前实例数据 */`);
119
- repositories.push(` save() { return ${className}.repository.save(this); }`);
120
- repositories.push(` /** 更新当前实例数据 */`);
121
- repositories.push(` update(data: Partial<${className}>) { return ${className}.repository.update(this, data); }`);
122
- repositories.push(` /** 删除当前实例数据 */`);
123
- repositories.push(` delete() { return ${className}.repository.delete(this); }`);
124
- }
125
- repositories.push('}');
126
- });
127
- // Repositories
128
- if (config.generateRepositories) {
129
- repositories.push('', `export class Repositories {`, ` constructor(private _query: QueryParam) {}`, ...models.map(({ className }) => ` get ${className}Repository() { return ${className}.query(this._query); }`), `}`, '');
130
- // 添加 Repositories 到目标模块中
131
- if (config.declareRepositoriesToModules) {
132
- for (const mod of config.declareRepositoriesToModules) {
133
- const _m = mod.split('.');
134
- repositories.push(`declare module '${_m[0]}' {`);
135
- repositories.push(` interface ${_m.slice(1, -1).join('.')} {`);
136
- repositories.push(` ${_m[_m.length - 1]}: Repositories;`);
137
- repositories.push(` }`);
138
- repositories.push(`}`);
139
- repositories.push(``);
140
- }
141
- }
142
- }
143
- const repositoriesFilename = path.join(outputDir, config.repositoriesFilename + '.ts');
144
- console.log(`write repositories file: ${repositoriesFilename}`);
145
- await fs_1.promises.writeFile(repositoriesFilename, repositories.join('\n'));
146
- // 生成 global.ts
147
- if (config.globalFilename) {
148
- const globalFilename = path.join(outputDir, config.globalFilename + '.ts');
149
- await (0, utils_1.notExistsPut)(globalFilename, () => {
150
- console.log(`write file: ${globalFilename}`);
151
- return 'export default class Global {}';
152
- });
153
- }
154
- // 生成 index.ts
155
- const indexFilename = path.join(outputDir, 'index.ts');
156
- await (0, utils_1.notExistsPut)(indexFilename, () => {
157
- console.log(`write file: ${indexFilename}`);
158
- return [
159
- `export * from './${config.tablesFilename}';`,
160
- `export * from './${config.repositoriesFilename}';`,
161
- ].join('\n');
162
- });
163
- }
164
- exports.generate = generate;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generate = void 0;
4
+ const fs_1 = require("fs");
5
+ const path = require("path");
6
+ const pascal_case_1 = require("pascal-case");
7
+ const snake_case_1 = require("snake-case");
8
+ const utils_1 = require("./utils");
9
+ const zenormName = process.env.ZENORM_NAME || 'zenorm';
10
+ async function generate(tables, cfg) {
11
+ console.log('generate models...');
12
+ const config = Object.assign({
13
+ outputDir: './src/model',
14
+ tablesFilename: '_tables',
15
+ repositoriesFilename: '_repositories',
16
+ }, cfg);
17
+ const outputDir = (0, utils_1.cwdPath)(config.outputDir);
18
+ await (0, utils_1.checkFileDir)(outputDir);
19
+ console.log('database:', config.database);
20
+ const remark = [
21
+ '// zenorm 自动生成文件',
22
+ '// 请不要修改此文件,因为此文件在每次重新生成数据库结构时会被覆盖',
23
+ `// create at: ${(0, utils_1.currentDatetime)()}`,
24
+ `// create by: ${process.env.USER || process.env.USERNAME || '-'}@${process.env.COMPUTERNAME || '-'}`,
25
+ `// database: ${config.database}`,
26
+ ];
27
+ const structs = [
28
+ ...remark,
29
+ config.globalFilename ? `import _Global from './${config.globalFilename}';` : null,
30
+ '',
31
+ ];
32
+ const models = [];
33
+ const filterRegExp = config.filter ? new RegExp(config.filter) : null;
34
+ const includeRegExp = config.include ? new RegExp(config.include) : null;
35
+ for await (const t of tables) {
36
+ const tableName = t.name;
37
+ if ((filterRegExp && filterRegExp.test(tableName))
38
+ || (includeRegExp && !includeRegExp.test(tableName))) {
39
+ // console.log('table:', tableName, 'ignore');
40
+ continue;
41
+ }
42
+ const className = (0, pascal_case_1.pascalCase)(tableName);
43
+ const name = (0, snake_case_1.snakeCase)(tableName);
44
+ const outputFilename = path.join(outputDir, name + '.ts');
45
+ console.log('table:', tableName);
46
+ let pk = 'id';
47
+ let pkType = 'number';
48
+ const props = [];
49
+ const columns = [];
50
+ for (const c of t.columns) {
51
+ if (c.pk) {
52
+ pk = c.name;
53
+ pkType = c.type;
54
+ }
55
+ if (c.comment && c.comment.length) {
56
+ props.push(` /**`);
57
+ for (const line of c.comment) {
58
+ props.push(` * ${line}`);
59
+ }
60
+ props.push(` */`);
61
+ }
62
+ props.push(` ${c.name}${c.required ? '!' : '?'}: ${c.type};`);
63
+ columns.push(c.name);
64
+ }
65
+ structs.push(`export class ${className}Table${config.globalFilename ? ' extends _Global' : ''} {`);
66
+ structs.push(` static columns = ${JSON.stringify(columns)};`);
67
+ structs.push(...props);
68
+ structs.push('}');
69
+ structs.push('');
70
+ // model class
71
+ await (0, utils_1.notExistsPut)(outputFilename, () => {
72
+ return [
73
+ `import { model } from '${zenormName}';`,
74
+ `import { ${className}Table } from './${config.tablesFilename}';`,
75
+ '',
76
+ `@model({`,
77
+ ` pk: '${pk}',`,
78
+ name != tableName ? ` name: '${name}',` : null,
79
+ ` table: '${tableName}',`,
80
+ `})`,
81
+ `export default class ${className} extends ${className}Table {`,
82
+ `}`,
83
+ '',
84
+ ].filter(i => i !== null).join('\n');
85
+ });
86
+ models.push({ name, className, pkType });
87
+ }
88
+ const tablesFilename = path.join(outputDir, config.tablesFilename + '.ts');
89
+ console.log(`write tables file: ${tablesFilename}`);
90
+ await fs_1.promises.writeFile(tablesFilename, structs.filter(i => i !== null).join('\n'));
91
+ const repositories = [
92
+ ...remark,
93
+ `import { ${(config.generateRepositories || config.bindQuery) ? `QueryParam, ` : ''}createRepositoryQuery } from '${zenormName}';`,
94
+ ...models.map(({ name, className }) => `import _${className} from './${name}';`),
95
+ ];
96
+ // 绑定静态 Query
97
+ if (config.bindQuery) {
98
+ repositories.push('', `let _bindQuery: QueryParam;`, `function _query() { return typeof _bindQuery === 'function' ? _bindQuery() : _bindQuery }`, `/** 绑定模型 Query 源 */`, `export function bindQuery(query: QueryParam) { _bindQuery = query; }`);
99
+ }
100
+ // static
101
+ models.forEach(({ className, pkType }) => {
102
+ repositories.push('', `export class ${className} extends _${className} {`, ` /** 使用指定 Query 对象查询 ${className}Repository */`, ` static query = createRepositoryQuery<${className}, ${pkType}>(${className});`);
103
+ if (config.bindQuery) {
104
+ repositories.push(` /** Query 绑定的 ${className}Repository */`);
105
+ repositories.push(` static repository = ${className}.query(_query);`);
106
+ repositories.push(...[
107
+ 'of',
108
+ 'find',
109
+ 'findByPk',
110
+ 'getByPk',
111
+ 'count',
112
+ 'exists',
113
+ 'create',
114
+ 'createAndGet',
115
+ 'save',
116
+ 'update',
117
+ 'delete',
118
+ ].map(i => ` static ${i}: typeof ${className}.repository.${i} = ${className}.repository.${i}.bind(${className}.repository);`));
119
+ // 实例方法
120
+ repositories.push(` /** 保存当前实例数据 */`);
121
+ repositories.push(` save() { return ${className}.repository.save(this); }`);
122
+ repositories.push(` /** 更新当前实例数据 */`);
123
+ repositories.push(` update(data: Partial<${className}>) { return ${className}.repository.update(this, data); }`);
124
+ repositories.push(` /** 删除当前实例数据 */`);
125
+ repositories.push(` delete() { return ${className}.repository.delete(this); }`);
126
+ }
127
+ repositories.push('}');
128
+ });
129
+ // Repositories
130
+ if (config.generateRepositories) {
131
+ repositories.push('', `export class Repositories {`, ` constructor(private _query: QueryParam) {}`, ...models.map(({ className }) => ` get ${className}Repository() { return ${className}.query(this._query); }`), `}`, '');
132
+ // 添加 Repositories 到目标模块中
133
+ if (config.declareRepositoriesToModules) {
134
+ for (const mod of config.declareRepositoriesToModules) {
135
+ const _m = mod.split('.');
136
+ repositories.push(`declare module '${_m[0]}' {`);
137
+ repositories.push(` interface ${_m.slice(1, -1).join('.')} {`);
138
+ repositories.push(` ${_m[_m.length - 1]}: Repositories;`);
139
+ repositories.push(` }`);
140
+ repositories.push(`}`);
141
+ repositories.push(``);
142
+ }
143
+ }
144
+ }
145
+ const repositoriesFilename = path.join(outputDir, config.repositoriesFilename + '.ts');
146
+ console.log(`write repositories file: ${repositoriesFilename}`);
147
+ await fs_1.promises.writeFile(repositoriesFilename, repositories.join('\n'));
148
+ // 生成 global.ts
149
+ if (config.globalFilename) {
150
+ const globalFilename = path.join(outputDir, config.globalFilename + '.ts');
151
+ await (0, utils_1.notExistsPut)(globalFilename, () => {
152
+ console.log(`write file: ${globalFilename}`);
153
+ return 'export default class Global {}';
154
+ });
155
+ }
156
+ // 生成 index.ts
157
+ const indexFilename = path.join(outputDir, 'index.ts');
158
+ await (0, utils_1.notExistsPut)(indexFilename, () => {
159
+ console.log(`write file: ${indexFilename}`);
160
+ return [
161
+ `export * from './${config.tablesFilename}';`,
162
+ `export * from './${config.repositoriesFilename}';`,
163
+ ].join('\n');
164
+ });
165
+ }
166
+ exports.generate = generate;
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './types';
1
+ export * from './types';
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
package/dist/types.d.ts CHANGED
@@ -1,120 +1,121 @@
1
- /**
2
- * 模型文件生成 - 列描述
3
- */
4
- export interface ColumnDescribe {
5
- /**
6
- * 是否为主键
7
- */
8
- pk: boolean;
9
- /**
10
- * 列名称
11
- */
12
- name: string;
13
- /**
14
- * 列类型,例如 number, string, boolean
15
- */
16
- type: string;
17
- /**
18
- * 是否为必须项(非NULL)
19
- */
20
- required: boolean;
21
- /**
22
- * 注释信息,一行一条
23
- */
24
- comment: string[];
25
- }
26
- /**
27
- * 模型文件生成 - 表描述
28
- */
29
- export interface TabelDescribe {
30
- /**
31
- * 表名称
32
- */
33
- name: string;
34
- /**
35
- * 列描述信息
36
- */
37
- columns: ColumnDescribe[];
38
- }
39
- /**
40
- * 生成配置
41
- */
42
- export interface GenerateConfig {
43
- /**
44
- * 目标数据库地址
45
- */
46
- host?: string;
47
- /**
48
- * 数据库端口
49
- */
50
- port?: number;
51
- /**
52
- * 数据库用户名
53
- */
54
- user?: string;
55
- /**
56
- * 数据库密码
57
- */
58
- password?: string;
59
- /**
60
- * 数据库名
61
- */
62
- database?: string;
63
- /**
64
- * 代码输出目录
65
- * @default './src/model'
66
- */
67
- outputDir?: string;
68
- /**
69
- * 生成数据库表结构文件名
70
- * - 此文件每次生成都会被重新改写
71
- * @default '_tables'
72
- */
73
- tablesFilename?: string;
74
- /**
75
- * 生成 repositories 文件名
76
- * - 此文件每次生成都会被重新改写
77
- * @default '_repositories'
78
- */
79
- repositoriesFilename?: string;
80
- /**
81
- * 全局文件名
82
- * - 例如设置为:'_global'
83
- * - 如果设置所有表将继承于此
84
- * - 如果文件不存在则自动创建
85
- */
86
- globalFilename?: string;
87
- /**
88
- * 绑定 Query 对象
89
- * - 设置 query 源,格式: 'QueryParam@filename' 例如: 'pool@../db'
90
- * - 生成模型的静态 Repository 方法
91
- * - 对于多租户数据库系统不适用
92
- */
93
- bindQuery?: string;
94
- /**
95
- * 是否生成 Repositories 类
96
- * - 通常用于多租户模式做数据库前置绑定 `Query` 对象
97
- * @default false
98
- */
99
- generateRepositories?: boolean;
100
- /**
101
- * 是否需将 Repositories 实例定义到目标模块中
102
- * - 例如: `["@zenweb/core.Core.repositories"]`
103
- * - 需要启用: `generateRepositories`
104
- * @default undefined
105
- */
106
- declareRepositoriesToModules?: string[];
107
- /**
108
- * 表过滤规则正则,默认不处理
109
- */
110
- filter?: string;
111
- /**
112
- * 表包含规则正则,默认不处理
113
- */
114
- include?: string;
115
- }
116
- /**
117
- * 数据库表信息生成方法
118
- * - 返回表描述的处理方法
119
- */
120
- export type GenerateFunction = (config: GenerateConfig) => AsyncGenerator<TabelDescribe>;
1
+ /**
2
+ * 模型文件生成 - 列描述
3
+ */
4
+ export interface ColumnDescribe {
5
+ /**
6
+ * 是否为主键
7
+ */
8
+ pk: boolean;
9
+ /**
10
+ * 列名称
11
+ */
12
+ name: string;
13
+ /**
14
+ * 列类型,例如 number, string, boolean
15
+ */
16
+ type: string;
17
+ /**
18
+ * 是否为必须项(非NULL)
19
+ */
20
+ required: boolean;
21
+ /**
22
+ * 注释信息,一行一条
23
+ */
24
+ comment: string[];
25
+ }
26
+ /**
27
+ * 模型文件生成 - 表描述
28
+ */
29
+ export interface TabelDescribe {
30
+ /**
31
+ * 表名称
32
+ */
33
+ name: string;
34
+ /**
35
+ * 列描述信息
36
+ */
37
+ columns: ColumnDescribe[];
38
+ }
39
+ /**
40
+ * 生成配置
41
+ */
42
+ export interface GenerateConfig {
43
+ /**
44
+ * 目标数据库地址
45
+ */
46
+ host?: string;
47
+ /**
48
+ * 数据库端口
49
+ */
50
+ port?: number;
51
+ /**
52
+ * 数据库用户名
53
+ */
54
+ user?: string;
55
+ /**
56
+ * 数据库密码
57
+ */
58
+ password?: string;
59
+ /**
60
+ * 数据库名
61
+ */
62
+ database?: string;
63
+ /**
64
+ * 代码输出目录
65
+ * @default './src/model'
66
+ */
67
+ outputDir?: string;
68
+ /**
69
+ * 生成数据库表结构文件名
70
+ * - 此文件每次生成都会被重新改写
71
+ * @default '_tables'
72
+ */
73
+ tablesFilename?: string;
74
+ /**
75
+ * 生成 repositories 文件名
76
+ * - 此文件每次生成都会被重新改写
77
+ * @default '_repositories'
78
+ */
79
+ repositoriesFilename?: string;
80
+ /**
81
+ * 全局文件名
82
+ * - 例如设置为:'_global'
83
+ * - 如果设置所有表将继承于此
84
+ * - 如果文件不存在则自动创建
85
+ */
86
+ globalFilename?: string;
87
+ /**
88
+ * 绑定 Query 对象
89
+ * - repositories 文件生成 bindQuery(query: QueryParam) 方法用于设置模型的 Query 源
90
+ * - 并生成模型的静态 Repository 方法
91
+ * - 对于多租户多数据库系统不适用
92
+ * @default false
93
+ */
94
+ bindQuery?: boolean;
95
+ /**
96
+ * 是否生成 Repositories
97
+ * - 通常用于多租户模式做数据库前置绑定 `Query` 对象
98
+ * @default false
99
+ */
100
+ generateRepositories?: boolean;
101
+ /**
102
+ * 是否需将 Repositories 实例定义到目标模块中
103
+ * - 例如: `["@zenweb/core.Core.repositories"]`
104
+ * - 需要启用: `generateRepositories`
105
+ * @default undefined
106
+ */
107
+ declareRepositoriesToModules?: string[];
108
+ /**
109
+ * 表过滤规则正则,默认不处理
110
+ */
111
+ filter?: string;
112
+ /**
113
+ * 表包含规则正则,默认不处理
114
+ */
115
+ include?: string;
116
+ }
117
+ /**
118
+ * 数据库表信息生成方法
119
+ * - 返回表描述的处理方法
120
+ */
121
+ export type GenerateFunction = (config: GenerateConfig) => AsyncGenerator<TabelDescribe>;
package/dist/types.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/utils.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- export declare function cwdPath(p: string): string;
2
- export declare function checkFileDir(dir: string): Promise<void>;
3
- export declare function fileExists(f: string): Promise<boolean>;
4
- /**
5
- * 文件不存在则创建并写入内容
6
- * @param filename
7
- * @param getContent
8
- */
9
- export declare function notExistsPut(filename: string, getContent: () => string | Promise<string>): Promise<boolean>;
10
- export declare function currentDatetime(): string;
1
+ export declare function cwdPath(p: string): string;
2
+ export declare function checkFileDir(dir: string): Promise<void>;
3
+ export declare function fileExists(f: string): Promise<boolean>;
4
+ /**
5
+ * 文件不存在则创建并写入内容
6
+ * @param filename
7
+ * @param getContent
8
+ */
9
+ export declare function notExistsPut(filename: string, getContent: () => string | Promise<string>): Promise<boolean>;
10
+ export declare function currentDatetime(): string;
package/dist/utils.js CHANGED
@@ -1,37 +1,37 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.currentDatetime = exports.notExistsPut = exports.fileExists = exports.checkFileDir = exports.cwdPath = void 0;
4
- const fs_1 = require("fs");
5
- const path = require("path");
6
- function cwdPath(p) {
7
- if (p.startsWith('./')) {
8
- return path.join(process.cwd(), p.slice(2));
9
- }
10
- return p;
11
- }
12
- exports.cwdPath = cwdPath;
13
- function checkFileDir(dir) {
14
- return fs_1.promises.mkdir(dir, { recursive: true });
15
- }
16
- exports.checkFileDir = checkFileDir;
17
- function fileExists(f) {
18
- return fs_1.promises.access(f).then(() => true, e => false);
19
- }
20
- exports.fileExists = fileExists;
21
- /**
22
- * 文件不存在则创建并写入内容
23
- * @param filename
24
- * @param getContent
25
- */
26
- async function notExistsPut(filename, getContent) {
27
- if (!await fileExists(filename)) {
28
- await fs_1.promises.writeFile(filename, await getContent());
29
- return true;
30
- }
31
- return false;
32
- }
33
- exports.notExistsPut = notExistsPut;
34
- function currentDatetime() {
35
- return new Date().toLocaleString();
36
- }
37
- exports.currentDatetime = currentDatetime;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.currentDatetime = exports.notExistsPut = exports.fileExists = exports.checkFileDir = exports.cwdPath = void 0;
4
+ const fs_1 = require("fs");
5
+ const path = require("path");
6
+ function cwdPath(p) {
7
+ if (p.startsWith('./')) {
8
+ return path.join(process.cwd(), p.slice(2));
9
+ }
10
+ return p;
11
+ }
12
+ exports.cwdPath = cwdPath;
13
+ function checkFileDir(dir) {
14
+ return fs_1.promises.mkdir(dir, { recursive: true });
15
+ }
16
+ exports.checkFileDir = checkFileDir;
17
+ function fileExists(f) {
18
+ return fs_1.promises.access(f).then(() => true, e => false);
19
+ }
20
+ exports.fileExists = fileExists;
21
+ /**
22
+ * 文件不存在则创建并写入内容
23
+ * @param filename
24
+ * @param getContent
25
+ */
26
+ async function notExistsPut(filename, getContent) {
27
+ if (!await fileExists(filename)) {
28
+ await fs_1.promises.writeFile(filename, await getContent());
29
+ return true;
30
+ }
31
+ return false;
32
+ }
33
+ exports.notExistsPut = notExistsPut;
34
+ function currentDatetime() {
35
+ return new Date().toLocaleString();
36
+ }
37
+ exports.currentDatetime = currentDatetime;
package/docs/.nojekyll ADDED
@@ -0,0 +1 @@
1
+ TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false.
package/docs/README.md ADDED
@@ -0,0 +1,9 @@
1
+ @zenorm/generate / [Exports](modules.md)
2
+
3
+ # ZenORM Generate
4
+
5
+ [ZenORM](https://www.npmjs.com/package/zenorm) Table Structure Code Generation Tool
6
+
7
+ [Generate Config](docs/interfaces/GenerateConfig.md)
8
+
9
+ [API Documents](docs/modules.md)
@@ -0,0 +1,55 @@
1
+ [@zenorm/generate](../README.md) / [Exports](../modules.md) / ColumnDescribe
2
+
3
+ # Interface: ColumnDescribe
4
+
5
+ 模型文件生成 - 列描述
6
+
7
+ ## Table of contents
8
+
9
+ ### Properties
10
+
11
+ - [comment](ColumnDescribe.md#comment)
12
+ - [name](ColumnDescribe.md#name)
13
+ - [pk](ColumnDescribe.md#pk)
14
+ - [required](ColumnDescribe.md#required)
15
+ - [type](ColumnDescribe.md#type)
16
+
17
+ ## Properties
18
+
19
+ ### comment
20
+
21
+ • **comment**: `string`[]
22
+
23
+ 注释信息,一行一条
24
+
25
+ ___
26
+
27
+ ### name
28
+
29
+ • **name**: `string`
30
+
31
+ 列名称
32
+
33
+ ___
34
+
35
+ ### pk
36
+
37
+ • **pk**: `boolean`
38
+
39
+ 是否为主键
40
+
41
+ ___
42
+
43
+ ### required
44
+
45
+ • **required**: `boolean`
46
+
47
+ 是否为必须项(非NULL)
48
+
49
+ ___
50
+
51
+ ### type
52
+
53
+ • **type**: `string`
54
+
55
+ 列类型,例如 number, string, boolean
@@ -0,0 +1,157 @@
1
+ [@zenorm/generate](../README.md) / [Exports](../modules.md) / GenerateConfig
2
+
3
+ # Interface: GenerateConfig
4
+
5
+ 生成配置
6
+
7
+ ## Table of contents
8
+
9
+ ### Properties
10
+
11
+ - [database](GenerateConfig.md#database)
12
+ - [declareRepositoriesToModules](GenerateConfig.md#declarerepositoriestomodules)
13
+ - [filter](GenerateConfig.md#filter)
14
+ - [generateRepositories](GenerateConfig.md#generaterepositories)
15
+ - [globalFilename](GenerateConfig.md#globalfilename)
16
+ - [host](GenerateConfig.md#host)
17
+ - [include](GenerateConfig.md#include)
18
+ - [outputDir](GenerateConfig.md#outputdir)
19
+ - [password](GenerateConfig.md#password)
20
+ - [port](GenerateConfig.md#port)
21
+ - [repositoriesFilename](GenerateConfig.md#repositoriesfilename)
22
+ - [tablesFilename](GenerateConfig.md#tablesfilename)
23
+ - [user](GenerateConfig.md#user)
24
+
25
+ ## Properties
26
+
27
+ ### database
28
+
29
+ • `Optional` **database**: `string`
30
+
31
+ 数据库名
32
+
33
+ ___
34
+
35
+ ### declareRepositoriesToModules
36
+
37
+ • `Optional` **declareRepositoriesToModules**: `string`[]
38
+
39
+ 是否需将 Repositories 实例定义到目标模块中
40
+ - 例如: `["@zenweb/core.Core.repositories"]`
41
+ - 需要: `generateRepositories: true`
42
+
43
+ **`Default`**
44
+
45
+ undefined
46
+
47
+ ___
48
+
49
+ ### filter
50
+
51
+ • `Optional` **filter**: `string`
52
+
53
+ 表过滤规则正则,默认不处理
54
+
55
+ ___
56
+
57
+ ### generateRepositories
58
+
59
+ • `Optional` **generateRepositories**: `boolean`
60
+
61
+ 是否生成 Repositories 类
62
+ - 通常用于多租户环境需要做模型前置绑定 `Query` 对象
63
+
64
+ **`Default`**
65
+
66
+ false
67
+
68
+ ___
69
+
70
+ ### globalFilename
71
+
72
+ • `Optional` **globalFilename**: `string`
73
+
74
+ 全局文件名
75
+ - 如果不存在生成
76
+
77
+ **`Default`**
78
+
79
+ '_global'
80
+
81
+ ___
82
+
83
+ ### host
84
+
85
+ • `Optional` **host**: `string`
86
+
87
+ 目标数据库地址
88
+
89
+ ___
90
+
91
+ ### include
92
+
93
+ • `Optional` **include**: `string`
94
+
95
+ 表包含规则正则,默认不处理
96
+
97
+ ___
98
+
99
+ ### outputDir
100
+
101
+ • `Optional` **outputDir**: `string`
102
+
103
+ 代码输出目录
104
+
105
+ **`Default`**
106
+
107
+ './src/model'
108
+
109
+ ___
110
+
111
+ ### password
112
+
113
+ • `Optional` **password**: `string`
114
+
115
+ 数据库密码
116
+
117
+ ___
118
+
119
+ ### port
120
+
121
+ • `Optional` **port**: `number`
122
+
123
+ 数据库端口
124
+
125
+ ___
126
+
127
+ ### repositoriesFilename
128
+
129
+ • `Optional` **repositoriesFilename**: `string`
130
+
131
+ 生成 repositories 文件名
132
+ - 此文件每次生成都会被重新改写
133
+
134
+ **`Default`**
135
+
136
+ '_repositories'
137
+
138
+ ___
139
+
140
+ ### tablesFilename
141
+
142
+ • `Optional` **tablesFilename**: `string`
143
+
144
+ 生成数据库表结构文件名
145
+ - 此文件每次生成都会被重新改写
146
+
147
+ **`Default`**
148
+
149
+ '_tables'
150
+
151
+ ___
152
+
153
+ ### user
154
+
155
+ • `Optional` **user**: `string`
156
+
157
+ 数据库用户名
@@ -0,0 +1,28 @@
1
+ [@zenorm/generate](../README.md) / [Exports](../modules.md) / TabelDescribe
2
+
3
+ # Interface: TabelDescribe
4
+
5
+ 模型文件生成 - 表描述
6
+
7
+ ## Table of contents
8
+
9
+ ### Properties
10
+
11
+ - [columns](TabelDescribe.md#columns)
12
+ - [name](TabelDescribe.md#name)
13
+
14
+ ## Properties
15
+
16
+ ### columns
17
+
18
+ • **columns**: [`ColumnDescribe`](ColumnDescribe.md)[]
19
+
20
+ 列描述信息
21
+
22
+ ___
23
+
24
+ ### name
25
+
26
+ • **name**: `string`
27
+
28
+ 表名称
@@ -0,0 +1,38 @@
1
+ [@zenorm/generate](README.md) / Exports
2
+
3
+ # @zenorm/generate
4
+
5
+ ## Table of contents
6
+
7
+ ### Interfaces
8
+
9
+ - [ColumnDescribe](interfaces/ColumnDescribe.md)
10
+ - [GenerateConfig](interfaces/GenerateConfig.md)
11
+ - [TabelDescribe](interfaces/TabelDescribe.md)
12
+
13
+ ### Type Aliases
14
+
15
+ - [GenerateFunction](modules.md#generatefunction)
16
+
17
+ ## Type Aliases
18
+
19
+ ### GenerateFunction
20
+
21
+ Ƭ **GenerateFunction**: (`config`: [`GenerateConfig`](interfaces/GenerateConfig.md)) => `AsyncGenerator`<[`TabelDescribe`](interfaces/TabelDescribe.md)\>
22
+
23
+ #### Type declaration
24
+
25
+ ▸ (`config`): `AsyncGenerator`<[`TabelDescribe`](interfaces/TabelDescribe.md)\>
26
+
27
+ 数据库表信息生成方法
28
+ - 返回表描述的处理方法
29
+
30
+ ##### Parameters
31
+
32
+ | Name | Type |
33
+ | :------ | :------ |
34
+ | `config` | [`GenerateConfig`](interfaces/GenerateConfig.md) |
35
+
36
+ ##### Returns
37
+
38
+ `AsyncGenerator`<[`TabelDescribe`](interfaces/TabelDescribe.md)\>
package/package.json CHANGED
@@ -1,45 +1,45 @@
1
- {
2
- "name": "@zenorm/generate",
3
- "description": "Easy ORM, easy query. easy typing! Auto generate typescript declaration.",
4
- "version": "1.1.1",
5
- "exports": "./dist/index.js",
6
- "types": "./dist/index.d.ts",
7
- "repository": "https://github.com/yefei/zenorm-generate",
8
- "author": "YeFei <316606233@qq.com>",
9
- "license": "MIT",
10
- "bin": {
11
- "zenorm-generate": "./dist/bin/zenorm-generate.js"
12
- },
13
- "files": [
14
- "docs",
15
- "dist"
16
- ],
17
- "scripts": {
18
- "build": "rimraf dist && tsc",
19
- "prepublishOnly": "npm run build",
20
- "gen": "cd test && ts-node ../src/bin/zenorm-generate.ts config.json",
21
- "t1": "cd test && cross-env DEBUG=* ts-node t1"
22
- },
23
- "keywords": [
24
- "mysql",
25
- "query",
26
- "model",
27
- "types",
28
- "generate",
29
- "database"
30
- ],
31
- "devDependencies": {
32
- "@types/node": "^12.20.41",
33
- "@zenorm/generate-mysql": "^1.2.0",
34
- "cross-env": "^7.0.3",
35
- "mysql-easy-query": "^3.12.0",
36
- "rimraf": "^4.4.1",
37
- "ts-node": "^10.9.1",
38
- "typescript": "^4.9.5",
39
- "zenorm": "^3.27.0"
40
- },
41
- "dependencies": {
42
- "pascal-case": "^3.1.2",
43
- "snake-case": "^3.0.4"
44
- }
45
- }
1
+ {
2
+ "name": "@zenorm/generate",
3
+ "description": "Easy ORM, easy query. easy typing! Auto generate typescript declaration.",
4
+ "version": "1.3.0",
5
+ "exports": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "repository": "https://github.com/yefei/zenorm-generate",
8
+ "author": "YeFei <316606233@qq.com>",
9
+ "license": "MIT",
10
+ "bin": {
11
+ "zenorm-generate": "./dist/bin/zenorm-generate.js"
12
+ },
13
+ "files": [
14
+ "docs",
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "rimraf dist && tsc",
19
+ "prepublishOnly": "npm run build",
20
+ "gen": "cd test && ts-node ../src/bin/zenorm-generate.ts config.json",
21
+ "t1": "cd test && cross-env DEBUG=* ts-node t1"
22
+ },
23
+ "keywords": [
24
+ "mysql",
25
+ "query",
26
+ "model",
27
+ "types",
28
+ "generate",
29
+ "database"
30
+ ],
31
+ "devDependencies": {
32
+ "@types/node": "^12.20.41",
33
+ "@zenorm/generate-mysql": "^1.2.0",
34
+ "cross-env": "^7.0.3",
35
+ "mysql-easy-query": "^3.12.0",
36
+ "rimraf": "^4.4.1",
37
+ "ts-node": "^10.9.1",
38
+ "typescript": "^4.9.5",
39
+ "zenorm": "^3.27.0"
40
+ },
41
+ "dependencies": {
42
+ "pascal-case": "^3.1.2",
43
+ "snake-case": "^3.0.4"
44
+ }
45
+ }