Multi tenant DB, registratie per huishouden V1.2

This commit is contained in:
2026-08-09 19:50:53 +02:00
parent 1f9fd73026
commit c37b8956d4
15 changed files with 148 additions and 96 deletions
+18
View File
@@ -210,5 +210,23 @@ CREATE TABLE IF NOT EXISTS product_stores (
`);
const addColumnIfMissing = (table, column, definition) => {
const columns = db.prepare(`PRAGMA table_info(${table})`).all();
if (!columns.some(existing => existing.name === column)) {
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
}
};
addColumnIfMissing("categories", "household_id", "INTEGER REFERENCES households(id)");
addColumnIfMissing("products", "household_id", "INTEGER REFERENCES households(id)");
const defaultHousehold = db.prepare("SELECT id FROM households ORDER BY id LIMIT 1").get();
if (defaultHousehold) {
db.prepare("UPDATE categories SET household_id = ? WHERE household_id IS NULL")
.run(defaultHousehold.id);
db.prepare("UPDATE products SET household_id = ? WHERE household_id IS NULL")
.run(defaultHousehold.id);
}
console.log("Database migratie voltooid.");
+15 -6
View File
@@ -19,24 +19,33 @@ const products = [
["WC papier", "Huishouden"]
];
const household = db.prepare(
"SELECT id FROM households ORDER BY id LIMIT 1"
).get();
if (!household) {
console.log("Seed overgeslagen: er is nog geen huishouden.");
process.exit(0);
}
const insertCategory = db.prepare(`
INSERT OR IGNORE INTO categories (name, icon) VALUES (?, ?)
INSERT OR IGNORE INTO categories (name, icon, household_id) VALUES (?, ?, ?)
`);
const insertProduct = db.prepare(`
INSERT OR IGNORE INTO products (name, category_id) VALUES (?, ?)
INSERT OR IGNORE INTO products (name, category_id, household_id) VALUES (?, ?, ?)
`);
db.transaction(() => {
for (const category of categories) {
insertCategory.run(category);
insertCategory.run(category[0], category[1], household.id);
}
for (const [name, categoryName] of products) {
const category = db.prepare(
"SELECT id FROM categories WHERE name = ?"
).get(categoryName);
insertProduct.run(name, category.id);
"SELECT id FROM categories WHERE name = ? AND household_id = ?"
).get(categoryName, household.id);
insertProduct.run(name, category.id, household.id);
}
})();