metal-orm 1.0.47 → 1.0.49

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.
@@ -10,757 +10,38 @@
10
10
  * Dialects supported: postgres, mysql, sqlite, mssql.
11
11
  */
12
12
 
13
- import fs from 'node:fs/promises';
14
13
  import { readFileSync } from 'node:fs';
15
14
  import path from 'node:path';
16
15
  import process from 'node:process';
17
- import { parseArgs as parseCliArgs } from 'node:util';
16
+ import { pathToFileURL } from 'node:url';
18
17
 
19
- import {
20
- introspectSchema,
21
- createPostgresExecutor,
22
- createMysqlExecutor,
23
- createSqliteExecutor,
24
- createMssqlExecutor
25
- } from '../dist/index.js';
18
+ import { parseOptions, printUsage } from './generate-entities/cli.mjs';
19
+ import { generateEntities } from './generate-entities/generate.mjs';
26
20
 
27
21
  const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
28
22
 
29
- const DIALECTS = new Set(['postgres', 'mysql', 'sqlite', 'mssql']);
23
+ const isEntrypoint =
24
+ typeof process.argv?.[1] === 'string' && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
30
25
 
31
- const parseArgs = () => {
32
- const {
33
- values,
34
- positionals
35
- } = parseCliArgs({
36
- options: {
37
- dialect: { type: 'string' },
38
- url: { type: 'string' },
39
- db: { type: 'string' },
40
- schema: { type: 'string' },
41
- include: { type: 'string' },
42
- exclude: { type: 'string' },
43
- out: { type: 'string' },
44
- 'dry-run': { type: 'boolean' },
45
- help: { type: 'boolean', short: 'h' },
46
- version: { type: 'boolean' }
47
- },
48
- strict: true
49
- });
50
-
51
- if (values.help) {
26
+ const main = async () => {
27
+ const result = parseOptions(process.argv.slice(2), process.env, process.cwd());
28
+ if (result.kind === 'help') {
52
29
  printUsage();
53
- process.exit(0);
30
+ return;
54
31
  }
55
-
56
- if (values.version) {
32
+ if (result.kind === 'version') {
57
33
  console.log(`metal-orm ${pkgVersion}`);
58
- process.exit(0);
59
- }
60
-
61
- if (positionals.length) {
62
- throw new Error(`Unexpected positional args: ${positionals.join(' ')}`);
63
- }
64
-
65
- const opts = {
66
- dialect: (values.dialect || 'postgres').toLowerCase(),
67
- url: values.url || process.env.DATABASE_URL,
68
- dbPath: values.db,
69
- schema: values.schema,
70
- include: values.include ? values.include.split(',').map(v => v.trim()).filter(Boolean) : undefined,
71
- exclude: values.exclude ? values.exclude.split(',').map(v => v.trim()).filter(Boolean) : undefined,
72
- out: values.out ? path.resolve(process.cwd(), values.out) : path.join(process.cwd(), 'generated-entities.ts'),
73
- dryRun: Boolean(values['dry-run'])
74
- };
75
-
76
- if (!DIALECTS.has(opts.dialect)) {
77
- throw new Error(`Unsupported dialect "${opts.dialect}". Supported: ${Array.from(DIALECTS).join(', ')}`);
78
- }
79
-
80
- if (opts.dialect === 'sqlite' && !opts.dbPath) {
81
- opts.dbPath = ':memory:';
82
- }
83
-
84
- if (opts.dialect !== 'sqlite' && !opts.url) {
85
- throw new Error('Missing connection string. Provide --url or set DATABASE_URL.');
86
- }
87
-
88
- return opts;
89
- };
90
-
91
- const printUsage = () => {
92
- console.log(
93
- `
94
- MetalORM decorator generator
95
- ---------------------------
96
- Usage:
97
- node scripts/generate-entities.mjs --dialect=postgres --url=<connection> --schema=public --include=users,orders [--out=src/entities.ts]
98
- node scripts/generate-entities.mjs --dialect=mysql --url=<connection> --schema=mydb --exclude=archived [--out=src/entities.ts]
99
- node scripts/generate-entities.mjs --dialect=sqlite --db=./my.db [--out=src/entities.ts]
100
- node scripts/generate-entities.mjs --dialect=mssql --url=mssql://user:pass@host/db [--out=src/entities.ts]
101
-
102
- Flags:
103
- --include=tbl1,tbl2 Only include these tables
104
- --exclude=tbl3,tbl4 Exclude these tables
105
- --dry-run Print to stdout instead of writing a file
106
- --help Show this help
107
- `
108
- );
109
- };
110
-
111
- const escapeJsString = value => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
112
-
113
- const toPascalCase = value =>
114
- value
115
- .split(/[^a-zA-Z0-9]+/)
116
- .filter(Boolean)
117
- .map(part => part.charAt(0).toUpperCase() + part.slice(1))
118
- .join('') || 'Entity';
119
-
120
- const toCamelCase = value => {
121
- const pascal = toPascalCase(value);
122
- return pascal.charAt(0).toLowerCase() + pascal.slice(1);
123
- };
124
-
125
- const singularize = name => {
126
- if (name.endsWith('ies')) return name.slice(0, -3) + 'y';
127
- if (name.endsWith('ses')) return name.slice(0, -2);
128
- if (name.endsWith('s')) return name.slice(0, -1);
129
- return name;
130
- };
131
-
132
- const pluralize = name => {
133
- if (name.endsWith('y')) return `${name.slice(0, -1)}ies`;
134
- if (name.endsWith('s')) return `${name}es`;
135
- return `${name}s`;
136
- };
137
-
138
- const deriveClassName = tableName => toPascalCase(singularize(tableName));
139
-
140
- const toSnakeCase = value =>
141
- value
142
- .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
143
- .replace(/[^a-z0-9_]+/gi, '_')
144
- .replace(/__+/g, '_')
145
- .replace(/^_|_$/g, '')
146
- .toLowerCase();
147
-
148
- const deriveDefaultTableNameFromClass = className => {
149
- const normalized = toSnakeCase(className);
150
- if (!normalized) return 'unknown';
151
- return normalized.endsWith('s') ? normalized : `${normalized}s`;
152
- };
153
-
154
- const deriveBelongsToName = (fkName, targetTable) => {
155
- const trimmed = fkName.replace(/_?id$/i, '');
156
- const base = trimmed && trimmed !== fkName ? trimmed : singularize(targetTable);
157
- return toCamelCase(base);
158
- };
159
-
160
- const deriveHasManyName = targetTable => toCamelCase(pluralize(targetTable));
161
- const deriveBelongsToManyName = targetTable => toCamelCase(pluralize(targetTable));
162
-
163
- const parseColumnType = colTypeRaw => {
164
- const type = (colTypeRaw || '').toLowerCase();
165
- const lengthMatch = type.match(/\((\d+)(?:\s*,\s*(\d+))?\)/);
166
- const length = lengthMatch ? Number(lengthMatch[1]) : undefined;
167
- const scale = lengthMatch && lengthMatch[2] ? Number(lengthMatch[2]) : undefined;
168
-
169
- const base = type.replace(/\(.*\)/, '');
170
-
171
- if (base === 'bit') return { factory: 'col.boolean()', ts: 'boolean' };
172
- if (base.includes('bigint')) return { factory: 'col.bigint()', ts: 'number' };
173
- if (base.includes('int')) return { factory: 'col.int()', ts: 'number' };
174
- if (base.includes('uuid') || base.includes('uniqueidentifier')) return { factory: 'col.uuid()', ts: 'string' };
175
- if (base === 'date') return { factory: 'col.date<Date>()', ts: 'Date' };
176
- if (base.includes('datetime') || base === 'time') return { factory: 'col.datetime<Date>()', ts: 'Date' };
177
- if (base.includes('char') || base.includes('text')) {
178
- const lenArg = length ? `${length}` : '255';
179
- return { factory: `col.varchar(${lenArg})`, ts: 'string' };
180
- }
181
- if (base.includes('json')) return { factory: 'col.json()', ts: 'any' };
182
- if (base.includes('bool') || (base.includes('tinyint') && length === 1)) {
183
- return { factory: 'col.boolean()', ts: 'boolean' };
184
- }
185
- if (base.includes('date') || base.includes('time')) return { factory: 'col.datetime<Date>()', ts: 'Date' };
186
- if (base.includes('decimal') || base.includes('numeric')) {
187
- const precision = length ?? 10;
188
- const scaleVal = scale ?? 0;
189
- return { factory: `col.decimal(${precision}, ${scaleVal})`, ts: 'number' };
190
- }
191
- if (base.includes('double')) return { factory: 'col.float()', ts: 'number' };
192
- if (base.includes('float') || base.includes('real')) return { factory: 'col.float()', ts: 'number' };
193
- if (base.includes('blob') || base.includes('binary') || base.includes('bytea')) {
194
- return { factory: 'col.blob()', ts: 'Buffer' };
195
- }
196
-
197
- return { factory: `col.varchar(255) /* TODO: review type ${colTypeRaw} */`, ts: 'any' };
198
- };
199
-
200
- const normalizeDefault = value => {
201
- if (value === undefined) return undefined;
202
- if (value === null) return { kind: 'value', code: 'null' };
203
- if (typeof value === 'number' || typeof value === 'boolean') {
204
- return { kind: 'value', code: JSON.stringify(value) };
205
- }
206
- if (typeof value === 'string') {
207
- const trimmed = value.trim();
208
- if (/^[-]?\d+(\.\d+)?$/.test(trimmed)) return { kind: 'value', code: trimmed };
209
- if (/^(true|false)$/i.test(trimmed)) return { kind: 'value', code: trimmed.toLowerCase() };
210
- if (/^null$/i.test(trimmed)) return { kind: 'value', code: 'null' };
211
- if (/current_|now\(\)|uuid_generate_v4|uuid\(\)/i.test(trimmed) || trimmed.includes('(')) {
212
- return { kind: 'raw', code: `'${escapeJsString(trimmed)}'` };
213
- }
214
- if (/^'.*'$/.test(trimmed) || /^".*"$/.test(trimmed)) {
215
- const unquoted = trimmed.slice(1, -1);
216
- return { kind: 'value', code: `'${escapeJsString(unquoted)}'` };
217
- }
218
- return { kind: 'raw', code: `'${escapeJsString(trimmed)}'` };
219
- }
220
- return { kind: 'value', code: JSON.stringify(value) };
221
- };
222
-
223
- const renderColumnExpression = (column, tablePk) => {
224
- const base = parseColumnType(column.type);
225
- let expr = base.factory;
226
-
227
- if (column.autoIncrement) {
228
- expr = `col.autoIncrement(${expr})`;
229
- }
230
- if (column.notNull) {
231
- expr = `col.notNull(${expr})`;
232
- }
233
- if (column.unique) {
234
- const name = typeof column.unique === 'string' ? `, '${escapeJsString(column.unique)}'` : '';
235
- expr = `col.unique(${expr}${name})`;
236
- }
237
- if (column.default !== undefined) {
238
- const def = normalizeDefault(column.default);
239
- if (def) {
240
- expr =
241
- def.kind === 'raw'
242
- ? `col.defaultRaw(${expr}, ${def.code})`
243
- : `col.default(${expr}, ${def.code})`;
244
- }
245
- }
246
- if (column.references) {
247
- const refParts = [
248
- `table: '${escapeJsString(column.references.table)}'`,
249
- `column: '${escapeJsString(column.references.column)}'`
250
- ];
251
- if (column.references.onDelete) refParts.push(`onDelete: '${escapeJsString(column.references.onDelete)}'`);
252
- if (column.references.onUpdate) refParts.push(`onUpdate: '${escapeJsString(column.references.onUpdate)}'`);
253
- expr = `col.references(${expr}, { ${refParts.join(', ')} })`;
254
- }
255
-
256
- const isPrimary = Array.isArray(tablePk) && tablePk.includes(column.name);
257
- const decorator = isPrimary ? 'PrimaryKey' : 'Column';
258
- const tsType = base.ts || 'any';
259
- const optional = !column.notNull;
260
-
261
- return {
262
- decorator,
263
- expr,
264
- tsType,
265
- optional
266
- };
267
- };
268
-
269
- const mapRelations = tables => {
270
- const normalizeName = name => (typeof name === 'string' && name.includes('.') ? name.split('.').pop() : name);
271
- const relationMap = new Map();
272
- const relationKeys = new Map();
273
- const fkIndex = new Map();
274
-
275
- for (const table of tables) {
276
- relationMap.set(table.name, []);
277
- relationKeys.set(table.name, new Set());
278
- for (const col of table.columns) {
279
- if (col.references) {
280
- const list = fkIndex.get(table.name) || [];
281
- list.push(col);
282
- fkIndex.set(table.name, list);
283
- }
284
- }
285
- }
286
-
287
- const findTable = name => {
288
- const norm = normalizeName(name);
289
- return tables.find(t => t.name === name || t.name === norm);
290
- };
291
-
292
- const pivotTables = new Set();
293
- for (const table of tables) {
294
- const fkCols = fkIndex.get(table.name) || [];
295
- const distinctTargets = Array.from(new Set(fkCols.map(c => normalizeName(c.references.table))));
296
- if (fkCols.length === 2 && distinctTargets.length === 2) {
297
- const [a, b] = fkCols;
298
- pivotTables.add(table.name);
299
- const targetA = findTable(a.references.table);
300
- const targetB = findTable(b.references.table);
301
- if (targetA && targetB) {
302
- const aKey = relationKeys.get(targetA.name);
303
- const bKey = relationKeys.get(targetB.name);
304
- const aProp = deriveBelongsToManyName(targetB.name);
305
- const bProp = deriveBelongsToManyName(targetA.name);
306
- if (!aKey.has(aProp)) {
307
- aKey.add(aProp);
308
- relationMap.get(targetA.name)?.push({
309
- kind: 'belongsToMany',
310
- property: aProp,
311
- target: targetB.name,
312
- pivotTable: table.name,
313
- pivotForeignKeyToRoot: a.name,
314
- pivotForeignKeyToTarget: b.name
315
- });
316
- }
317
- if (!bKey.has(bProp)) {
318
- bKey.add(bProp);
319
- relationMap.get(targetB.name)?.push({
320
- kind: 'belongsToMany',
321
- property: bProp,
322
- target: targetA.name,
323
- pivotTable: table.name,
324
- pivotForeignKeyToRoot: b.name,
325
- pivotForeignKeyToTarget: a.name
326
- });
327
- }
328
- }
329
- }
330
- }
331
-
332
- for (const table of tables) {
333
- const fkCols = fkIndex.get(table.name) || [];
334
- for (const fk of fkCols) {
335
- const targetTable = fk.references.table;
336
- const targetKey = normalizeName(targetTable);
337
- const belongsKey = relationKeys.get(table.name);
338
- const hasManyKey = targetKey ? relationKeys.get(targetKey) : undefined;
339
-
340
- if (!belongsKey || !hasManyKey) continue;
341
-
342
- const belongsProp = deriveBelongsToName(fk.name, targetTable);
343
- if (!belongsKey.has(belongsProp)) {
344
- belongsKey.add(belongsProp);
345
- relationMap.get(table.name)?.push({
346
- kind: 'belongsTo',
347
- property: belongsProp,
348
- target: targetTable,
349
- foreignKey: fk.name
350
- });
351
- }
352
-
353
- const hasManyProp = deriveHasManyName(table.name);
354
- if (!hasManyKey.has(hasManyProp)) {
355
- hasManyKey.add(hasManyProp);
356
- relationMap.get(targetKey)?.push({
357
- kind: 'hasMany',
358
- property: hasManyProp,
359
- target: table.name,
360
- foreignKey: fk.name
361
- });
362
- }
363
- }
34
+ return;
364
35
  }
365
-
366
- return relationMap;
36
+ await generateEntities(result.options);
367
37
  };
368
38
 
369
- const renderEntityFile = (schema, options) => {
370
- const tables = schema.tables.map(t => ({
371
- name: t.name,
372
- schema: t.schema,
373
- columns: t.columns,
374
- primaryKey: t.primaryKey || []
375
- }));
376
-
377
- const classNames = new Map();
378
- tables.forEach(t => {
379
- const className = deriveClassName(t.name);
380
- classNames.set(t.name, className);
381
- if (t.schema) {
382
- const qualified = `${t.schema}.${t.name}`;
383
- if (!classNames.has(qualified)) {
384
- classNames.set(qualified, className);
385
- }
386
- }
39
+ if (isEntrypoint) {
40
+ main().catch(err => {
41
+ console.error(err);
42
+ process.exit(1);
387
43
  });
44
+ }
388
45
 
389
- const resolveClassName = target => {
390
- if (!target) return undefined;
391
- if (classNames.has(target)) return classNames.get(target);
392
- const fallback = target.split('.').pop();
393
- if (fallback && classNames.has(fallback)) {
394
- return classNames.get(fallback);
395
- }
396
- return undefined;
397
- };
398
-
399
- const relations = mapRelations(tables);
400
-
401
- const usage = {
402
- needsCol: false,
403
- needsEntity: tables.length > 0,
404
- needsColumnDecorator: false,
405
- needsPrimaryKeyDecorator: false,
406
- needsHasManyDecorator: false,
407
- needsBelongsToDecorator: false,
408
- needsBelongsToManyDecorator: false,
409
- needsHasManyCollection: false,
410
- needsManyToManyCollection: false
411
- };
412
-
413
- const lines = [];
414
- lines.push('// AUTO-GENERATED by scripts/generate-entities.mjs');
415
- lines.push('// Regenerate after schema changes.');
416
- const imports = [];
417
-
418
- for (const table of tables) {
419
- for (const col of table.columns) {
420
- usage.needsCol = true;
421
- const rendered = renderColumnExpression(col, table.primaryKey);
422
- if (rendered.decorator === 'PrimaryKey') {
423
- usage.needsPrimaryKeyDecorator = true;
424
- } else {
425
- usage.needsColumnDecorator = true;
426
- }
427
- }
428
-
429
- const rels = relations.get(table.name) || [];
430
- for (const rel of rels) {
431
- if (rel.kind === 'hasMany') {
432
- usage.needsHasManyDecorator = true;
433
- usage.needsHasManyCollection = true;
434
- }
435
- if (rel.kind === 'belongsTo') {
436
- usage.needsBelongsToDecorator = true;
437
- }
438
- if (rel.kind === 'belongsToMany') {
439
- usage.needsBelongsToManyDecorator = true;
440
- usage.needsManyToManyCollection = true;
441
- }
442
- }
443
- }
444
-
445
- if (usage.needsCol) {
446
- imports.push("import { col } from 'metal-orm';");
447
- }
448
-
449
- const decoratorSet = new Set(['bootstrapEntities', 'getTableDefFromEntity']);
450
- if (usage.needsEntity) decoratorSet.add('Entity');
451
- if (usage.needsColumnDecorator) decoratorSet.add('Column');
452
- if (usage.needsPrimaryKeyDecorator) decoratorSet.add('PrimaryKey');
453
- if (usage.needsHasManyDecorator) decoratorSet.add('HasMany');
454
- if (usage.needsBelongsToDecorator) decoratorSet.add('BelongsTo');
455
- if (usage.needsBelongsToManyDecorator) decoratorSet.add('BelongsToMany');
456
- const decoratorOrder = [
457
- 'Entity',
458
- 'Column',
459
- 'PrimaryKey',
460
- 'HasMany',
461
- 'BelongsTo',
462
- 'BelongsToMany',
463
- 'bootstrapEntities',
464
- 'getTableDefFromEntity'
465
- ];
466
- const decoratorImports = decoratorOrder.filter(name => decoratorSet.has(name));
467
- if (decoratorImports.length) {
468
- imports.push(`import { ${decoratorImports.join(', ')} } from 'metal-orm';`);
469
- }
470
-
471
- const ormTypes = [];
472
- if (usage.needsHasManyCollection) ormTypes.push('HasManyCollection');
473
- if (usage.needsManyToManyCollection) ormTypes.push('ManyToManyCollection');
474
- if (ormTypes.length) {
475
- imports.push(`import { ${ormTypes.join(', ')} } from 'metal-orm';`);
476
- }
477
-
478
- if (imports.length) {
479
- lines.push(...imports, '');
480
- }
481
-
482
- for (const table of tables) {
483
- const className = classNames.get(table.name);
484
- const derivedDefault = deriveDefaultTableNameFromClass(className);
485
- const needsTableNameOption = table.name !== derivedDefault;
486
- const entityOpts = needsTableNameOption ? `{ tableName: '${escapeJsString(table.name)}' }` : '';
487
- lines.push(`@Entity(${entityOpts})`);
488
- lines.push(`export class ${className} {`);
489
-
490
- for (const col of table.columns) {
491
- const rendered = renderColumnExpression(col, table.primaryKey);
492
- lines.push(` @${rendered.decorator}(${rendered.expr})`);
493
- lines.push(` ${col.name}${rendered.optional ? '?:' : '!:'} ${rendered.tsType};`);
494
- lines.push('');
495
- }
496
-
497
- const rels = relations.get(table.name) || [];
498
- for (const rel of rels) {
499
- const targetClass = resolveClassName(rel.target);
500
- if (!targetClass) continue;
501
- switch (rel.kind) {
502
- case 'belongsTo':
503
- lines.push(
504
- ` @BelongsTo({ target: () => ${targetClass}, foreignKey: '${escapeJsString(rel.foreignKey)}' })`
505
- );
506
- lines.push(` ${rel.property}?: ${targetClass};`);
507
- lines.push('');
508
- break;
509
- case 'hasMany':
510
- lines.push(
511
- ` @HasMany({ target: () => ${targetClass}, foreignKey: '${escapeJsString(rel.foreignKey)}' })`
512
- );
513
- lines.push(` ${rel.property}!: HasManyCollection<${targetClass}>;`);
514
- lines.push('');
515
- break;
516
- case 'belongsToMany':
517
- const pivotClass = resolveClassName(rel.pivotTable);
518
- if (!pivotClass) break;
519
- lines.push(
520
- ` @BelongsToMany({ target: () => ${targetClass}, pivotTable: () => ${pivotClass}, pivotForeignKeyToRoot: '${escapeJsString(rel.pivotForeignKeyToRoot)}', pivotForeignKeyToTarget: '${escapeJsString(rel.pivotForeignKeyToTarget)}' })`
521
- );
522
- lines.push(` ${rel.property}!: ManyToManyCollection<${targetClass}>;`);
523
- lines.push('');
524
- break;
525
- default:
526
- break;
527
- }
528
- }
529
-
530
- lines.push('}');
531
- lines.push('');
532
- }
533
-
534
- lines.push(
535
- 'export const bootstrapEntityTables = () => {',
536
- ' const tables = bootstrapEntities();',
537
- ' return {',
538
- ...tables.map(t => ` ${classNames.get(t.name)}: getTableDefFromEntity(${classNames.get(t.name)})!,`),
539
- ' };',
540
- '};'
541
- );
542
-
543
- lines.push('');
544
- lines.push(
545
- 'export const allTables = () => bootstrapEntities();'
546
- );
547
-
548
- return lines.join('\n');
549
- };
550
-
551
- const parseSqlServerConnectionConfig = connectionString => {
552
- if (!connectionString) {
553
- throw new Error('Missing connection string for SQL Server');
554
- }
555
- const url = new URL(connectionString);
556
- const config = {
557
- server: url.hostname,
558
- authentication: {
559
- type: 'default',
560
- options: {
561
- userName: decodeURIComponent(url.username || ''),
562
- password: decodeURIComponent(url.password || '')
563
- }
564
- },
565
- options: {}
566
- };
567
-
568
- const database = url.pathname ? url.pathname.replace(/^\//, '') : '';
569
- if (database) {
570
- config.options.database = database;
571
- }
572
- if (url.port) {
573
- config.options.port = Number(url.port);
574
- }
575
-
576
- for (const [key, value] of url.searchParams) {
577
- config.options[key] = parseSqlServerOptionValue(value);
578
- }
579
-
580
- return config;
581
- };
582
-
583
- const parseSqlServerOptionValue = value => {
584
- if (!value) return value;
585
- if (/^-?\d+$/.test(value)) return Number(value);
586
- if (/^(true|false)$/i.test(value)) return value.toLowerCase() === 'true';
587
- return value;
588
- };
589
-
590
- const getTediousParameterType = (value, TYPES) => {
591
- if (value === null || value === undefined) {
592
- return TYPES.NVarChar;
593
- }
594
- if (typeof value === 'number') {
595
- return Number.isInteger(value) ? TYPES.Int : TYPES.Float;
596
- }
597
- if (typeof value === 'bigint') {
598
- return TYPES.BigInt;
599
- }
600
- if (typeof value === 'boolean') {
601
- return TYPES.Bit;
602
- }
603
- if (value instanceof Date) {
604
- return TYPES.DateTime;
605
- }
606
- if (Buffer.isBuffer(value)) {
607
- return TYPES.VarBinary;
608
- }
609
- return TYPES.NVarChar;
610
- };
611
-
612
- const loadDriver = async (dialect, url, dbPath) => {
613
- switch (dialect) {
614
- case 'postgres': {
615
- const mod = await import('pg');
616
- const { Client } = mod;
617
- const client = new Client({ connectionString: url });
618
- await client.connect();
619
- const executor = createPostgresExecutor(client);
620
- const cleanup = async () => client.end();
621
- return { executor, cleanup };
622
- }
623
- case 'mysql': {
624
- const mod = await import('mysql2/promise');
625
- const conn = await mod.createConnection(url);
626
- const executor = createMysqlExecutor({
627
- query: (...args) => conn.execute(...args),
628
- beginTransaction: () => conn.beginTransaction(),
629
- commit: () => conn.commit(),
630
- rollback: () => conn.rollback()
631
- });
632
- const cleanup = async () => conn.end();
633
- return { executor, cleanup };
634
- }
635
- case 'sqlite': {
636
- const mod = await import('sqlite3');
637
- const sqlite3 = mod.default || mod;
638
- const db = new sqlite3.Database(dbPath);
639
- const execAll = (sql, params) =>
640
- new Promise((resolve, reject) => {
641
- db.all(sql, params || [], (err, rows) => {
642
- if (err) return reject(err);
643
- resolve(rows);
644
- });
645
- });
646
- const executor = createSqliteExecutor({
647
- all: execAll,
648
- beginTransaction: () => execAll('BEGIN'),
649
- commitTransaction: () => execAll('COMMIT'),
650
- rollbackTransaction: () => execAll('ROLLBACK')
651
- });
652
- const cleanup = async () =>
653
- new Promise((resolve, reject) => db.close(err => (err ? reject(err) : resolve())));
654
- return { executor, cleanup };
655
- }
656
- case 'mssql': {
657
- const mod = await import('tedious');
658
- const { Connection, Request, TYPES } = mod;
659
- const config = parseSqlServerConnectionConfig(url);
660
- const connection = new Connection(config);
661
-
662
- await new Promise((resolve, reject) => {
663
- const onConnect = err => {
664
- connection.removeListener('error', onError);
665
- if (err) return reject(err);
666
- resolve();
667
- };
668
- const onError = err => {
669
- connection.removeListener('connect', onConnect);
670
- reject(err);
671
- };
672
- connection.once('connect', onConnect);
673
- connection.once('error', onError);
674
- // Tedious requires an explicit connect() call to start the handshake.
675
- connection.connect();
676
- });
677
-
678
- const execQuery = (sql, params) =>
679
- new Promise((resolve, reject) => {
680
- const rows = [];
681
- const request = new Request(sql, err => {
682
- if (err) return reject(err);
683
- resolve({ recordset: rows });
684
- });
685
- request.on('row', columns => {
686
- const row = {};
687
- for (const column of columns) {
688
- row[column.metadata.colName] = column.value;
689
- }
690
- rows.push(row);
691
- });
692
- params?.forEach((value, index) => {
693
- request.addParameter(`p${index + 1}`, getTediousParameterType(value, TYPES), value);
694
- });
695
- connection.execSql(request);
696
- });
697
-
698
- const executor = createMssqlExecutor({
699
- query: execQuery,
700
- beginTransaction: () =>
701
- new Promise((resolve, reject) => {
702
- connection.beginTransaction(err => (err ? reject(err) : resolve()));
703
- }),
704
- commit: () =>
705
- new Promise((resolve, reject) => {
706
- connection.commitTransaction(err => (err ? reject(err) : resolve()));
707
- }),
708
- rollback: () =>
709
- new Promise((resolve, reject) => {
710
- connection.rollbackTransaction(err => (err ? reject(err) : resolve()));
711
- })
712
- });
713
-
714
- const cleanup = async () =>
715
- new Promise((resolve, reject) => {
716
- const onEnd = () => {
717
- connection.removeListener('error', onError);
718
- resolve();
719
- };
720
- const onError = err => {
721
- connection.removeListener('end', onEnd);
722
- reject(err);
723
- };
724
- connection.once('end', onEnd);
725
- connection.once('error', onError);
726
- connection.close();
727
- });
728
-
729
- return { executor, cleanup };
730
- }
731
- default:
732
- throw new Error(`Unsupported dialect ${dialect}`);
733
- }
734
- };
735
-
736
- const main = async () => {
737
- const opts = parseArgs();
738
-
739
- const { executor, cleanup } = await loadDriver(opts.dialect, opts.url, opts.dbPath);
740
- let schema;
741
- try {
742
- schema = await introspectSchema(executor, opts.dialect, {
743
- schema: opts.schema,
744
- includeTables: opts.include,
745
- excludeTables: opts.exclude
746
- });
747
- } finally {
748
- await cleanup?.();
749
- }
750
-
751
- const code = renderEntityFile(schema, opts);
752
-
753
- if (opts.dryRun) {
754
- console.log(code);
755
- return;
756
- }
757
-
758
- await fs.mkdir(path.dirname(opts.out), { recursive: true });
759
- await fs.writeFile(opts.out, code, 'utf8');
760
- console.log(`Wrote ${opts.out} (${schema.tables.length} tables)`);
761
- };
762
-
763
- main().catch(err => {
764
- console.error(err);
765
- process.exit(1);
766
- });
46
+ export { mapRelations, buildSchemaMetadata } from './generate-entities/schema.mjs';
47
+ export { renderEntityFile } from './generate-entities/render.mjs';