@digilogiclabs/platform-core 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,379 @@
1
+ /**
2
+ * Database Migration Interface
3
+ *
4
+ * Provides a vendor-agnostic way to manage database schema migrations.
5
+ * Supports:
6
+ * - Forward and rollback migrations
7
+ * - Migration versioning and tracking
8
+ * - Transaction-safe migrations
9
+ * - Dry-run mode for testing
10
+ * - Migration locking to prevent concurrent runs
11
+ */
12
+ interface Migration {
13
+ /** Unique migration version (e.g., '20240101120000' or '001') */
14
+ version: string;
15
+ /** Human-readable name */
16
+ name: string;
17
+ /** SQL or function to apply the migration */
18
+ up: string | ((db: IMigrationDatabase) => Promise<void>);
19
+ /** SQL or function to rollback the migration */
20
+ down: string | ((db: IMigrationDatabase) => Promise<void>);
21
+ /** Optional: run in a transaction (default: true) */
22
+ transactional?: boolean;
23
+ /** Optional: checksum for detecting modified migrations */
24
+ checksum?: string;
25
+ }
26
+ interface MigrationRecord {
27
+ /** Migration version */
28
+ version: string;
29
+ /** Migration name */
30
+ name: string;
31
+ /** When the migration was applied */
32
+ appliedAt: Date;
33
+ /** How long the migration took (ms) */
34
+ executionTime: number;
35
+ /** Migration checksum at time of application */
36
+ checksum?: string;
37
+ }
38
+ interface MigrationResult {
39
+ /** The migration that was run */
40
+ migration: Migration;
41
+ /** Whether it succeeded */
42
+ success: boolean;
43
+ /** Execution time in milliseconds */
44
+ executionTime: number;
45
+ /** Error if failed */
46
+ error?: Error;
47
+ /** Whether this was a dry run */
48
+ dryRun: boolean;
49
+ }
50
+ interface MigrationStatus {
51
+ /** Currently applied migrations */
52
+ applied: MigrationRecord[];
53
+ /** Pending migrations (not yet applied) */
54
+ pending: Migration[];
55
+ /** Current schema version (last applied migration) */
56
+ currentVersion: string | null;
57
+ /** Latest available version */
58
+ latestVersion: string | null;
59
+ }
60
+ interface MigratorConfig {
61
+ /** Table name for tracking migrations (default: '_migrations') */
62
+ tableName?: string;
63
+ /** Schema for migration table (default: 'public') */
64
+ schema?: string;
65
+ /** Lock timeout in seconds (default: 60) */
66
+ lockTimeout?: number;
67
+ /** Whether to validate checksums (default: true) */
68
+ validateChecksums?: boolean;
69
+ /** Directory containing migration files (for file-based loading) */
70
+ migrationsDir?: string;
71
+ }
72
+ /**
73
+ * Simplified database interface for migrations
74
+ * Migrations only need raw SQL execution capability
75
+ */
76
+ interface IMigrationDatabase {
77
+ /**
78
+ * Execute raw SQL
79
+ */
80
+ raw<T = unknown>(sql: string, params?: unknown[]): Promise<{
81
+ data: T[];
82
+ error?: Error;
83
+ }>;
84
+ /**
85
+ * Execute within a transaction
86
+ */
87
+ transaction<T>(fn: (db: IMigrationDatabase) => Promise<T>): Promise<T>;
88
+ }
89
+ interface IMigrator {
90
+ /**
91
+ * Get current migration status
92
+ */
93
+ status(): Promise<MigrationStatus>;
94
+ /**
95
+ * Run all pending migrations
96
+ */
97
+ up(options?: {
98
+ dryRun?: boolean;
99
+ to?: string;
100
+ }): Promise<MigrationResult[]>;
101
+ /**
102
+ * Rollback the last migration
103
+ */
104
+ down(options?: {
105
+ dryRun?: boolean;
106
+ steps?: number;
107
+ }): Promise<MigrationResult[]>;
108
+ /**
109
+ * Rollback all migrations and re-run them
110
+ */
111
+ reset(options?: {
112
+ dryRun?: boolean;
113
+ }): Promise<MigrationResult[]>;
114
+ /**
115
+ * Migrate to a specific version (up or down as needed)
116
+ */
117
+ goto(version: string, options?: {
118
+ dryRun?: boolean;
119
+ }): Promise<MigrationResult[]>;
120
+ /**
121
+ * Add migrations to the migrator
122
+ */
123
+ addMigrations(migrations: Migration[]): void;
124
+ /**
125
+ * Load migrations from directory
126
+ */
127
+ loadMigrations(dir: string): Promise<void>;
128
+ /**
129
+ * Create a new migration file
130
+ */
131
+ create(name: string): Promise<string>;
132
+ /**
133
+ * Validate migration integrity
134
+ */
135
+ validate(): Promise<{
136
+ valid: boolean;
137
+ errors: string[];
138
+ }>;
139
+ /**
140
+ * Acquire migration lock (for concurrent safety)
141
+ */
142
+ lock(): Promise<boolean>;
143
+ /**
144
+ * Release migration lock
145
+ */
146
+ unlock(): Promise<void>;
147
+ }
148
+
149
+ /**
150
+ * Database Migrator
151
+ *
152
+ * Enterprise-grade database migration system supporting:
153
+ * - PostgreSQL (primary)
154
+ * - Memory database (for testing)
155
+ * - Transaction-safe migrations
156
+ * - Concurrent execution locking
157
+ * - Checksum validation
158
+ * - Dry-run mode
159
+ */
160
+
161
+ declare class Migrator implements IMigrator {
162
+ private db;
163
+ private config;
164
+ private migrations;
165
+ private initialized;
166
+ private locked;
167
+ constructor(db: IMigrationDatabase, config?: MigratorConfig);
168
+ /**
169
+ * Get the fully qualified migration table name
170
+ */
171
+ private get tableName();
172
+ /**
173
+ * Get the lock table name
174
+ */
175
+ private get lockTableName();
176
+ /**
177
+ * Initialize migration tracking tables
178
+ */
179
+ private initialize;
180
+ /**
181
+ * Acquire migration lock
182
+ */
183
+ lock(): Promise<boolean>;
184
+ /**
185
+ * Release migration lock
186
+ */
187
+ unlock(): Promise<void>;
188
+ /**
189
+ * Add migrations to the migrator
190
+ */
191
+ addMigrations(migrations: Migration[]): void;
192
+ /**
193
+ * Load migrations from directory
194
+ * Expects files named: {version}_{name}.ts or {version}_{name}.sql
195
+ */
196
+ loadMigrations(dir: string): Promise<void>;
197
+ /**
198
+ * Parse SQL migration file with -- UP and -- DOWN sections
199
+ */
200
+ private parseSqlMigration;
201
+ /**
202
+ * Get current migration status
203
+ */
204
+ status(): Promise<MigrationStatus>;
205
+ /**
206
+ * Run all pending migrations (or up to a specific version)
207
+ */
208
+ up(options?: {
209
+ dryRun?: boolean;
210
+ to?: string;
211
+ }): Promise<MigrationResult[]>;
212
+ /**
213
+ * Rollback migrations
214
+ */
215
+ down(options?: {
216
+ dryRun?: boolean;
217
+ steps?: number;
218
+ }): Promise<MigrationResult[]>;
219
+ /**
220
+ * Rollback all migrations and re-run them
221
+ */
222
+ reset(options?: {
223
+ dryRun?: boolean;
224
+ }): Promise<MigrationResult[]>;
225
+ /**
226
+ * Migrate to a specific version
227
+ */
228
+ goto(version: string, options?: {
229
+ dryRun?: boolean;
230
+ }): Promise<MigrationResult[]>;
231
+ /**
232
+ * Run a single migration
233
+ */
234
+ private runMigration;
235
+ /**
236
+ * Create a new migration file
237
+ */
238
+ create(name: string): Promise<string>;
239
+ /**
240
+ * Validate migration integrity
241
+ */
242
+ validate(): Promise<{
243
+ valid: boolean;
244
+ errors: string[];
245
+ }>;
246
+ }
247
+
248
+ /**
249
+ * Migration Helper Functions
250
+ *
251
+ * Utilities for creating migrations in a type-safe and convenient way.
252
+ */
253
+
254
+ /**
255
+ * Create a SQL-based migration
256
+ *
257
+ * @example
258
+ * ```typescript
259
+ * export default sqlMigration({
260
+ * version: '20240101000000',
261
+ * name: 'create_users',
262
+ * up: `
263
+ * CREATE TABLE users (
264
+ * id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
265
+ * email VARCHAR(255) UNIQUE NOT NULL,
266
+ * created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
267
+ * )
268
+ * `,
269
+ * down: `DROP TABLE users`
270
+ * });
271
+ * ```
272
+ */
273
+ declare function sqlMigration(migration: {
274
+ version: string;
275
+ name: string;
276
+ up: string;
277
+ down: string;
278
+ transactional?: boolean;
279
+ }): Migration;
280
+ /**
281
+ * Create a function-based migration for complex logic
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * export default createMigration({
286
+ * version: '20240102000000',
287
+ * name: 'seed_initial_data',
288
+ * up: async (db) => {
289
+ * await db.raw(`INSERT INTO users (email) VALUES ('admin@example.com')`);
290
+ * await db.raw(`INSERT INTO settings (key, value) VALUES ('version', '1.0.0')`);
291
+ * },
292
+ * down: async (db) => {
293
+ * await db.raw(`DELETE FROM settings WHERE key = 'version'`);
294
+ * await db.raw(`DELETE FROM users WHERE email = 'admin@example.com'`);
295
+ * }
296
+ * });
297
+ * ```
298
+ */
299
+ declare function createMigration(migration: {
300
+ version: string;
301
+ name: string;
302
+ up: (db: IMigrationDatabase) => Promise<void>;
303
+ down: (db: IMigrationDatabase) => Promise<void>;
304
+ transactional?: boolean;
305
+ }): Migration;
306
+ /**
307
+ * Type-safe migration definition with inference
308
+ * Useful for defining migrations in separate files
309
+ *
310
+ * @example
311
+ * ```typescript
312
+ * // migrations/20240101000000_create_users.ts
313
+ * export const migration = defineMigration({
314
+ * version: '20240101000000',
315
+ * name: 'create_users',
316
+ * up: 'CREATE TABLE users (...)',
317
+ * down: 'DROP TABLE users'
318
+ * });
319
+ *
320
+ * // Or with functions
321
+ * export const migration = defineMigration({
322
+ * version: '20240102000000',
323
+ * name: 'complex_migration',
324
+ * up: async (db) => { ... },
325
+ * down: async (db) => { ... }
326
+ * });
327
+ * ```
328
+ */
329
+ declare function defineMigration<T extends {
330
+ version: string;
331
+ name: string;
332
+ up: string | ((db: IMigrationDatabase) => Promise<void>);
333
+ down: string | ((db: IMigrationDatabase) => Promise<void>);
334
+ transactional?: boolean;
335
+ }>(migration: T): Migration;
336
+ /**
337
+ * Generate a version timestamp for new migrations
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const version = generateVersion(); // '20240315143052'
342
+ * ```
343
+ */
344
+ declare function generateVersion(): string;
345
+ /**
346
+ * Common SQL snippets for migrations
347
+ */
348
+ declare const SQL: {
349
+ /**
350
+ * Create updated_at trigger function (PostgreSQL)
351
+ */
352
+ createUpdatedAtFunction: string;
353
+ /**
354
+ * Create an updated_at trigger for a table
355
+ */
356
+ createUpdatedAtTrigger: (tableName: string) => string;
357
+ /**
358
+ * Drop an updated_at trigger
359
+ */
360
+ dropUpdatedAtTrigger: (tableName: string) => string;
361
+ /**
362
+ * Standard timestamp columns
363
+ */
364
+ timestampColumns: string;
365
+ /**
366
+ * UUID primary key with default
367
+ */
368
+ uuidPrimaryKey: string;
369
+ /**
370
+ * Enable UUID extension
371
+ */
372
+ enableUuidExtension: string;
373
+ /**
374
+ * Enable pgcrypto for gen_random_uuid()
375
+ */
376
+ enablePgCrypto: string;
377
+ };
378
+
379
+ export { type IMigrator as I, Migrator as M, SQL as S, type Migration as a, type MigrationRecord as b, createMigration as c, defineMigration as d, type MigrationResult as e, type MigrationStatus as f, generateVersion as g, type MigratorConfig as h, type IMigrationDatabase as i, sqlMigration as s };