Working example

This commit is contained in:
Håkon Størdal 2025-09-02 22:51:17 +02:00
parent 5c04a0f1ee
commit b4444e7bd2
14 changed files with 935 additions and 22 deletions

81
src/lib/db.ts Normal file
View file

@ -0,0 +1,81 @@
import { DATABASE_URL } from '$env/static/private';
import { Pool } from 'pg';
// Create a connection pool
const pool = new Pool({
connectionString: DATABASE_URL,
ssl: false
});
// Simple database client
export const db = {
// Execute a query
async query(text: string, params?: any[]) {
const client = await pool.connect();
try {
const result = await client.query(text, params);
return result;
} finally {
client.release();
}
},
// Test connection
async testConnection() {
try {
const result = await this.query('SELECT NOW() as current_time');
console.log('Database connected successfully:', result.rows[0]);
return true;
} catch (error) {
console.error('Database connection failed:', error);
return false;
}
},
// Create tables for tracking daily exercises
async createTables() {
// Create exercises table with all activities in one table
await this.query(`
CREATE TABLE IF NOT EXISTS daily_exercises (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
date DATE NOT NULL UNIQUE,
pushups INTEGER DEFAULT 0,
situps INTEGER DEFAULT 0,
plank_time_seconds INTEGER DEFAULT 0,
run_distance_km DECIMAL(5,2) DEFAULT 0.0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create index for faster date lookups
await this.query(`
CREATE INDEX IF NOT EXISTS idx_daily_exercises_date
ON daily_exercises(date)
`);
// Create trigger to update updated_at timestamp
await this.query(`
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ language 'plpgsql'
`);
await this.query(`
DROP TRIGGER IF EXISTS update_daily_exercises_updated_at ON daily_exercises;
CREATE TRIGGER update_daily_exercises_updated_at
BEFORE UPDATE ON daily_exercises
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column()
`);
},
// Close all connections
async close() {
await pool.end();
}
};