masterrecord 1.1.0 → 1.1.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,199 +1,80 @@
1
1
  # MasterRecord Changelog
2
2
 
3
- ## v1.0.0 — ESM-only
4
-
5
- **BREAKING:** MasterRecord is now a pure ECMAScript Modules (ESM) package.
6
-
7
- - `package.json` declares `"type": "module"` and publishes an `exports` map.
8
- - Requires **Node.js 20 or newer**.
9
- - All sources converted from `require` / `module.exports` to `import` / `export default`.
10
- - `context.js` imports the SQLite driver (`better-sqlite3`) statically at the top of the module instead of `require(sqlName)` at runtime.
11
- - Environment config files (`env.*.json`) and migration snapshot files (`*_contextSnapShot.json`) are now loaded with `fs.readFileSync` + `JSON.parse` instead of `require()`, keeping `context.env()` synchronous.
12
- - User-authored migration files are loaded via `await import(pathToFileURL(file).href)` — `Migrations/cli.js` has always had this path; the CJS `Module.prototype.require` hook that aliased `require('masterrecord')` to the globally installed package has been removed. Host projects must install masterrecord as a local dependency.
13
- - `Migrations/migrationTemplate.js` always emits ESM migrations (`import masterrecord from 'masterrecord'; … export default <Name>;`). The CJS branch and `moduleType` parameter are gone.
14
- - `context.js` exports the default class plus named error classes (`ContextError`, `ConfigurationError`, `DatabaseConnectionError`, `EntityValidationError`) and the internal `_poolKey` helper.
15
- - `Cache/QueryCache.js` background cleanup timer is now `.unref()`'d so it no longer keeps the Node event loop alive after user code finishes.
16
- - `.eslintrc.js` / `.prettierrc.js` replaced with flat ESM configs (`eslint.config.js`, `prettier.config.js`).
17
- - Test suite rewritten on top of Node's built-in `node --test` runner (`npm test`).
18
- - Documentation (`readme.md`, `docs/MIGRATIONS_GUIDE.md`, `docs/POSTGRESQL_SETUP.md`, `docs/QUERY_CACHING_GUIDE.md`, `FOREIGN_KEY_STRING_FIX.md`) updated to ESM syntax throughout.
19
-
20
- ### Migration guide for consumers
21
-
22
- 1. Bump your Node.js runtime to 20+.
23
- 2. Add `"type": "module"` to your application's `package.json`.
24
- 3. Replace `const X = require('masterrecord/…')` with `import X from 'masterrecord/…'`.
25
- 4. Replace `module.exports = MyContext` with `export default MyContext`.
26
- 5. Add `.js` extensions to all relative import paths (ESM requires explicit extensions).
27
- 6. Regenerate any existing migration files (or rewrite the top/bottom: `import masterrecord from 'masterrecord';` … `export default <Name>;`).
28
-
29
- ---
30
-
31
- ## Previous: v0.x — FAANG-Level Improvements
32
-
33
- Updated `context.js` and `deleteManager.js` to meet Google/Meta/Amazon engineering standards with critical bug fixes, input validation, and performance improvements.
34
-
35
- ## Critical Fixes Applied
36
-
37
- ### 1. ✅ Fixed PostgreSQL Async Bug
38
- **Issue:** Race condition - code returned before PostgreSQL initialized
39
- **Fix:** Return the promise properly so callers can await
40
- ```javascript
41
- // Now returns promise for async initialization
42
- return (async () => {
43
- this.db = await this.__postgresInit(options, 'pg');
44
- return this;
45
- })();
46
- ```
47
- **Impact:** PostgreSQL users must now `await ctx.env()`
48
-
49
- ### 2. ✅ Secure ID Generation
50
- **Issue:** Random IDs had 1/100,000 collision risk
51
- **Fix:** Sequential IDs with zero collision risk
52
- ```javascript
53
- model.__ID = `entity_${context._nextEntityId++}`;
54
- ```
55
-
56
- ### 3. ✅ Error Logging
57
- **Issue:** Errors silently swallowed in config search
58
- **Fix:** Collect and log all search errors
59
- ```javascript
60
- searchErrors.push(`${candidateRoots[i]}: ${error.message}`);
61
- console.log('[Context] Config search errors:', searchErrors.join('; '));
62
- ```
63
-
64
- ### 4. ✅ Input Validation
65
- **Issue:** No validation on dbset() - crashes and SQL injection risk
66
- **Fix:** Validate model and table name
67
- ```javascript
68
- if(!model) throw new Error('dbset() requires a valid model');
69
- if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)){
70
- throw new Error(`Invalid table name: ${tableName}`);
71
- }
72
- ```
73
-
74
- ### 5. ✅ Code Style
75
- **Issue:** Mixed var/const/let
76
- **Fix:** Use const/let consistently (FAANG standard)
77
-
78
- ## Performance Improvements
79
- - Entity tracking: O(n) → O(1) [100x faster]
80
- - ID generation: Zero collision risk
81
- - Better error messages for debugging
82
-
83
- ## Breaking Changes
84
- **PostgreSQL users:** Must now await the `env()` method
85
- ```javascript
86
- // OLD:
87
- ctx.env('./config');
88
-
89
- // NEW:
90
- await ctx.env('./config');
91
- ```
92
-
93
- ## Files Updated
94
- - ✅ context.js v1.0.0 (critical bug fixes + performance)
95
- - ✅ deleteManager.js v1.0.0 (error handling + code quality)
96
-
97
- ## Additional Files
98
- - .eslintrc.js (FAANG linting rules)
99
- - .prettierrc.js (code formatting)
100
-
101
- ---
102
-
103
- ## DeleteManager.js Improvements
104
-
105
- ### Critical Fixes Applied
106
-
107
- #### 1. ✅ Proper Error Handling
108
- **Issue:** Threw string instead of Error object
109
- **Fix:** Now throws Error objects with context
110
- ```javascript
111
- // OLD:
112
- throw "No relationship record found - please set hasOne or hasMany to nullable."
113
-
114
- // NEW:
115
- throw new Error(
116
- `Cannot delete ${entity.__entity.__name}: ` +
117
- `required relationship '${property}' is null. ` +
118
- `Set nullable: true if this is intentional.`
119
- );
120
- ```
121
-
122
- #### 2. ✅ Input Validation
123
- **Issue:** No validation on currentModel parameter
124
- **Fix:** Validates inputs before processing
125
- ```javascript
126
- if (!currentModel) {
127
- throw new Error('DeleteManager.init() requires a valid model');
128
- }
129
- if (!entity.__entity) {
130
- throw new Error('Entity missing __entity metadata');
131
- }
132
- ```
133
-
134
- #### 3. ✅ Null Safety
135
- **Issue:** Didn't handle null entities in arrays
136
- **Fix:** Warns and skips null entities safely
137
- ```javascript
138
- if (!entity) {
139
- console.warn(`DeleteManager: Skipping null entity at index ${i}`);
140
- continue;
141
- }
142
- ```
143
-
144
- #### 4. ✅ Code Quality Refactoring
145
- **Issue:** Duplicate code for single entity vs array handling
146
- **Fix:** Extracted into focused methods
147
- ```javascript
148
- // Now split into clear, testable methods:
149
- _deleteSingleEntity(entity) // Handle one entity
150
- _deleteMultipleEntities(entities) // Handle array
151
- _isRelationshipType(type) // Type checking helper
152
- ```
153
-
154
- #### 5. ✅ Constants for Relationship Types
155
- **Issue:** Magic strings ("hasOne", "hasMany") throughout code
156
- **Fix:** Constants at module level
157
- ```javascript
158
- const RELATIONSHIP_TYPES = {
159
- HAS_ONE: 'hasOne',
160
- HAS_MANY: 'hasMany',
161
- HAS_MANY_THROUGH: 'hasManyThrough'
162
- };
163
- ```
164
-
165
- ### Code Quality Improvements
166
- - Comprehensive JSDoc documentation
167
- - Modern JavaScript (const/let, no var)
168
- - Removed unused `$that = this` pattern
169
- - Better error messages with context
170
- - Reduced cyclomatic complexity
171
-
172
- ### Example Usage
173
- ```javascript
174
- // Clear error messages guide developers
175
- const user = db.User.findById(1);
176
-
177
- try {
178
- db.User.remove(user);
179
- db.saveChanges();
180
- } catch (error) {
181
- console.error(error.message);
182
- // "Cannot delete User: required relationship 'Profile' is null.
183
- // Set nullable: true if this is intentional."
184
- }
185
- ```
186
-
187
- ---
188
-
189
- ## Context.js Improvements (Previously Applied)
190
-
191
- ## Next Steps
192
- 1. Update PostgreSQL initialization calls to use `await`
193
- 2. Run `npm install --save-dev eslint prettier`
194
- 3. Run `npm run lint` to check for any remaining issues
195
- 4. Test thoroughly before deploying
196
-
197
- ## Grade
198
- **Before:** C+ (Needs Improvement)
199
- **After:** A (Production Ready)
3
+ ## v1.1.2 — belongsTo FK type resolution + MySQL/SQLite type-map gaps
4
+
5
+ **Bug:** `belongsTo()` hardcoded the FK column type to `integer` at entity-definition time, before the parent entity was registered. If the parent's PK was `string` / `bigint` / `uuid`, the FK was still emitted as `INTEGER`. SQLite accepted the mismatch silently (dynamic typing); Postgres and MySQL rejected inserts of string IDs into integer columns.
6
+
7
+ **Fix:** after every `dbset()` call, walk every registered entity and re-resolve each `belongsTo` column's `type` from its parent's primary-key type. Order-independent (works whether parent or child is registered first), idempotent (running multiple times produces the same result), case-insensitive on the `foreignTable` lookup.
8
+
9
+ | Parent PK type | SQLite FK | MySQL FK | Postgres FK |
10
+ | -------------- | --------- | ------------ | ----------- |
11
+ | `string` | TEXT | VARCHAR(255) | VARCHAR(255) |
12
+ | `integer` | INTEGER | INTEGER | INTEGER |
13
+ | `bigint` | INTEGER | BIGINT | BIGINT |
14
+ | `uuid` | TEXT | VARCHAR(36) | UUID |
15
+
16
+ **Related cleanup in the migration type maps:**
17
+
18
+ - **MySQL** `typeManager` now handles `bigint`, `uuid`, `int`, `jsonb`, and falls back to `TEXT` for unknown types. Previously these emitted literal `undefined` into the DDL string (e.g. `` `run_id` undefined NOT NULL ``).
19
+ - **SQLite** `typeManager` now handles `bigint`, `uuid`, `int`, `float`, `decimal`, `binary`/`blob`, `json`/`jsonb`, `date`/`datetime`/`timestamp` explicitly (collapsing to the appropriate SQLite affinity). Same `TEXT` fallback as before.
20
+
21
+ 17 new tests cover the resolver across all four PK types, both `dbset()` orders, and every engine's emitted DDL.
22
+
23
+ ## v1.1.1 — Documentation
24
+
25
+ - Documented the v1.1.0 full-text search feature: new [`docs/FULL_TEXT_SEARCH.md`](docs/FULL_TEXT_SEARCH.md), README section, and `.search()` entry in [`docs/METHODS_REFERENCE.md`](docs/METHODS_REFERENCE.md).
26
+ - Documented `createFullTextIndex` / `dropFullTextIndex` in [`docs/MIGRATIONS_GUIDE.md`](docs/MIGRATIONS_GUIDE.md).
27
+ - Removed stale per-bug postmortem markdown files (kept their fixes; deleted the writeups).
28
+
29
+ ## v1.1.0 — Portable Full-Text Search
30
+
31
+ A single API that targets each engine's native FTS implementation.
32
+
33
+ - **Migrations** — `createFullTextIndex({ tableName, columns, indexName?, config? })` and `dropFullTextIndex({ tableName, indexName? })`:
34
+ - **SQLite** — FTS5 external-content virtual table + AFTER INSERT/UPDATE/DELETE triggers
35
+ - **PostgreSQL** — `tsvector` column + GIN index + maintenance trigger (`config` controls `to_tsvector` config, default `'english'`)
36
+ - **MySQL** — `ALTER TABLE … ADD FULLTEXT INDEX`
37
+ - **Runtime** — `.search({ in: [columns], query: 'terms' })` fluent method on any dbset. Composes with `.where()`, `.take()`, `.skip()`, `.orderBy()`. Each result row has a `__rank` field; default ordering is rank descending.
38
+ - 17 new tests cover DDL output per engine, generated SQL strings, and an end-to-end SQLite ranking test.
39
+
40
+ ## v1.0.8 — Idempotent dropColumn + Postgres getTableInfo
41
+
42
+ - `dropColumn` is now idempotent across all engines (uses `IF EXISTS` where supported; no-op when the column is already gone).
43
+ - PostgreSQL: implemented `getTableInfo()` against `information_schema.columns` so introspection-driven migrations work.
44
+
45
+ ## v1.0.7 — Postgres identifier quoting + cross-engine cleanup
46
+
47
+ - PostgreSQL: all generated DDL and DML now quotes identifiers (`"camelCase"`, `"updatedAt"`, etc.) so mixed-case entity and column names work. Previously these were lowercased silently by Postgres, breaking queries.
48
+ - Removed accidental case transformations from `buildWhere` / `buildAnd` in the SQLite, MySQL, and Postgres engines — field names are now used as declared.
49
+ - MySQL: `bulkDelete` honors the entity's actual primary key column instead of hard-coding `id`.
50
+
51
+ ## v1.0.x — Bug fixes
52
+
53
+ - `.new()` setter with `transform.toDatabase`: object-valued fields were silently dropped on save. Now applied via the field transformer.
54
+ - Nested-array property assignment no longer corrupts adjacent fields.
55
+ - SQLite engine: absolute paths in `connection` were being concatenated with the project root, producing `/abs//abs/path`. Now passed through unchanged.
56
+ - Query builder parity: `ORDER BY`, `LIMIT`, `OFFSET`, `AND`, and `COUNT` are emitted consistently across all three engines. Previously each engine had a different subset of dropped clauses depending on the call path.
57
+ - CLI `update-database`: now applies every pending migration via a tracking table, not just the latest file.
58
+
59
+ ## v1.0.0 — ESM only
60
+
61
+ **BREAKING:** Pure ESM. Requires **Node.js 20+** and `"type": "module"` in the host project's `package.json`. No CommonJS build.
62
+
63
+ - All sources moved from `require` / `module.exports` to `import` / `export default`.
64
+ - Static import of `better-sqlite3` in `context.js` (no more runtime `require(sqlName)`).
65
+ - Environment config files and migration snapshot files load via `fs.readFileSync` + `JSON.parse` instead of `require()` — `context.env()` stays synchronous.
66
+ - User-authored migration files load via `await import(pathToFileURL(file).href)`. The CJS `Module.prototype.require` aliasing hook is gone; host projects must install `masterrecord` as a local dependency.
67
+ - `Migrations/migrationTemplate.js` emits ESM migrations only.
68
+ - `context.js` exports the default class plus named error classes (`ContextError`, `ConfigurationError`, `DatabaseConnectionError`, `EntityValidationError`).
69
+ - `Cache/QueryCache.js` cleanup timer is `.unref()`'d so it no longer keeps the event loop alive.
70
+ - Lint / format configs migrated to flat ESM (`eslint.config.js`, `prettier.config.js`).
71
+ - Test suite rewritten on `node --test`.
72
+
73
+ ### Upgrading
74
+
75
+ 1. Node 20 or newer.
76
+ 2. `"type": "module"` in your `package.json`.
77
+ 3. `require('masterrecord/…')` → `import X from 'masterrecord/…'`.
78
+ 4. `module.exports = MyContext` → `export default MyContext`.
79
+ 5. Add `.js` extensions to all relative imports (ESM requires explicit extensions).
80
+ 6. Regenerate migration files (or update the top/bottom): `import masterrecord from 'masterrecord';` … `export default <Name>;`.
@@ -89,52 +89,46 @@ class migrationMySQLQuery {
89
89
  switch(type) {
90
90
  case "string":
91
91
  return "VARCHAR(255)"
92
- break;
93
92
  case "text":
94
93
  return "TEXT"
95
- break;
96
94
  case "mediumtext":
97
95
  return "MEDIUMTEXT"
98
- break;
99
96
  case "longtext":
100
97
  return "LONGTEXT"
101
- break;
102
98
  case "float":
103
- return "fLOAT(24)"
104
- break;
99
+ return "FLOAT(24)"
105
100
  case "decimal":
106
101
  return "DECIMAL"
107
- break;
108
102
  case "datetime":
109
103
  return "DATETIME"
110
- break;
111
104
  case "timestamp":
112
105
  return "TIMESTAMP"
113
- break;
114
106
  case "date":
115
107
  return "DATE"
116
- break;
117
108
  case "time":
118
109
  return "TIME"
119
- break;
120
110
  case "boolean":
121
111
  return "TINYINT"
122
- break;
123
112
  case "integer":
113
+ case "int":
124
114
  return "INTEGER"
125
- break;
115
+ case "bigint":
116
+ return "BIGINT"
117
+ case "uuid":
118
+ // MySQL has no native UUID type; store as fixed-length string.
119
+ return "VARCHAR(36)"
126
120
  case "binary":
127
- return "BLOB"
128
- break;
129
121
  case "blob":
130
122
  return "BLOB"
131
- break;
132
123
  case "json":
124
+ case "jsonb":
133
125
  return "JSON"
134
- break;
135
- }
136
- // :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean
137
- }
126
+ default:
127
+ // Fallback so we never emit `undefined` for an unknown type
128
+ // (matches SQLite's and Postgres's lenient behavior).
129
+ return "TEXT"
130
+ }
131
+ }
138
132
 
139
133
  // table is the altered field
140
134
  alterColumn( table){
@@ -70,26 +70,32 @@ class migrationSQLiteQuery {
70
70
  #typeManager(type){
71
71
  switch(type) {
72
72
  case "string":
73
- return "TEXT"
74
- break;
75
73
  case "text":
76
74
  case "mediumtext":
77
75
  case "longtext":
78
- // SQLite TEXT is unlimited — MEDIUMTEXT/LONGTEXT collapse to TEXT
79
- // for cross-engine portability. (Previously "text" had no case
80
- // here at all, which produced "<colname> undefined NOT NULL"
81
- // SQL — accepted by SQLite's lax type affinity but still wrong.)
76
+ case "uuid":
77
+ // SQLite TEXT is unlimited; MEDIUMTEXT/LONGTEXT/UUID collapse to
78
+ // TEXT for cross-engine portability.
82
79
  return "TEXT"
83
- break;
84
80
  case "time":
81
+ case "date":
82
+ case "datetime":
83
+ case "timestamp":
85
84
  return "TEXT"
86
- break;
87
85
  case "boolean":
88
- return "INTEGER"
89
- break;
90
86
  case "integer":
87
+ case "int":
88
+ case "bigint":
91
89
  return "INTEGER"
92
- break;
90
+ case "float":
91
+ case "decimal":
92
+ return "REAL"
93
+ case "binary":
94
+ case "blob":
95
+ return "BLOB"
96
+ case "json":
97
+ case "jsonb":
98
+ return "TEXT"
93
99
  default:
94
100
  // Fallback for unknown types so we never emit `undefined`.
95
101
  return "TEXT"
package/context.js CHANGED
@@ -1299,12 +1299,60 @@ class context {
1299
1299
  enumerable: true
1300
1300
  });
1301
1301
 
1302
+ // belongsTo() hardcodes type='integer' before the parent entity is known.
1303
+ // Now that another entity is registered, re-resolve every belongsTo FK
1304
+ // column's type from its parent's primary-key type. Idempotent.
1305
+ this.#resolveBelongsToTypes();
1306
+
1302
1307
  // Return chainable object with seed() method
1303
1308
  return {
1304
1309
  seed: (data) => this.#addSeedData(tableName, data)
1305
1310
  };
1306
1311
  }
1307
1312
 
1313
+ // Walk every registered entity. For each column with relationshipType ===
1314
+ // 'belongsTo', look up the parent entity by foreignTable name and copy the
1315
+ // parent's primary-key type onto the FK column. Without this, FKs to a
1316
+ // string/uuid/bigint PK end up declared INTEGER, which SQLite tolerates
1317
+ // (dynamic typing) but Postgres and MySQL reject.
1318
+ #resolveBelongsToTypes() {
1319
+ const entities = this.__entities;
1320
+ if (!entities || entities.length === 0) return;
1321
+
1322
+ // Case-insensitive lookup table — users may write
1323
+ // db.belongsTo('run') while the class is `Run`.
1324
+ const byName = {};
1325
+ for (const e of entities) {
1326
+ if (e && e.__name) {
1327
+ byName[e.__name.toLowerCase()] = e;
1328
+ }
1329
+ }
1330
+
1331
+ for (const entity of entities) {
1332
+ for (const key of Object.keys(entity)) {
1333
+ const col = entity[key];
1334
+ if (!col || typeof col !== 'object') continue;
1335
+ if (col.relationshipType !== 'belongsTo') continue;
1336
+ if (!col.foreignTable) continue;
1337
+
1338
+ const parent = byName[String(col.foreignTable).toLowerCase()];
1339
+ if (!parent) continue;
1340
+
1341
+ // Find the parent's primary-key column.
1342
+ for (const pKey of Object.keys(parent)) {
1343
+ const pCol = parent[pKey];
1344
+ if (!pCol || typeof pCol !== 'object') continue;
1345
+ if (pCol.primary === true && pCol.type) {
1346
+ if (col.type !== pCol.type) {
1347
+ col.type = pCol.type;
1348
+ }
1349
+ break;
1350
+ }
1351
+ }
1352
+ }
1353
+ }
1354
+ }
1355
+
1308
1356
  /**
1309
1357
  * Define a composite index on an entity (Option C - Context-level)
1310
1358
  * @param {Function|string} model - Entity class or table name