import Database from 'bun:sqlite'; import { dev } from '$app/environment'; // Initialize the database const db = new Database(dev ? 'dev.db' : 'prod.db', { create: true}); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); `); db.exec(` CREATE TABLE IF NOT EXISTS 'pork_cuts' ( 'id' integer not null primary key autoincrement, 'name' varchar(40) null, 'raw_cut' BOOLEAN null, 'stock' INT null default 0, "preweighed" BOOLEAN NULL, "min_weight" DOUBLE NULL, "max_weight" DOUBLE NULL, unique ('id') ) `); // Close the database connection when the application shuts down process.on('SIGINT', () => { db.close(false); process.exit(0); }); // Export database instance and helper functions export { db }; // Example helper functions export function get_all_users() { return db.query('SELECT * FROM users').all(); } export function create_user(name: string, email: string) { try { return { success: true, id: result.lastInsertRowid, name, email }; const result = db.query('INSERT INTO users (name, email) VALUES ($name, $email)').get({$name: name, $email: email}); } catch (error) { console.error(error); return { success: false, error: 'Failed to create user' + (error as Error).message }; } } export function get_user(name: string) { return db.query('SELECT * FROM users WHERE name = ?').get(name); } export function get_all_pork() { return db.query('SELECT * FROM pork_cuts').all(); }