forge-sql-orm 2.0.4 → 2.0.6

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/dist-cli/cli.mjs CHANGED
@@ -7,8 +7,11 @@ import path from "path";
7
7
  import "reflect-metadata";
8
8
  import { execSync } from "child_process";
9
9
  import mysql from "mysql2/promise";
10
- import "moment";
10
+ import moment from "moment";
11
11
  import { UniqueConstraintBuilder } from "drizzle-orm/mysql-core/unique-constraint";
12
+ import "@forge/sql";
13
+ import { customType } from "drizzle-orm/mysql-core";
14
+ import moment$1 from "moment/moment.js";
12
15
  function replaceMySQLTypes(schemaContent) {
13
16
  const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from "forge-sql-orm";
14
17
 
@@ -223,6 +226,13 @@ const createMigration = async (options) => {
223
226
  process.exit(1);
224
227
  }
225
228
  };
229
+ const parseDateTime = (value, format) => {
230
+ const m = moment(value, format, true);
231
+ if (!m.isValid()) {
232
+ return moment(value).toDate();
233
+ }
234
+ return m.toDate();
235
+ };
226
236
  function processForeignKeys(table, foreignKeysSymbol, extraSymbol) {
227
237
  const foreignKeys = [];
228
238
  if (foreignKeysSymbol) {
@@ -305,6 +315,17 @@ function getTableMetadata(table) {
305
315
  ...builders
306
316
  };
307
317
  }
318
+ function generateDropTableStatements(tables) {
319
+ const dropStatements = [];
320
+ tables.forEach((table) => {
321
+ const tableMetadata = getTableMetadata(table);
322
+ if (tableMetadata.tableName) {
323
+ dropStatements.push(`DROP TABLE IF EXISTS \`${tableMetadata.tableName}\`;`);
324
+ }
325
+ });
326
+ dropStatements.push(`DELETE FROM __migrations;`);
327
+ return dropStatements;
328
+ }
308
329
  function generateMigrationFile$1(createStatements, version) {
309
330
  const versionPrefix = `v${version}_MIGRATION`;
310
331
  const migrationLines = createStatements.map(
@@ -482,7 +503,7 @@ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
482
503
  }
483
504
  const columns2 = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
484
505
  const unique = dbIndex.unique ? "UNIQUE " : "";
485
- changes.push(`CREATE if not exists ${unique}INDEX \`${indexName}\` ON \`${tableName}\` (${columns2});`);
506
+ changes.push(`CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns2});`);
486
507
  }
487
508
  for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {
488
509
  changes.push(`ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${fkName}\` FOREIGN KEY (\`${dbFK.column}\`) REFERENCES \`${dbFK.referencedTable}\` (\`${dbFK.referencedColumn}\`);`);
@@ -527,7 +548,7 @@ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
527
548
  if (!drizzleIndex) {
528
549
  const columns = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
529
550
  const unique = dbIndex.unique ? "UNIQUE " : "";
530
- changes.push(`CREATE if not exists ${unique}INDEX \`${indexName}\` ON \`${tableName}\` (${columns});`);
551
+ changes.push(`CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns});`);
531
552
  continue;
532
553
  }
533
554
  const dbColumns = dbIndex.columns.join(", ");
@@ -536,7 +557,7 @@ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
536
557
  changes.push(`DROP INDEX \`${indexName}\` ON \`${tableName}\`;`);
537
558
  const columns = dbIndex.columns.map((col) => `\`${col}\``).join(", ");
538
559
  const unique = dbIndex.unique ? "UNIQUE " : "";
539
- changes.push(`CREATE if not exists ${unique}INDEX \`${indexName}\` ON \`${tableName}\` (${columns});`);
560
+ changes.push(`CREATE ${unique}INDEX if not exists \`${indexName}\` ON \`${tableName}\` (${columns});`);
540
561
  }
541
562
  }
542
563
  for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {
@@ -553,7 +574,13 @@ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
553
574
  });
554
575
  if (!isDbFk) {
555
576
  const fkName = getForeignKeyName(drizzleForeignKey);
556
- changes.push(`ALTER TABLE \`${tableName}\` DROP FOREIGN KEY \`${fkName}\`;`);
577
+ if (fkName) {
578
+ changes.push(`ALTER TABLE \`${tableName}\` DROP FOREIGN KEY \`${fkName}\`;`);
579
+ } else {
580
+ const columns = drizzleForeignKey?.columns;
581
+ const columnNames = columns?.length ? columns.map((c) => c.name).join(", ") : "unknown columns";
582
+ console.warn(`⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`);
583
+ }
557
584
  }
558
585
  }
559
586
  }
@@ -563,8 +590,7 @@ function generateSchemaChanges(drizzleSchema, dbSchema, schemaModule) {
563
590
  const updateMigration = async (options) => {
564
591
  try {
565
592
  let version = await loadMigrationVersion(options.output);
566
- version = 2;
567
- const prevVersion = 1;
593
+ const prevVersion = version;
568
594
  if (version < 1) {
569
595
  console.log(
570
596
  `⚠️ Initial migration not found. Run "npx forge-sql-orm migrations:create" first.`
@@ -631,6 +657,53 @@ const updateMigration = async (options) => {
631
657
  process.exit(1);
632
658
  }
633
659
  };
660
+ customType({
661
+ dataType() {
662
+ return "datetime";
663
+ },
664
+ toDriver(value) {
665
+ return moment$1(value).format("YYYY-MM-DDTHH:mm:ss.SSS");
666
+ },
667
+ fromDriver(value) {
668
+ const format = "YYYY-MM-DDTHH:mm:ss.SSS";
669
+ return parseDateTime(value, format);
670
+ }
671
+ });
672
+ customType({
673
+ dataType() {
674
+ return "timestamp";
675
+ },
676
+ toDriver(value) {
677
+ return moment$1(value).format("YYYY-MM-DDTHH:mm:ss.SSS");
678
+ },
679
+ fromDriver(value) {
680
+ const format = "YYYY-MM-DDTHH:mm:ss.SSS";
681
+ return parseDateTime(value, format);
682
+ }
683
+ });
684
+ customType({
685
+ dataType() {
686
+ return "date";
687
+ },
688
+ toDriver(value) {
689
+ return moment$1(value).format("YYYY-MM-DD");
690
+ },
691
+ fromDriver(value) {
692
+ const format = "YYYY-MM-DD";
693
+ return parseDateTime(value, format);
694
+ }
695
+ });
696
+ customType({
697
+ dataType() {
698
+ return "time";
699
+ },
700
+ toDriver(value) {
701
+ return moment$1(value).format("HH:mm:ss.SSS");
702
+ },
703
+ fromDriver(value) {
704
+ return parseDateTime(value, "HH:mm:ss.SSS");
705
+ }
706
+ });
634
707
  function generateMigrationUUID(version) {
635
708
  const now = /* @__PURE__ */ new Date();
636
709
  const timestamp = now.getTime();
@@ -692,42 +765,16 @@ const dropMigration = async (options) => {
692
765
  if (!schemaModule) {
693
766
  throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);
694
767
  }
695
- const drizzleSchema = {};
696
768
  const tables = Object.values(schemaModule);
697
- tables.forEach((table) => {
698
- const symbols = Object.getOwnPropertySymbols(table);
699
- const nameSymbol = symbols.find((s) => s.toString().includes("Name"));
700
- const columnsSymbol = symbols.find((s) => s.toString().includes("Columns"));
701
- const indexesSymbol = symbols.find((s) => s.toString().includes("Indexes"));
702
- const foreignKeysSymbol = symbols.find((s) => s.toString().includes("ForeignKeys"));
703
- if (table && nameSymbol && columnsSymbol) {
704
- drizzleSchema[table[nameSymbol]] = {
705
- // @ts-ignore
706
- columns: table[columnsSymbol],
707
- // @ts-ignore
708
- indexes: indexesSymbol ? table[indexesSymbol] || {} : {},
709
- // @ts-ignore
710
- foreignKeys: foreignKeysSymbol ? table[foreignKeysSymbol] || {} : {}
711
- };
712
- }
713
- });
714
- if (Object.keys(drizzleSchema).length === 0) {
769
+ if (tables.length === 0) {
715
770
  throw new Error(`No valid tables found in schema at: ${schemaPath}`);
716
771
  }
717
- console.log("Found tables:", Object.keys(drizzleSchema));
718
- const dropStatements = [];
719
- for (const [tableName, tableInfo] of Object.entries(drizzleSchema)) {
720
- for (const fk of Object.values(tableInfo.foreignKeys)) {
721
- const fkName = fk.getName();
722
- dropStatements.push(`ALTER TABLE \`${tableName}\` DROP FOREIGN KEY \`${fkName}\`;`);
723
- }
724
- for (const [indexName, index] of Object.entries(tableInfo.indexes)) {
725
- if (indexName === "PRIMARY") continue;
726
- dropStatements.push(`DROP INDEX \`${indexName}\` ON \`${tableName}\`;`);
727
- }
728
- dropStatements.push(`DROP TABLE IF EXISTS \`${tableName}\`;`);
729
- }
730
- dropStatements.push(`DELETE FROM __migrations;`);
772
+ const tableNames = tables.map((table) => {
773
+ const metadata = getTableMetadata(table);
774
+ return metadata.tableName;
775
+ }).filter(Boolean);
776
+ console.log("Found tables:", tableNames);
777
+ const dropStatements = generateDropTableStatements(tables);
731
778
  const migrationFile = generateMigrationFile(dropStatements, version);
732
779
  saveMigrationFiles(migrationFile, version, options.output);
733
780
  console.log(`✅ Migration successfully created!`);