forge-sql-orm-cli 1.0.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.
@@ -0,0 +1,862 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
4
+ const commander = require("commander");
5
+ const dotenv = require("dotenv");
6
+ const inquirer = require("inquirer");
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+ require("reflect-metadata");
10
+ const child_process = require("child_process");
11
+ const mysql = require("mysql2/promise");
12
+ const forgeSqlOrm = require("forge-sql-orm");
13
+ const uniqueConstraint = require("drizzle-orm/mysql-core/unique-constraint");
14
+ function replaceMySQLTypes(schemaContent) {
15
+ const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from "forge-sql-orm";
16
+
17
+ `;
18
+ let modifiedContent = schemaContent.replace(
19
+ /datetime\(['"]([^'"]+)['"],\s*{\s*mode:\s*['"]string['"]\s*}\)/g,
20
+ "forgeDateTimeString('$1')"
21
+ ).replace(/datetime\(['"]([^'"]+)['"]\)/g, "forgeDateTimeString('$1')").replace(/datetime\(\s*{\s*mode:\s*['"]string['"]\s*}\s*\)/g, "forgeDateTimeString()").replace(/time\(['"]([^'"]+)['"],\s*{\s*mode:\s*['"]string['"]\s*}\)/g, "forgeTimeString('$1')").replace(/time\(['"]([^'"]+)['"]\)/g, "forgeTimeString('$1')").replace(/time\(\s*{\s*mode:\s*['"]string['"]\s*}\s*\)/g, "forgeTimeString()").replace(/date\(['"]([^'"]+)['"],\s*{\s*mode:\s*['"]string['"]\s*}\)/g, "forgeDateString('$1')").replace(/date\(['"]([^'"]+)['"]\)/g, "forgeDateString('$1')").replace(/date\(\s*{\s*mode:\s*['"]string['"]\s*}\s*\)/g, "forgeDateString()").replace(
22
+ /timestamp\(['"]([^'"]+)['"],\s*{\s*mode:\s*['"]string['"]\s*}\)/g,
23
+ "forgeTimestampString('$1')"
24
+ ).replace(/timestamp\(['"]([^'"]+)['"]\)/g, "forgeTimestampString('$1')").replace(/timestamp\(\s*{\s*mode:\s*['"]string['"]\s*}\s*\)/g, "forgeTimestampString()");
25
+ if (!modifiedContent.includes("import { forgeDateTimeString")) {
26
+ modifiedContent = imports + modifiedContent;
27
+ }
28
+ return modifiedContent;
29
+ }
30
+ const generateModels = async (options) => {
31
+ try {
32
+ await child_process.execSync(
33
+ `npx drizzle-kit pull --dialect mysql --url mysql://${options.user}:${options.password}@${options.host}:${options.port}/${options.dbName} --out ${options.output}`,
34
+ { encoding: "utf-8" }
35
+ );
36
+ const metaDir = path.join(options.output, "meta");
37
+ const additionalMetadata = {};
38
+ if (fs.existsSync(metaDir)) {
39
+ const snapshotFile = path.join(metaDir, "0000_snapshot.json");
40
+ if (fs.existsSync(snapshotFile)) {
41
+ const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, "utf-8"));
42
+ for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {
43
+ const table = tableData;
44
+ const versionField = Object.entries(table.columns).find(
45
+ ([_, col]) => col.name.toLowerCase() === options.versionField
46
+ );
47
+ if (versionField) {
48
+ const [_, col] = versionField;
49
+ const fieldType = col.type;
50
+ const isSupportedType = fieldType === "datetime" || fieldType === "timestamp" || fieldType === "int" || fieldType === "number" || fieldType === "decimal";
51
+ if (!col.notNull) {
52
+ console.warn(
53
+ `Version field "${col.name}" in table ${tableName} is nullable. Versioning may not work correctly.`
54
+ );
55
+ } else if (!isSupportedType) {
56
+ console.warn(
57
+ `Version field "${col.name}" in table ${tableName} has unsupported type "${fieldType}". Only datetime, timestamp, int, and decimal types are supported for versioning. Versioning will be skipped.`
58
+ );
59
+ } else {
60
+ additionalMetadata[tableName] = {
61
+ tableName,
62
+ versionField: {
63
+ fieldName: col.name
64
+ }
65
+ };
66
+ }
67
+ }
68
+ }
69
+ }
70
+ }
71
+ const versionMetadataContent = `/**
72
+ * This file was auto-generated by forge-sql-orm
73
+ * Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}
74
+ *
75
+ * DO NOT EDIT THIS FILE MANUALLY
76
+ * Any changes will be overwritten on next generation
77
+ */
78
+
79
+
80
+ export * from "./relations";
81
+ export * from "./schema";
82
+
83
+ export interface VersionFieldMetadata {
84
+ fieldName: string;
85
+ }
86
+
87
+ export interface TableMetadata {
88
+ tableName: string;
89
+ versionField: VersionFieldMetadata;
90
+ }
91
+
92
+ export type AdditionalMetadata = Record<string, TableMetadata>;
93
+
94
+ export const additionalMetadata: AdditionalMetadata = ${JSON.stringify(additionalMetadata, null, 2)};
95
+ `;
96
+ fs.writeFileSync(path.join(options.output, "index.ts"), versionMetadataContent);
97
+ const schemaPath = path.join(options.output, "schema.ts");
98
+ if (fs.existsSync(schemaPath)) {
99
+ const schemaContent = fs.readFileSync(schemaPath, "utf-8");
100
+ const modifiedContent = replaceMySQLTypes(schemaContent);
101
+ fs.writeFileSync(schemaPath, modifiedContent);
102
+ console.log(`✅ Updated schema types in: ${schemaPath}`);
103
+ }
104
+ const migrationDir = path.join(options.output, "migrations");
105
+ if (fs.existsSync(migrationDir)) {
106
+ fs.rmSync(migrationDir, { recursive: true, force: true });
107
+ console.log(`✅ Removed: ${migrationDir}`);
108
+ }
109
+ if (fs.existsSync(metaDir)) {
110
+ const journalFile = path.join(metaDir, "_journal.json");
111
+ if (fs.existsSync(journalFile)) {
112
+ const journalData = JSON.parse(fs.readFileSync(journalFile, "utf-8"));
113
+ for (const entry of journalData.entries) {
114
+ const sqlFile = path.join(options.output, `${entry.tag}.sql`);
115
+ if (fs.existsSync(sqlFile)) {
116
+ fs.rmSync(sqlFile, { force: true });
117
+ console.log(`✅ Removed SQL file: ${entry.tag}.sql`);
118
+ }
119
+ }
120
+ }
121
+ fs.rmSync(metaDir, { recursive: true, force: true });
122
+ console.log(`✅ Removed: ${metaDir}`);
123
+ }
124
+ console.log(`✅ Successfully generated models and version metadata`);
125
+ process.exit(0);
126
+ } catch (error) {
127
+ console.error(`❌ Error during model generation:`, error);
128
+ process.exit(1);
129
+ }
130
+ };
131
+ const loadMigrationVersion$1 = async (migrationPath) => {
132
+ try {
133
+ const migrationCountFilePath = path.resolve(path.join(migrationPath, "migrationCount.ts"));
134
+ if (!fs.existsSync(migrationCountFilePath)) {
135
+ console.log(`✅ Current migration version: 0`);
136
+ return 0;
137
+ }
138
+ const { MIGRATION_VERSION } = await import(migrationCountFilePath);
139
+ console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);
140
+ return MIGRATION_VERSION;
141
+ } catch (error) {
142
+ console.error(`❌ Error loading migrationCount:`, error);
143
+ process.exit(1);
144
+ }
145
+ };
146
+ function cleanSQLStatement(sql) {
147
+ sql = sql.replace(/create\s+table\s+(\w+)/gi, "create table if not exists $1");
148
+ sql = sql.replace(/create\s+index\s+(\w+)/gi, "create index if not exists $1");
149
+ sql = sql.replace(
150
+ /alter\s+table\s+(\w+)\s+add\s+index\s+(\w+)/gi,
151
+ "alter table $1 add index if not exists $2"
152
+ );
153
+ sql = sql.replace(
154
+ /alter\s+table\s+(\w+)\s+add\s+constraint\s+(\w+)/gi,
155
+ "alter table $1 add constraint if not exists $2"
156
+ );
157
+ return sql.replace(/\s+default\s+character\s+set\s+utf8mb4\s+engine\s*=\s*InnoDB;?/gi, "").trim();
158
+ }
159
+ function generateMigrationFile$2(createStatements, version) {
160
+ const versionPrefix = `v${version}_MIGRATION`;
161
+ const migrationLines = createStatements.map(
162
+ (stmt, index) => ` .enqueue("${versionPrefix}${index}", "${cleanSQLStatement(stmt).replace(/\s+/g, " ")}")`
163
+ ).join("\n");
164
+ return `import { MigrationRunner } from "@forge/sql/out/migration";
165
+
166
+ export default (migrationRunner: MigrationRunner): MigrationRunner => {
167
+ return migrationRunner
168
+ ${migrationLines};
169
+ };`;
170
+ }
171
+ function saveMigrationFiles$2(migrationCode, version, outputDir) {
172
+ if (!fs.existsSync(outputDir)) {
173
+ fs.mkdirSync(outputDir, { recursive: true });
174
+ }
175
+ const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);
176
+ const migrationCountPath = path.join(outputDir, `migrationCount.ts`);
177
+ const indexFilePath = path.join(outputDir, `index.ts`);
178
+ fs.writeFileSync(migrationFilePath, migrationCode);
179
+ fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);
180
+ const indexFileContent = `import { MigrationRunner } from "@forge/sql/out/migration";
181
+ import { MIGRATION_VERSION } from "./migrationCount";
182
+
183
+ export type MigrationType = (
184
+ migrationRunner: MigrationRunner,
185
+ ) => MigrationRunner;
186
+
187
+ export default async (
188
+ migrationRunner: MigrationRunner,
189
+ ): Promise<MigrationRunner> => {
190
+ for (let i = 1; i <= MIGRATION_VERSION; i++) {
191
+ const migrations = (await import(\`./migrationV\${i}\`)) as {
192
+ default: MigrationType;
193
+ };
194
+ migrations.default(migrationRunner);
195
+ }
196
+ return migrationRunner;
197
+ };`;
198
+ fs.writeFileSync(indexFilePath, indexFileContent);
199
+ console.log(`✅ Migration file created: ${migrationFilePath}`);
200
+ console.log(`✅ Migration count file updated: ${migrationCountPath}`);
201
+ console.log(`✅ Migration index file created: ${indexFilePath}`);
202
+ }
203
+ const extractCreateStatements = (schema) => {
204
+ const statements = schema.split(/--> statement-breakpoint|;/).map((s) => s.trim()).filter((s) => s.length > 0);
205
+ return statements.filter(
206
+ (stmt) => stmt.toLowerCase().startsWith("create table") || stmt.toLowerCase().startsWith("alter table") || stmt.toLowerCase().includes("add index") || stmt.toLowerCase().includes("create index") || stmt.toLowerCase().includes("add unique index") || stmt.toLowerCase().includes("add constraint")
207
+ );
208
+ };
209
+ const createMigration = async (options) => {
210
+ try {
211
+ let version = await loadMigrationVersion$1(options.output);
212
+ if (version > 0) {
213
+ if (options.force) {
214
+ console.warn(
215
+ `⚠️ Warning: Migration already exists. Creating new migration with force flag...`
216
+ );
217
+ } else {
218
+ console.error(
219
+ `❌ Error: Migration has already been created. Use --force flag to override.`
220
+ );
221
+ process.exit(1);
222
+ }
223
+ }
224
+ version = 1;
225
+ await child_process.execSync(
226
+ `npx drizzle-kit generate --name=init --dialect mysql --out ${options.output} --schema ${options.entitiesPath}`,
227
+ { encoding: "utf-8" }
228
+ );
229
+ const initSqlFile = path.join(options.output, "0000_init.sql");
230
+ const sql = fs.readFileSync(initSqlFile, "utf-8");
231
+ const createStatements = extractCreateStatements(sql);
232
+ const migrationFile = generateMigrationFile$2(createStatements, 1);
233
+ saveMigrationFiles$2(migrationFile, 1, options.output);
234
+ fs.rmSync(initSqlFile, { force: true });
235
+ console.log(`✅ Removed SQL file: ${initSqlFile}`);
236
+ let metaDir = path.join(options.output, "meta");
237
+ fs.rmSync(metaDir, { recursive: true, force: true });
238
+ console.log(`✅ Removed: ${metaDir}`);
239
+ console.log(`✅ Migration successfully created!`);
240
+ process.exit(0);
241
+ } catch (error) {
242
+ console.error(`❌ Error during migration creation:`, error);
243
+ process.exit(1);
244
+ }
245
+ };
246
+ function generateMigrationFile$1(createStatements, version) {
247
+ const versionPrefix = `v${version}_MIGRATION`;
248
+ const migrationLines = createStatements.map((stmt, index) => ` .enqueue("${versionPrefix}${index}", "${stmt}")`).join("\n");
249
+ return `import { MigrationRunner } from "@forge/sql/out/migration";
250
+
251
+ export default (migrationRunner: MigrationRunner): MigrationRunner => {
252
+ return migrationRunner
253
+ ${migrationLines};
254
+ };`;
255
+ }
256
+ function filterWithPreviousMigration(newStatements, prevVersion, outputDir) {
257
+ const prevMigrationPath = path.join(outputDir, `migrationV${prevVersion}.ts`);
258
+ if (!fs.existsSync(prevMigrationPath)) {
259
+ return newStatements.map((s) => s.replace(/\s+/g, " "));
260
+ }
261
+ const prevContent = fs.readFileSync(prevMigrationPath, "utf-8");
262
+ const prevStatements = prevContent.split("\n").filter((line) => line.includes(".enqueue(")).map((line) => {
263
+ const match = line.match(/\.enqueue\([^,]+,\s*"([^"]+)"/);
264
+ return match ? match[1].replace(/\s+/g, " ").trim() : "";
265
+ });
266
+ return newStatements.filter((s) => !prevStatements.includes(s.replace(/\s+/g, " "))).map((s) => s.replace(/\s+/g, " "));
267
+ }
268
+ function saveMigrationFiles$1(migrationCode, version, outputDir) {
269
+ if (!fs.existsSync(outputDir)) {
270
+ fs.mkdirSync(outputDir, { recursive: true });
271
+ }
272
+ const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);
273
+ const migrationCountPath = path.join(outputDir, `migrationCount.ts`);
274
+ const indexFilePath = path.join(outputDir, `index.ts`);
275
+ fs.writeFileSync(migrationFilePath, migrationCode);
276
+ fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);
277
+ const indexFileContent = `import { MigrationRunner } from "@forge/sql/out/migration";
278
+ import { MIGRATION_VERSION } from "./migrationCount";
279
+
280
+ export type MigrationType = (
281
+ migrationRunner: MigrationRunner,
282
+ ) => MigrationRunner;
283
+
284
+ export default async (
285
+ migrationRunner: MigrationRunner,
286
+ ): Promise<MigrationRunner> => {
287
+ for (let i = 1; i <= MIGRATION_VERSION; i++) {
288
+ const migrations = (await import(\`./migrationV\${i}\`)) as {
289
+ default: MigrationType;
290
+ };
291
+ migrations.default(migrationRunner);
292
+ }
293
+ return migrationRunner;
294
+ };`;
295
+ fs.writeFileSync(indexFilePath, indexFileContent);
296
+ console.log(`✅ Migration file created: ${migrationFilePath}`);
297
+ console.log(`✅ Migration count file updated: ${migrationCountPath}`);
298
+ console.log(`✅ Migration index file created: ${indexFilePath}`);
299
+ return true;
300
+ }
301
+ const loadMigrationVersion = async (migrationPath) => {
302
+ try {
303
+ const migrationCountFilePath = path.resolve(path.join(migrationPath, "migrationCount.ts"));
304
+ if (!fs.existsSync(migrationCountFilePath)) {
305
+ console.warn(
306
+ `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`
307
+ );
308
+ return 0;
309
+ }
310
+ const { MIGRATION_VERSION } = await import(migrationCountFilePath);
311
+ console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);
312
+ return MIGRATION_VERSION;
313
+ } catch (error) {
314
+ console.error(`❌ Error loading migrationCount:`, error);
315
+ process.exit(1);
316
+ }
317
+ };
318
+ async function getDatabaseSchema(connection, dbName) {
319
+ const [columns] = await connection.execute(
320
+ `
321
+ SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA
322
+ FROM INFORMATION_SCHEMA.COLUMNS
323
+ WHERE TABLE_SCHEMA = ?
324
+ `,
325
+ [dbName]
326
+ );
327
+ const [indexes] = await connection.execute(
328
+ `
329
+ SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE
330
+ FROM INFORMATION_SCHEMA.STATISTICS
331
+ WHERE TABLE_SCHEMA = ?
332
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
333
+ `,
334
+ [dbName]
335
+ );
336
+ const [foreignKeys] = await connection.execute(
337
+ `
338
+ SELECT
339
+ TABLE_NAME,
340
+ COLUMN_NAME,
341
+ CONSTRAINT_NAME,
342
+ REFERENCED_TABLE_NAME,
343
+ REFERENCED_COLUMN_NAME
344
+ FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
345
+ WHERE TABLE_SCHEMA = ?
346
+ AND REFERENCED_TABLE_NAME IS NOT NULL
347
+ `,
348
+ [dbName]
349
+ );
350
+ const schema = {};
351
+ columns.forEach((row) => {
352
+ if (!schema[row.TABLE_NAME]) {
353
+ schema[row.TABLE_NAME] = {
354
+ columns: {},
355
+ indexes: {},
356
+ foreignKeys: {}
357
+ };
358
+ }
359
+ schema[row.TABLE_NAME].columns[row.COLUMN_NAME] = row;
360
+ });
361
+ indexes.forEach((row) => {
362
+ if (!schema[row.TABLE_NAME].indexes[row.INDEX_NAME]) {
363
+ schema[row.TABLE_NAME].indexes[row.INDEX_NAME] = {
364
+ columns: [],
365
+ unique: !row.NON_UNIQUE
366
+ };
367
+ }
368
+ schema[row.TABLE_NAME].indexes[row.INDEX_NAME].columns.push(row.COLUMN_NAME);
369
+ });
370
+ foreignKeys.forEach((row) => {
371
+ if (!schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME]) {
372
+ schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME] = {
373
+ column: row.COLUMN_NAME,
374
+ referencedTable: row.REFERENCED_TABLE_NAME,
375
+ referencedColumn: row.REFERENCED_COLUMN_NAME
376
+ };
377
+ }
378
+ });
379
+ return schema;
380
+ }
381
+ function normalizeMySQLType(mysqlType) {
382
+ let normalized = mysqlType.replace(/\([^)]*\)/, "").toLowerCase();
383
+ normalized = normalized.replace(/^mysql/, "");
384
+ return normalized;
385
+ }
386
+ function getForeignKeyName(fk) {
387
+ return fk.name;
388
+ }
389
+ function getIndexName(index) {
390
+ return index.name;
391
+ }
392
+ function getUniqueConstraintName(uc) {
393
+ return uc.name;
394
+ }
395
+ function getIndexColumns(index) {
396
+ return index.columns.map((col) => col.name);
397
+ }
398
+ function compareForeignKey(fk, { columns }) {
399
+ const fcolumns = fk.columns.map((c) => c.name);
400
+ return fcolumns.sort().join(",") === columns.sort().join(",");
401
+ }
402
+ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
403
+ const changes = [];
404
+ for (const [tableName, dbTable] of Object.entries(dbSchema)) {
405
+ const drizzleColumns = drizzleSchema[tableName];
406
+ if (!drizzleColumns) {
407
+ const columns = Object.entries(dbTable.columns).map(([colName, col]) => {
408
+ const type = col.COLUMN_TYPE;
409
+ const nullable = col.IS_NULLABLE === "YES" ? "NULL" : "NOT NULL";
410
+ const autoIncrement = col.EXTRA.includes("auto_increment") ? "AUTO_INCREMENT" : "";
411
+ return `\`${colName}\` ${type} ${nullable} ${autoIncrement}`.trim();
412
+ }).join(",\n ");
413
+ changes.push(`CREATE TABLE if not exists \`${tableName}\` (
414
+ ${columns}
415
+ );`);
416
+ for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {
417
+ if (indexName === "PRIMARY") {
418
+ continue;
419
+ }
420
+ const isForeignKeyIndex = dbIndex.columns.some((colName) => {
421
+ const column = dbTable.columns[colName];
422
+ return column && column.COLUMN_KEY === "MUL" && column.EXTRA.includes("foreign key");
423
+ });
424
+ if (isForeignKeyIndex) {
425
+ continue;
426
+ }
427
+ const columns2 = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
428
+ const unique = dbIndex.unique ? "UNIQUE " : "";
429
+ changes.push(
430
+ `CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns2});`
431
+ );
432
+ }
433
+ for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {
434
+ changes.push(
435
+ `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${fkName}\` FOREIGN KEY (\`${dbFK.column}\`) REFERENCES \`${dbFK.referencedTable}\` (\`${dbFK.referencedColumn}\`);`
436
+ );
437
+ }
438
+ continue;
439
+ }
440
+ for (const [colName, dbCol] of Object.entries(dbTable.columns)) {
441
+ const drizzleCol = Object.values(drizzleColumns).find((c) => c.name === colName);
442
+ if (!drizzleCol) {
443
+ const type = dbCol.COLUMN_TYPE;
444
+ const nullable = dbCol.IS_NULLABLE === "YES" ? "NULL" : "NOT NULL";
445
+ changes.push(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${colName}\` ${type} ${nullable};`);
446
+ continue;
447
+ }
448
+ const normalizedDbType = normalizeMySQLType(dbCol.COLUMN_TYPE);
449
+ const normalizedDrizzleType = normalizeMySQLType(drizzleCol.getSQLType());
450
+ if (normalizedDbType !== normalizedDrizzleType) {
451
+ const type = dbCol.COLUMN_TYPE;
452
+ const nullable = dbCol.IS_NULLABLE === "YES" ? "NULL" : "NOT NULL";
453
+ changes.push(
454
+ `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${colName}\` ${type} ${nullable};`
455
+ );
456
+ }
457
+ }
458
+ const table = Object.values(schemaModule).find((t) => {
459
+ const metadata = forgeSqlOrm.getTableMetadata(t);
460
+ return metadata.tableName === tableName;
461
+ });
462
+ if (table) {
463
+ const metadata = forgeSqlOrm.getTableMetadata(table);
464
+ for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {
465
+ if (indexName === "PRIMARY") {
466
+ continue;
467
+ }
468
+ const isForeignKeyIndex = metadata.foreignKeys.some(
469
+ (fk) => getForeignKeyName(fk) === indexName || compareForeignKey(fk, dbIndex)
470
+ );
471
+ if (isForeignKeyIndex) {
472
+ continue;
473
+ }
474
+ const existsUniqIndex = metadata.uniqueConstraints.find(
475
+ (uc) => getUniqueConstraintName(uc) === indexName
476
+ );
477
+ let drizzleIndex = metadata.indexes.find((i) => getIndexName(i) === indexName);
478
+ if (!drizzleIndex && existsUniqIndex) {
479
+ drizzleIndex = existsUniqIndex;
480
+ }
481
+ if (!drizzleIndex) {
482
+ const columns = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
483
+ const unique = dbIndex.unique ? "UNIQUE " : "";
484
+ changes.push(
485
+ `CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns});`
486
+ );
487
+ continue;
488
+ }
489
+ const dbColumns = dbIndex.columns.join(", ");
490
+ const drizzleColumns2 = getIndexColumns(drizzleIndex).join(", ");
491
+ if (dbColumns !== drizzleColumns2 || dbIndex.unique !== drizzleIndex instanceof uniqueConstraint.UniqueConstraintBuilder) {
492
+ changes.push(`DROP INDEX \`${indexName}\` ON \`${tableName}\`;`);
493
+ const columns = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
494
+ const unique = dbIndex.unique ? "UNIQUE " : "";
495
+ changes.push(
496
+ `CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns});`
497
+ );
498
+ }
499
+ }
500
+ for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {
501
+ const drizzleFK = metadata.foreignKeys.find(
502
+ (fk) => getForeignKeyName(fk) === fkName || compareForeignKey(fk, { columns: [dbFK.column] })
503
+ );
504
+ if (!drizzleFK) {
505
+ changes.push(
506
+ `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${fkName}\` FOREIGN KEY (\`${dbFK.column}\`) REFERENCES \`${dbFK.referencedTable}\` (\`${dbFK.referencedColumn}\`);`
507
+ );
508
+ continue;
509
+ }
510
+ }
511
+ for (const drizzleForeignKey of metadata.foreignKeys) {
512
+ const isDbFk = Object.keys(dbTable.foreignKeys).find((fk) => {
513
+ let foreignKey = dbTable.foreignKeys[fk];
514
+ return fk === getForeignKeyName(drizzleForeignKey) || compareForeignKey(drizzleForeignKey, { columns: [foreignKey.column] });
515
+ });
516
+ if (!isDbFk) {
517
+ const fkName = getForeignKeyName(drizzleForeignKey);
518
+ if (fkName) {
519
+ changes.push(`ALTER TABLE \`${tableName}\` DROP FOREIGN KEY \`${fkName}\`;`);
520
+ } else {
521
+ const columns = drizzleForeignKey?.columns;
522
+ const columnNames = columns?.length ? columns.map((c) => c.name).join(", ") : "unknown columns";
523
+ console.warn(
524
+ `⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`
525
+ );
526
+ }
527
+ }
528
+ }
529
+ }
530
+ }
531
+ return changes;
532
+ }
533
+ const updateMigration = async (options) => {
534
+ try {
535
+ let version = await loadMigrationVersion(options.output);
536
+ const prevVersion = version;
537
+ if (version < 1) {
538
+ console.log(
539
+ `⚠️ Initial migration not found. Run "npx forge-sql-orm migrations:create" first.`
540
+ );
541
+ process.exit(0);
542
+ }
543
+ version += 1;
544
+ const connection = await mysql.createConnection({
545
+ host: options.host,
546
+ port: options.port,
547
+ user: options.user,
548
+ password: options.password,
549
+ database: options.dbName
550
+ });
551
+ try {
552
+ const dbSchema = await getDatabaseSchema(connection, options.dbName);
553
+ const schemaPath = path.resolve(options.entitiesPath, "schema.ts");
554
+ if (!fs.existsSync(schemaPath)) {
555
+ throw new Error(`Schema file not found at: ${schemaPath}`);
556
+ }
557
+ const schemaModule = await import(schemaPath);
558
+ if (!schemaModule) {
559
+ throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);
560
+ }
561
+ const drizzleSchema = {};
562
+ const tables = Object.values(schemaModule);
563
+ tables.forEach((table) => {
564
+ const metadata = forgeSqlOrm.getTableMetadata(table);
565
+ if (metadata.tableName) {
566
+ const columns = {};
567
+ Object.entries(metadata.columns).forEach(([name, column]) => {
568
+ columns[name] = {
569
+ type: column.dataType,
570
+ notNull: column.notNull,
571
+ autoincrement: column.autoincrement,
572
+ columnType: column.columnType,
573
+ name: column.name,
574
+ getSQLType: () => column.getSQLType()
575
+ };
576
+ });
577
+ drizzleSchema[metadata.tableName] = columns;
578
+ }
579
+ });
580
+ if (Object.keys(drizzleSchema).length === 0) {
581
+ throw new Error(`No valid tables found in schema at: ${schemaPath}`);
582
+ }
583
+ console.log("Found tables:", Object.keys(drizzleSchema));
584
+ const createStatements = filterWithPreviousMigration(
585
+ generateSchemaChanges(drizzleSchema, dbSchema, schemaModule),
586
+ prevVersion,
587
+ options.output
588
+ );
589
+ if (createStatements.length) {
590
+ const migrationFile = generateMigrationFile$1(createStatements, version);
591
+ if (saveMigrationFiles$1(migrationFile, version, options.output)) {
592
+ console.log(`✅ Migration successfully updated!`);
593
+ }
594
+ process.exit(0);
595
+ } else {
596
+ console.log(`⚠️ No new migration changes detected.`);
597
+ process.exit(0);
598
+ }
599
+ } finally {
600
+ await connection.end();
601
+ }
602
+ } catch (error) {
603
+ console.error(`❌ Error during migration update:`, error);
604
+ process.exit(1);
605
+ }
606
+ };
607
+ function generateMigrationUUID(version) {
608
+ const now = /* @__PURE__ */ new Date();
609
+ const timestamp = now.getTime();
610
+ return `MIGRATION_V${version}_${timestamp}`;
611
+ }
612
+ function generateMigrationFile(createStatements, version) {
613
+ const uniqId = generateMigrationUUID(version);
614
+ const migrationLines = createStatements.map(
615
+ (stmt, index) => ` .enqueue("${uniqId}_${index}", "${stmt}")`
616
+ // eslint-disable-line no-useless-escape
617
+ ).join("\n");
618
+ return `import { MigrationRunner } from "@forge/sql/out/migration";
619
+
620
+ export default (migrationRunner: MigrationRunner): MigrationRunner => {
621
+ return migrationRunner
622
+ ${migrationLines};
623
+ };`;
624
+ }
625
+ function saveMigrationFiles(migrationCode, version, outputDir) {
626
+ if (!fs.existsSync(outputDir)) {
627
+ fs.mkdirSync(outputDir, { recursive: true });
628
+ }
629
+ const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);
630
+ const migrationCountPath = path.join(outputDir, `migrationCount.ts`);
631
+ const indexFilePath = path.join(outputDir, `index.ts`);
632
+ fs.writeFileSync(migrationFilePath, migrationCode);
633
+ fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);
634
+ const indexFileContent = `import { MigrationRunner } from "@forge/sql/out/migration";
635
+ import { MIGRATION_VERSION } from "./migrationCount";
636
+
637
+ export type MigrationType = (
638
+ migrationRunner: MigrationRunner,
639
+ ) => MigrationRunner;
640
+
641
+ export default async (
642
+ migrationRunner: MigrationRunner,
643
+ ): Promise<MigrationRunner> => {
644
+ for (let i = 1; i <= MIGRATION_VERSION; i++) {
645
+ const migrations = (await import(\`./migrationV\${i}\`)) as {
646
+ default: MigrationType;
647
+ };
648
+ migrations.default(migrationRunner);
649
+ }
650
+ return migrationRunner;
651
+ };`;
652
+ fs.writeFileSync(indexFilePath, indexFileContent);
653
+ console.log(`✅ Migration file created: ${migrationFilePath}`);
654
+ console.log(`✅ Migration count file updated: ${migrationCountPath}`);
655
+ console.log(`✅ Migration index file created: ${indexFilePath}`);
656
+ }
657
+ const dropMigration = async (options) => {
658
+ try {
659
+ const version = 1;
660
+ const schemaPath = path.resolve(options.entitiesPath, "schema.ts");
661
+ if (!fs.existsSync(schemaPath)) {
662
+ throw new Error(`Schema file not found at: ${schemaPath}`);
663
+ }
664
+ const schemaModule = await import(schemaPath);
665
+ if (!schemaModule) {
666
+ throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);
667
+ }
668
+ const tables = Object.values(schemaModule);
669
+ if (tables.length === 0) {
670
+ throw new Error(`No valid tables found in schema at: ${schemaPath}`);
671
+ }
672
+ const tableNames = tables.map((table) => {
673
+ const metadata = forgeSqlOrm.getTableMetadata(table);
674
+ return metadata.tableName;
675
+ }).filter(Boolean);
676
+ console.log("Found tables:", tableNames);
677
+ const dropStatements = forgeSqlOrm.generateDropTableStatements(tables);
678
+ const migrationFile = generateMigrationFile(dropStatements, version);
679
+ saveMigrationFiles(migrationFile, version, options.output);
680
+ console.log(`✅ Migration successfully created!`);
681
+ process.exit(0);
682
+ } catch (error) {
683
+ console.error(`❌ Error during migration creation:`, error);
684
+ process.exit(1);
685
+ }
686
+ };
687
+ const ENV_PATH = path.resolve(process.cwd(), ".env");
688
+ dotenv.config({ path: ENV_PATH });
689
+ const saveEnvFile = (config) => {
690
+ let envContent = "";
691
+ const envFilePath = ENV_PATH;
692
+ if (fs.existsSync(envFilePath)) {
693
+ envContent = fs.readFileSync(envFilePath, "utf8");
694
+ }
695
+ const envVars = envContent.split("\n").filter((line) => line.trim() !== "" && !line.startsWith("#")).reduce((acc, line) => {
696
+ const [key, ...value] = line.split("=");
697
+ acc[key] = value.join("=");
698
+ return acc;
699
+ }, {});
700
+ Object.entries(config).forEach(([key, value]) => {
701
+ envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;
702
+ });
703
+ const updatedEnvContent = Object.entries(envVars).map(([key, value]) => `${key}=${value}`).join("\n");
704
+ fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: "utf8" });
705
+ console.log("✅ Configuration saved to .env without overwriting other variables.");
706
+ };
707
+ const askMissingParams = async (config, defaultOutput, customAskMissingParams) => {
708
+ const questions = [];
709
+ if (!config.host)
710
+ questions.push({
711
+ type: "input",
712
+ name: "host",
713
+ message: "Enter database host:",
714
+ default: "localhost"
715
+ });
716
+ if (!config.port)
717
+ questions.push({
718
+ type: "input",
719
+ name: "port",
720
+ message: "Enter database port:",
721
+ default: "3306",
722
+ validate: (input) => !isNaN(parseInt(input, 10))
723
+ });
724
+ if (!config.user)
725
+ questions.push({
726
+ type: "input",
727
+ name: "user",
728
+ message: "Enter database user:",
729
+ default: "root"
730
+ });
731
+ if (!config.password)
732
+ questions.push({
733
+ type: "password",
734
+ name: "password",
735
+ message: "Enter database password:",
736
+ mask: "*"
737
+ });
738
+ if (!config.dbName)
739
+ questions.push({
740
+ type: "input",
741
+ name: "dbName",
742
+ message: "Enter database name:"
743
+ });
744
+ if (!config.output)
745
+ questions.push({
746
+ type: "input",
747
+ name: "output",
748
+ message: "Enter output path:",
749
+ default: defaultOutput
750
+ });
751
+ if (customAskMissingParams) {
752
+ customAskMissingParams(config, questions);
753
+ }
754
+ if (questions.length > 0) {
755
+ const answers = await inquirer.prompt(questions);
756
+ return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };
757
+ }
758
+ return config;
759
+ };
760
+ const getConfig = async (cmd, defaultOutput, customConfig, customAskMissingParams) => {
761
+ let config = {
762
+ host: cmd.host || process.env.FORGE_SQL_ORM_HOST,
763
+ port: cmd.port ? parseInt(cmd.port, 10) : process.env.FORGE_SQL_ORM_PORT ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10) : void 0,
764
+ user: cmd.user || process.env.FORGE_SQL_ORM_USER,
765
+ password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,
766
+ dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,
767
+ output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT
768
+ };
769
+ if (customConfig) {
770
+ config = { ...config, ...customConfig() };
771
+ }
772
+ const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);
773
+ if (cmd.saveEnv) {
774
+ saveEnvFile(conf);
775
+ }
776
+ return conf;
777
+ };
778
+ const program = new commander.Command();
779
+ program.version("1.0.0");
780
+ program.command("generate:model").description("Generate MikroORM models from the database.").option("--host <string>", "Database host").option("--port <number>", "Database port").option("--user <string>", "Database user").option("--password <string>", "Database password").option("--dbName <string>", "Database name").option("--output <string>", "Output path for entities").option("--versionField <string>", "Field name for versioning").option("--saveEnv", "Save configuration to .env file").action(async (cmd) => {
781
+ const config = await getConfig(
782
+ cmd,
783
+ "./database/entities",
784
+ () => ({
785
+ versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD
786
+ }),
787
+ (cfg, questions) => {
788
+ if (!cfg.versionField) {
789
+ questions.push({
790
+ type: "input",
791
+ name: "versionField",
792
+ message: "Enter the field name for versioning (leave empty to skip):",
793
+ default: ""
794
+ });
795
+ }
796
+ }
797
+ );
798
+ await generateModels(config);
799
+ });
800
+ program.command("migrations:create").description("Generate an initial migration for the entire database.").option("--host <string>", "Database host").option("--port <number>", "Database port").option("--user <string>", "Database user").option("--password <string>", "Database password").option("--dbName <string>", "Database name").option("--output <string>", "Output path for migrations").option("--entitiesPath <string>", "Path to the folder containing entities").option("--force", "Force creation even if migrations exist").option("--saveEnv", "Save configuration to .env file").action(async (cmd) => {
801
+ const config = await getConfig(
802
+ cmd,
803
+ "./database/migration",
804
+ () => ({
805
+ entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,
806
+ force: cmd.force || false
807
+ }),
808
+ (cfg, questions) => {
809
+ if (!cfg.entitiesPath)
810
+ questions.push({
811
+ type: "input",
812
+ name: "entitiesPath",
813
+ message: "Enter the path to entities:",
814
+ default: "./database/entities"
815
+ });
816
+ }
817
+ );
818
+ await createMigration(config);
819
+ });
820
+ program.command("migrations:update").description("Generate a migration to update the database schema.").option("--host <string>", "Database host").option("--port <number>", "Database port").option("--user <string>", "Database user").option("--password <string>", "Database password").option("--dbName <string>", "Database name").option("--output <string>", "Output path for migrations").option("--entitiesPath <string>", "Path to the folder containing entities").option("--saveEnv", "Save configuration to .env file").action(async (cmd) => {
821
+ const config = await getConfig(
822
+ cmd,
823
+ "./database/migration",
824
+ () => ({
825
+ entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH
826
+ }),
827
+ (cfg, questions) => {
828
+ if (!cfg.entitiesPath)
829
+ questions.push({
830
+ type: "input",
831
+ name: "entitiesPath",
832
+ message: "Enter the path to entities:",
833
+ default: "./database/entities"
834
+ });
835
+ }
836
+ );
837
+ await updateMigration(config);
838
+ });
839
+ program.command("migrations:drop").description("Generate a migration to drop all tables and clear migrations history.").option("--host <string>", "Database host").option("--port <number>", "Database port").option("--user <string>", "Database user").option("--password <string>", "Database password").option("--dbName <string>", "Database name").option("--output <string>", "Output path for migrations").option("--entitiesPath <string>", "Path to the folder containing entities").option("--saveEnv", "Save configuration to .env file").action(async (cmd) => {
840
+ const config = await getConfig(
841
+ cmd,
842
+ "./database/migration",
843
+ () => ({
844
+ entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH
845
+ }),
846
+ (cfg, questions) => {
847
+ if (!cfg.entitiesPath)
848
+ questions.push({
849
+ type: "input",
850
+ name: "entitiesPath",
851
+ message: "Enter the path to entities:",
852
+ default: "./database/entities"
853
+ });
854
+ }
855
+ );
856
+ await dropMigration(config);
857
+ });
858
+ if (require.main === module) {
859
+ program.parse(process.argv);
860
+ }
861
+ exports.program = program;
862
+ //# sourceMappingURL=cli.js.map