source: Klonkt/src/config/database.js@ 52215bc

main
Last change on this file since 52215bc was 52215bc, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

tenancy: /gebruikers -> /user/ in settings text + comments (Robin's naming choice)

Co-Authored-By: Claude <noreply@â€Ļ>

  • Property mode set to 100644
File size: 5.1 KB
Line 
1import Database from 'better-sqlite3';
2import path from 'path';
3import { fileURLToPath } from 'url';
4import fs from 'fs';
5
6const __dirname = path.dirname(fileURLToPath(import.meta.url));
7const dbPath = process.env.DATABASE_PATH || path.join(__dirname, '../../storage/database.sqlite');
8
9// Ensure storage directory exists
10const storageDir = path.dirname(dbPath);
11if (!fs.existsSync(storageDir)) {
12 fs.mkdirSync(storageDir, { recursive: true });
13}
14
15// Initialize database
16const db = new Database(dbPath);
17db.pragma('journal_mode = WAL');
18db.pragma('foreign_keys = ON');
19
20export function initializeDatabase() {
21 const tableExists = db.prepare(`
22 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
23 `).get();
24
25 if (!tableExists) {
26 console.log('🔧 Initializing database schema...');
27 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
28 const schema = fs.readFileSync(schemaPath, 'utf-8');
29 db.exec(schema);
30 console.log('✅ Database initialized with v9-soul schema');
31 }
32
33 // Additive column migrations — safe to run every boot.
34 // SQLite throws if the column already exists; we swallow that.
35 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
36 ensureColumn('sites', 'profile_photo', 'TEXT');
37 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
38 ensureColumn('audio_tracks', 'album', 'TEXT');
39 ensureColumn('users', 'reset_token', 'TEXT');
40 ensureColumn('users', 'reset_token_expires', 'DATETIME');
41 // Google OAuth: koppel een Google-account aan een user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
43 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
44 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'trust'");
45 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
46 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
47
48 // v9 audit additions —————————————————————————————————————————
49 // SEO/social columns the v9 template uses (most live in 001-init.sql already
50 // for fresh DBs but ensureColumn is idempotent for existing DBs).
51 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
52 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
53 ensureColumn('sites', 'publisher_name', 'TEXT');
54 ensureColumn('sites', 'publisher_url', 'TEXT');
55 ensureColumn('sites', 'publisher_logo', 'TEXT');
56 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
57 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
58 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
59 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
60 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'timeline'"); // timeline | grid
61 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
62 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
63 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
64
65 // Per-post noindex + type
66 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
67 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
68
69 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
70 // idempotent so it's safe to run on every boot regardless of DB age.
71 db.exec(`
72 CREATE TABLE IF NOT EXISTS playlists (
73 id TEXT PRIMARY KEY,
74 site_id TEXT NOT NULL,
75 title TEXT NOT NULL,
76 artist TEXT,
77 year INTEGER,
78 cover_url TEXT,
79 kind TEXT DEFAULT 'album',
80 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
81 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
82 FOREIGN KEY (site_id) REFERENCES sites(id)
83 );
84 CREATE TABLE IF NOT EXISTS playlist_tracks (
85 playlist_id TEXT NOT NULL,
86 track_id TEXT NOT NULL,
87 position INTEGER NOT NULL DEFAULT 0,
88 PRIMARY KEY (playlist_id, track_id),
89 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
90 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
91 );
92 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
93 ON playlist_tracks(playlist_id, position);
94 `);
95
96 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
97 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
98 db.exec(`
99 CREATE TABLE IF NOT EXISTS app_settings (
100 key TEXT PRIMARY KEY,
101 value TEXT,
102 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
103 );
104 `);
105 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
106}
107
108function ensureColumn(table, column, definition) {
109 try {
110 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
111 console.log(`🔧 Added column ${table}.${column}`);
112 } catch (e) {
113 // "duplicate column name" → already there. Anything else, surface it.
114 if (!/duplicate column/i.test(e.message)) {
115 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
116 }
117 }
118}
119
120export default db;
Note: See TracBrowser for help on using the repository browser.