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