A deployable markdown editor that connects with your self hosted files and lets you edit in a beautiful interface
1package database
2
3import (
4 "database/sql"
5 "fmt"
6 "log"
7 "os"
8 "path/filepath"
9
10 _ "modernc.org/sqlite"
11)
12
13// DB wraps the database connection
14type DB struct {
15 *sql.DB
16}
17
18// New creates a new database connection
19func New(dbPath string) (*DB, error) {
20 // Ensure the directory exists
21 dir := filepath.Dir(dbPath)
22 if err := os.MkdirAll(dir, 0755); err != nil {
23 return nil, fmt.Errorf("failed to create database directory: %w", err)
24 }
25
26 // Open database connection
27 db, err := sql.Open("sqlite", dbPath)
28 if err != nil {
29 return nil, fmt.Errorf("failed to open database: %w", err)
30 }
31
32 // Configure connection pool
33 db.SetMaxOpenConns(1) // SQLite works best with single connection
34 db.SetMaxIdleConns(1)
35
36 // Enable WAL mode for better concurrency
37 if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
38 db.Close()
39 return nil, fmt.Errorf("failed to enable WAL mode: %w", err)
40 }
41
42 // Enable foreign keys
43 if _, err := db.Exec("PRAGMA foreign_keys=ON"); err != nil {
44 db.Close()
45 return nil, fmt.Errorf("failed to enable foreign keys: %w", err)
46 }
47
48 // Test connection
49 if err := db.Ping(); err != nil {
50 db.Close()
51 return nil, fmt.Errorf("failed to ping database: %w", err)
52 }
53
54 log.Printf("Connected to database: %s", dbPath)
55
56 return &DB{db}, nil
57}
58
59// Close closes the database connection
60func (db *DB) Close() error {
61 return db.DB.Close()
62}