40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import Database from 'bun:sqlite';
|
|
import { dev } from '$app/environment';
|
|
|
|
// Initialize the database
|
|
const db = new Database(dev ? 'dev.db' : 'prod.db', { create: true});
|
|
|
|
|
|
// 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();
|
|
}
|
|
|