metal-orm 1.0.20 → 1.0.23

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/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "metal-orm",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
+ "bin": {
7
+ "metal-orm-gen": "./scripts/generate-entities.mjs"
8
+ },
6
9
  "exports": {
7
10
  ".": {
8
11
  "types": "./dist/index.d.ts",
@@ -18,7 +21,8 @@
18
21
  "files": [
19
22
  "dist",
20
23
  "src",
21
- "global.d.ts"
24
+ "global.d.ts",
25
+ "scripts"
22
26
  ],
23
27
  "scripts": {
24
28
  "build": "tsup",
@@ -0,0 +1,666 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Introspects a live database and generates decorator-based entity classes.
4
+ *
5
+ * Usage examples:
6
+ * node scripts/generate-entities.mjs --dialect=postgres --url=$DATABASE_URL --schema=public --include=users,orders --out=src/entities.ts
7
+ * node scripts/generate-entities.mjs --dialect=mysql --url=$DATABASE_URL --exclude=archived --out=src/entities.ts
8
+ * node scripts/generate-entities.mjs --dialect=sqlite --db=./app.db --out=src/entities.ts
9
+ *
10
+ * Dialects supported: postgres, mysql, sqlite, mssql.
11
+ */
12
+
13
+ import fs from 'node:fs/promises';
14
+ import { readFileSync } from 'node:fs';
15
+ import path from 'node:path';
16
+ import process from 'node:process';
17
+ import { parseArgs as parseCliArgs } from 'node:util';
18
+
19
+ import {
20
+ introspectSchema,
21
+ createPostgresExecutor,
22
+ createMysqlExecutor,
23
+ createSqliteExecutor,
24
+ createMssqlExecutor
25
+ } from '../dist/index.js';
26
+
27
+ const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
28
+
29
+ const DIALECTS = new Set(['postgres', 'mysql', 'sqlite', 'mssql']);
30
+
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) {
52
+ printUsage();
53
+ process.exit(0);
54
+ }
55
+
56
+ if (values.version) {
57
+ 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.includes('bigint')) return { factory: 'col.bigint()', ts: 'number' };
172
+ if (base.includes('int')) return { factory: 'col.int()', ts: 'number' };
173
+ if (base.includes('uuid')) return { factory: 'col.uuid()', ts: 'string' };
174
+ if (base.includes('char') || base.includes('text')) {
175
+ const lenArg = length ? `${length}` : '255';
176
+ return { factory: `col.varchar(${lenArg})`, ts: 'string' };
177
+ }
178
+ if (base.includes('json')) return { factory: 'col.json()', ts: 'any' };
179
+ if (base.includes('bool') || (base.includes('tinyint') && length === 1)) {
180
+ return { factory: 'col.boolean()', ts: 'boolean' };
181
+ }
182
+ if (base.includes('date') || base.includes('time')) return { factory: 'col.datetime()', ts: 'Date' };
183
+ if (base.includes('decimal') || base.includes('numeric')) {
184
+ const precision = length ?? 10;
185
+ const scaleVal = scale ?? 0;
186
+ return { factory: `col.decimal(${precision}, ${scaleVal})`, ts: 'number' };
187
+ }
188
+ if (base.includes('double')) return { factory: 'col.float()', ts: 'number' };
189
+ if (base.includes('float') || base.includes('real')) return { factory: 'col.float()', ts: 'number' };
190
+ if (base.includes('blob') || base.includes('binary') || base.includes('bytea')) {
191
+ return { factory: 'col.blob()', ts: 'Buffer' };
192
+ }
193
+
194
+ return { factory: `col.varchar(255) /* TODO: review type ${colTypeRaw} */`, ts: 'any' };
195
+ };
196
+
197
+ const normalizeDefault = value => {
198
+ if (value === undefined) return undefined;
199
+ if (value === null) return { kind: 'value', code: 'null' };
200
+ if (typeof value === 'number' || typeof value === 'boolean') {
201
+ return { kind: 'value', code: JSON.stringify(value) };
202
+ }
203
+ if (typeof value === 'string') {
204
+ const trimmed = value.trim();
205
+ if (/^[-]?\d+(\.\d+)?$/.test(trimmed)) return { kind: 'value', code: trimmed };
206
+ if (/^(true|false)$/i.test(trimmed)) return { kind: 'value', code: trimmed.toLowerCase() };
207
+ if (/^null$/i.test(trimmed)) return { kind: 'value', code: 'null' };
208
+ if (/current_|now\(\)|uuid_generate_v4|uuid\(\)/i.test(trimmed) || trimmed.includes('(')) {
209
+ return { kind: 'raw', code: `'${escapeJsString(trimmed)}'` };
210
+ }
211
+ if (/^'.*'$/.test(trimmed) || /^".*"$/.test(trimmed)) {
212
+ const unquoted = trimmed.slice(1, -1);
213
+ return { kind: 'value', code: `'${escapeJsString(unquoted)}'` };
214
+ }
215
+ return { kind: 'raw', code: `'${escapeJsString(trimmed)}'` };
216
+ }
217
+ return { kind: 'value', code: JSON.stringify(value) };
218
+ };
219
+
220
+ const renderColumnExpression = (column, tablePk) => {
221
+ const base = parseColumnType(column.type);
222
+ let expr = base.factory;
223
+
224
+ if (column.autoIncrement) {
225
+ expr = `col.autoIncrement(${expr})`;
226
+ }
227
+ if (column.notNull) {
228
+ expr = `col.notNull(${expr})`;
229
+ }
230
+ if (column.unique) {
231
+ const name = typeof column.unique === 'string' ? `, '${escapeJsString(column.unique)}'` : '';
232
+ expr = `col.unique(${expr}${name})`;
233
+ }
234
+ if (column.default !== undefined) {
235
+ const def = normalizeDefault(column.default);
236
+ if (def) {
237
+ expr =
238
+ def.kind === 'raw'
239
+ ? `col.defaultRaw(${expr}, ${def.code})`
240
+ : `col.default(${expr}, ${def.code})`;
241
+ }
242
+ }
243
+ if (column.references) {
244
+ const refParts = [
245
+ `table: '${escapeJsString(column.references.table)}'`,
246
+ `column: '${escapeJsString(column.references.column)}'`
247
+ ];
248
+ if (column.references.onDelete) refParts.push(`onDelete: '${escapeJsString(column.references.onDelete)}'`);
249
+ if (column.references.onUpdate) refParts.push(`onUpdate: '${escapeJsString(column.references.onUpdate)}'`);
250
+ expr = `col.references(${expr}, { ${refParts.join(', ')} })`;
251
+ }
252
+
253
+ const isPrimary = Array.isArray(tablePk) && tablePk.includes(column.name);
254
+ const decorator = isPrimary ? 'PrimaryKey' : 'Column';
255
+ const tsType = base.ts || 'any';
256
+ const optional = !column.notNull;
257
+
258
+ return {
259
+ decorator,
260
+ expr,
261
+ tsType,
262
+ optional
263
+ };
264
+ };
265
+
266
+ const mapRelations = tables => {
267
+ const relationMap = new Map();
268
+ const relationKeys = new Map();
269
+ const fkIndex = new Map();
270
+
271
+ for (const table of tables) {
272
+ relationMap.set(table.name, []);
273
+ relationKeys.set(table.name, new Set());
274
+ for (const col of table.columns) {
275
+ if (col.references) {
276
+ const list = fkIndex.get(table.name) || [];
277
+ list.push(col);
278
+ fkIndex.set(table.name, list);
279
+ }
280
+ }
281
+ }
282
+
283
+ const findTable = name => tables.find(t => t.name === name);
284
+
285
+ const pivotTables = new Set();
286
+ for (const table of tables) {
287
+ const fkCols = fkIndex.get(table.name) || [];
288
+ const distinctTargets = Array.from(new Set(fkCols.map(c => c.references.table)));
289
+ if (fkCols.length === 2 && distinctTargets.length === 2) {
290
+ const [a, b] = fkCols;
291
+ pivotTables.add(table.name);
292
+ const targetA = findTable(a.references.table);
293
+ const targetB = findTable(b.references.table);
294
+ if (targetA && targetB) {
295
+ const aKey = relationKeys.get(targetA.name);
296
+ const bKey = relationKeys.get(targetB.name);
297
+ const aProp = deriveBelongsToManyName(targetB.name);
298
+ const bProp = deriveBelongsToManyName(targetA.name);
299
+ if (!aKey.has(aProp)) {
300
+ aKey.add(aProp);
301
+ relationMap.get(targetA.name)?.push({
302
+ kind: 'belongsToMany',
303
+ property: aProp,
304
+ target: targetB.name,
305
+ pivotTable: table.name,
306
+ pivotForeignKeyToRoot: a.name,
307
+ pivotForeignKeyToTarget: b.name
308
+ });
309
+ }
310
+ if (!bKey.has(bProp)) {
311
+ bKey.add(bProp);
312
+ relationMap.get(targetB.name)?.push({
313
+ kind: 'belongsToMany',
314
+ property: bProp,
315
+ target: targetA.name,
316
+ pivotTable: table.name,
317
+ pivotForeignKeyToRoot: b.name,
318
+ pivotForeignKeyToTarget: a.name
319
+ });
320
+ }
321
+ }
322
+ }
323
+ }
324
+
325
+ for (const table of tables) {
326
+ const fkCols = fkIndex.get(table.name) || [];
327
+ for (const fk of fkCols) {
328
+ const targetTable = fk.references.table;
329
+ const belongsKey = relationKeys.get(table.name);
330
+ const hasManyKey = relationKeys.get(targetTable);
331
+
332
+ const belongsProp = deriveBelongsToName(fk.name, targetTable);
333
+ if (!belongsKey.has(belongsProp)) {
334
+ belongsKey.add(belongsProp);
335
+ relationMap.get(table.name)?.push({
336
+ kind: 'belongsTo',
337
+ property: belongsProp,
338
+ target: targetTable,
339
+ foreignKey: fk.name
340
+ });
341
+ }
342
+
343
+ const hasManyProp = deriveHasManyName(table.name);
344
+ if (!hasManyKey.has(hasManyProp)) {
345
+ hasManyKey.add(hasManyProp);
346
+ relationMap.get(targetTable)?.push({
347
+ kind: 'hasMany',
348
+ property: hasManyProp,
349
+ target: table.name,
350
+ foreignKey: fk.name
351
+ });
352
+ }
353
+ }
354
+ }
355
+
356
+ return relationMap;
357
+ };
358
+
359
+ const renderEntityFile = (schema, options) => {
360
+ const tables = schema.tables.map(t => ({
361
+ name: t.name,
362
+ columns: t.columns,
363
+ primaryKey: t.primaryKey || []
364
+ }));
365
+
366
+ const classNames = new Map();
367
+ tables.forEach(t => classNames.set(t.name, deriveClassName(t.name)));
368
+
369
+ const relations = mapRelations(tables);
370
+
371
+ const imports = [
372
+ "import { col } from 'metal-orm';",
373
+ "import { Entity, Column, PrimaryKey, HasMany, BelongsTo, BelongsToMany, bootstrapEntities, getTableDefFromEntity } from 'metal-orm/decorators';",
374
+ "import { HasManyCollection, ManyToManyCollection } from 'metal-orm';"
375
+ ];
376
+
377
+ const lines = [];
378
+ lines.push('// AUTO-GENERATED by scripts/generate-entities.mjs');
379
+ lines.push('// Regenerate after schema changes.');
380
+ lines.push(...imports, '');
381
+
382
+ for (const table of tables) {
383
+ const className = classNames.get(table.name);
384
+ const derivedDefault = deriveDefaultTableNameFromClass(className);
385
+ const needsTableNameOption = table.name !== derivedDefault;
386
+ const entityOpts = needsTableNameOption ? `{ tableName: '${escapeJsString(table.name)}' }` : '';
387
+ lines.push(`@Entity(${entityOpts})`);
388
+ lines.push(`export class ${className} {`);
389
+
390
+ for (const col of table.columns) {
391
+ const rendered = renderColumnExpression(col, table.primaryKey);
392
+ lines.push(` @${rendered.decorator}(${rendered.expr})`);
393
+ lines.push(` ${col.name}${rendered.optional ? '?:' : '!:'} ${rendered.tsType};`);
394
+ lines.push('');
395
+ }
396
+
397
+ const rels = relations.get(table.name) || [];
398
+ for (const rel of rels) {
399
+ const targetClass = classNames.get(rel.target);
400
+ if (!targetClass) continue;
401
+ switch (rel.kind) {
402
+ case 'belongsTo':
403
+ lines.push(
404
+ ` @BelongsTo({ target: () => ${targetClass}, foreignKey: '${escapeJsString(rel.foreignKey)}' })`
405
+ );
406
+ lines.push(` ${rel.property}?: ${targetClass};`);
407
+ lines.push('');
408
+ break;
409
+ case 'hasMany':
410
+ lines.push(
411
+ ` @HasMany({ target: () => ${targetClass}, foreignKey: '${escapeJsString(rel.foreignKey)}' })`
412
+ );
413
+ lines.push(` ${rel.property}!: HasManyCollection<${targetClass}>;`);
414
+ lines.push('');
415
+ break;
416
+ case 'belongsToMany':
417
+ lines.push(
418
+ ` @BelongsToMany({ target: () => ${targetClass}, pivotTable: () => ${classNames.get(
419
+ rel.pivotTable
420
+ )}, pivotForeignKeyToRoot: '${escapeJsString(rel.pivotForeignKeyToRoot)}', pivotForeignKeyToTarget: '${escapeJsString(rel.pivotForeignKeyToTarget)}' })`
421
+ );
422
+ lines.push(` ${rel.property}!: ManyToManyCollection<${targetClass}>;`);
423
+ lines.push('');
424
+ break;
425
+ default:
426
+ break;
427
+ }
428
+ }
429
+
430
+ lines.push('}');
431
+ lines.push('');
432
+ }
433
+
434
+ lines.push(
435
+ 'export const bootstrapEntityTables = () => {',
436
+ ' const tables = bootstrapEntities();',
437
+ ' return {',
438
+ ...tables.map(t => ` ${classNames.get(t.name)}: getTableDefFromEntity(${classNames.get(t.name)})!,`),
439
+ ' };',
440
+ '};'
441
+ );
442
+
443
+ lines.push('');
444
+ lines.push(
445
+ 'export const allTables = () => bootstrapEntities();'
446
+ );
447
+
448
+ return lines.join('\n');
449
+ };
450
+
451
+ const parseSqlServerConnectionConfig = connectionString => {
452
+ if (!connectionString) {
453
+ throw new Error('Missing connection string for SQL Server');
454
+ }
455
+ const url = new URL(connectionString);
456
+ const config = {
457
+ server: url.hostname,
458
+ authentication: {
459
+ type: 'default',
460
+ options: {
461
+ userName: decodeURIComponent(url.username || ''),
462
+ password: decodeURIComponent(url.password || '')
463
+ }
464
+ },
465
+ options: {}
466
+ };
467
+
468
+ const database = url.pathname ? url.pathname.replace(/^\//, '') : '';
469
+ if (database) {
470
+ config.options.database = database;
471
+ }
472
+ if (url.port) {
473
+ config.options.port = Number(url.port);
474
+ }
475
+
476
+ for (const [key, value] of url.searchParams) {
477
+ config.options[key] = parseSqlServerOptionValue(value);
478
+ }
479
+
480
+ return config;
481
+ };
482
+
483
+ const parseSqlServerOptionValue = value => {
484
+ if (!value) return value;
485
+ if (/^-?\d+$/.test(value)) return Number(value);
486
+ if (/^(true|false)$/i.test(value)) return value.toLowerCase() === 'true';
487
+ return value;
488
+ };
489
+
490
+ const getTediousParameterType = (value, TYPES) => {
491
+ if (value === null || value === undefined) {
492
+ return TYPES.NVarChar;
493
+ }
494
+ if (typeof value === 'number') {
495
+ return Number.isInteger(value) ? TYPES.Int : TYPES.Float;
496
+ }
497
+ if (typeof value === 'bigint') {
498
+ return TYPES.BigInt;
499
+ }
500
+ if (typeof value === 'boolean') {
501
+ return TYPES.Bit;
502
+ }
503
+ if (value instanceof Date) {
504
+ return TYPES.DateTime;
505
+ }
506
+ if (Buffer.isBuffer(value)) {
507
+ return TYPES.VarBinary;
508
+ }
509
+ return TYPES.NVarChar;
510
+ };
511
+
512
+ const loadDriver = async (dialect, url, dbPath) => {
513
+ switch (dialect) {
514
+ case 'postgres': {
515
+ const mod = await import('pg');
516
+ const { Client } = mod;
517
+ const client = new Client({ connectionString: url });
518
+ await client.connect();
519
+ const executor = createPostgresExecutor(client);
520
+ const cleanup = async () => client.end();
521
+ return { executor, cleanup };
522
+ }
523
+ case 'mysql': {
524
+ const mod = await import('mysql2/promise');
525
+ const conn = await mod.createConnection(url);
526
+ const executor = createMysqlExecutor({
527
+ query: (...args) => conn.execute(...args),
528
+ beginTransaction: () => conn.beginTransaction(),
529
+ commit: () => conn.commit(),
530
+ rollback: () => conn.rollback()
531
+ });
532
+ const cleanup = async () => conn.end();
533
+ return { executor, cleanup };
534
+ }
535
+ case 'sqlite': {
536
+ const mod = await import('sqlite3');
537
+ const sqlite3 = mod.default || mod;
538
+ const db = new sqlite3.Database(dbPath);
539
+ const execAll = (sql, params) =>
540
+ new Promise((resolve, reject) => {
541
+ db.all(sql, params || [], (err, rows) => {
542
+ if (err) return reject(err);
543
+ resolve(rows);
544
+ });
545
+ });
546
+ const executor = createSqliteExecutor({
547
+ all: execAll,
548
+ beginTransaction: () => execAll('BEGIN'),
549
+ commitTransaction: () => execAll('COMMIT'),
550
+ rollbackTransaction: () => execAll('ROLLBACK')
551
+ });
552
+ const cleanup = async () =>
553
+ new Promise((resolve, reject) => db.close(err => (err ? reject(err) : resolve())));
554
+ return { executor, cleanup };
555
+ }
556
+ case 'mssql': {
557
+ const mod = await import('tedious');
558
+ const { Connection, Request, TYPES } = mod;
559
+ const config = parseSqlServerConnectionConfig(url);
560
+ const connection = new Connection(config);
561
+
562
+ await new Promise((resolve, reject) => {
563
+ const onConnect = err => {
564
+ connection.removeListener('error', onError);
565
+ if (err) return reject(err);
566
+ resolve();
567
+ };
568
+ const onError = err => {
569
+ connection.removeListener('connect', onConnect);
570
+ reject(err);
571
+ };
572
+ connection.once('connect', onConnect);
573
+ connection.once('error', onError);
574
+ // Tedious requires an explicit connect() call to start the handshake.
575
+ connection.connect();
576
+ });
577
+
578
+ const execQuery = (sql, params) =>
579
+ new Promise((resolve, reject) => {
580
+ const rows = [];
581
+ const request = new Request(sql, err => {
582
+ if (err) return reject(err);
583
+ resolve({ recordset: rows });
584
+ });
585
+ request.on('row', columns => {
586
+ const row = {};
587
+ for (const column of columns) {
588
+ row[column.metadata.colName] = column.value;
589
+ }
590
+ rows.push(row);
591
+ });
592
+ params?.forEach((value, index) => {
593
+ request.addParameter(`p${index + 1}`, getTediousParameterType(value, TYPES), value);
594
+ });
595
+ connection.execSql(request);
596
+ });
597
+
598
+ const executor = createMssqlExecutor({
599
+ query: execQuery,
600
+ beginTransaction: () =>
601
+ new Promise((resolve, reject) => {
602
+ connection.beginTransaction(err => (err ? reject(err) : resolve()));
603
+ }),
604
+ commit: () =>
605
+ new Promise((resolve, reject) => {
606
+ connection.commitTransaction(err => (err ? reject(err) : resolve()));
607
+ }),
608
+ rollback: () =>
609
+ new Promise((resolve, reject) => {
610
+ connection.rollbackTransaction(err => (err ? reject(err) : resolve()));
611
+ })
612
+ });
613
+
614
+ const cleanup = async () =>
615
+ new Promise((resolve, reject) => {
616
+ const onEnd = () => {
617
+ connection.removeListener('error', onError);
618
+ resolve();
619
+ };
620
+ const onError = err => {
621
+ connection.removeListener('end', onEnd);
622
+ reject(err);
623
+ };
624
+ connection.once('end', onEnd);
625
+ connection.once('error', onError);
626
+ connection.close();
627
+ });
628
+
629
+ return { executor, cleanup };
630
+ }
631
+ default:
632
+ throw new Error(`Unsupported dialect ${dialect}`);
633
+ }
634
+ };
635
+
636
+ const main = async () => {
637
+ const opts = parseArgs();
638
+
639
+ const { executor, cleanup } = await loadDriver(opts.dialect, opts.url, opts.dbPath);
640
+ let schema;
641
+ try {
642
+ schema = await introspectSchema(executor, opts.dialect, {
643
+ schema: opts.schema,
644
+ includeTables: opts.include,
645
+ excludeTables: opts.exclude
646
+ });
647
+ } finally {
648
+ await cleanup?.();
649
+ }
650
+
651
+ const code = renderEntityFile(schema, opts);
652
+
653
+ if (opts.dryRun) {
654
+ console.log(code);
655
+ return;
656
+ }
657
+
658
+ await fs.mkdir(path.dirname(opts.out), { recursive: true });
659
+ await fs.writeFile(opts.out, code, 'utf8');
660
+ console.log(`Wrote ${opts.out} (${schema.tables.length} tables)`);
661
+ };
662
+
663
+ main().catch(err => {
664
+ console.error(err);
665
+ process.exit(1);
666
+ });