masterrecord 1.2.0 → 1.2.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/CHANGES.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.2.2 — deterministic migration snapshots (no transient `tableName` leak)
4
+
5
+ The generated `*_contextSnapShot.json` could differ run-to-run for an unchanged schema, producing noisy git diffs and occasional spurious "schema changed" detections.
6
+
7
+ **Root cause:** `buildUpObject()` attached a transient `tableName` to column objects in place (`columnInfo.new[column].tableName = item.name`). Because `cleanEntities()` shallow-copies, those column objects are shared with the schema serialized into the snapshot — so `tableName` leaked in, but only onto the columns that happened to change that run.
8
+
9
+ **Fix:**
10
+ - `buildUpObject()` now tags a **copy** (`{ ...col, tableName }`) instead of mutating the shared column object — the migration template/query-builder still gets the `tableName` it needs, but the schema definitions stay clean.
11
+ - `createSnapShot()` normalizes the schema before writing (strips any transient `tableName` from column defs), so the persisted snapshot is deterministic regardless of upstream mutation.
12
+
13
+ Result: two consecutive snapshot generations of an unchanged schema are now **byte-identical**. New test: `test/snapshot-determinism.test.js`.
14
+
15
+ > Note: the related *live-timestamp* non-determinism (a `created_at`-style snapshot value changing each run) is **not** a masterrecord bug — it comes from a model/seed using a JS-evaluated default (`Date.now()`/`new Date()`), which is re-evaluated per context build. Pin it with a SQL default (`default('CURRENT_TIMESTAMP')`) or set it in a `beforeSave` hook.
16
+
17
+ ## v1.2.1 — Postgres multi-schema support (configurable schema / search_path)
18
+
19
+ Closes the gap noted in 1.2.0: a table living in a schema outside the connection's `search_path` was read as "absent" during migrations. You can now target a schema explicitly:
20
+
21
+ ```javascript
22
+ await db.env({ type: 'postgres', /* … */, schema: 'tenant1' });
23
+ // or: searchPath: 'tenant1,public'
24
+ ```
25
+
26
+ - The schema is applied to **every pooled connection** via libpq's `search_path` startup option (`PostgresSyncConnect` sets `options: '-c search_path=…'`). Introspection (`current_schemas`), migrations/DDL, and runtime queries then all resolve to it — no per-identifier qualification, matching how Knex's `searchPath` works.
27
+ - On connect, `CREATE SCHEMA IF NOT EXISTS "<schema>"` runs so a fresh deploy self-creates the schema before any table lands in it.
28
+ - `schema: 'x'` expands to search_path `x,public`; use `searchPath` for an explicit ordered list (first entry = where new tables are created).
29
+ - Schema/searchPath identifiers are strictly validated (letters/digits/underscore, non-leading digit) — invalid names throw at connect rather than being interpolated into the connection string or `CREATE SCHEMA`.
30
+ - Backward compatible: with neither option set, behavior is unchanged.
31
+
32
+ All Postgres engine connections (initial connect + post-create retry) honor the option; the admin pool used to `CREATE DATABASE` intentionally doesn't need it.
33
+
34
+ New tests: `test/postgres-search-path.test.js` (resolution + injection-safe validation). Verified by unit test; end-to-end relies on the standard libpq `options` parameter (no live Postgres in CI here).
35
+
3
36
  ## v1.2.0 — reliable schema introspection + observable migrations (fixes silent column-skip)
4
37
 
5
38
  **Bug:** adding a column to an existing table could silently no-op on MySQL/Postgres — the column was never added, with no error. Root cause: `tableExists()` and `getTableInfo()` wrapped everything in `catch (_) { return false / [] }`. Any real introspection failure (a connection/permission/`INFORMATION_SCHEMA` error, or — on Postgres — a `search_path` mismatch) was disguised as *"table absent."* `schema.createTable()` then took its blind `CREATE TABLE IF NOT EXISTS` branch, which is a no-op on an existing table, so `syncTable()` (the code that adds the missing column) never ran. Compounded by migration DDL only being logged when `NODE_ENV !== 'production'`, the whole thing was invisible in prod. SQLite was unaffected in practice because its introspection is a local `PRAGMA` that essentially never errors.
@@ -409,6 +409,30 @@ class Migrations{
409
409
  return newEntity;
410
410
  }
411
411
 
412
+ // Produce a clean, snapshot-safe copy of the schema: shallow-copy each
413
+ // entity and each column definition, dropping the transient `tableName`
414
+ // key (attached at migration-build time). Functions on column defs
415
+ // (transform/validators/get/set) are not JSON-serializable and are
416
+ // already dropped by JSON.stringify, so omitting them here is harmless.
417
+ #normalizeSchemaForSnapshot(entities){
418
+ if (!Array.isArray(entities)) return entities;
419
+ return entities.map((entity) => {
420
+ if (!entity || typeof entity !== 'object') return entity;
421
+ const cleanEntity = {};
422
+ for (const key of Object.keys(entity)) {
423
+ const value = entity[key];
424
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
425
+ const { tableName, ...rest } = value; // drop transient tableName
426
+ void tableName;
427
+ cleanEntity[key] = rest;
428
+ } else {
429
+ cleanEntity[key] = value;
430
+ }
431
+ }
432
+ return cleanEntity;
433
+ });
434
+ }
435
+
412
436
  createSnapShot(snap){
413
437
  // Place migrations alongside the Context file by default:
414
438
  // <ContextDir>/db/migrations/<context>_contextSnapShot.json
@@ -433,11 +457,18 @@ class Migrations{
433
457
  ? snap.context.getOrderedSeedData()
434
458
  : snap.contextSeedData || {};
435
459
 
460
+ // Normalize the schema before serializing so the snapshot is
461
+ // DETERMINISTIC: strip the transient `tableName` field that the
462
+ // migration builder may have attached to column objects. It is not
463
+ // part of the schema definition (a column's table is implied by its
464
+ // parent entity's __name), and leaking it produced run-to-run diffs.
465
+ const normalizedSchema = this.#normalizeSchemaForSnapshot(snap.contextEntities);
466
+
436
467
  const content = {
437
468
  contextLocation: relContextLocation,
438
469
  migrationFolder: relMigrationFolder,
439
470
  snapShotLocation: relSnapshotLocation,
440
- schema : snap.contextEntities,
471
+ schema : normalizedSchema,
441
472
  seedData: orderedSeedData,
442
473
  seedConfig: snap.contextSeedConfig || {}
443
474
  };
@@ -468,14 +499,21 @@ class Migrations{
468
499
  tableObj[item.name] = columnInfo.new;
469
500
  });
470
501
 
502
+ // NOTE: `tableName` is a transient field the migration
503
+ // template/query-builder needs to know which table a
504
+ // column belongs to. It must be attached to a COPY — the
505
+ // source column objects are shared (cleanEntities shallow-
506
+ // copies them) with the schema that gets serialized into
507
+ // the snapshot. Mutating them in place leaked `tableName`
508
+ // into the snapshot non-deterministically (only on the
509
+ // columns that happened to change that run), producing
510
+ // noisy diffs and spurious "schema changed" detections.
471
511
  item.newColumns.forEach(function (column, _ind) {
472
- columnInfo.new[column].tableName = item.name;
473
- tableObj[column] = columnInfo.new[column];
512
+ tableObj[column] = { ...columnInfo.new[column], tableName: item.name };
474
513
  });
475
514
 
476
515
  item.deletedColumns.forEach(function (column, _ind) {
477
- columnInfo.old[column].tableName = item.name;
478
- tableObj[column] = columnInfo.old[column];
516
+ tableObj[column] = { ...columnInfo.old[column], tableName: item.name };
479
517
  });
480
518
 
481
519
  item.updatedColumns.forEach(function (column, _ind) {
@@ -483,8 +521,7 @@ class Migrations{
483
521
  });
484
522
 
485
523
  if(item.new === null){
486
- columnInfo.old.tableName = item.name;
487
- tableObj["new"] = columnInfo.old;
524
+ tableObj["new"] = { ...columnInfo.old, tableName: item.name };
488
525
  }
489
526
 
490
527
  tableObj.___table = item;
@@ -102,6 +102,32 @@ await db.saveChanges();
102
102
 
103
103
  ## Advanced Features
104
104
 
105
+ ### Schemas (multi-schema / search_path)
106
+
107
+ By default MasterRecord uses the connection's default `search_path` (typically `public`). To put your tables in a specific Postgres schema — for multi-tenant deployments, or when your tables don't live in the default schema — set `schema` (or `searchPath`) in the connection config:
108
+
109
+ ```javascript
110
+ await db.env({
111
+ type: 'postgres',
112
+ host: 'localhost',
113
+ database: 'your_database',
114
+ user: 'your_user',
115
+ password: 'your_password',
116
+ schema: 'tenant1', // tables created/queried in "tenant1"
117
+ // or, for an explicit list (first entry is where new tables are created):
118
+ // searchPath: 'tenant1,public'
119
+ });
120
+ ```
121
+
122
+ How it works:
123
+ - The schema is applied to **every pooled connection** via libpq's `search_path` startup option, so introspection, migrations (DDL), and runtime queries all resolve to it — no per-query schema qualification needed.
124
+ - On connect, MasterRecord runs `CREATE SCHEMA IF NOT EXISTS "<schema>"`, so a fresh deploy self-creates the schema before any table is created in it.
125
+ - `schema: 'x'` expands to a search_path of `x,public` (so shared objects in `public` remain reachable). Use `searchPath` to control the full list/order.
126
+
127
+ Identifiers are validated (letters, digits, underscore; not starting with a digit) — an invalid schema name throws at connect rather than being interpolated into SQL.
128
+
129
+ > Without this option, behavior is unchanged. (This closes the prior gap where a table in a non-search-path schema was misread as "absent" during migrations.)
130
+
105
131
  ### Transactions
106
132
 
107
133
  ```javascript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
@@ -15,6 +15,44 @@ class PostgresSyncConnect {
15
15
  this.config = null;
16
16
  }
17
17
 
18
+ /**
19
+ * Resolve an optional Postgres schema / search_path from the connection
20
+ * config into a safe `search_path` value (multi-schema support).
21
+ *
22
+ * - `config.searchPath`: explicit, comma-separated list (first entry is
23
+ * where new tables are created). e.g. `'tenant1,public'`.
24
+ * - `config.schema`: single schema; expands to `'<schema>,public'`.
25
+ * - neither: returns nulls → default Postgres behavior (unchanged).
26
+ *
27
+ * Every identifier is validated against a strict pattern because the
28
+ * result is interpolated into a connection `options` string and a
29
+ * `CREATE SCHEMA` statement (neither can be parameterized). An invalid
30
+ * name throws rather than risking injection.
31
+ *
32
+ * @returns {{ searchPath: string|null, primarySchema: string|null }}
33
+ */
34
+ static resolveSearchPath(config = {}) {
35
+ const validIdent = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
36
+ if (config.searchPath) {
37
+ const parts = String(config.searchPath).split(',').map(s => s.trim()).filter(Boolean);
38
+ if (parts.length === 0) return { searchPath: null, primarySchema: null };
39
+ for (const p of parts) {
40
+ if (!validIdent.test(p)) {
41
+ throw new Error(`PostgreSQL: invalid searchPath entry '${p}' (allowed: letters, digits, underscore; must not start with a digit)`);
42
+ }
43
+ }
44
+ return { searchPath: parts.join(','), primarySchema: parts[0] };
45
+ }
46
+ if (config.schema) {
47
+ const s = String(config.schema).trim();
48
+ if (!validIdent.test(s)) {
49
+ throw new Error(`PostgreSQL: invalid schema name '${config.schema}' (allowed: letters, digits, underscore; must not start with a digit)`);
50
+ }
51
+ return { searchPath: `${s},public`, primarySchema: s };
52
+ }
53
+ return { searchPath: null, primarySchema: null };
54
+ }
55
+
18
56
  /**
19
57
  * Initialize PostgreSQL connection
20
58
  * @param {Object} config - Connection configuration
@@ -38,6 +76,9 @@ class PostgresSyncConnect {
38
76
  throw new Error('PostgreSQL: password is required');
39
77
  }
40
78
 
79
+ // Multi-schema support: resolve an optional schema / search_path.
80
+ const { searchPath, primarySchema } = PostgresSyncConnect.resolveSearchPath(config);
81
+
41
82
  this.config = {
42
83
  host: config.host || 'localhost',
43
84
  port: config.port || 5432,
@@ -51,6 +92,16 @@ class PostgresSyncConnect {
51
92
  // Enable better error messages
52
93
  application_name: 'MasterRecord',
53
94
  };
95
+ this.schema = primarySchema;
96
+
97
+ // Apply the search_path to EVERY pooled connection via the libpq
98
+ // `options` startup parameter. This is the robust, standard approach
99
+ // (same as Knex's searchPath): introspection (current_schemas), DDL,
100
+ // and runtime queries then all resolve to the configured schema with
101
+ // no per-identifier qualification needed.
102
+ if (searchPath) {
103
+ this.config.options = `-c search_path=${searchPath}`;
104
+ }
54
105
 
55
106
  // Create connection pool
56
107
  this.pool = new Pool(this.config);
@@ -58,13 +109,25 @@ class PostgresSyncConnect {
58
109
  // Test connection
59
110
  try {
60
111
  const client = await this.pool.connect();
61
- console.log(`PostgreSQL connected to ${config.database} at ${config.host}:${config.port}`);
112
+ console.log(`PostgreSQL connected to ${config.database} at ${config.host}:${config.port}${primarySchema ? ` (schema: ${primarySchema})` : ''}`);
62
113
  client.release();
63
114
  } catch (err) {
64
115
  console.error('PostgreSQL connection failed:', err.message);
65
116
  throw err;
66
117
  }
67
118
 
119
+ // Ensure the target schema exists so a fresh deploy self-creates it
120
+ // before any CREATE TABLE lands in it. (search_path may reference a
121
+ // not-yet-existing schema harmlessly; this makes it real.)
122
+ if (primarySchema && primarySchema !== 'public') {
123
+ try {
124
+ await this.pool.query(`CREATE SCHEMA IF NOT EXISTS "${primarySchema}"`);
125
+ } catch (err) {
126
+ console.error(`PostgreSQL: failed to ensure schema "${primarySchema}" exists:`, err.message);
127
+ throw err;
128
+ }
129
+ }
130
+
68
131
  // Initialize engine
69
132
  this.engine = new postgresEngine();
70
133
  this.engine.setDB(this.pool, 'postgres');