I am trying to create a POST route as shown below. My Timesheet table has a FOREIGN KEY constraint set on it referencing the Employee table. When I try and insert a timesheet from an employee that doesn't exist using DB Browser I get the correct error triggered by the constraint. However, when I run the code below, it ignores this constraint and inserts the record. Have I set this up incorrectly or is this not a valid constraint under this scenario?
timesheetRouter.post("/", getParams, (req, res, next) => {
const tsData = req.body.timesheet;
console.log("ID", req.empID);
db.run(`insert into Timesheet (hours, rate, date, employee_id)
values ($hours, $rate, $date, $emp);`, {
$hours: tsData.hours,
$rate: tsData.rate,
$date: tsData.date,
$emp: req.empID
}, function(err) {
if (err) {
return res.status(404).send(err);
} else {
db.get("select * from Timesheet where id = $id", {$id: this.lastID},
(err, row) => {
return res.status(201).send({timesheet: row});
});
}
});
});
Table creation code:
db.serialize(() => {
db.run("DROP TABLE IF EXISTS Timesheet", err => {
if (err) {
throw new Error(err);
}
});
db.run(`create table Timesheet (id integer PRIMARY KEY,
hours integer NOT NULL,
rate integer NOT NULL,
date integer NOT NULL,
employee_id integer NOT NULL, FOREIGN KEY (employee_id) REFERENCES Employee (id))`,
err => {
if (err) {
throw new Error(err);
}
});
});
Note: getParams is a function to determine the value for empID.