@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.
- package/LICENSE +21 -21
- package/index.js +35 -35
- package/lib/debug.js +372 -0
- package/lib/orm/adapters/json.js +290 -0
- package/lib/orm/adapters/memory.js +764 -0
- package/lib/orm/adapters/mongo.js +764 -0
- package/lib/orm/adapters/mysql.js +933 -0
- package/lib/orm/adapters/postgres.js +1144 -0
- package/lib/orm/adapters/redis.js +1534 -0
- package/lib/orm/adapters/sql-base.js +212 -0
- package/lib/orm/adapters/sqlite.js +858 -0
- package/lib/orm/audit.js +649 -0
- package/lib/orm/cache.js +394 -0
- package/lib/orm/geo.js +387 -0
- package/lib/orm/index.js +784 -0
- package/lib/orm/migrate.js +432 -0
- package/lib/orm/model.js +1706 -0
- package/lib/orm/plugin.js +375 -0
- package/lib/orm/procedures.js +836 -0
- package/lib/orm/profiler.js +233 -0
- package/lib/orm/query.js +1772 -0
- package/lib/orm/replicas.js +241 -0
- package/lib/orm/schema.js +307 -0
- package/lib/orm/search.js +380 -0
- package/lib/orm/seed/data/commerce.js +136 -0
- package/lib/orm/seed/data/internet.js +111 -0
- package/lib/orm/seed/data/locations.js +204 -0
- package/lib/orm/seed/data/names.js +338 -0
- package/lib/orm/seed/data/person.js +128 -0
- package/lib/orm/seed/data/phone.js +211 -0
- package/lib/orm/seed/data/words.js +134 -0
- package/lib/orm/seed/factory.js +178 -0
- package/lib/orm/seed/fake.js +1186 -0
- package/lib/orm/seed/index.js +18 -0
- package/lib/orm/seed/rng.js +71 -0
- package/lib/orm/seed/seeder.js +125 -0
- package/lib/orm/seed/unique.js +68 -0
- package/lib/orm/snapshot.js +366 -0
- package/lib/orm/tenancy.js +605 -0
- package/lib/orm/views.js +350 -0
- package/package.json +11 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @module seed/index
|
|
5
|
+
* @description Public API for the seed subsystem.
|
|
6
|
+
*
|
|
7
|
+
* Re-exports:
|
|
8
|
+
* - `Fake` — static fake-data generator
|
|
9
|
+
* - `Factory` — model factory for defining / creating test fixtures
|
|
10
|
+
* - `Seeder` — base class for database seeders
|
|
11
|
+
* - `SeederRunner` — orchestrates running multiple seeders
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const { Fake } = require('./fake');
|
|
15
|
+
const { Factory } = require('./factory');
|
|
16
|
+
const { Seeder, SeederRunner } = require('./seeder');
|
|
17
|
+
|
|
18
|
+
module.exports = { Fake, Factory, Seeder, SeederRunner };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @module seed/rng
|
|
5
|
+
* @description Seeded PRNG (mulberry32) for reproducible fake data generation.
|
|
6
|
+
* When no seed is set, falls back to Math.random so default
|
|
7
|
+
* behaviour is indistinguishable from the original implementation.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const { seed, rand } = require('./rng');
|
|
11
|
+
* seed(42); // deterministic from here on
|
|
12
|
+
* rand(); // always the same sequence for seed 42
|
|
13
|
+
* seed(null); // back to crypto-quality Math.random
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* mulberry32 — minimal, high-quality 32-bit PRNG.
|
|
18
|
+
* @param {number} s - Unsigned 32-bit integer seed.
|
|
19
|
+
* @returns {() => number} Float in [0, 1).
|
|
20
|
+
*/
|
|
21
|
+
function _mulberry32(s) {
|
|
22
|
+
s = s >>> 0;
|
|
23
|
+
return function () {
|
|
24
|
+
s += 0x6D2B79F5;
|
|
25
|
+
let t = s;
|
|
26
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
27
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
28
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** FNV-1a string → unsigned 32-bit integer. */
|
|
33
|
+
function _hashString(str) {
|
|
34
|
+
let h = 0x811c9dc5;
|
|
35
|
+
for (let i = 0; i < str.length; i++) {
|
|
36
|
+
h ^= str.charCodeAt(i);
|
|
37
|
+
h = Math.imul(h, 0x01000193);
|
|
38
|
+
}
|
|
39
|
+
return h >>> 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let _rng = Math.random.bind(Math);
|
|
43
|
+
let _seed = null;
|
|
44
|
+
|
|
45
|
+
/** Return a random float in [0, 1). */
|
|
46
|
+
function rand() { return _rng(); }
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Set a deterministic seed. Pass `null` / `undefined` to reset to Math.random.
|
|
50
|
+
*
|
|
51
|
+
* @param {number|string|null} [value] - Value to set.
|
|
52
|
+
* @returns {number|null} The numeric seed that was applied (or null if reset).
|
|
53
|
+
*/
|
|
54
|
+
function seed(value) {
|
|
55
|
+
if (value === undefined || value === null) {
|
|
56
|
+
_rng = Math.random.bind(Math);
|
|
57
|
+
_seed = null;
|
|
58
|
+
} else {
|
|
59
|
+
const n = typeof value === 'number'
|
|
60
|
+
? (value >>> 0)
|
|
61
|
+
: _hashString(String(value));
|
|
62
|
+
_seed = n;
|
|
63
|
+
_rng = _mulberry32(n);
|
|
64
|
+
}
|
|
65
|
+
return _seed;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @returns {number|null} Active numeric seed, or null when using Math.random. */
|
|
69
|
+
function getSeed() { return _seed; }
|
|
70
|
+
|
|
71
|
+
module.exports = { rand, seed, getSeed };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @module seed/seeder
|
|
5
|
+
* @description Base Seeder class and SeederRunner for orchestrating database
|
|
6
|
+
* seeding operations.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* class UserSeeder extends Seeder {
|
|
10
|
+
* async run(db) {
|
|
11
|
+
* const factory = new Factory(User);
|
|
12
|
+
* factory.define({ name: () => Fake.fullName(), email: () => Fake.email() });
|
|
13
|
+
* await factory.count(50).create();
|
|
14
|
+
* }
|
|
15
|
+
* }
|
|
16
|
+
*
|
|
17
|
+
* const runner = new SeederRunner(db);
|
|
18
|
+
* await runner.run(UserSeeder, PostSeeder);
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const log = require('../../debug')('zero:seed');
|
|
22
|
+
|
|
23
|
+
// ================================================================
|
|
24
|
+
// Seeder base class
|
|
25
|
+
// ================================================================
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Extend this class to create a seeder. Override `run(db)` with your
|
|
29
|
+
* seeding logic.
|
|
30
|
+
*/
|
|
31
|
+
class Seeder
|
|
32
|
+
{
|
|
33
|
+
/**
|
|
34
|
+
* Run the seeder. Must be overridden in subclasses.
|
|
35
|
+
*
|
|
36
|
+
* @param {import('../index').Database} db - Database instance.
|
|
37
|
+
* @returns {Promise<void>}
|
|
38
|
+
*/
|
|
39
|
+
async run(db) // eslint-disable-line no-unused-vars
|
|
40
|
+
{
|
|
41
|
+
throw new Error(`Seeder ${this.constructor.name}: run() is not implemented`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ================================================================
|
|
46
|
+
// SeederRunner
|
|
47
|
+
// ================================================================
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Orchestrates running one or more seeders against a database connection.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* const runner = new SeederRunner(db);
|
|
54
|
+
* await runner.run(UserSeeder, PostSeeder);
|
|
55
|
+
* await runner.call(UserSeeder); // single seeder
|
|
56
|
+
* await runner.fresh(UserSeeder); // clear then seed
|
|
57
|
+
*/
|
|
58
|
+
class SeederRunner
|
|
59
|
+
{
|
|
60
|
+
/**
|
|
61
|
+
* @constructor
|
|
62
|
+
* @param {import('../index').Database} db - Database connection instance.
|
|
63
|
+
*/
|
|
64
|
+
constructor(db)
|
|
65
|
+
{
|
|
66
|
+
this._db = db;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Run one or more seeder classes (or instances) in order.
|
|
71
|
+
*
|
|
72
|
+
* @param {...(Function|Function[])} seeders - Seeder classes or instances.
|
|
73
|
+
* @returns {Promise<string[]>} Names of the seeders that ran.
|
|
74
|
+
*/
|
|
75
|
+
async run(...seeders)
|
|
76
|
+
{
|
|
77
|
+
const flat = seeders.flat();
|
|
78
|
+
const names = [];
|
|
79
|
+
|
|
80
|
+
for (const SeederClass of flat)
|
|
81
|
+
{
|
|
82
|
+
const instance = typeof SeederClass === 'function'
|
|
83
|
+
? new SeederClass()
|
|
84
|
+
: SeederClass;
|
|
85
|
+
|
|
86
|
+
const name = instance.constructor.name || 'AnonymousSeeder';
|
|
87
|
+
log('Seeding: %s', name);
|
|
88
|
+
|
|
89
|
+
await instance.run(this._db);
|
|
90
|
+
names.push(name);
|
|
91
|
+
|
|
92
|
+
log('Seeded: %s', name);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return names;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run a single seeder class or instance.
|
|
100
|
+
*
|
|
101
|
+
* @param {Function} SeederClass - Seeder class or instance to run.
|
|
102
|
+
* @returns {Promise<void>}
|
|
103
|
+
*/
|
|
104
|
+
async call(SeederClass)
|
|
105
|
+
{
|
|
106
|
+
await this.run(SeederClass);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Clear all adapter data then run the provided seeders.
|
|
111
|
+
* Works with adapters that expose a `clear()` method (memory, json, redis).
|
|
112
|
+
*
|
|
113
|
+
* @param {...Function} seeders - Seeder classes to run after clearing.
|
|
114
|
+
* @returns {Promise<string[]>} Names of the seeders that ran.
|
|
115
|
+
*/
|
|
116
|
+
async fresh(...seeders)
|
|
117
|
+
{
|
|
118
|
+
if (typeof this._db.adapter.clear === 'function')
|
|
119
|
+
await this._db.adapter.clear();
|
|
120
|
+
|
|
121
|
+
return this.run(...seeders);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = { Seeder, SeederRunner };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @module seed/unique
|
|
5
|
+
* @description Per-namespace deduplication tracker used by `Fake.unique()`.
|
|
6
|
+
* Keeps a `Set` of already-returned values per key and retries
|
|
7
|
+
* the generator until a fresh value is produced.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const DEFAULT_MAX_ATTEMPTS = 1000;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Tracks generated values per namespace so callers can guarantee uniqueness
|
|
14
|
+
* within a seeding session without maintaining external state.
|
|
15
|
+
*/
|
|
16
|
+
class UniqueTracker {
|
|
17
|
+
constructor() {
|
|
18
|
+
/** @type {Map<string, Set<any>>} */
|
|
19
|
+
this._store = new Map();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Call `fn()` repeatedly until it returns a value not yet seen under `key`.
|
|
24
|
+
*
|
|
25
|
+
* @param {string} key - Uniqueness namespace (e.g. `'email'`).
|
|
26
|
+
* @param {() => any} fn - Value generator.
|
|
27
|
+
* @param {number} [maxAttempts] - Give up after this many retries.
|
|
28
|
+
* @returns {any} The unique generated value.
|
|
29
|
+
* @throws {Error} When the generator pool is exhausted.
|
|
30
|
+
*/
|
|
31
|
+
generate(key, fn, maxAttempts = DEFAULT_MAX_ATTEMPTS) {
|
|
32
|
+
if (!this._store.has(key)) this._store.set(key, new Set());
|
|
33
|
+
const seen = this._store.get(key);
|
|
34
|
+
|
|
35
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
36
|
+
const val = fn();
|
|
37
|
+
if (!seen.has(val)) {
|
|
38
|
+
seen.add(val);
|
|
39
|
+
return val;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
throw new Error(
|
|
44
|
+
`Fake.unique: exhausted ${maxAttempts} attempts for key "${key}". ` +
|
|
45
|
+
`The data pool may be too small. Call Fake.resetUnique("${key}") to start fresh.`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Clear uniqueness tracking.
|
|
51
|
+
* @param {string} [key] - Clear only this namespace, or all if omitted.
|
|
52
|
+
*/
|
|
53
|
+
reset(key) {
|
|
54
|
+
if (key !== undefined) this._store.delete(key);
|
|
55
|
+
else this._store.clear();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* How many unique values have been generated for a namespace.
|
|
60
|
+
* @param {string} key - Cache or storage key.
|
|
61
|
+
* @returns {number} Count of unique values tracked for the key.
|
|
62
|
+
*/
|
|
63
|
+
seen(key) {
|
|
64
|
+
return this._store.has(key) ? this._store.get(key).size : 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = { UniqueTracker };
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module orm/snapshot
|
|
3
|
+
* @description Schema snapshot and diff engine for EF Core–style auto-generated
|
|
4
|
+
* migrations. Compares the current Model schemas against a stored
|
|
5
|
+
* snapshot and produces a structured change-set that the CLI can
|
|
6
|
+
* render into migration code.
|
|
7
|
+
*
|
|
8
|
+
* The snapshot file (_schema_snapshot.json) is a plain JSON representation of
|
|
9
|
+
* every tracked table's schema at the time the last migration was generated.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const { diffSnapshots, buildSnapshot } = require('./snapshot');
|
|
13
|
+
*
|
|
14
|
+
* const current = buildSnapshot(models); // from Model classes
|
|
15
|
+
* const previous = loadSnapshot(dir); // from JSON file
|
|
16
|
+
* const changes = diffSnapshots(previous, current);
|
|
17
|
+
*
|
|
18
|
+
* // changes = { tables: { created: [...], dropped: [...] },
|
|
19
|
+
* // columns: { added: [...], dropped: [...], altered: [...] } }
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
'use strict';
|
|
23
|
+
|
|
24
|
+
const fs = require('fs');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const SNAPSHOT_FILE = '_schema_snapshot.json';
|
|
28
|
+
|
|
29
|
+
// -- Building a snapshot ----------------------------------------
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build a normalised snapshot from an array of Model classes.
|
|
33
|
+
* Each Model must have `static table` and `static schema`.
|
|
34
|
+
*
|
|
35
|
+
* @param {Function[]} models - Array of Model subclasses.
|
|
36
|
+
* @returns {object} Snapshot keyed by table name.
|
|
37
|
+
*/
|
|
38
|
+
function buildSnapshot(models)
|
|
39
|
+
{
|
|
40
|
+
const snap = {};
|
|
41
|
+
|
|
42
|
+
for (const M of models)
|
|
43
|
+
{
|
|
44
|
+
const table = M.table;
|
|
45
|
+
if (!table) continue;
|
|
46
|
+
|
|
47
|
+
const schema = typeof M._fullSchema === 'function'
|
|
48
|
+
? M._fullSchema()
|
|
49
|
+
: { ...M.schema };
|
|
50
|
+
|
|
51
|
+
// Normalise each column to a serialisable form (strip functions)
|
|
52
|
+
const cols = {};
|
|
53
|
+
for (const [colName, def] of Object.entries(schema))
|
|
54
|
+
{
|
|
55
|
+
cols[colName] = _normaliseDef(def);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
snap[table] = {
|
|
59
|
+
schema: cols,
|
|
60
|
+
timestamps: !!M.timestamps,
|
|
61
|
+
softDelete: !!M.softDelete,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return snap;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Normalise a column definition to a JSON-serialisable object.
|
|
70
|
+
* Strips function defaults to `null`.
|
|
71
|
+
* @private
|
|
72
|
+
*/
|
|
73
|
+
function _normaliseDef(def)
|
|
74
|
+
{
|
|
75
|
+
const out = {};
|
|
76
|
+
for (const [k, v] of Object.entries(def))
|
|
77
|
+
{
|
|
78
|
+
if (typeof v === 'function') out[k] = null; // fn defaults not serialisable
|
|
79
|
+
else if (v instanceof RegExp) out[k] = v.source; // match patterns
|
|
80
|
+
else out[k] = v;
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// -- Loading / saving snapshots ---------------------------------
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Load a previously saved snapshot from disk.
|
|
89
|
+
* Returns an empty object if no file exists.
|
|
90
|
+
*
|
|
91
|
+
* @param {string} dir - Directory containing the snapshot file.
|
|
92
|
+
* @returns {object} Snapshot.
|
|
93
|
+
*/
|
|
94
|
+
function loadSnapshot(dir)
|
|
95
|
+
{
|
|
96
|
+
const p = path.join(dir, SNAPSHOT_FILE);
|
|
97
|
+
if (!fs.existsSync(p)) return {};
|
|
98
|
+
return JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Write a snapshot to disk.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} dir - Directory to write to.
|
|
105
|
+
* @param {object} snapshot - The snapshot object.
|
|
106
|
+
*/
|
|
107
|
+
function saveSnapshot(dir, snapshot)
|
|
108
|
+
{
|
|
109
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
110
|
+
fs.writeFileSync(
|
|
111
|
+
path.join(dir, SNAPSHOT_FILE),
|
|
112
|
+
JSON.stringify(snapshot, null, 4) + '\n',
|
|
113
|
+
'utf8'
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// -- Diffing two snapshots --------------------------------------
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Diff two snapshots and return a structured change-set.
|
|
121
|
+
*
|
|
122
|
+
* @param {object} prev - Previous snapshot (from file).
|
|
123
|
+
* @param {object} current - Current snapshot (from live models).
|
|
124
|
+
* @returns {object} `{ tables, columns }` change-set.
|
|
125
|
+
*/
|
|
126
|
+
function diffSnapshots(prev, current)
|
|
127
|
+
{
|
|
128
|
+
const prevTables = Object.keys(prev);
|
|
129
|
+
const currTables = Object.keys(current);
|
|
130
|
+
|
|
131
|
+
const createdTables = currTables.filter(t => !prev[t]);
|
|
132
|
+
const droppedTables = prevTables.filter(t => !current[t]);
|
|
133
|
+
const commonTables = currTables.filter(t => !!prev[t]);
|
|
134
|
+
|
|
135
|
+
const addedCols = [];
|
|
136
|
+
const droppedCols = [];
|
|
137
|
+
const alteredCols = [];
|
|
138
|
+
|
|
139
|
+
for (const table of commonTables)
|
|
140
|
+
{
|
|
141
|
+
const prevCols = Object.keys(prev[table].schema);
|
|
142
|
+
const currCols = Object.keys(current[table].schema);
|
|
143
|
+
|
|
144
|
+
// New columns
|
|
145
|
+
for (const col of currCols)
|
|
146
|
+
{
|
|
147
|
+
if (!prev[table].schema[col])
|
|
148
|
+
{
|
|
149
|
+
addedCols.push({ table, column: col, def: current[table].schema[col] });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Dropped columns
|
|
154
|
+
for (const col of prevCols)
|
|
155
|
+
{
|
|
156
|
+
if (!current[table].schema[col])
|
|
157
|
+
{
|
|
158
|
+
droppedCols.push({ table, column: col, def: prev[table].schema[col] });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Altered columns (type or constraints changed)
|
|
163
|
+
for (const col of currCols)
|
|
164
|
+
{
|
|
165
|
+
if (prev[table].schema[col] && current[table].schema[col])
|
|
166
|
+
{
|
|
167
|
+
if (!_defsEqual(prev[table].schema[col], current[table].schema[col]))
|
|
168
|
+
{
|
|
169
|
+
alteredCols.push({
|
|
170
|
+
table,
|
|
171
|
+
column: col,
|
|
172
|
+
from: prev[table].schema[col],
|
|
173
|
+
to: current[table].schema[col],
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
tables: { created: createdTables, dropped: droppedTables },
|
|
182
|
+
columns: { added: addedCols, dropped: droppedCols, altered: alteredCols },
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Deep-compare two column definitions (JSON-serialisable).
|
|
188
|
+
* @private
|
|
189
|
+
*/
|
|
190
|
+
function _defsEqual(a, b)
|
|
191
|
+
{
|
|
192
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Returns true when the change-set has no changes.
|
|
197
|
+
*
|
|
198
|
+
* @param {object} changes - Output of `diffSnapshots`.
|
|
199
|
+
* @returns {boolean}
|
|
200
|
+
*/
|
|
201
|
+
function hasNoChanges(changes)
|
|
202
|
+
{
|
|
203
|
+
return changes.tables.created.length === 0
|
|
204
|
+
&& changes.tables.dropped.length === 0
|
|
205
|
+
&& changes.columns.added.length === 0
|
|
206
|
+
&& changes.columns.dropped.length === 0
|
|
207
|
+
&& changes.columns.altered.length === 0;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// -- Code generation -------------------------------------------
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Generate the JavaScript source for a migration file from a change-set.
|
|
214
|
+
*
|
|
215
|
+
* @param {string} migrationName - Timestamped migration name.
|
|
216
|
+
* @param {object} changes - Output of `diffSnapshots`.
|
|
217
|
+
* @param {object} currentSnap - Current snapshot (for full table schemas on create).
|
|
218
|
+
* @returns {string} Migration file source code.
|
|
219
|
+
*/
|
|
220
|
+
function generateMigrationCode(migrationName, changes, currentSnap)
|
|
221
|
+
{
|
|
222
|
+
const upLines = [];
|
|
223
|
+
const downLines = [];
|
|
224
|
+
|
|
225
|
+
// -- Created tables --
|
|
226
|
+
for (const table of changes.tables.created)
|
|
227
|
+
{
|
|
228
|
+
const schema = currentSnap[table].schema;
|
|
229
|
+
upLines.push(` await db.adapter.createTable('${table}', ${_schemaLiteral(schema)});`);
|
|
230
|
+
downLines.push(` await db.adapter.dropTable('${table}');`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// -- Dropped tables (reverse of create) --
|
|
234
|
+
for (const table of changes.tables.dropped)
|
|
235
|
+
{
|
|
236
|
+
upLines.push(` await db.adapter.dropTable('${table}');`);
|
|
237
|
+
// down recreates — but we need the previous snapshot's schema for that
|
|
238
|
+
// This is handled via the `prev` reference embedded in the dropped table
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// -- Added columns --
|
|
242
|
+
for (const { table, column, def } of changes.columns.added)
|
|
243
|
+
{
|
|
244
|
+
upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
|
|
245
|
+
downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// -- Dropped columns --
|
|
249
|
+
for (const { table, column, def } of changes.columns.dropped)
|
|
250
|
+
{
|
|
251
|
+
upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
|
|
252
|
+
downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(def)});`);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// -- Altered columns (drop + re-add with new def) --
|
|
256
|
+
for (const { table, column, from, to } of changes.columns.altered)
|
|
257
|
+
{
|
|
258
|
+
upLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
|
|
259
|
+
upLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(to)});`);
|
|
260
|
+
downLines.push(` await db.adapter.dropColumn('${table}', '${column}');`);
|
|
261
|
+
downLines.push(` await db.adapter.addColumn('${table}', '${column}', ${_defLiteral(from)});`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Build the final source
|
|
265
|
+
const upBody = upLines.length > 0 ? upLines.join('\n') : ' // No changes';
|
|
266
|
+
const downBody = downLines.length > 0 ? downLines.join('\n') : ' // No changes';
|
|
267
|
+
|
|
268
|
+
return `'use strict';
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Auto-generated migration — ${migrationName}
|
|
272
|
+
* Generated by: npx zh make:migration
|
|
273
|
+
*/
|
|
274
|
+
module.exports = {
|
|
275
|
+
name: '${migrationName}',
|
|
276
|
+
|
|
277
|
+
async up(db) {
|
|
278
|
+
${upBody}
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
async down(db) {
|
|
282
|
+
${downBody}
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
`;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Serialise a full table schema into a code literal string.
|
|
290
|
+
* @private
|
|
291
|
+
*/
|
|
292
|
+
function _schemaLiteral(schema)
|
|
293
|
+
{
|
|
294
|
+
const entries = [];
|
|
295
|
+
for (const [col, def] of Object.entries(schema))
|
|
296
|
+
{
|
|
297
|
+
entries.push(` ${col}: ${_defLiteral(def)}`);
|
|
298
|
+
}
|
|
299
|
+
return `{\n${entries.join(',\n')},\n }`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Serialise one column definition into a code literal string.
|
|
304
|
+
* @private
|
|
305
|
+
*/
|
|
306
|
+
function _defLiteral(def)
|
|
307
|
+
{
|
|
308
|
+
const parts = [];
|
|
309
|
+
for (const [k, v] of Object.entries(def))
|
|
310
|
+
{
|
|
311
|
+
if (v === null || v === undefined) continue;
|
|
312
|
+
if (typeof v === 'string') parts.push(`${k}: '${v}'`);
|
|
313
|
+
else if (typeof v === 'boolean' || typeof v === 'number') parts.push(`${k}: ${v}`);
|
|
314
|
+
else if (Array.isArray(v)) parts.push(`${k}: ${JSON.stringify(v)}`);
|
|
315
|
+
else if (typeof v === 'object') parts.push(`${k}: ${JSON.stringify(v)}`);
|
|
316
|
+
}
|
|
317
|
+
return `{ ${parts.join(', ')} }`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// -- Model discovery -------------------------------------------
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Load all Model classes from a directory.
|
|
324
|
+
*
|
|
325
|
+
* @param {string} dir - Absolute path to the models directory.
|
|
326
|
+
* @param {Function} ModelBase - The base Model class to check `instanceof`.
|
|
327
|
+
* @returns {Function[]} Array of Model subclasses.
|
|
328
|
+
*/
|
|
329
|
+
function discoverModels(dir, ModelBase)
|
|
330
|
+
{
|
|
331
|
+
if (!fs.existsSync(dir)) return [];
|
|
332
|
+
|
|
333
|
+
const files = fs.readdirSync(dir).filter(f => f.endsWith('.js')).sort();
|
|
334
|
+
const models = [];
|
|
335
|
+
|
|
336
|
+
for (const file of files)
|
|
337
|
+
{
|
|
338
|
+
try
|
|
339
|
+
{
|
|
340
|
+
const exported = require(path.join(dir, file));
|
|
341
|
+
const M = typeof exported === 'function' ? exported
|
|
342
|
+
: (exported && exported.default && typeof exported.default === 'function')
|
|
343
|
+
? exported.default
|
|
344
|
+
: null;
|
|
345
|
+
|
|
346
|
+
if (M && M.table && M.schema && (M.prototype instanceof ModelBase || M === ModelBase))
|
|
347
|
+
{
|
|
348
|
+
models.push(M);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
catch (_) { /* skip files that fail to load */ }
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return models;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
module.exports = {
|
|
358
|
+
buildSnapshot,
|
|
359
|
+
loadSnapshot,
|
|
360
|
+
saveSnapshot,
|
|
361
|
+
diffSnapshots,
|
|
362
|
+
hasNoChanges,
|
|
363
|
+
generateMigrationCode,
|
|
364
|
+
discoverModels,
|
|
365
|
+
SNAPSHOT_FILE,
|
|
366
|
+
};
|