@zero-server/orm 0.9.1 → 0.9.2

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.
Files changed (41) hide show
  1. package/LICENSE +21 -21
  2. package/index.js +35 -35
  3. package/lib/debug.js +372 -0
  4. package/lib/orm/adapters/json.js +290 -0
  5. package/lib/orm/adapters/memory.js +764 -0
  6. package/lib/orm/adapters/mongo.js +764 -0
  7. package/lib/orm/adapters/mysql.js +933 -0
  8. package/lib/orm/adapters/postgres.js +1144 -0
  9. package/lib/orm/adapters/redis.js +1534 -0
  10. package/lib/orm/adapters/sql-base.js +212 -0
  11. package/lib/orm/adapters/sqlite.js +858 -0
  12. package/lib/orm/audit.js +649 -0
  13. package/lib/orm/cache.js +394 -0
  14. package/lib/orm/geo.js +387 -0
  15. package/lib/orm/index.js +784 -0
  16. package/lib/orm/migrate.js +432 -0
  17. package/lib/orm/model.js +1706 -0
  18. package/lib/orm/plugin.js +375 -0
  19. package/lib/orm/procedures.js +836 -0
  20. package/lib/orm/profiler.js +233 -0
  21. package/lib/orm/query.js +1772 -0
  22. package/lib/orm/replicas.js +241 -0
  23. package/lib/orm/schema.js +307 -0
  24. package/lib/orm/search.js +380 -0
  25. package/lib/orm/seed/data/commerce.js +136 -0
  26. package/lib/orm/seed/data/internet.js +111 -0
  27. package/lib/orm/seed/data/locations.js +204 -0
  28. package/lib/orm/seed/data/names.js +338 -0
  29. package/lib/orm/seed/data/person.js +128 -0
  30. package/lib/orm/seed/data/phone.js +211 -0
  31. package/lib/orm/seed/data/words.js +134 -0
  32. package/lib/orm/seed/factory.js +178 -0
  33. package/lib/orm/seed/fake.js +1186 -0
  34. package/lib/orm/seed/index.js +18 -0
  35. package/lib/orm/seed/rng.js +71 -0
  36. package/lib/orm/seed/seeder.js +125 -0
  37. package/lib/orm/seed/unique.js +68 -0
  38. package/lib/orm/snapshot.js +366 -0
  39. package/lib/orm/tenancy.js +605 -0
  40. package/lib/orm/views.js +350 -0
  41. package/package.json +11 -2
@@ -0,0 +1,432 @@
1
+ /**
2
+ * @module orm/migrate
3
+ * @description Versioned migration framework for the zero-server ORM.
4
+ * Supports up/down migrations, batch tracking, rollback,
5
+ * status reporting, and full reset/fresh operations.
6
+ *
7
+ * @example
8
+ * const { Database, Migrator } = require('@zero-server/sdk');
9
+ *
10
+ * const db = Database.connect('sqlite', { filename: './app.db' });
11
+ *
12
+ * const migrator = new Migrator(db);
13
+ *
14
+ * // Define migrations
15
+ * migrator.add({
16
+ * name: '001_create_users',
17
+ * async up(db) {
18
+ * await db.adapter.execute({
19
+ * action: 'raw',
20
+ * sql: `CREATE TABLE users (
21
+ * id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ * name TEXT NOT NULL,
23
+ * email TEXT UNIQUE
24
+ * )`
25
+ * });
26
+ * },
27
+ * async down(db) {
28
+ * await db.adapter.dropTable('users');
29
+ * }
30
+ * });
31
+ *
32
+ * // Run pending migrations
33
+ * const result = await migrator.migrate();
34
+ *
35
+ * // Rollback last batch
36
+ * await migrator.rollback();
37
+ *
38
+ * // Check status
39
+ * const status = await migrator.status();
40
+ */
41
+
42
+ const log = require('../debug')('zero:migrate');
43
+
44
+ /**
45
+ * Internal model for tracking migration state.
46
+ * Stored in a `_migrations` table within the same database.
47
+ */
48
+ const MIGRATION_TABLE = '_migrations';
49
+ const MIGRATION_SCHEMA = {
50
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
51
+ name: { type: 'string', required: true, unique: true },
52
+ batch: { type: 'integer', required: true },
53
+ executed: { type: 'datetime' },
54
+ };
55
+
56
+ class Migrator
57
+ {
58
+ /**
59
+ * @constructor
60
+ * @param {import('./index').Database} db - Database instance.
61
+ * @param {object} [options] - Configuration options.
62
+ * @param {string} [options.table='_migrations'] - Migration tracking table name.
63
+ */
64
+ constructor(db, options = {})
65
+ {
66
+ this._db = db;
67
+ this._adapter = db.adapter;
68
+ this._table = options.table || MIGRATION_TABLE;
69
+ this._migrations = [];
70
+ this._initialized = false;
71
+ }
72
+
73
+ /**
74
+ * Add a migration definition.
75
+ * @param {object} migration - Migration definition.
76
+ * @param {string} migration.name - Unique migration name (e.g., '001_create_users').
77
+ * @param {Function} migration.up - Forward migration: `async (db) => {}`.
78
+ * @param {Function} migration.down - Reverse migration: `async (db) => {}`.
79
+ * @returns {Migrator} this (for chaining)
80
+ */
81
+ add(migration)
82
+ {
83
+ if (!migration.name || typeof migration.name !== 'string')
84
+ throw new Error('Migration must have a name');
85
+ if (!/^[\w\-.]+$/.test(migration.name))
86
+ throw new Error(`Migration name "${migration.name}" contains invalid characters (only letters, digits, underscore, hyphen, dot allowed)`);
87
+ if (typeof migration.up !== 'function') throw new Error(`Migration "${migration.name}": up() must be a function`);
88
+ if (typeof migration.down !== 'function') throw new Error(`Migration "${migration.name}": down() must be a function`);
89
+
90
+ // Prevent duplicate names
91
+ if (this._migrations.some(m => m.name === migration.name))
92
+ {
93
+ throw new Error(`Migration "${migration.name}" is already registered`);
94
+ }
95
+
96
+ this._migrations.push(migration);
97
+ return this;
98
+ }
99
+
100
+ /**
101
+ * Add multiple migrations at once.
102
+ * @param {object[]} migrations - Array of migration definitions.
103
+ * @returns {Migrator} this (for chaining)
104
+ */
105
+ addAll(migrations)
106
+ {
107
+ for (const m of migrations) this.add(m);
108
+ return this;
109
+ }
110
+
111
+ /**
112
+ * Ensure the migration tracking table exists.
113
+ * @private
114
+ */
115
+ async _init()
116
+ {
117
+ if (this._initialized) return;
118
+
119
+ await this._adapter.createTable(this._table, MIGRATION_SCHEMA);
120
+ this._initialized = true;
121
+ }
122
+
123
+ /**
124
+ * Get all previously executed migrations from the tracking table.
125
+ * @private
126
+ * @returns {Promise<object[]>} Executed migration records.
127
+ */
128
+ async _getExecuted()
129
+ {
130
+ await this._init();
131
+ try
132
+ {
133
+ const rows = await this._adapter.execute({
134
+ action: 'select',
135
+ table: this._table,
136
+ where: [],
137
+ orderBy: [{ field: 'id', dir: 'ASC' }],
138
+ });
139
+ return Array.isArray(rows) ? rows : [];
140
+ }
141
+ catch (_)
142
+ {
143
+ return [];
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Record a migration as executed.
149
+ * @private
150
+ */
151
+ async _record(name, batch)
152
+ {
153
+ await this._adapter.insert(this._table, {
154
+ name,
155
+ batch,
156
+ executed: new Date().toISOString(),
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Remove a migration record.
162
+ * @private
163
+ */
164
+ async _unrecord(name)
165
+ {
166
+ await this._adapter.deleteWhere(this._table, { name });
167
+ }
168
+
169
+ /**
170
+ * Get the next batch number.
171
+ * @private
172
+ * @returns {Promise<number>} Next batch number.
173
+ */
174
+ async _nextBatch()
175
+ {
176
+ const executed = await this._getExecuted();
177
+ if (executed.length === 0) return 1;
178
+ return Math.max(...executed.map(m => m.batch)) + 1;
179
+ }
180
+
181
+ /**
182
+ * Run all pending migrations.
183
+ *
184
+ * @returns {Promise<{ migrated: string[], batch: number }>}
185
+ * List of migration names that were executed and the batch number.
186
+ *
187
+ * @example
188
+ * const { migrated, batch } = await migrator.migrate();
189
+ * console.log(`Ran ${migrated.length} migrations in batch ${batch}`);
190
+ */
191
+ async migrate()
192
+ {
193
+ await this._init();
194
+
195
+ const executed = await this._getExecuted();
196
+ const executedNames = new Set(executed.map(m => m.name));
197
+ const pending = this._migrations.filter(m => !executedNames.has(m.name));
198
+
199
+ if (pending.length === 0)
200
+ {
201
+ log('No pending migrations');
202
+ return { migrated: [], batch: 0 };
203
+ }
204
+
205
+ const batch = await this._nextBatch();
206
+ const migrated = [];
207
+
208
+ for (const migration of pending)
209
+ {
210
+ log(`Migrating: ${migration.name}`);
211
+ try
212
+ {
213
+ await migration.up(this._db);
214
+ await this._record(migration.name, batch);
215
+ migrated.push(migration.name);
216
+ log(`Migrated: ${migration.name}`);
217
+ }
218
+ catch (err)
219
+ {
220
+ const error = new Error(
221
+ `Migration "${migration.name}" failed: ${err.message}`
222
+ );
223
+ error.migration = migration.name;
224
+ error.batch = batch;
225
+ error.cause = err;
226
+ throw error;
227
+ }
228
+ }
229
+
230
+ return { migrated, batch };
231
+ }
232
+
233
+ /**
234
+ * Rollback the last batch of migrations.
235
+ *
236
+ * @returns {Promise<{ rolledBack: string[], batch: number }>}
237
+ *
238
+ * @example
239
+ * const { rolledBack } = await migrator.rollback();
240
+ * console.log(`Rolled back: ${rolledBack.join(', ')}`);
241
+ */
242
+ async rollback()
243
+ {
244
+ await this._init();
245
+
246
+ const executed = await this._getExecuted();
247
+ if (executed.length === 0)
248
+ {
249
+ return { rolledBack: [], batch: 0 };
250
+ }
251
+
252
+ const lastBatch = Math.max(...executed.map(m => m.batch));
253
+ const toRollback = executed
254
+ .filter(m => m.batch === lastBatch)
255
+ .reverse(); // Roll back in reverse order
256
+
257
+ const rolledBack = [];
258
+
259
+ for (const record of toRollback)
260
+ {
261
+ const migration = this._migrations.find(m => m.name === record.name);
262
+ if (!migration)
263
+ {
264
+ throw new Error(
265
+ `Cannot rollback "${record.name}": migration definition not found. ` +
266
+ `Ensure all migrations are registered before rolling back.`
267
+ );
268
+ }
269
+
270
+ log(`Rolling back: ${record.name}`);
271
+ try
272
+ {
273
+ await migration.down(this._db);
274
+ await this._unrecord(record.name);
275
+ rolledBack.push(record.name);
276
+ log(`Rolled back: ${record.name}`);
277
+ }
278
+ catch (err)
279
+ {
280
+ const error = new Error(
281
+ `Rollback of "${record.name}" failed: ${err.message}`
282
+ );
283
+ error.migration = record.name;
284
+ error.cause = err;
285
+ throw error;
286
+ }
287
+ }
288
+
289
+ return { rolledBack, batch: lastBatch };
290
+ }
291
+
292
+ /**
293
+ * Rollback all migrations (in reverse order, batch by batch).
294
+ *
295
+ * @returns {Promise<{ rolledBack: string[] }>}
296
+ */
297
+ async rollbackAll()
298
+ {
299
+ const allRolledBack = [];
300
+ let result;
301
+ do
302
+ {
303
+ result = await this.rollback();
304
+ allRolledBack.push(...result.rolledBack);
305
+ }
306
+ while (result.rolledBack.length > 0);
307
+
308
+ return { rolledBack: allRolledBack };
309
+ }
310
+
311
+ /**
312
+ * Reset the database: rollback all migrations, then re-run all.
313
+ *
314
+ * @returns {Promise<{ rolledBack: string[], migrated: string[], batch: number }>}
315
+ */
316
+ async reset()
317
+ {
318
+ const { rolledBack } = await this.rollbackAll();
319
+ const { migrated, batch } = await this.migrate();
320
+ return { rolledBack, migrated, batch };
321
+ }
322
+
323
+ /**
324
+ * Fresh start: drop ALL tables (not just migrated ones) then re-migrate.
325
+ * ⚠️ DESTRUCTIVE — use with caution.
326
+ *
327
+ * @returns {Promise<{ migrated: string[], batch: number }>}
328
+ */
329
+ async fresh()
330
+ {
331
+ // Drop all registered model tables via db.drop()
332
+ try { await this._db.drop(); } catch (_) { /* ignore if no models registered */ }
333
+
334
+ // Also drop the migration tracking table
335
+ try { await this._adapter.dropTable(this._table); } catch (_) { /* ignore */ }
336
+
337
+ this._initialized = false;
338
+
339
+ // Re-run all migrations
340
+ return this.migrate();
341
+ }
342
+
343
+ /**
344
+ * Get the current migration status.
345
+ *
346
+ * @returns {Promise<{ executed: object[], pending: string[], lastBatch: number }>}
347
+ *
348
+ * @example
349
+ * const { executed, pending, lastBatch } = await migrator.status();
350
+ * console.log(`Executed: ${executed.length}, Pending: ${pending.length}`);
351
+ */
352
+ async status()
353
+ {
354
+ await this._init();
355
+
356
+ const executed = await this._getExecuted();
357
+ const executedNames = new Set(executed.map(m => m.name));
358
+ const pending = this._migrations
359
+ .filter(m => !executedNames.has(m.name))
360
+ .map(m => m.name);
361
+
362
+ const lastBatch = executed.length > 0
363
+ ? Math.max(...executed.map(m => m.batch))
364
+ : 0;
365
+
366
+ return {
367
+ executed: executed.map(m => ({
368
+ name: m.name,
369
+ batch: m.batch,
370
+ executedAt: m.executed,
371
+ })),
372
+ pending,
373
+ lastBatch,
374
+ };
375
+ }
376
+
377
+ /**
378
+ * Check if there are any pending migrations.
379
+ * @returns {Promise<boolean>} True if there are pending migrations.
380
+ */
381
+ async hasPending()
382
+ {
383
+ const { pending } = await this.status();
384
+ return pending.length > 0;
385
+ }
386
+
387
+ /**
388
+ * Get the list of registered migration names.
389
+ * @returns {string[]} Registered migration names in order.
390
+ */
391
+ list()
392
+ {
393
+ return this._migrations.map(m => m.name);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Helper to create a migration definition object.
399
+ *
400
+ * @param {string} name - Name identifier.
401
+ * @param {Function} up - `async (db) => { ... }`
402
+ * @param {Function} down - `async (db) => { ... }`
403
+ * @returns {{ name: string, up: Function, down: Function }}
404
+ *
405
+ * @example
406
+ * const { defineMigration } = require('@zero-server/sdk');
407
+ *
408
+ * module.exports = defineMigration('001_create_users',
409
+ * async (db) => {
410
+ * // up
411
+ * await db.addColumn('users', 'avatar', { type: TYPES.STRING });
412
+ * },
413
+ * async (db) => {
414
+ * // down
415
+ * await db.dropColumn('users', 'avatar');
416
+ * }
417
+ * );
418
+ */
419
+ function defineMigration(name, up, down)
420
+ {
421
+ if (!name || typeof name !== 'string')
422
+ throw new Error('defineMigration: name is required');
423
+ if (!/^[\w\-.]+$/.test(name))
424
+ throw new Error(`defineMigration: name "${name}" contains invalid characters`);
425
+ if (typeof up !== 'function')
426
+ throw new Error(`defineMigration "${name}": up must be a function`);
427
+ if (typeof down !== 'function')
428
+ throw new Error(`defineMigration "${name}": down must be a function`);
429
+ return { name, up, down };
430
+ }
431
+
432
+ module.exports = { Migrator, defineMigration };