masterrecord 1.1.0 → 1.1.1
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 +58 -197
- package/docs/FULL_TEXT_SEARCH.md +219 -0
- package/docs/METHODS_REFERENCE.md +15 -0
- package/docs/MIGRATIONS_GUIDE.md +35 -0
- package/docs/POSTGRESQL_SETUP.md +3 -3
- package/package.json +1 -1
- package/readme.md +47 -12
- package/.github/FUTURE_IMPROVEMENTS.md +0 -138
- package/FOREIGN_KEY_STRING_FIX.md +0 -288
- package/GLOBAL_REGISTRY_VERIFICATION.md +0 -375
|
@@ -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! 🎉
|