import { db, initializeDatabase } from '../../src/db'; import { describe, test, expect, beforeEach } from 'bun:test'; describe('Database', () => { beforeEach(() => { // Reset database between tests db.exec('DROP TABLE IF EXISTS tasks'); db.exec('DROP TABLE IF EXISTS task_assignments'); db.exec('DROP TABLE IF EXISTS users'); db.exec('DROP TABLE IF EXISTS groups'); initializeDatabase(); }); describe('Table Creation', () => { test('should create all required tables', () => { const tables = db .query("SELECT name FROM sqlite_master WHERE type='table'") .all() .map((t: any) => t.name); const expectedTables = ['groups', 'task_assignments', 'tasks', 'users']; const userTables = tables.filter(t => !t.startsWith('sqlite_')); expect(userTables.sort()).toEqual(expectedTables.sort()); }); }); describe('Table Schemas', () => { test('users table should have correct columns', () => { const columns = db .query("PRAGMA table_info(users)") .all() .map((c: any) => c.name); expect(columns).toEqual(['id', 'first_seen', 'last_seen']); }); test('tasks table should have required columns', () => { const columns = db .query("PRAGMA table_info(tasks)") .all() .map((c: any) => c.name); expect(columns).toContain('description'); expect(columns).toContain('due_date'); expect(columns).toContain('group_id'); expect(columns).toContain('created_by'); }); test('groups table should have active flag default to true', () => { db.exec(` INSERT INTO groups (id, community_id, name) VALUES ('test-group', 'test-community', 'Test Group') `); const group = db.query("SELECT active FROM groups WHERE id = 'test-group'").get(); expect(group.active).toBe(1); }); }); describe('Foreign Keys', () => { test('task_assignments should reference tasks', () => { const fkInfo = db .query("PRAGMA foreign_key_list(task_assignments)") .all(); expect(fkInfo.length).toBe(1); expect(fkInfo[0].from).toBe('task_id'); expect(fkInfo[0].to).toBe('id'); expect(fkInfo[0].table).toBe('tasks'); }); test('tasks should reference users via created_by', () => { const fkInfo = db .query("PRAGMA foreign_key_list(tasks)") .all(); expect(fkInfo.length).toBe(1); expect(fkInfo[0].from).toBe('created_by'); expect(fkInfo[0].to).toBe('id'); expect(fkInfo[0].table).toBe('users'); }); }); describe('Data Operations', () => { beforeEach(() => { db.exec(` INSERT INTO users (id) VALUES ('34650112233'); INSERT INTO groups (id, community_id, name) VALUES ('test-group', 'test-community', 'Test Group') `); }); test('should allow inserting group tasks', () => { const result = db.prepare(` INSERT INTO tasks (description, created_by, group_id) VALUES ('Test task', '34650112233', 'test-group') `).run(); expect(result.changes).toBe(1); }); test('should allow inserting private tasks', () => { const result = db.prepare(` INSERT INTO tasks (description, created_by) VALUES ('Private task', '34650112233') `).run(); expect(result.changes).toBe(1); }); }); });