sqlmorpheus 1.0.0 → 1.1.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,450 @@
1
+ import "polyfill-symbol-metadata";
2
+ //#region src/lib/typings/DatabaseAccess.d.ts
3
+ interface DatabaseAccess {
4
+ createBackup?(backupName: string): Promise<any>;
5
+ runReadStatement(query: string): Promise<unknown>;
6
+ runWriteStatement(query: string): Promise<any>;
7
+ runTransaction(query: string): Promise<any>;
8
+ }
9
+ //#endregion
10
+ //#region src/lib/typings/TableClassInterface.d.ts
11
+ type Class<T> = new (...args: never[]) => T;
12
+ /**
13
+ * This does nothing. It mainly exists in case we want to filter class types in the future
14
+ */
15
+ type TableClassInterface = {
16
+ [key: string]: any;
17
+ };
18
+ //#endregion
19
+ //#region src/lib/typings/AllowedMigrations.d.ts
20
+ declare const ALLOWED = "allowed";
21
+ declare const USED = "allowedAndUsed";
22
+ type AllowedMigrationState = typeof ALLOWED | typeof USED;
23
+ interface AllowedMigrations {
24
+ recreateTable?: Record<string, AllowedMigrationState>;
25
+ dropTable?: Record<string, AllowedMigrationState>;
26
+ dropColumn?: Record<string, AllowedMigrationState>;
27
+ alterPrimaryKey?: Record<string, AllowedMigrationState>;
28
+ removeForeignKey?: Record<string, AllowedMigrationState>;
29
+ alterForeignKey?: Record<string, AllowedMigrationState>;
30
+ dropIndex?: Record<string, AllowedMigrationState>;
31
+ }
32
+ //#endregion
33
+ //#region src/lib/typings/MigrationInstructions.d.ts
34
+ interface RenameData {
35
+ oldName: string;
36
+ newName: string;
37
+ }
38
+ interface MigrationInstructions {
39
+ tableRenaming?: RenameData;
40
+ recreate: boolean;
41
+ /**
42
+ * Stores changes to column. One entry per column.
43
+ */
44
+ renamedColumns: RenameData[];
45
+ allowedMigrations: AllowedMigrations;
46
+ }
47
+ //#endregion
48
+ //#region src/lib/typings/ColumnInfo.d.ts
49
+ interface ColumnInfo {
50
+ name: string;
51
+ sqlType: string;
52
+ maxLength?: number;
53
+ defaultValue?: string;
54
+ isPrimaryKey: boolean;
55
+ }
56
+ //#endregion
57
+ //#region src/lib/typings/ForeignKeyInfo.d.ts
58
+ type ForeignKeyActions = "SET NULL" | "SET DEFAULT" | "RESTRICT" | "NO ACTION" | "CASCADE";
59
+ interface ForeignKeyInfo {
60
+ fromTable: string;
61
+ fromColumn: string;
62
+ toTable: string;
63
+ toColumn: string;
64
+ onUpdate?: ForeignKeyActions;
65
+ onDelete?: ForeignKeyActions;
66
+ }
67
+ //#endregion
68
+ //#region src/lib/typings/IndexInfo.d.ts
69
+ interface IndexInfo {
70
+ name: string;
71
+ columns: string[];
72
+ isUnique: boolean;
73
+ }
74
+ /**
75
+ * Index definition as provided by the user. If no name is provided, a name is generated from the table and column names.
76
+ */
77
+ interface InputIndexInfo extends Omit<IndexInfo, "name"> {
78
+ name?: string;
79
+ }
80
+ //#endregion
81
+ //#region src/lib/typings/TableStructure.d.ts
82
+ interface TableStructure {
83
+ table: string;
84
+ primaryKey?: string;
85
+ columns: Record<string, ColumnInfo>;
86
+ foreignKeys?: ForeignKeyInfo[];
87
+ indexes?: IndexInfo[];
88
+ }
89
+ //#endregion
90
+ //#region src/lib/Migrations.d.ts
91
+ /**
92
+ * The Migrations class is responsible for managing manual database schema migrations.
93
+ */
94
+ declare class Migrations {
95
+ private fromVersion;
96
+ private toVersion;
97
+ private lastUsedVersion;
98
+ private migrationData;
99
+ private migrationDataForOldTableNames;
100
+ private alwaysAllowed;
101
+ private notAllowedChanges;
102
+ /**
103
+ * Resets the migration state to its initial values.
104
+ * Only used internally.
105
+ *
106
+ * @param dbInstructions - The instructions containing database metadata and migration details.
107
+ * @param fromVersion - The version of the actual database.
108
+ */
109
+ reset(dbInstructions: DatabaseInstructions, fromVersion: number): void;
110
+ /**
111
+ * Retrieves the migration instructions for the specified table.
112
+ *
113
+ * @param tableName - The name of the table for which the entry is to be retrieved or created.
114
+ * @return The migration instructions corresponding to the given table input.
115
+ */
116
+ private getEntryFromTableName;
117
+ /**
118
+ * Checks whether a provided version is relevant based on database version ({@link fromVersion}) and target version ({@link toVersion}).
119
+ * Also makes sure that version checks happen in order.
120
+ *
121
+ * @param version - The version to check for relevance.
122
+ * @return Returns true if the version is relevant, otherwise false.
123
+ * @throws Error if versions are not properly ordered
124
+ */
125
+ private versionIsRelevant;
126
+ /**
127
+ * Verifies the renaming tasks specified in {@link DatabaseInstructions.preMigration} that were considered are valid.
128
+ * Called after all SQL queries have been generated.
129
+ * Only used internally.
130
+ *
131
+ * @param newTables - The table structures extracted from {@link DatabaseInstructions.tables}.
132
+ * @throws Error if a renaming task is invalid.
133
+ */
134
+ verifyRenamingTasks(newTables: Record<string, TableStructure>): Error | void;
135
+ /**
136
+ * Making sure all considered calls to {@link allowMigration()} where necessary to prevent input mistakes.
137
+ * Called after all SQL queries have been generated.
138
+ * Only used internally.
139
+ *
140
+ * @throws Error if unnecessary calls were discovered. All discovered calls are collected and thrown as one Error.
141
+ */
142
+ verifyAllowedMigrations(): Error | void;
143
+ /**
144
+ * Called by {@link MigrationManager} to check if a specific destructive query is allowed.
145
+ * Only used internally.
146
+ *
147
+ * @see allowMigration()
148
+ * @param tableName - The name of the table to check the migration against.
149
+ * @param type - The type of destructive migration being checked.
150
+ * @param column - The column name for which the migration is allowed. Only needed for "dropColumn", "removeForeignKey" and "alterForeignKey".
151
+ * For "dropIndex", the index name is used instead.
152
+ */
153
+ compareWithAllowedMigration(tableName: string, type: keyof AllowedMigrations, column?: string): void;
154
+ /**
155
+ * Retrieves the migration data containing instructions for data migration.
156
+ * Only used internally.
157
+ *
158
+ * @return An object where each key corresponds to the table name,
159
+ * and the value is the associated migration instructions.
160
+ */
161
+ getMigrationData(): Record<string, MigrationInstructions>;
162
+ /**
163
+ * Iterates over renamed columns for the specified table and executes a callback for each pair of old and new column names.
164
+ * Only used internally.
165
+ *
166
+ * @param tableName - Name of the table whose renamed columns should be processed.
167
+ * @param callback - A function to execute for each renamed column, receiving the old and new column names as arguments.
168
+ */
169
+ loopRenamedColumns(tableName: string, callback: (oldColumnName: string, newColumnName: string) => void): void;
170
+ /**
171
+ * Considers the renaming of a table and returns its (newest) name after the migration or
172
+ * the original name if no renaming is queued.
173
+ * Only used internally.
174
+ *
175
+ * @see getOldTableName()
176
+ * @param tableName - The current table name in the database.
177
+ * @return The newest table name if available, otherwise the current table name.
178
+ */
179
+ getNewestTableName(tableName: string): string;
180
+ /**
181
+ * Retrieves the current table name in the database.
182
+ * Only used internally.
183
+ *
184
+ * @see getNewestTableName()
185
+ * @param tableName - The name of the newest table name.
186
+ * @return The current table name in the database.
187
+ */
188
+ getOldTableName(tableName: string): string;
189
+ /**
190
+ * Considers the renaming of a column in a table and returns its (newest) name after the migration or
191
+ * the original name if no renaming is queued.
192
+ * Only used internally.
193
+ *
194
+ * @param tableName - The name of the table containing the column.
195
+ * @param oldColumnName - The current name of the column in the database.
196
+ * @return The newest column name if available, otherwise the original column name.
197
+ */
198
+ getNewestColumnName(tableName: string, oldColumnName: string): string;
199
+ /**
200
+ * Determines if the specified table is marked to be recreated.
201
+ * Only used internally.
202
+ *
203
+ * @param tableName The name of the table to check.
204
+ * @return Returns true if the table will be recreated, false otherwise.
205
+ */
206
+ willBeRecreated(tableName: string): boolean;
207
+ /**
208
+ * Marks a table to be recreated and logs the recreation reason for the user.
209
+ * Only used internally.
210
+ *
211
+ * @param tableName - The name of the table to be marked for recreation.
212
+ * @param reason - The reason why the table is being marked for recreation.
213
+ */
214
+ internalRecreate(tableName: string, reason: string): void;
215
+ /**
216
+ * SqlMorpheus only allows destructive statements if it was specifically allowed in {@link DatabaseInstructions.preMigration()}.
217
+ * Use this method to allow a destructive statement for a specific version.
218
+ * This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
219
+ *
220
+ * @param version - The target version for which the specific migration is allowed. Must be provided to make sure this method will only have an effect when specified.
221
+ * @param tableName - The current table name in the database at the time of the migration version.
222
+ * @param allowedMigration - The keys representing the migrations to be allowed.
223
+ * @param column - The column name for which the migration is allowed. Only needed for "dropColumn", "removeForeignKey" and "alterForeignKey".
224
+ * For "dropIndex", provide the index name instead.
225
+ *
226
+ * @throws Error if the provided column name is not valid for the specified migration.
227
+ */
228
+ allowMigration(version: number, tableName: string, allowedMigration: keyof AllowedMigrations, column?: string): void;
229
+ /**
230
+ * When you change the name of a table, SqlMorpheus will assume the original table was meant to be dropped
231
+ * and the new table was meant to be added, which would lead to data loss.
232
+ * Use this method to mark a table to be renamed instead.
233
+ * This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
234
+ *
235
+ * @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
236
+ * @param oldTableName - The current name in the database at the time of the migration version.
237
+ * @param newTableName - The new table name at the time of the migration version.
238
+ */
239
+ renameTable(version: number, oldTableName: string, newTableName: string): void;
240
+ /**
241
+ * When you change the name of a column, SqlMorpheus will assume the original column was meant to be removed
242
+ * and the new column was meant to be added, which would lead to data loss.
243
+ * Use this method to mark a column to be renamed instead.
244
+ * This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
245
+ *
246
+ * @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
247
+ * @param tableName - The current table name in the database at the time of the migration version.
248
+ * @param oldColumn The current name in the database at the time of the migration.
249
+ * @param newColumn The new name to assign to the column.
250
+ */
251
+ renameColumn(version: number, tableName: string, oldColumn: string, newColumn: string): void;
252
+ /**
253
+ * Should not be needed most of the time.
254
+ * Marks a table to be recreated
255
+ * (a copy of the table will be created, all data will be moved over, the original table will be dropped and the new table will be renamed to the original name).
256
+ * This method will be ignored if {@link version} is smaller than the current database version or higher than the target version of {@link DatabaseInstructions}.
257
+ *
258
+ * @param version - The target version for which the table should be renamed. Must be provided to make sure this method will only have an effect when specified.
259
+ * @param tableName - The current table name in the database at the time of the migration version.
260
+ */
261
+ recreateTable(version: number, tableName: string): void;
262
+ }
263
+ type PublicMigrations = Pick<Migrations, "recreateTable" | "renameTable" | "renameColumn" | "allowMigration">;
264
+ //#endregion
265
+ //#region src/lib/typings/SqlChanges.d.ts
266
+ interface SqlChanges {
267
+ up: string;
268
+ down: string;
269
+ }
270
+ //#endregion
271
+ //#region src/lib/tableInfo/DataTypeOptions.d.ts
272
+ type NativeDataTypeOptions = "boolean" | "number" | "bigint" | "string";
273
+ type AddedDataTypeOptions = "date" | "time" | "dateTime" | "text";
274
+ type DataTypeOptions = NativeDataTypeOptions | AddedDataTypeOptions;
275
+ //#endregion
276
+ //#region src/lib/typings/InputColumnInfo.d.ts
277
+ interface InputColumnInfo extends ColumnInfo {
278
+ inputType?: DataTypeOptions;
279
+ inputDefaultValue?: unknown;
280
+ }
281
+ //#endregion
282
+ //#region src/lib/typings/InputTableStructure.d.ts
283
+ interface InputTableStructure extends Omit<TableStructure, "indexes"> {
284
+ columns: Record<string, InputColumnInfo>;
285
+ indexes?: InputIndexInfo[];
286
+ }
287
+ //#endregion
288
+ //#region src/lib/tableInfo/TableObjHelper.d.ts
289
+ type AllowedTypes = boolean | number | bigint | string | null | Date;
290
+ //#endregion
291
+ //#region src/lib/tableInfo/TableObj.d.ts
292
+ interface ColumnOptions {
293
+ primaryKey?: boolean;
294
+ dataType?: DataTypeOptions;
295
+ maxCharacterLength?: number;
296
+ }
297
+ type DataFormat = Record<string, AllowedTypes | [AllowedTypes, ColumnOptions]>;
298
+ type GetColumns<T> = T extends PublicTableObj<infer Item> ? Item : never;
299
+ type PublicTableObj<T extends DataFormat> = Pick<TableObj<T>, "foreignKey" | "index" | "sealType">;
300
+ type TableObjInput = PublicTableObj<DataFormat>;
301
+ /**
302
+ * Use this class to define tables for DatabaseInstructions
303
+ * (as an alternative for Class decorators)
304
+ *
305
+ */
306
+ declare class TableObj<T extends DataFormat> {
307
+ readonly IS_TABLE_OBJ = true;
308
+ readonly tableName: string;
309
+ tableStructure: InputTableStructure;
310
+ private constructor();
311
+ private applyOptions;
312
+ /**
313
+ * Creates a foreign key relationship between the current table and a target table.
314
+ *
315
+ * @param fromColumn - The column in the current table that will serve as the foreign key.
316
+ * @param toTable - The target table object that the foreign key will reference.
317
+ * @param toColumn - The column in the target table that the foreign key will reference.
318
+ * @param options - Optional configurations for the foreign key, specifying actions on update or delete.
319
+ */
320
+ foreignKey<TOther extends Partial<TableObj<DataFormat>>>(fromColumn: keyof T, toTable: TOther, toColumn: keyof GetColumns<TOther>, options?: {
321
+ onUpdate?: ForeignKeyActions;
322
+ onDelete?: ForeignKeyActions;
323
+ }): PublicTableObj<T>;
324
+ /**
325
+ * Creates an index on one or more columns of the current table.
326
+ *
327
+ * @param columns - The columns that will be part of the index (in order).
328
+ * @param options - Optional configurations for the index.
329
+ * If no name is provided, the name is generated from the table and column names.
330
+ */
331
+ index(columns: (keyof T)[], options?: {
332
+ name?: string;
333
+ unique?: boolean;
334
+ }): PublicTableObj<T>;
335
+ /**
336
+ * An optional helper function to deal with `TS2589: Type instantiation is excessively deep and possibly infinite. when used as method parameter`
337
+ * Does nothing in runtime
338
+ */
339
+ sealType(): TableObjInput;
340
+ static create<T extends DataFormat>(tableName: string, columns: T): PublicTableObj<T>;
341
+ }
342
+ //#endregion
343
+ //#region src/lib/Logger.d.ts
344
+ type LoggerMode = "silent" | "error" | "warn" | "log" | "debug";
345
+ //#endregion
346
+ //#region src/lib/typings/DatabaseInstructions.d.ts
347
+ type TableInput = TableObjInput | Class<TableClassInterface>;
348
+ interface DatabaseInstructions {
349
+ dialect: "Sqlite" | "MsSql" | "MySql" | "Postgres";
350
+ tables: TableInput[];
351
+ version: number;
352
+ /**
353
+ * Usually SqlMorpheus throws an exception if it needs to execute a destructive database change and is not explicitly confirmed in
354
+ * (using `allowMigration()` in `preMigration()`).
355
+ * If true, no exception will be thrown and an error message will be logged to the console instead.
356
+ */
357
+ doNotThrowIfNotAllowed?: boolean;
358
+ /**
359
+ * Defines how much should be logged to the console.
360
+ */
361
+ loggerMode?: LoggerMode;
362
+ /**
363
+ * Usually SqlMorpheus throws an exception if it needs to execute a destructive database change and is not explicitly allowed to do so
364
+ * (using `allowMigration()` in `preMigration()`).
365
+ * if defined, the confirmation will be skipped for each migration type defined in `alwaysAllowedMigrations`.
366
+ */
367
+ alwaysAllowedMigrations?: (keyof AllowedMigrations)[];
368
+ /**
369
+ * Custom migrations that will run before any database changes are applied.
370
+ * @param migrations - The migration object that will be validated after this.
371
+ * @param dbAccess - The database access object to interact with the database.
372
+ * @param fromVersion - Version of the current database.
373
+ * @param toVersion - Version of the database after update.
374
+ * @return custom SQL that should be executed before migrations are executed.
375
+ */
376
+ preMigration?(migrations: PublicMigrations, dbAccess: DatabaseAccess, fromVersion: number, toVersion: number): SqlChanges | void;
377
+ /**
378
+ * Custom migrations that will run after database changes have been applied (but before the transaction is finished)
379
+ * @param dbAccess - The database access object to interact with the database.
380
+ * @param fromVersion - Version of the current database.
381
+ * @param toVersion - Version of the database after update.
382
+ * @return custom SQL that should be executed after migrations were executed.
383
+ */
384
+ postMigration?(dbAccess: DatabaseAccess, fromVersion: number, toVersion: number): SqlChanges;
385
+ }
386
+ //#endregion
387
+ //#region src/lib/tableInfo/decorators/TableClass.d.ts
388
+ /**
389
+ * Decorator function to configure a database table with its name and primary key.
390
+ *
391
+ * @param tableName - The name of the database table used in SQL.
392
+ * @param primaryKey - The property name representing the primary property of the table.
393
+ */
394
+ declare function TableClass<T extends TableClassInterface>(tableName: string, primaryKey?: keyof T): (table: Class<T>, context?: any) => void;
395
+ //#endregion
396
+ //#region src/lib/tableInfo/decorators/DataType.d.ts
397
+ /**
398
+ * Decorator function to assign a specific data type to a column.
399
+ * Should be used if you want to use a data type that does not exist in JavaScript or
400
+ * if the default value should be NULL
401
+ *
402
+ * @param type - The data type to be assigned.
403
+ */
404
+ declare function DataType(type: DataTypeOptions): (table: any, context: any) => void;
405
+ //#endregion
406
+ //#region src/lib/tableInfo/decorators/ForeignKey.d.ts
407
+ /**
408
+ * Decorator function to define a foreign key relationship for a database table.
409
+ *
410
+ * @param toTable - The target table class to which the foreign key points.
411
+ * @param toColumn - The column name in the target table to which the foreign key points.
412
+ * @param options - Additional options.
413
+ */
414
+ declare function ForeignKey<TOther extends TableClassInterface>(toTable: Class<TOther>, toColumn: keyof TOther, options?: {
415
+ onDelete?: ForeignKeyActions;
416
+ onUpdate?: ForeignKeyActions;
417
+ }): (table: any, context: any) => void;
418
+ //#endregion
419
+ //#region src/lib/tableInfo/decorators/Index.d.ts
420
+ /**
421
+ * Decorator function to create an index on one or more columns of a table.
422
+ * This decorator must be used at the head of the class.
423
+ *
424
+ * @param columns - The columns that will be part of the index (in order).
425
+ * @param options - Additional options. If no name is provided, the name is generated from the table and column names.
426
+ */
427
+ declare function Index<T extends TableClassInterface>(columns: (keyof T)[], options?: {
428
+ name?: string;
429
+ unique?: boolean;
430
+ }): (table: Class<T>, context?: any) => void;
431
+ //#endregion
432
+ //#region src/index.d.ts
433
+ /**
434
+ * Executes a database migration based on the provided database connection and migration instructions.
435
+ *
436
+ * @param db - The database access object used to interact with the database.
437
+ * @param dbInstructions - The migration instructions, including target version, logger mode, and dialect.
438
+ * @return A promise that resolves when the migration process is successfully completed.
439
+ */
440
+ export declare function runMigration(db: DatabaseAccess, dbInstructions: DatabaseInstructions): Promise<void>;
441
+ /**
442
+ * Rolls back the database to the provided toVersion
443
+ * @param dbAccess - Access to the database.
444
+ * @param toVersion - the version to which the database should be upgraded to.
445
+ * @param dialect - the dialect that should be used for the database. Usually is the value defined in DatabaseInstructions
446
+ * @param loggerMode - defines how much should be logged to the console.
447
+ */
448
+ export declare function rollback(dbAccess: DatabaseAccess, toVersion: number, dialect: DatabaseInstructions["dialect"], loggerMode?: DatabaseInstructions["loggerMode"]): Promise<number>;
449
+ //#endregion
450
+ export { DataType, type DatabaseAccess, type DatabaseInstructions, ForeignKey, Index, type PublicMigrations, type SqlChanges, TableClass, TableObj };