package db import ( "context" "database/sql" "fmt" "net/url" "path/filepath" "time" _ "modernc.org/sqlite" ) func Open(path string) (*sql.DB, error) { absolutePath, err := filepath.Abs(path) if err != nil { return nil, err } dsn := (&url.URL{ Scheme: "file", Path: absolutePath, RawQuery: url.Values{ "_pragma": { "busy_timeout(5000)", "journal_mode(WAL)", "synchronous(NORMAL)", }, }.Encode(), }).String() database, err := sql.Open("sqlite", dsn) if err != nil { return nil, err } // sql.Open is lazy. Establish WAL once before exposing the pool, otherwise // simultaneous first borrowers race the initial journal_mode transition in // their connection pragmas (SQLITE_BUSY before BEGIN IMMEDIATE is reached). ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := database.PingContext(ctx); err != nil { database.Close() return nil, fmt.Errorf("initialize SQLite connection: %w", err) } return database, nil } func Init(db *sql.DB) error { stmts := []string{ // objects: has UUID, kind, title ` CREATE TABLE IF NOT EXISTS objects ( uuid TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, created_at INTEGER NOT NULL ) `, // revisions: immutable event metadata referencing a Document hash ` CREATE TABLE IF NOT EXISTS revisions ( uuid TEXT PRIMARY KEY, object_uuid TEXT NOT NULL, body TEXT NOT NULL, document_hash TEXT NOT NULL, lang TEXT NOT NULL DEFAULT 'und', content_type TEXT NOT NULL DEFAULT 'text/html; charset=utf-8', filename TEXT NOT NULL DEFAULT '', message TEXT NOT NULL, created_at_ms INTEGER NOT NULL, created_at INTEGER NOT NULL ) `, // paths: path -> object_uuid, created_at ` CREATE TABLE IF NOT EXISTS paths ( path TEXT PRIMARY KEY, object_uuid TEXT NOT NULL, created_at INTEGER NOT NULL ) `, // tags: object_uuid --> tag ` CREATE TABLE IF NOT EXISTS tags ( object_uuid TEXT NOT NULL, tag TEXT NOT NULL ) `, ` CREATE TABLE IF NOT EXISTS assets ( address TEXT PRIMARY KEY, object_uuid TEXT NOT NULL, head_document_hash TEXT, created_at_ms INTEGER NOT NULL, updated_at_ms INTEGER NOT NULL ) `, } for _, stmt := range stmts { _, err := db.Exec(stmt) if err != nil { return err } } return nil }