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.
@@ -0,0 +1,253 @@
1
+ /**
2
+ * belongsTo FK type resolution (1.1.2).
3
+ *
4
+ * Bug: belongsTo() hardcoded type='integer' on the FK column at entity-
5
+ * definition time, before the parent entity was known. If the parent's PK
6
+ * was string/bigint/uuid, the FK column was still declared INTEGER. SQLite
7
+ * accepted the mismatch (dynamic typing); Postgres and MySQL rejected it.
8
+ *
9
+ * Fix: after each dbset() call, walk every entity and re-resolve every
10
+ * belongsTo column's `type` from its parent's primary-key type. Order-
11
+ * independent, idempotent.
12
+ *
13
+ * Notes for future maintenance:
14
+ * - EntityModelBuilder only sees own-prototype methods. Test entity classes
15
+ * must declare their fields directly (no `extends`) or the build silently
16
+ * produces an empty entity with no PK and the resolver has nothing to copy.
17
+ * - bigint/uuid go through EntityModel.type('bigint') because EntityModel
18
+ * doesn't have dedicated bigint()/uuid() field-setter methods.
19
+ */
20
+
21
+ import { test } from 'node:test';
22
+ import assert from 'node:assert/strict';
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ process.env.master = 'fktypes';
28
+
29
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
+ const fixturesDir = path.join(__dirname, 'fixtures', 'belongs-to-fk-type');
31
+ const envDir = path.join(fixturesDir, 'config', 'environments');
32
+ const dbDir = path.join(fixturesDir, 'db');
33
+ fs.mkdirSync(envDir, { recursive: true });
34
+ fs.mkdirSync(dbDir, { recursive: true });
35
+
36
+ fs.writeFileSync(
37
+ path.join(envDir, 'env.fktypes.json'),
38
+ JSON.stringify({
39
+ StringPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
40
+ IntPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
41
+ OutOfOrderCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
42
+ BigintPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
43
+ UuidPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
44
+ })
45
+ );
46
+
47
+ const { default: context } = await import('../context.js');
48
+ const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
49
+ const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
50
+ const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
51
+
52
+ // =====================================================================
53
+ // Resolver behavior (per parent PK type)
54
+ // =====================================================================
55
+
56
+ test('belongsTo FK type resolves from string PK on parent', () => {
57
+ class Run {
58
+ id(db) { db.string().primary(); }
59
+ name(db) { db.string(); }
60
+ }
61
+ class Step {
62
+ id(db) { db.integer().primary().auto(); }
63
+ name(db) { db.string(); }
64
+ Run(db) { db.belongsTo('Run').notNullable(); }
65
+ }
66
+ class StringPkCtx extends context {
67
+ constructor() {
68
+ super();
69
+ this.env(envDir);
70
+ this.dbset(Run);
71
+ this.dbset(Step);
72
+ }
73
+ }
74
+ const ctx = new StringPkCtx();
75
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
76
+ const fk = stepEntity.Run;
77
+ assert.equal(fk.relationshipType, 'belongsTo');
78
+ assert.equal(fk.foreignKey, 'run_id');
79
+ assert.equal(fk.type, 'string', 'FK type should match parent string PK');
80
+ });
81
+
82
+ test('belongsTo FK type stays integer when parent PK is integer', () => {
83
+ class Run {
84
+ id(db) { db.integer().primary().auto(); }
85
+ name(db) { db.string(); }
86
+ }
87
+ class Step {
88
+ id(db) { db.integer().primary().auto(); }
89
+ Run(db) { db.belongsTo('Run').notNullable(); }
90
+ }
91
+ class IntPkCtx extends context {
92
+ constructor() {
93
+ super();
94
+ this.env(envDir);
95
+ this.dbset(Run);
96
+ this.dbset(Step);
97
+ }
98
+ }
99
+ const ctx = new IntPkCtx();
100
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
101
+ assert.equal(stepEntity.Run.type, 'integer');
102
+ });
103
+
104
+ test('belongsTo FK type resolves regardless of dbset() order', () => {
105
+ class Run {
106
+ id(db) { db.string().primary(); }
107
+ name(db) { db.string(); }
108
+ }
109
+ class Step {
110
+ id(db) { db.integer().primary().auto(); }
111
+ Run(db) { db.belongsTo('Run').notNullable(); }
112
+ }
113
+ class OutOfOrderCtx extends context {
114
+ constructor() {
115
+ super();
116
+ this.env(envDir);
117
+ this.dbset(Step); // child first
118
+ this.dbset(Run); // parent second
119
+ }
120
+ }
121
+ const ctx = new OutOfOrderCtx();
122
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
123
+ assert.equal(stepEntity.Run.type, 'string', 'resolution must be order-independent');
124
+ });
125
+
126
+ test('belongsTo FK type resolves for bigint parent PK', () => {
127
+ class Run {
128
+ id(db) { db.type('bigint').primary().auto(); }
129
+ name(db) { db.string(); }
130
+ }
131
+ class Step {
132
+ id(db) { db.integer().primary().auto(); }
133
+ Run(db) { db.belongsTo('Run').notNullable(); }
134
+ }
135
+ class BigintPkCtx extends context {
136
+ constructor() {
137
+ super();
138
+ this.env(envDir);
139
+ this.dbset(Run);
140
+ this.dbset(Step);
141
+ }
142
+ }
143
+ const ctx = new BigintPkCtx();
144
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
145
+ assert.equal(stepEntity.Run.type, 'bigint');
146
+ });
147
+
148
+ test('belongsTo FK type resolves for uuid parent PK', () => {
149
+ class Run {
150
+ id(db) { db.type('uuid').primary(); }
151
+ name(db) { db.string(); }
152
+ }
153
+ class Step {
154
+ id(db) { db.integer().primary().auto(); }
155
+ Run(db) { db.belongsTo('Run').notNullable(); }
156
+ }
157
+ class UuidPkCtx extends context {
158
+ constructor() {
159
+ super();
160
+ this.env(envDir);
161
+ this.dbset(Run);
162
+ this.dbset(Step);
163
+ }
164
+ }
165
+ const ctx = new UuidPkCtx();
166
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
167
+ assert.equal(stepEntity.Run.type, 'uuid');
168
+ });
169
+
170
+ // =====================================================================
171
+ // Migration DDL output — verify each engine emits a matching SQL type.
172
+ // Bypasses context; feeds a minimal table-like object straight to the
173
+ // migration query builders. Shape mirrors what the resolver produces.
174
+ // =====================================================================
175
+
176
+ function stepTableWith(fkType) {
177
+ return {
178
+ __name: 'Step',
179
+ id: { name: 'id', type: 'integer', primary: true, auto: true },
180
+ name: { name: 'name', type: 'string' },
181
+ Run: {
182
+ name: 'Run',
183
+ type: fkType,
184
+ relationshipType: 'belongsTo',
185
+ foreignTable: 'Run',
186
+ foreignKey: 'run_id',
187
+ nullable: false,
188
+ },
189
+ };
190
+ }
191
+
192
+ test('Postgres createTable emits VARCHAR(255) for FK to string PK', () => {
193
+ const sql = new PostgresQuery().createTable(stepTableWith('string'));
194
+ assert.match(sql, /"run_id"\s+VARCHAR\(255\)/, sql);
195
+ assert.doesNotMatch(sql, /"run_id"\s+INTEGER/);
196
+ });
197
+
198
+ test('Postgres createTable emits INTEGER for FK to integer PK', () => {
199
+ const sql = new PostgresQuery().createTable(stepTableWith('integer'));
200
+ assert.match(sql, /"run_id"\s+INTEGER/, sql);
201
+ });
202
+
203
+ test('Postgres createTable emits BIGINT for FK to bigint PK', () => {
204
+ const sql = new PostgresQuery().createTable(stepTableWith('bigint'));
205
+ assert.match(sql, /"run_id"\s+BIGINT/, sql);
206
+ });
207
+
208
+ test('Postgres createTable emits UUID for FK to uuid PK', () => {
209
+ const sql = new PostgresQuery().createTable(stepTableWith('uuid'));
210
+ assert.match(sql, /"run_id"\s+UUID/, sql);
211
+ });
212
+
213
+ test('MySQL createTable emits VARCHAR(255) for FK to string PK', () => {
214
+ const sql = new MySQLQuery().createTable(stepTableWith('string'));
215
+ assert.match(sql, /`run_id`\s+VARCHAR\(255\)/, sql);
216
+ });
217
+
218
+ test('MySQL createTable emits BIGINT for FK to bigint PK', () => {
219
+ const sql = new MySQLQuery().createTable(stepTableWith('bigint'));
220
+ assert.match(sql, /`run_id`\s+BIGINT/, sql);
221
+ });
222
+
223
+ test('MySQL createTable emits VARCHAR(36) for FK to uuid PK', () => {
224
+ const sql = new MySQLQuery().createTable(stepTableWith('uuid'));
225
+ assert.match(sql, /`run_id`\s+VARCHAR\(36\)/, sql);
226
+ });
227
+
228
+ test('MySQL createTable never emits "undefined" for any FK type', () => {
229
+ for (const t of ['string', 'integer', 'bigint', 'uuid', 'text']) {
230
+ const sql = new MySQLQuery().createTable(stepTableWith(t));
231
+ assert.doesNotMatch(sql, /undefined/, `MySQL ${t}: ${sql}`);
232
+ }
233
+ });
234
+
235
+ test('SQLite createTable emits TEXT for FK to string PK', () => {
236
+ const sql = new SQLiteQuery().createTable(stepTableWith('string'));
237
+ assert.match(sql, /\[?run_id\]?\s+TEXT/i, sql);
238
+ });
239
+
240
+ test('SQLite createTable emits INTEGER for FK to integer PK', () => {
241
+ const sql = new SQLiteQuery().createTable(stepTableWith('integer'));
242
+ assert.match(sql, /\[?run_id\]?\s+INTEGER/i, sql);
243
+ });
244
+
245
+ test('SQLite createTable emits INTEGER for FK to bigint PK', () => {
246
+ const sql = new SQLiteQuery().createTable(stepTableWith('bigint'));
247
+ assert.match(sql, /\[?run_id\]?\s+INTEGER/i, sql);
248
+ });
249
+
250
+ test('SQLite createTable emits TEXT for FK to uuid PK', () => {
251
+ const sql = new SQLiteQuery().createTable(stepTableWith('uuid'));
252
+ assert.match(sql, /\[?run_id\]?\s+TEXT/i, sql);
253
+ });
@@ -1,138 +0,0 @@
1
- # Future Improvements for MasterRecord
2
-
3
- ## Metadata Property Handling
4
-
5
- ### Context
6
- The `.index()` bug fix (commit 6e774a7) introduced a blacklist approach to skip metadata properties during schema processing. While this solves the immediate problem, there are architectural improvements to consider for future versions.
7
-
8
- ### Current Solution (v0.3.33)
9
- ```javascript
10
- for (var key in table) {
11
- // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
12
- if(key === 'indexes' || key.startsWith('__')){
13
- continue;
14
- }
15
- // ... process columns
16
- }
17
- ```
18
-
19
- **Status:** ✅ Shipped - Works well, well-tested, solves the problem
20
-
21
- ### Future Considerations
22
-
23
- #### 1. Document the Metadata Convention
24
- **Priority:** Medium
25
- **Effort:** Low
26
-
27
- Add clear documentation explaining that properties starting with `__` are reserved for internal metadata and will be skipped during schema processing. This should be documented in:
28
- - README.md (Entity Model section)
29
- - Code comments in `entityModel.js`
30
- - Migration guide if breaking changes are made
31
-
32
- **Example documentation:**
33
- ```markdown
34
- ## Reserved Property Names
35
- - Properties starting with `__` (double underscore) are reserved for internal metadata
36
- - `indexes` property is reserved for index definitions
37
- - These properties are automatically skipped during table creation
38
- ```
39
-
40
- #### 2. Whitelist Approach (Long-term)
41
- **Priority:** Low
42
- **Effort:** Medium
43
- **Breaking Change:** Potentially
44
-
45
- Instead of blacklisting specific properties, consider only processing properties that are actually column definitions.
46
-
47
- **Pros:**
48
- - More robust if new metadata properties are added
49
- - Explicit about what gets processed
50
- - Self-documenting code
51
-
52
- **Cons:**
53
- - Requires careful design to not break existing functionality
54
- - More complex validation logic
55
- - Could impact performance
56
-
57
- **Example approach:**
58
- ```javascript
59
- for (var key in table) {
60
- if(typeof table[key] !== "object") continue;
61
-
62
- var col = table[key];
63
-
64
- // Only process objects that have column-like properties
65
- if(!col.name || !col.type) continue;
66
-
67
- // Skip relationship types
68
- if(col.type === 'hasOne' || col.type === 'hasMany' || col.type === 'hasManyThrough'){
69
- continue;
70
- }
71
-
72
- queryVar += `${this.#columnMapping(col)}, `;
73
- }
74
- ```
75
-
76
- #### 3. Use JavaScript Symbols for Metadata (v1.0+)
77
- **Priority:** Low
78
- **Effort:** High
79
- **Breaking Change:** Yes
80
-
81
- For future major versions, consider using JavaScript Symbols for all internal metadata. Symbols don't appear in `for...in` loops or `Object.keys()`, eliminating this entire class of bugs.
82
-
83
- **Benefits:**
84
- - Metadata becomes truly invisible to iteration
85
- - No special-case filtering needed
86
- - Cleaner separation of concerns
87
- - More idiomatic JavaScript
88
-
89
- **Migration path:**
90
- ```javascript
91
- // Current (v0.x)
92
- table.__name = 'Users';
93
- table.indexes = ['idx_name'];
94
-
95
- // Future (v1.0+)
96
- const META_NAME = Symbol('name');
97
- const META_INDEXES = Symbol('indexes');
98
-
99
- table[META_NAME] = 'Users';
100
- table[META_INDEXES] = ['idx_name'];
101
- ```
102
-
103
- **Challenges:**
104
- - Requires refactoring all metadata access
105
- - Breaks existing code that accesses `__name`, `__compositeIndexes`, etc.
106
- - Would need comprehensive migration guide
107
- - Testing burden is significant
108
-
109
- **When to consider:**
110
- - During a major version bump (v1.0)
111
- - When other breaking changes are planned
112
- - After gathering user feedback on current metadata usage patterns
113
-
114
- ---
115
-
116
- ## Implementation Notes
117
-
118
- ### Current Fix is Good to Ship ✅
119
- The blacklist approach (`indexes` and `__*` properties) is:
120
- - Practical and solves the immediate problem
121
- - Well-tested (5 comprehensive tests)
122
- - Easy to understand and maintain
123
- - Not over-engineered
124
-
125
- ### Recommendation
126
- 1. **Ship the current fix** (already committed)
127
- 2. **Add documentation** about the `__` convention in next minor release
128
- 3. **Track whitelist approach** as a potential v0.4+ enhancement
129
- 4. **Consider Symbols** only for v1.0 major version
130
-
131
- ---
132
-
133
- ## Related Issues
134
- - Index bug fix: commit 6e774a7
135
- - Test suite: `test/index-bug-fix-test.js`
136
-
137
- ## Feedback Credit
138
- These suggestions came from code review feedback on the index bug fix implementation.
@@ -1,288 +0,0 @@
1
- # Foreign Key String Value Bug - FIXED in v0.3.39
2
-
3
- ## Problem Summary
4
-
5
- When assigning string values to foreign key fields defined via `belongsTo()`, MasterRecord silently excluded them from INSERT statements, causing NOT NULL constraint failures.
6
-
7
- ## Example of the Bug
8
-
9
- ```javascript
10
- // Entity with belongsTo relationship
11
- class UserOrganizationRole extends EntityModel {
12
- User(db) {
13
- db.belongsTo('User', 'user_id'); // Creates foreignKey 'user_id'
14
- }
15
-
16
- Organization(db) {
17
- db.belongsTo('Organization', 'organization_id');
18
- }
19
- }
20
-
21
- // User code
22
- const orgRole = new UserOrganizationRole();
23
- orgRole.user_id = currentUser.id; // currentUser.id is STRING "2"
24
- orgRole.organization_id = newOrg.id; // newOrg.id is NUMBER 8
25
- orgRole.role = 'org_admin';
26
-
27
- await userContext.saveChanges();
28
- // ❌ BEFORE: SqliteError: NOT NULL constraint failed: UserOrganizationRole.user_id
29
- // ✅ AFTER: Works perfectly!
30
- ```
31
-
32
- ## Root Cause
33
-
34
- 1. `belongsTo('User', 'user_id')` creates an entity property named `User` with metadata `foreignKey: 'user_id'`
35
- 2. The INSERT builder looked for `fields['User']` (navigation property name)
36
- 3. But users set `fields['user_id']` (foreign key field name)
37
- 4. Field not found → silently skipped → INSERT statement missing the field
38
-
39
- **Generated SQL (BEFORE):**
40
- ```sql
41
- INSERT INTO [UserOrganizationRole] ([organization_id], [role])
42
- VALUES (8, 'org_admin')
43
- -- ❌ user_id is missing!
44
- ```
45
-
46
- **Generated SQL (AFTER):**
47
- ```sql
48
- INSERT INTO [UserOrganizationRole] ([user_id], [organization_id], [role])
49
- VALUES (2, 8, 'org_admin')
50
- -- ✅ user_id is included and auto-converted from "2" to 2
51
- ```
52
-
53
- ## The Fix
54
-
55
- Modified `_buildSQLInsertObjectParameterized()` in all three database engines to check BOTH the navigation property name AND the foreign key field name:
56
-
57
- ```javascript
58
- // SQLLiteEngine.js, mySQLEngine.js, postgresEngine.js
59
- for (const column in modelEntity) {
60
- if (column.indexOf("__") === -1) {
61
- let fieldColumn = fields[column]; // Check navigation property (e.g., 'User')
62
-
63
- // 🔥 NEW: Also check the foreignKey field name (e.g., 'user_id')
64
- if ((fieldColumn === undefined || fieldColumn === null) &&
65
- modelEntity[column].relationshipType === "belongsTo" &&
66
- modelEntity[column].foreignKey) {
67
- fieldColumn = fields[modelEntity[column].foreignKey];
68
- }
69
-
70
- if ((fieldColumn !== undefined && fieldColumn !== null) && typeof(fieldColumn) !== "object") {
71
- // Existing validation and type coercion logic...
72
- // This already handles string-to-integer conversion!
73
- }
74
- }
75
- }
76
- ```
77
-
78
- ## Auto-Conversion
79
-
80
- The existing `_validateAndCoerceFieldType()` method already handled string-to-integer conversion:
81
-
82
- ```javascript
83
- case "integer":
84
- if (actualType === 'string') {
85
- const parsed = parseInt(value, 10);
86
- if (isNaN(parsed)) {
87
- throw new Error(`Type mismatch for ${entityName}.${fieldName}: Expected integer, got string "${value}" which cannot be converted`);
88
- }
89
- console.warn(`⚠️ Field ${entityName}.${fieldName}: Auto-converting string "${value}" to integer ${parsed}`);
90
- return parsed;
91
- }
92
- ```
93
-
94
- So once the field is found, the conversion happens automatically!
95
-
96
- ## Why String IDs Happen in Real Apps
97
-
98
- ### 1. authService Returns String IDs
99
- ```javascript
100
- // authService.js line 167:
101
- res.id = String(obj.user.id); // Explicit string conversion
102
-
103
- // Returns:
104
- {
105
- id: "2", // ← STRING
106
- email: "customer1@bookbag.ai",
107
- system_role: "system_user"
108
- }
109
- ```
110
-
111
- ### 2. HTTP Requests (JSON)
112
- ```javascript
113
- // Client sends:
114
- { "user_id": "2", "organization_id": "8" }
115
-
116
- // Express parses as strings
117
- req.body.user_id // "2" (string)
118
- ```
119
-
120
- ### 3. JWT Tokens
121
- ```javascript
122
- const token = jwt.decode(req.headers.authorization);
123
- token.userId // "2" (string from JWT claim)
124
- ```
125
-
126
- ### 4. Database Returns Numbers
127
- ```javascript
128
- const newOrg = new Organization();
129
- // ... set properties ...
130
- await organizationContext.saveChanges();
131
-
132
- newOrg.id // 8 (NUMBER from auto-increment)
133
- ```
134
-
135
- **Result:** Mixed types are common in real-world apps!
136
-
137
- ## Both Patterns Now Work
138
-
139
- ### Pattern 1: Navigation Property (OLD, still works)
140
- ```javascript
141
- const user = await ctx.User.where(u => u.id == 2).first();
142
- orgRole.User = user; // Set navigation property
143
- ```
144
-
145
- ### Pattern 2: Foreign Key Field (NEW, now works!)
146
- ```javascript
147
- orgRole.user_id = currentUser.id; // "2" (string)
148
- // Auto-converted to 2 (integer) ✅
149
- ```
150
-
151
- ### Pattern 3: Direct Integer (always worked)
152
- ```javascript
153
- orgRole.user_id = 2; // Already a number
154
- ```
155
-
156
- ## Test Coverage
157
-
158
- **8 comprehensive tests** verify:
159
- 1. ✅ String foreign key value included in INSERT
160
- 2. ✅ Number foreign key value still works
161
- 3. ✅ Mixed string and number foreign keys
162
- 4. ✅ String with leading zeros ("007" → 7)
163
- 5. ✅ Invalid strings throw clear error
164
- 6. ✅ Empty strings throw clear error
165
- 7. ✅ Backward compatible (navigation property)
166
- 8. ✅ Prefers navigation property if both set
167
-
168
- Run tests:
169
- ```bash
170
- node test/foreign-key-string-value-test.js
171
- ```
172
-
173
- ## Affected Database Engines
174
-
175
- All three engines fixed:
176
- - ✅ SQLiteEngine (`SQLLiteEngine.js`)
177
- - ✅ MySQLEngine (`mySQLEngine.js`)
178
- - ✅ PostgresEngine (`postgresEngine.js`)
179
-
180
- ## Upgrade Path
181
-
182
- ```bash
183
- npm install -g masterrecord@0.3.39
184
- ```
185
-
186
- **No code changes needed!** The fix is automatic.
187
-
188
- ### If You Have Workarounds
189
-
190
- If you added `parseInt()` workarounds like this:
191
- ```javascript
192
- orgRole.user_id = parseInt(currentUser.id, 10);
193
- ```
194
-
195
- You can now remove them (but leaving them is harmless):
196
- ```javascript
197
- orgRole.user_id = currentUser.id; // Works directly now!
198
- ```
199
-
200
- ## Error Messages (Before vs After)
201
-
202
- ### Before v0.3.39
203
- ```
204
- SqliteError: NOT NULL constraint failed: UserOrganizationRole.user_id
205
- ```
206
- **Confusing!** The field WAS set, but silently skipped.
207
-
208
- ### After v0.3.39
209
- If you pass an invalid string:
210
- ```
211
- INSERT failed: Type mismatch for UserOrganizationRole.User: Expected integer, got string "invalid" which cannot be converted to a number
212
- ```
213
- **Clear!** Tells you exactly what's wrong.
214
-
215
- ## Impact
216
-
217
- - ✅ **Auto-converts** string foreign keys to integers
218
- - ✅ **Clear errors** for invalid values (not silent failures)
219
- - ✅ **Backward compatible** - all existing code works
220
- - ✅ **Matches real-world usage** where IDs are often strings
221
- - ✅ **Works across all databases** (SQLite, MySQL, PostgreSQL)
222
-
223
- ## Files Changed
224
-
225
- 1. **SQLLiteEngine.js** - Lines 1127-1137
226
- 2. **mySQLEngine.js** - Lines 654-664
227
- 3. **postgresEngine.js** - Lines 601-611
228
- 4. **test/foreign-key-string-value-test.js** (NEW)
229
- 5. **package.json** - Version 0.3.39
230
- 6. **readme.md** - Changelog entry
231
- 7. **MEMORY.md** - Implementation notes
232
-
233
- ## Related Issues
234
-
235
- This bug was reported by Bookbag.ai Engineering Team and affects any application that:
236
- - Uses JWT tokens for authentication (IDs as strings)
237
- - Receives data from HTTP requests (JSON has string values)
238
- - Mixes data from different sources (auth service + database)
239
- - Uses authService pattern (converts IDs to strings for consistency)
240
-
241
- ## Verification
242
-
243
- To verify the fix works with your code:
244
-
245
- ```javascript
246
- import UserOrganizationRole from './models/userOrganizationRole.js';
247
- import userContext from './models/userContext.js';
248
-
249
- async function testFix() {
250
- const ctx = new userContext();
251
-
252
- const orgRole = new UserOrganizationRole();
253
- orgRole.user_id = "2"; // ← STRING VALUE
254
- orgRole.organization_id = 1;
255
- orgRole.role = "org_admin";
256
- orgRole.created_at = Date.now().toString();
257
- orgRole.updated_at = Date.now().toString();
258
-
259
- ctx.UserOrganizationRole.add(orgRole);
260
-
261
- try {
262
- await ctx.saveChanges();
263
- console.log('✅ SUCCESS! String foreign key value was auto-converted.');
264
- console.log('Inserted record:', orgRole);
265
- } catch (err) {
266
- console.error('❌ FAILED:', err.message);
267
- }
268
- }
269
-
270
- testFix();
271
- ```
272
-
273
- Expected output:
274
- ```
275
- ⚠️ Field UserOrganizationRole.User: Auto-converting string "2" to integer 2
276
- ✅ SUCCESS! String foreign key value was auto-converted.
277
- Inserted record: { id: 1, user_id: 2, organization_id: 1, role: 'org_admin', ... }
278
- ```
279
-
280
- ## Conclusion
281
-
282
- The bug is **completely fixed** in v0.3.39. String values assigned to foreign key fields are now:
283
- 1. **Detected** (checked in both navigation property and foreign key field name)
284
- 2. **Validated** (throws error for invalid strings)
285
- 3. **Converted** (auto-converts to integer)
286
- 4. **Included** in INSERT statements (no more silent failures)
287
-
288
- Upgrade to v0.3.39 and enjoy hassle-free foreign key handling! 🎉