baja-lite 1.0.4 → 1.0.5

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.
Files changed (74) hide show
  1. package/cjs/boot-remote.d.ts +2 -0
  2. package/cjs/boot-remote.js +35 -0
  3. package/cjs/boot.d.ts +2 -0
  4. package/cjs/boot.js +152 -0
  5. package/cjs/code.d.ts +1 -0
  6. package/cjs/code.js +345 -1
  7. package/cjs/convert-xml.d.ts +10 -0
  8. package/cjs/convert-xml.js +413 -0
  9. package/cjs/enum.d.ts +10 -0
  10. package/cjs/enum.js +32 -0
  11. package/cjs/error.js +1 -1
  12. package/cjs/index.d.ts +2 -0
  13. package/cjs/index.js +2 -0
  14. package/cjs/object.d.ts +7 -1
  15. package/cjs/object.js +36 -2
  16. package/cjs/sql.d.ts +405 -148
  17. package/cjs/sql.js +1229 -861
  18. package/cjs/sqlite.d.ts +38 -0
  19. package/cjs/sqlite.js +194 -0
  20. package/cjs/test-mysql.d.ts +1 -1
  21. package/cjs/test-mysql.js +72 -63
  22. package/cjs/test-sqlite.d.ts +1 -1
  23. package/cjs/test-sqlite.js +3 -1
  24. package/cjs/test-xml.d.ts +1 -0
  25. package/cjs/test-xml.js +75 -0
  26. package/es/boot-remote.d.ts +2 -0
  27. package/es/boot-remote.js +31 -0
  28. package/es/boot.d.ts +2 -0
  29. package/es/boot.js +125 -0
  30. package/es/code.d.ts +1 -0
  31. package/es/code.js +341 -2
  32. package/es/convert-xml.d.ts +10 -0
  33. package/es/convert-xml.js +409 -0
  34. package/es/enum.d.ts +10 -0
  35. package/es/enum.js +28 -0
  36. package/es/error.js +1 -1
  37. package/es/index.d.ts +2 -0
  38. package/es/index.js +2 -0
  39. package/es/object.d.ts +7 -1
  40. package/es/object.js +28 -1
  41. package/es/sql.d.ts +405 -148
  42. package/es/sql.js +1099 -735
  43. package/es/sqlite.d.ts +38 -0
  44. package/es/sqlite.js +164 -0
  45. package/es/test-mysql.d.ts +1 -1
  46. package/es/test-mysql.js +72 -63
  47. package/es/test-sqlite.d.ts +1 -1
  48. package/es/test-sqlite.js +3 -1
  49. package/es/test-xml.d.ts +1 -0
  50. package/es/test-xml.js +70 -0
  51. package/package.json +10 -7
  52. package/src/boot-remote.ts +31 -0
  53. package/src/boot.ts +129 -0
  54. package/src/code.ts +326 -1
  55. package/src/convert-xml.ts +461 -0
  56. package/src/enum.ts +31 -0
  57. package/src/error.ts +1 -1
  58. package/src/index.ts +3 -1
  59. package/src/object.ts +47 -14
  60. package/src/sql.ts +1145 -787
  61. package/src/sqlite.ts +161 -0
  62. package/src/test-mysql.ts +72 -63
  63. package/src/test-sqlite.ts +3 -1
  64. package/src/test-xml.ts +70 -0
  65. package/cjs/constant.d.ts +0 -13
  66. package/cjs/constant.js +0 -19
  67. package/cjs/redis.d.ts +0 -0
  68. package/cjs/redis.js +0 -1
  69. package/es/constant.d.ts +0 -13
  70. package/es/constant.js +0 -16
  71. package/es/redis.d.ts +0 -0
  72. package/es/redis.js +0 -1
  73. package/src/constant.ts +0 -14
  74. package/src/redis.ts +0 -0
package/src/boot.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { _GlobalSqlOption, GlobalSqlOption, _EventBus, _defOption, logger, _sqlCache, SqlCache, _dao, DBType, _primaryDB, SqliteRemote, _fs, _path, Mysql, Sqlite, _Hump, ColumnMode } from './sql';
2
+
3
+ export const Boot = async function (options: GlobalSqlOption) {
4
+ globalThis[_GlobalSqlOption] = Object.assign({}, _defOption, options);
5
+ globalThis[_Hump] = globalThis[_GlobalSqlOption].columnMode === ColumnMode.HUMP;
6
+ if (options.sqlDir) {
7
+ globalThis[_path] = await import('path');
8
+ globalThis[_fs] = await import('fs');
9
+ }
10
+ logger.level = options.log ?? 'info';
11
+ globalThis[_sqlCache] = new SqlCache();
12
+ if (options.sqlMap || options.sqlDir) {
13
+ await globalThis[_sqlCache].init(options);
14
+ }
15
+ globalThis[_dao] = {
16
+ [DBType.Mongo]: {},
17
+ [DBType.Mysql]: {},
18
+ [DBType.Sqlite]: {},
19
+ [DBType.SqliteRemote]: {},
20
+ [DBType.Redis]: {}
21
+ };
22
+ if (options.Mysql) {
23
+ const { createPool } = await import('mysql2/promise');
24
+ if (options.Mysql['host']) {
25
+ globalThis[_dao][DBType.Mysql][_primaryDB] = new Mysql(createPool({
26
+ ...options.Mysql,
27
+ multipleStatements: true,
28
+ decimalNumbers: true,
29
+ supportBigNumbers: true
30
+ }));
31
+ } else {
32
+ let flag = false;
33
+ for (const [key, option] of Object.entries(options.Mysql)) {
34
+ const db = new Mysql(createPool({
35
+ ...option,
36
+ multipleStatements: true,
37
+ decimalNumbers: true,
38
+ supportBigNumbers: true
39
+ }));
40
+ if (flag === false) {
41
+ globalThis[_dao][DBType.Mysql][_primaryDB] = db;
42
+ flag = true;
43
+ }
44
+ globalThis[_dao][DBType.Mysql][key] = db;
45
+ }
46
+ }
47
+ }
48
+ if (options.Sqlite) {
49
+ const BetterSqlite3 = await import('better-sqlite3');
50
+ if (typeof options.Sqlite === 'string') {
51
+ globalThis[_dao][DBType.Sqlite][_primaryDB] = new Sqlite(new BetterSqlite3.default(options.Sqlite, { fileMustExist: false }));
52
+ } else {
53
+ let flag = false;
54
+ for (const [key, fileName] of Object.entries(options.Sqlite)) {
55
+ const db = new Sqlite(new BetterSqlite3.default(fileName, { fileMustExist: false }));
56
+ if (flag === false) {
57
+ globalThis[_dao][DBType.Sqlite][_primaryDB] = db;
58
+ flag = true;
59
+ }
60
+ globalThis[_dao][DBType.Sqlite][key] = db;
61
+ }
62
+ }
63
+ }
64
+ if (options.SqliteRemote) {
65
+ if (typeof options.SqliteRemote.db === 'string') {
66
+ await options.SqliteRemote.service.initDB(options.SqliteRemote.db);
67
+ globalThis[_dao][DBType.SqliteRemote][_primaryDB] = new SqliteRemote(options.SqliteRemote.service, options.SqliteRemote.db);
68
+ } else {
69
+ let flag = false;
70
+ for (const [key, fileName] of Object.entries(options.SqliteRemote.db)) {
71
+ await options.SqliteRemote.service.initDB(fileName);
72
+ const db = new SqliteRemote(options.SqliteRemote.service, fileName);
73
+ if (flag === false) {
74
+ globalThis[_dao][DBType.SqliteRemote][_primaryDB] = db;
75
+ flag = true;
76
+ }
77
+ globalThis[_dao][DBType.SqliteRemote][key] = db;
78
+ }
79
+ }
80
+ }
81
+ if (options.Redis) {
82
+ const { Redis } = await import('ioredis');
83
+ if (options.Redis['host']) {
84
+ globalThis[_dao][DBType.Redis][_primaryDB] = new Redis(options.Redis);
85
+ } else {
86
+ let flag = false;
87
+ for (const [key, option] of Object.entries(options.Redis)) {
88
+ const db = new Redis(option);
89
+ if (flag === false) {
90
+ globalThis[_dao][DBType.Redis][_primaryDB] = db;
91
+ flag = true;
92
+ }
93
+ globalThis[_dao][DBType.Redis][key] = db;
94
+ }
95
+ }
96
+ const clients = Object.values(globalThis[_dao][DBType.Redis]) as any;
97
+ const Redlock = await import('redlock');
98
+ globalThis[_dao][DBType.RedisLock] = new Redlock.default(
99
+ clients,
100
+ {
101
+ // The expected clock drift; for more details see:
102
+ // http://redis.io/topics/distlock
103
+ driftFactor: 0.01, // multiplied by lock ttl to determine drift time
104
+
105
+ // The max number of times Redlock will attempt to lock a resource
106
+ // before erroring.
107
+ retryCount: 10,
108
+
109
+ // the time in ms between attempts
110
+ retryDelay: 200, // time in ms
111
+
112
+ // the max time in ms randomly added to retries
113
+ // to improve performance under high contention
114
+ // see https://www.awsarchitectureblog.com/2015/03/backoff.html
115
+ retryJitter: 200, // time in ms
116
+
117
+ // The minimum remaining time on a lock before an extension is automatically
118
+ // attempted with the `using` API.
119
+ automaticExtensionThreshold: 500, // time in ms
120
+ }
121
+ );
122
+ const { EventEmitter } = await import('events');
123
+ const event = new EventEmitter({ captureRejections: true });
124
+ event.on('error', error => {
125
+ logger.error('event-bus', error);
126
+ });
127
+ globalThis[_EventBus] = event;
128
+ }
129
+ }
package/src/code.ts CHANGED
@@ -1,2 +1,327 @@
1
1
  #!/usr/bin/env node
2
- console.log(__dirname);
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import { start } from 'repl';
5
+ import { createPool } from 'mysql2/promise';
6
+ import mustache from 'mustache';
7
+
8
+ const lxMap = {
9
+ tinyint: "number",
10
+ smallint: "number",
11
+ mediumint: "number",
12
+ int: "number",
13
+ integer: "number",
14
+ bigint: "BigInt",
15
+ bit: "boolean",
16
+ double: "number",
17
+ real: "number",
18
+ float: "number",
19
+ decimal: "number",
20
+ numeric: "number",
21
+ char: "string",
22
+ varchar: "string",
23
+ date: "Date",
24
+ time: "string",
25
+ year: "string",
26
+ timestamp: "BigInt",
27
+ datetime: "Date",
28
+ tinyblob: "string",
29
+ blob: "string",
30
+ mediumblob: "string",
31
+ longblob: "string",
32
+ tinytext: "string",
33
+ text: "string",
34
+ mediumtext: "string",
35
+ longtext: "string",
36
+ enum: "string",
37
+ set: "string",
38
+ binary: "string",
39
+ varbinary: "string",
40
+ point: "Object",
41
+ linestring: "Object",
42
+ polygon: "Object",
43
+ geometry: "string",
44
+ multipoint: "Object",
45
+ multilinestring: "Object",
46
+ multipolygon: "Object",
47
+ geometrycollection: "Object"
48
+ };
49
+ let force = false;
50
+ const basepath = path.join(__dirname, '..', '..', '..');
51
+ const config = path.join(basepath, 'baja.code.json');
52
+ const templatePath = path.join(basepath, 'code-template');
53
+ console.log(`
54
+ **********************-----------
55
+ 配置文件:
56
+ 请在项目根目录添加文件:baja.code.json!配置如下:
57
+ {
58
+ "host": "",
59
+ "port": "",
60
+ "user": "",
61
+ "password": "",
62
+ "database": "",
63
+
64
+ "command": {
65
+ "entity": "src/{vueName}/{vueName}.entity.ts",
66
+ "controller": "src/{vueName}/{vueName}.controller.ts",
67
+ "service": "src/{vueName}/{vueName}.service.ts",
68
+ "sql": "src/sql/{vueName}.mu",
69
+ "module": "src/{vueName}/{vueName}.module.ts"
70
+ },
71
+ "commands": {
72
+ "s": ["entity", "controller", "service", "sql", "module"]
73
+ }
74
+ "commands": {
75
+ "s": ["entity", "controller", "service", "sql", "module"]
76
+ },
77
+ "output": "{ClassName}Module",
78
+ }
79
+ command是生成命令,这里声明命令同时定义文件生成路径:可用下面的变量替换.同时必须有同名模板.
80
+ 路径是相对于项目根目录的
81
+ commands是组合命令,上面表示输入s,同时生成:"entity", "controller", "service", "sql", "module"
82
+ output 是生成后打印出的内容
83
+ 模板转义:<%& 变量 %>
84
+ **********************-----------
85
+ **********************-----------
86
+ **********************-----------
87
+ 模板文件
88
+ 请在项目根目录的code-template添加模板文件, 按照mustache(标签定义成了[ '<%', '%>' ])进行格式化,变量:
89
+ title,
90
+
91
+ tableName,
92
+ className,
93
+ ClassName,
94
+ vueName,
95
+ splitName,
96
+
97
+ columns: [
98
+ comment:
99
+ name: sku_id
100
+ Name: skuId
101
+ Field
102
+ Type
103
+ ], Field(类型string),表示字段的注解, Type 表示JS类型
104
+ columnNames_join: 'sku_id, sku_name'
105
+ ColumnNames_join: 'sku_id skuId, sku_name skuName'
106
+
107
+ columns_no_id: [], 同columns,没有ID而已
108
+ columnNames_no_id: [],
109
+
110
+ ids: [], 参见 FieldOption,多一个参数Field,表示字段的注解, Type 表示JS类型
111
+ idNames: [], 主键字段数组
112
+ idNames_join: []
113
+
114
+ modelName: 模块名称,可能为空字符串
115
+ modelPath: 模块名称实际就影响访问路径,所以这里会直接拼好controller的模块访问路径,如果模块为空,则该属性就是空字符串,否则是 /模块名称/
116
+ -----
117
+ 命令 table1,table2,table3:模块名称
118
+ table=. 表示扫描全库表
119
+ :模块名称 可以省略
120
+ -----
121
+ force: 切换是否覆盖
122
+ `);
123
+
124
+
125
+ try {
126
+ const outputs = new Set<string>();
127
+ const _configData = fs.readFileSync(config, { encoding: 'utf-8' }).toString();
128
+ const configData = JSON.parse(_configData) ;
129
+ const templates = Object.fromEntries(fs.readdirSync(templatePath).map(r => [path.basename(r, '.mu'), fs.readFileSync(path.join(templatePath, r), { encoding: 'utf-8' }).toString()]));
130
+ const pool = createPool({
131
+ host: configData.host,
132
+ port: configData.port,
133
+ user: configData.user,
134
+ password: configData.password,
135
+ database: configData.database
136
+ });
137
+ async function getTables(tableName: string) {
138
+ const conn = await pool.getConnection();
139
+ const params = [configData.database];
140
+ let sql = `
141
+ SELECT TABLE_NAME tableName, IFNULL(TABLE_COMMENT, TABLE_NAME) title FROM information_schema.TABLES
142
+ WHERE TABLE_SCHEMA= ? AND TABLE_TYPE = 'BASE TABLE'`;
143
+ if (tableName !== '.') {
144
+ sql += ` AND TABLE_NAME IN (?)`;
145
+ params.push(tableName.split(/,|\s/).map(r => r.trim()));
146
+ }
147
+ const [result] = await conn.query<any[]>(sql, params);
148
+ conn.release();
149
+ return result;
150
+ }
151
+ async function getColumns(tableName: string) {
152
+ const conn = await pool.getConnection();
153
+ const [result] = await conn.query<any[]>(`
154
+ SELECT
155
+ DATA_TYPE type,
156
+ COLUMN_NAME \`name\`,
157
+ IFNULL(IFNULL(CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION),DATETIME_PRECISION) \`length\`,
158
+ NUMERIC_SCALE scale,
159
+ COLUMN_DEFAULT def,
160
+ IF(COLUMN_KEY = 'PRI', 1, 0) id,
161
+ IF(IS_NULLABLE = 'NO', 1, 0) notNull,
162
+ COLUMN_COMMENT \`comment\`
163
+ FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME = ?;
164
+ `, [configData.database, tableName]);
165
+ const columns = result.map(r => {
166
+ if (r.id === 1) { r.id = true; }
167
+ else delete r.id;
168
+ if (r.notNull === 1) { r.notNull = true; }
169
+ else delete r.notNull;
170
+ r.comment = `* ${r.comment??''}(\`${tableName}.${r.name}\`)`;
171
+ const fields = new Array<string>(`type:SqlType.${r.type}`);
172
+ if (r.length !== null) { fields.push(`length:${r.length}`); }
173
+ if (r.scale !== null) { fields.push(`scale:${r.scale}`); }
174
+ if (r.def !== null) {
175
+ r.def ??= '';
176
+ if (isNaN(r.def) || r.def === '') {
177
+ fields.push(`def:'${r.def}'`);
178
+ } else {
179
+ fields.push(`def:${r.def}`);
180
+ }
181
+ }
182
+ if (r.id === true) { fields.push(`id:true`); }
183
+ if (r.notNull === true) { fields.push(`notNull:true`); }
184
+ r.Type = lxMap[r.type];
185
+ r.Field = `@Field({${fields.join(',')}})`;
186
+ r.Name = r.name.replace(/_(\w)/g, (a: string, b: string) => b.toUpperCase());
187
+ return r;
188
+ });
189
+ conn.release();
190
+ return columns;
191
+ }
192
+ async function excute(command: string, input: string, modelName: string) {
193
+ const tables = await getTables(input);
194
+ if (input !== '.') {
195
+ const checkTable = input.split(/,|\s/).map(r => r.trim())
196
+ if (checkTable.length !== tables.length) {
197
+ console.error(`[错误] 输入的表与数据库查询返回表不符,数据库返回${tables.length}个:${tables.map(i => i.tableName).join(',')}`);
198
+ return;
199
+ }
200
+ }
201
+ modelName ??= '';
202
+ const modelPath = modelName ? `/${modelName}/` : '';
203
+ for (const { tableName, title } of tables) {
204
+ const columns = await getColumns(tableName);
205
+ const className = tableName.replace(/_(\w)/g, (a: string, b: string) => b.toUpperCase());
206
+ const ClassName = className.replace(/\w/, (v: string) => v.toUpperCase());
207
+ const vueName = tableName.replace(/_/g, '-');
208
+ const splitName = tableName.replace(/_/g, '/');
209
+ const data = {
210
+ title,
211
+
212
+ tableName,
213
+ className,
214
+ ClassName,
215
+ vueName,
216
+ splitName,
217
+
218
+ columns,
219
+ columnNames: columns?.map(i => i.name),
220
+ columnNames_join: columns?.map(i => i.name).join(','),
221
+ ColumnNames_join: columns?.map(i => `${i.name} ${i.Name}`).join(','),
222
+
223
+ columns_no_id: columns?.filter(i => !i.id),
224
+ columnNames_no_id: columns?.filter(i => !i.id).map(i => i.name),
225
+ columnNames_no_id_join: columns?.filter(i => !i.id).map(i => i.name).join(','),
226
+
227
+ ids: columns?.filter(i => i.id),
228
+ idNames: columns?.filter(i => i.id).map(i => i.name),
229
+ idNames_join: columns?.filter(i => i.id).map(i => i.name).join(','),
230
+
231
+ modelName,
232
+ modelPath
233
+ };
234
+ const template = templates[command];
235
+ if (!template) {
236
+ console.error(`[错误] ${command} 未定义模板!`);
237
+ return;
238
+ }
239
+ const txt = mustache.render(template, data, {}, ['<%', '%>']);
240
+ const fileName = configData.command[command].replace(/{([a-zA-Z]+)}/g, (a: string, b: string) => data[b]);
241
+ const filePath = path.join(basepath, fileName);
242
+ const dirname = path.dirname(filePath);
243
+ try {
244
+ fs.statSync(dirname);
245
+ } catch (error) {
246
+ fs.mkdirSync(dirname);
247
+ console.info(`[生成] ${dirname}`);
248
+ }
249
+ try {
250
+ fs.statSync(filePath);
251
+ if (force === false) {
252
+ console.warn(`[跳过] ${filePath}`);
253
+ return;
254
+ } else {
255
+ console.warn(`[覆盖] ${filePath}`);
256
+ }
257
+ } catch (error) {
258
+ console.info(`[生成] ${filePath}`);
259
+ }
260
+ if (configData.output) {
261
+ outputs.add(configData.output.replace(/{([a-zA-Z]+)}/g, (a: string, b: string) => data[b]));
262
+ }
263
+ fs.writeFileSync(path.join(basepath, fileName), txt);
264
+ }
265
+ }
266
+ const replServer = start();
267
+ function defineCommand(command: string, comands?: string[]) {
268
+ if (comands) {
269
+ console.log(`[组合]${command}>${comands.join(',')}注册成功`);
270
+ } else {
271
+ console.log(`[命令]${command}注册成功`);
272
+ }
273
+ if (comands) {
274
+ replServer.defineCommand(command, async input => {
275
+ outputs.clear();
276
+ const inputs = input.match(/([^:]+):{0,1}([a-zA-Z0-9]*)/);
277
+ if (inputs?.length !== 3) {
278
+ return console.error(`[错误]命令格式应为: table1,table2[:模块名]`);
279
+ }
280
+ const [_, tables, modelName] = inputs;
281
+ for (const c of comands) {
282
+ await excute(c, tables!, modelName ?? '');
283
+ }
284
+ console.info('执行完毕!下面打印生成的输出');
285
+ console.info(Array.from(outputs).join(','));
286
+ });
287
+ } else {
288
+ replServer.defineCommand(command, async input => {
289
+ outputs.clear();
290
+ const inputs = input.match(/([^:]+):{0,1}([a-zA-Z0-9]*)/);
291
+ if (inputs?.length !== 3) {
292
+ return console.error(`[错误]命令格式应为: table1,table2[:模块名]`);
293
+ }
294
+ const [_, tables, modelName] = inputs;
295
+ await excute(command, tables!, modelName ?? '');
296
+ console.info('执行完毕!下面打印生成的输出');
297
+ console.info(Array.from(outputs).join(','));
298
+ });
299
+ }
300
+ }
301
+ replServer.defineCommand('force', () => {
302
+ force = !force;
303
+ console.log(force ? '覆盖生成' : '不覆盖生成!');
304
+ });
305
+ if (configData.command) {
306
+ for (const command of Object.keys(configData.command)) {
307
+ if (!templates[command]) {
308
+ console.error(`命令:${command}没有定义模板,该命令不会生效`);
309
+ } else {
310
+ defineCommand(command);
311
+ }
312
+ }
313
+ }
314
+ if (configData.commands) {
315
+ for (const [command, commands] of Object.entries(configData.commands)) {
316
+ const keys = commands as string[];
317
+ const error = keys.filter(k => !templates[k]).join(',');
318
+ if (error) {
319
+ console.error(`组合命令:${command}定义了${commands},但是${error}没有定义模板,该命令不会生效`);
320
+ } else {
321
+ defineCommand(command, keys);
322
+ }
323
+ }
324
+ }
325
+ } catch (error) {
326
+ console.error(error);
327
+ }