Skip to content

Commit ea716e1

Browse files
Copilotmathiasrw
andcommitted
Add NaN check to inline FK and test for NULL values with inline FKs
Co-authored-by: mathiasrw <[email protected]>
1 parent 740b984 commit ea716e1

File tree

2 files changed

+34
-9
lines changed

2 files changed

+34
-9
lines changed

src/60createtable.js

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -173,15 +173,16 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
173173
};
174174
var fkfn = function (r) {
175175
var rr = {};
176-
if (r[col.columnid] == null) {
177-
return true;
178-
}
179-
rr[fk.columnid] = r[col.columnid];
180-
var addr = fktable.pk.onrightfn(rr);
181-
if (!fktable.uniqs[fktable.pk.hh][addr]) {
182-
throw new Error(
183-
'Foreign key "' + r[col.columnid] + '" not found in table "' + fk.tableid + '"'
184-
);
176+
var val = r[col.columnid];
177+
// Only check foreign key if value is not null, undefined, or NaN
178+
if (val != null && !(typeof val === 'number' && isNaN(val))) {
179+
rr[fk.columnid] = val;
180+
var addr = fktable.pk.onrightfn(rr);
181+
if (!fktable.uniqs[fktable.pk.hh][addr]) {
182+
throw new Error(
183+
'Foreign key "' + val + '" not found in table "' + fk.tableid + '"'
184+
);
185+
}
185186
}
186187
return true;
187188
};

test/test1643.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,4 +345,28 @@ describe('Test 1643 - Foreign Key and Primary Key Column Detection', function ()
345345
var table = db.tables.InlineChild;
346346
assert(table.xcolumns.ParentId.foreignkey, 'ParentId should have foreignkey property');
347347
});
348+
349+
it('L) Inline foreign key should allow NULL values', function () {
350+
alasql('DROP TABLE IF EXISTS InlineNullChild');
351+
alasql('DROP TABLE IF EXISTS InlineNullParent');
352+
353+
alasql(`CREATE TABLE InlineNullParent (
354+
Id INT PRIMARY KEY
355+
)`);
356+
357+
alasql(`CREATE TABLE InlineNullChild (
358+
ChildId INT PRIMARY KEY,
359+
ParentId INT FOREIGN KEY REFERENCES InlineNullParent(Id)
360+
)`);
361+
362+
alasql('INSERT INTO InlineNullParent VALUES (1)');
363+
364+
// Insert with NULL foreign key should succeed (NULL is allowed)
365+
var res = alasql('INSERT INTO InlineNullChild VALUES (1, NULL)');
366+
assert.equal(res, 1, 'Insert with NULL inline foreign key should succeed');
367+
368+
// Insert with valid foreign key should succeed
369+
var res2 = alasql('INSERT INTO InlineNullChild VALUES (2, 1)');
370+
assert.equal(res2, 1, 'Insert with valid inline foreign key should succeed');
371+
});
348372
});

0 commit comments

Comments
 (0)