sqlmorpheus 0.1.4 → 0.1.5

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/index.d.mts CHANGED
@@ -121,6 +121,7 @@ declare function ForeignKey<TOther extends BackendTable>(toTable: Class<TOther>,
121
121
  declare function prepareMigration(db: DatabaseAccess, instructions: DatabaseInstructions, overwriteExisting?: boolean): Promise<void>;
122
122
  declare function runPreparedMigrations(db: DatabaseAccess, instructions: DatabaseInstructions): Promise<void>;
123
123
  declare function prepareAndRunMigration(db: DatabaseAccess, instructions: DatabaseInstructions, overwriteExisting?: boolean): Promise<void>;
124
+ declare function runMigrationWithoutHistory(db: DatabaseAccess, instructions: DatabaseInstructions): Promise<void>;
124
125
  declare function rollback(db: DatabaseAccess, instructions: DatabaseInstructions, toVersion: number): Promise<void>;
125
126
 
126
- export { type DatabaseInstructions, DbTable, ForeignKey, prepareAndRunMigration, prepareMigration, rollback, runPreparedMigrations };
127
+ export { type DatabaseInstructions, DbTable, ForeignKey, prepareAndRunMigration, prepareMigration, rollback, runMigrationWithoutHistory, runPreparedMigrations };
package/dist/index.d.ts CHANGED
@@ -121,6 +121,7 @@ declare function ForeignKey<TOther extends BackendTable>(toTable: Class<TOther>,
121
121
  declare function prepareMigration(db: DatabaseAccess, instructions: DatabaseInstructions, overwriteExisting?: boolean): Promise<void>;
122
122
  declare function runPreparedMigrations(db: DatabaseAccess, instructions: DatabaseInstructions): Promise<void>;
123
123
  declare function prepareAndRunMigration(db: DatabaseAccess, instructions: DatabaseInstructions, overwriteExisting?: boolean): Promise<void>;
124
+ declare function runMigrationWithoutHistory(db: DatabaseAccess, instructions: DatabaseInstructions): Promise<void>;
124
125
  declare function rollback(db: DatabaseAccess, instructions: DatabaseInstructions, toVersion: number): Promise<void>;
125
126
 
126
- export { type DatabaseInstructions, DbTable, ForeignKey, prepareAndRunMigration, prepareMigration, rollback, runPreparedMigrations };
127
+ export { type DatabaseInstructions, DbTable, ForeignKey, prepareAndRunMigration, prepareMigration, rollback, runMigrationWithoutHistory, runPreparedMigrations };
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ __export(index_exports, {
25
25
  prepareAndRunMigration: () => prepareAndRunMigration,
26
26
  prepareMigration: () => prepareMigration,
27
27
  rollback: () => rollback,
28
+ runMigrationWithoutHistory: () => runMigrationWithoutHistory,
28
29
  runPreparedMigrations: () => runPreparedMigrations
29
30
  });
30
31
  module.exports = __toCommonJS(index_exports);
@@ -253,6 +254,12 @@ var MigrationHistoryManager = class {
253
254
  (0, import_node_fs.mkdirSync)(this.configPath, { recursive: true });
254
255
  (0, import_node_fs.mkdirSync)(this.migrationsPath, { recursive: true });
255
256
  }
257
+ /**
258
+ * Retrieves the last recorded history version from the configuration path.
259
+ * If the version is not already cached in memory, this method reads it from a file on disk.
260
+ *
261
+ * @return The last version number, or 0 if the version file does not exist or cannot be parsed.
262
+ */
256
263
  getLastHistoryVersion() {
257
264
  if (this.lastVersion)
258
265
  return this.lastVersion;
@@ -260,9 +267,21 @@ var MigrationHistoryManager = class {
260
267
  this.lastVersion = (0, import_node_fs.existsSync)(path) ? parseInt((0, import_fs.readFileSync)(`${this.configPath}/last_version.txt`, { encoding: "utf-8" })) ?? 0 : 0;
261
268
  return this.lastVersion;
262
269
  }
270
+ /**
271
+ * Updates the "last history version" information by writing the given version to a file.
272
+ *
273
+ * @param version - The version number to set as the last history version.
274
+ */
263
275
  setLastHistoryVersion(version) {
264
276
  (0, import_node_fs.writeFileSync)(`${this.configPath}/last_version.txt`, version.toString(), { encoding: "utf-8" });
265
277
  }
278
+ /**
279
+ * Creates migration history files for upgrading and downgrading database schemas.
280
+ *
281
+ * @param toVersion - The target version number for the migration.
282
+ * @param changes - An object containing the SQL changes for upgrading (`changes.up`) and downgrading (`changes.down`).
283
+ * @param overwriteExisting - A flag that determines if existing migration files should be overwritten. Defaults to `false`.
284
+ */
266
285
  createMigrationHistory(toVersion, changes, overwriteExisting) {
267
286
  const fromVersion = this.getLastHistoryVersion();
268
287
  const upPath = `${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`;
@@ -279,9 +298,22 @@ ${changes.up}`, { encoding: "utf-8" });
279
298
  -- To: Version ${fromVersion}
280
299
  ${changes.down}`, { encoding: "utf-8" });
281
300
  }
301
+ /**
302
+ * Retrieves the SQL migration script for upgrading to the specified version.
303
+ * If no version is provided, it retrieves the migration script for the latest version in the history.
304
+ *
305
+ * @param toVersion - The version of the migration script to retrieve. If not specified, the latest version is used.
306
+ * @return The content of the SQL migration script as a string.
307
+ */
282
308
  getUpMigration(toVersion) {
283
309
  return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion ?? this.getLastHistoryVersion()}.sql`, { encoding: "utf-8" });
284
310
  }
311
+ /**
312
+ * Retrieves the SQL migration script for downgrading to the specified version.
313
+ *
314
+ * @param version - The version number of the migration to retrieve.
315
+ * @return The SQL script for the down migration.
316
+ */
285
317
  getDownMigration(version) {
286
318
  return (0, import_fs.readFileSync)(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${version}.sql`, { encoding: "utf-8" });
287
319
  }
@@ -581,6 +613,17 @@ var MigrationManager = class {
581
613
  this.tableStructureGenerator = new TableStructureGenerator(dbInstructions, this.dialect);
582
614
  this.migrationHistoryManager = new MigrationHistoryManager(this.dbInstructions.configPath);
583
615
  }
616
+ /**
617
+ * Generates the SQL changes required to migrate a database from its current version
618
+ * to the target version defined in the database instructions. Handles the creation
619
+ * and deletion of tables, migration of foreign keys and columns, renaming of columns,
620
+ * and recreating tables, along with executing any pre- and post-migration custom logic.
621
+ *
622
+ * @return A promise that resolves to an object containing the SQL
623
+ * changes for the migration (`up` and `down` changes) or null if no migration is required.
624
+ * Throws an error in scenarios such as attempting to migrate to a lower version
625
+ * or an invalid starting version.
626
+ */
584
627
  async getMigrateSql() {
585
628
  if (this.dbInstructions.version <= 0)
586
629
  throw new Error("Cannot migrate to version 0 or lower");
@@ -649,12 +692,28 @@ ${foreignKeyOnQuery}`;
649
692
  ${foreignKeyOnQuery}`;
650
693
  return changes;
651
694
  }
695
+ /**
696
+ * Prepares the migration by generating the SQL changes and creating a migration history entry.
697
+ * If no changes are needed, the method exits early.
698
+ *
699
+ * @param overwriteExisting - Optional flag indicating if overwriting existing changes is allowed.
700
+ * @return - A promise that resolves once the migration preparation is complete.
701
+ */
652
702
  async prepareMigration(overwriteExisting) {
653
703
  const changes = await this.getMigrateSql();
654
704
  if (!changes)
655
705
  return;
656
706
  this.migrationHistoryManager.createMigrationHistory(this.dbInstructions.version, changes, overwriteExisting);
657
707
  }
708
+ /**
709
+ * Generates SQL change statements for creating and dropping tables based on the current table structure
710
+ * and existing table configurations in the database. The `up` changes include SQL statements for creating
711
+ * new tables, while the `down` changes include SQL statements for dropping the corresponding tables or
712
+ * recreating them if necessary.
713
+ *
714
+ * @return {Promise<SqlChanges>} A promise that resolves to an object containing `up` and `down` SQL
715
+ * change statements for migrating the database schema.
716
+ */
658
717
  async createAndDropTables() {
659
718
  let changes = {
660
719
  up: "\n\n-- Create tables\n",
@@ -681,6 +740,16 @@ ${foreignKeyOnQuery}`;
681
740
  }
682
741
  return changes;
683
742
  }
743
+ /**
744
+ * Generates an SQL string to create a table with the specified schema.
745
+ *
746
+ * @param tableName - The name of the table to be created.
747
+ * @param columns - An array of objects defining the columns of the table, including their names, types
748
+ * default values, and whether they are primary keys.
749
+ * @param foreignKeys - An optional array of objects defining the foreign key constraints for the table,
750
+ * including the source column, target table, target column, action on update, and action on delete.
751
+ * @return The complete SQL string to create the table with the specified structure and constraints.
752
+ */
684
753
  createTableSql(tableName, columns, foreignKeys) {
685
754
  const queryLines = [];
686
755
  for (const columnInfo of columns) {
@@ -693,9 +762,20 @@ ${foreignKeyOnQuery}`;
693
762
  }
694
763
  return this.dialect.createTable(tableName, queryLines);
695
764
  }
765
+ /**
766
+ * Checks if the specified table does not exist in the list of existing tables.
767
+ *
768
+ * @param tableName - The name of the table to check.
769
+ * @return Returns true if the table does not exist, otherwise false.
770
+ */
696
771
  tableDoesNotExists(tableName) {
697
772
  return this.existingTables.indexOf(tableName) == -1;
698
773
  }
774
+ /**
775
+ * Recreates database tables that have been flagged to be recreated in migration data.
776
+ * This method generated the necessary SQL code for backing up the current table data, dropping and recreating
777
+ * the tables, and reinserting the preserved data into the recreated tables.
778
+ */
699
779
  async recreateTables() {
700
780
  const changes = {
701
781
  up: "\n\n-- Recreate tables\n",
@@ -724,6 +804,9 @@ ${foreignKeyOnQuery}`;
724
804
  }
725
805
  return changes;
726
806
  }
807
+ /**
808
+ * Migrates foreign key constraints for all defined tables.
809
+ */
727
810
  async migrateForeignKeys() {
728
811
  if (!this.dialect.canAlterForeignKeys)
729
812
  return { up: "", down: "" };
@@ -847,12 +930,22 @@ ${foreignKeyOnQuery}`;
847
930
  }
848
931
  return changes;
849
932
  }
933
+ /**
934
+ * Retrieves the name of the primary key column from a list of column information.
935
+ *
936
+ * @param columnInfoList - An array of ColumnInfo objects containing details about each column.
937
+ * @return The name of the primary key column if found; otherwise, undefined.
938
+ */
850
939
  getPrimaryKeyColumn(columnInfoList) {
851
940
  for (const columnInfo of columnInfoList) {
852
941
  if (columnInfo.isPrimaryKey)
853
942
  return columnInfo.name;
854
943
  }
855
944
  }
945
+ /**
946
+ * Handles the renaming of columns in database tables by generating SQL changes for both applying and reverting the renames.
947
+ * Skips tables that are marked for recreation.
948
+ */
856
949
  renameColumns() {
857
950
  const changes = {
858
951
  up: "\n\n-- Rename columns\n",
@@ -932,6 +1025,13 @@ async function prepareAndRunMigration(db, instructions, overwriteExisting) {
932
1025
  await prepareMigration(db, instructions, overwriteExisting);
933
1026
  await runPreparedMigrations(db, instructions);
934
1027
  }
1028
+ async function runMigrationWithoutHistory(db, instructions) {
1029
+ Logger.setMode(instructions.loggerMode);
1030
+ const mm = new MigrationManager(db, instructions);
1031
+ const changes = await mm.getMigrateSql();
1032
+ if (changes)
1033
+ await db.runMultipleWriteStatements(changes.up);
1034
+ }
935
1035
  async function rollback(db, instructions, toVersion) {
936
1036
  Logger.setMode(instructions.loggerMode);
937
1037
  const migrationHistoryManager = new MigrationHistoryManager(instructions.configPath);
@@ -952,5 +1052,6 @@ async function rollback(db, instructions, toVersion) {
952
1052
  prepareAndRunMigration,
953
1053
  prepareMigration,
954
1054
  rollback,
1055
+ runMigrationWithoutHistory,
955
1056
  runPreparedMigrations
956
1057
  });
package/dist/index.mjs CHANGED
@@ -222,6 +222,12 @@ var MigrationHistoryManager = class {
222
222
  mkdirSync(this.configPath, { recursive: true });
223
223
  mkdirSync(this.migrationsPath, { recursive: true });
224
224
  }
225
+ /**
226
+ * Retrieves the last recorded history version from the configuration path.
227
+ * If the version is not already cached in memory, this method reads it from a file on disk.
228
+ *
229
+ * @return The last version number, or 0 if the version file does not exist or cannot be parsed.
230
+ */
225
231
  getLastHistoryVersion() {
226
232
  if (this.lastVersion)
227
233
  return this.lastVersion;
@@ -229,9 +235,21 @@ var MigrationHistoryManager = class {
229
235
  this.lastVersion = existsSync(path) ? parseInt(readFileSync(`${this.configPath}/last_version.txt`, { encoding: "utf-8" })) ?? 0 : 0;
230
236
  return this.lastVersion;
231
237
  }
238
+ /**
239
+ * Updates the "last history version" information by writing the given version to a file.
240
+ *
241
+ * @param version - The version number to set as the last history version.
242
+ */
232
243
  setLastHistoryVersion(version) {
233
244
  writeFileSync(`${this.configPath}/last_version.txt`, version.toString(), { encoding: "utf-8" });
234
245
  }
246
+ /**
247
+ * Creates migration history files for upgrading and downgrading database schemas.
248
+ *
249
+ * @param toVersion - The target version number for the migration.
250
+ * @param changes - An object containing the SQL changes for upgrading (`changes.up`) and downgrading (`changes.down`).
251
+ * @param overwriteExisting - A flag that determines if existing migration files should be overwritten. Defaults to `false`.
252
+ */
235
253
  createMigrationHistory(toVersion, changes, overwriteExisting) {
236
254
  const fromVersion = this.getLastHistoryVersion();
237
255
  const upPath = `${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion}.sql`;
@@ -248,9 +266,22 @@ ${changes.up}`, { encoding: "utf-8" });
248
266
  -- To: Version ${fromVersion}
249
267
  ${changes.down}`, { encoding: "utf-8" });
250
268
  }
269
+ /**
270
+ * Retrieves the SQL migration script for upgrading to the specified version.
271
+ * If no version is provided, it retrieves the migration script for the latest version in the history.
272
+ *
273
+ * @param toVersion - The version of the migration script to retrieve. If not specified, the latest version is used.
274
+ * @return The content of the SQL migration script as a string.
275
+ */
251
276
  getUpMigration(toVersion) {
252
277
  return readFileSync(`${this.migrationsPath}/${FILENAME_UP_PREFIX}${toVersion ?? this.getLastHistoryVersion()}.sql`, { encoding: "utf-8" });
253
278
  }
279
+ /**
280
+ * Retrieves the SQL migration script for downgrading to the specified version.
281
+ *
282
+ * @param version - The version number of the migration to retrieve.
283
+ * @return The SQL script for the down migration.
284
+ */
254
285
  getDownMigration(version) {
255
286
  return readFileSync(`${this.migrationsPath}/${FILENAME_DOWN_PREFIX}${version}.sql`, { encoding: "utf-8" });
256
287
  }
@@ -550,6 +581,17 @@ var MigrationManager = class {
550
581
  this.tableStructureGenerator = new TableStructureGenerator(dbInstructions, this.dialect);
551
582
  this.migrationHistoryManager = new MigrationHistoryManager(this.dbInstructions.configPath);
552
583
  }
584
+ /**
585
+ * Generates the SQL changes required to migrate a database from its current version
586
+ * to the target version defined in the database instructions. Handles the creation
587
+ * and deletion of tables, migration of foreign keys and columns, renaming of columns,
588
+ * and recreating tables, along with executing any pre- and post-migration custom logic.
589
+ *
590
+ * @return A promise that resolves to an object containing the SQL
591
+ * changes for the migration (`up` and `down` changes) or null if no migration is required.
592
+ * Throws an error in scenarios such as attempting to migrate to a lower version
593
+ * or an invalid starting version.
594
+ */
553
595
  async getMigrateSql() {
554
596
  if (this.dbInstructions.version <= 0)
555
597
  throw new Error("Cannot migrate to version 0 or lower");
@@ -618,12 +660,28 @@ ${foreignKeyOnQuery}`;
618
660
  ${foreignKeyOnQuery}`;
619
661
  return changes;
620
662
  }
663
+ /**
664
+ * Prepares the migration by generating the SQL changes and creating a migration history entry.
665
+ * If no changes are needed, the method exits early.
666
+ *
667
+ * @param overwriteExisting - Optional flag indicating if overwriting existing changes is allowed.
668
+ * @return - A promise that resolves once the migration preparation is complete.
669
+ */
621
670
  async prepareMigration(overwriteExisting) {
622
671
  const changes = await this.getMigrateSql();
623
672
  if (!changes)
624
673
  return;
625
674
  this.migrationHistoryManager.createMigrationHistory(this.dbInstructions.version, changes, overwriteExisting);
626
675
  }
676
+ /**
677
+ * Generates SQL change statements for creating and dropping tables based on the current table structure
678
+ * and existing table configurations in the database. The `up` changes include SQL statements for creating
679
+ * new tables, while the `down` changes include SQL statements for dropping the corresponding tables or
680
+ * recreating them if necessary.
681
+ *
682
+ * @return {Promise<SqlChanges>} A promise that resolves to an object containing `up` and `down` SQL
683
+ * change statements for migrating the database schema.
684
+ */
627
685
  async createAndDropTables() {
628
686
  let changes = {
629
687
  up: "\n\n-- Create tables\n",
@@ -650,6 +708,16 @@ ${foreignKeyOnQuery}`;
650
708
  }
651
709
  return changes;
652
710
  }
711
+ /**
712
+ * Generates an SQL string to create a table with the specified schema.
713
+ *
714
+ * @param tableName - The name of the table to be created.
715
+ * @param columns - An array of objects defining the columns of the table, including their names, types
716
+ * default values, and whether they are primary keys.
717
+ * @param foreignKeys - An optional array of objects defining the foreign key constraints for the table,
718
+ * including the source column, target table, target column, action on update, and action on delete.
719
+ * @return The complete SQL string to create the table with the specified structure and constraints.
720
+ */
653
721
  createTableSql(tableName, columns, foreignKeys) {
654
722
  const queryLines = [];
655
723
  for (const columnInfo of columns) {
@@ -662,9 +730,20 @@ ${foreignKeyOnQuery}`;
662
730
  }
663
731
  return this.dialect.createTable(tableName, queryLines);
664
732
  }
733
+ /**
734
+ * Checks if the specified table does not exist in the list of existing tables.
735
+ *
736
+ * @param tableName - The name of the table to check.
737
+ * @return Returns true if the table does not exist, otherwise false.
738
+ */
665
739
  tableDoesNotExists(tableName) {
666
740
  return this.existingTables.indexOf(tableName) == -1;
667
741
  }
742
+ /**
743
+ * Recreates database tables that have been flagged to be recreated in migration data.
744
+ * This method generated the necessary SQL code for backing up the current table data, dropping and recreating
745
+ * the tables, and reinserting the preserved data into the recreated tables.
746
+ */
668
747
  async recreateTables() {
669
748
  const changes = {
670
749
  up: "\n\n-- Recreate tables\n",
@@ -693,6 +772,9 @@ ${foreignKeyOnQuery}`;
693
772
  }
694
773
  return changes;
695
774
  }
775
+ /**
776
+ * Migrates foreign key constraints for all defined tables.
777
+ */
696
778
  async migrateForeignKeys() {
697
779
  if (!this.dialect.canAlterForeignKeys)
698
780
  return { up: "", down: "" };
@@ -816,12 +898,22 @@ ${foreignKeyOnQuery}`;
816
898
  }
817
899
  return changes;
818
900
  }
901
+ /**
902
+ * Retrieves the name of the primary key column from a list of column information.
903
+ *
904
+ * @param columnInfoList - An array of ColumnInfo objects containing details about each column.
905
+ * @return The name of the primary key column if found; otherwise, undefined.
906
+ */
819
907
  getPrimaryKeyColumn(columnInfoList) {
820
908
  for (const columnInfo of columnInfoList) {
821
909
  if (columnInfo.isPrimaryKey)
822
910
  return columnInfo.name;
823
911
  }
824
912
  }
913
+ /**
914
+ * Handles the renaming of columns in database tables by generating SQL changes for both applying and reverting the renames.
915
+ * Skips tables that are marked for recreation.
916
+ */
825
917
  renameColumns() {
826
918
  const changes = {
827
919
  up: "\n\n-- Rename columns\n",
@@ -901,6 +993,13 @@ async function prepareAndRunMigration(db, instructions, overwriteExisting) {
901
993
  await prepareMigration(db, instructions, overwriteExisting);
902
994
  await runPreparedMigrations(db, instructions);
903
995
  }
996
+ async function runMigrationWithoutHistory(db, instructions) {
997
+ Logger.setMode(instructions.loggerMode);
998
+ const mm = new MigrationManager(db, instructions);
999
+ const changes = await mm.getMigrateSql();
1000
+ if (changes)
1001
+ await db.runMultipleWriteStatements(changes.up);
1002
+ }
904
1003
  async function rollback(db, instructions, toVersion) {
905
1004
  Logger.setMode(instructions.loggerMode);
906
1005
  const migrationHistoryManager = new MigrationHistoryManager(instructions.configPath);
@@ -920,5 +1019,6 @@ export {
920
1019
  prepareAndRunMigration,
921
1020
  prepareMigration,
922
1021
  rollback,
1022
+ runMigrationWithoutHistory,
923
1023
  runPreparedMigrations
924
1024
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sqlmorpheus",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "author": "JodliDev",
5
5
  "keywords": [],
6
6
  "license": "MIT",