Major changes: - Consolidated schema into single migration with IRC envelope format - Messages table stores command/from/to/body(JSON)/meta(JSON) per spec - Per-client delivery queues (client_queues table) with fan-out - In-memory broker for long-poll notifications (no busy polling) - GET /messages supports ?after=<queue_id>&timeout=15 long-polling - All commands (JOIN/PART/NICK/TOPIC/QUIT/PING) broadcast events - Channels are ephemeral (deleted when last member leaves) - PRIVMSG to nicks (DMs) fan out to both sender and recipient - SPA rewritten in vanilla JS (no build step needed): - Long-poll via recursive fetch (not setInterval) - IRC envelope parsing with system message display - /nick, /join, /part, /msg, /quit commands - Unread indicators on inactive tabs - DM tabs from user list clicks - Removed unused models package (was for UUID-based schema) - Removed conflicting UUID-based db methods - Increased HTTP write timeout to 60s for long-poll support
212 lines
4.5 KiB
Go
212 lines
4.5 KiB
Go
// Package db provides database access and migration management.
|
|
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
"fmt"
|
|
"io/fs"
|
|
"log/slog"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.eeqj.de/sneak/chat/internal/config"
|
|
"git.eeqj.de/sneak/chat/internal/logger"
|
|
"go.uber.org/fx"
|
|
|
|
_ "github.com/joho/godotenv/autoload" // loads .env file
|
|
_ "modernc.org/sqlite" // SQLite driver
|
|
)
|
|
|
|
const (
|
|
minMigrationParts = 2
|
|
)
|
|
|
|
// SchemaFiles contains embedded SQL migration files.
|
|
//
|
|
//go:embed schema/*.sql
|
|
var SchemaFiles embed.FS
|
|
|
|
// Params defines the dependencies for creating a Database.
|
|
type Params struct {
|
|
fx.In
|
|
|
|
Logger *logger.Logger
|
|
Config *config.Config
|
|
}
|
|
|
|
// Database manages the SQLite database connection and migrations.
|
|
type Database struct {
|
|
db *sql.DB
|
|
log *slog.Logger
|
|
params *Params
|
|
}
|
|
|
|
// New creates a new Database instance and registers lifecycle hooks.
|
|
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
|
s := new(Database)
|
|
s.params = ¶ms
|
|
s.log = params.Logger.Get()
|
|
|
|
s.log.Info("Database instantiated")
|
|
|
|
lc.Append(fx.Hook{
|
|
OnStart: func(ctx context.Context) error {
|
|
s.log.Info("Database OnStart Hook")
|
|
return s.connect(ctx)
|
|
},
|
|
OnStop: func(_ context.Context) error {
|
|
s.log.Info("Database OnStop Hook")
|
|
if s.db != nil {
|
|
return s.db.Close()
|
|
}
|
|
return nil
|
|
},
|
|
})
|
|
|
|
return s, nil
|
|
}
|
|
|
|
// GetDB returns the underlying sql.DB connection.
|
|
func (s *Database) GetDB() *sql.DB {
|
|
return s.db
|
|
}
|
|
|
|
func (s *Database) connect(ctx context.Context) error {
|
|
dbURL := s.params.Config.DBURL
|
|
if dbURL == "" {
|
|
dbURL = "file:./data.db?_journal_mode=WAL"
|
|
}
|
|
|
|
s.log.Info("connecting to database", "url", dbURL)
|
|
|
|
d, err := sql.Open("sqlite", dbURL)
|
|
if err != nil {
|
|
s.log.Error("failed to open database", "error", err)
|
|
return err
|
|
}
|
|
|
|
err = d.PingContext(ctx)
|
|
if err != nil {
|
|
s.log.Error("failed to ping database", "error", err)
|
|
return err
|
|
}
|
|
|
|
s.db = d
|
|
s.log.Info("database connected")
|
|
|
|
if _, err := s.db.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
|
|
return fmt.Errorf("enable foreign keys: %w", err)
|
|
}
|
|
|
|
return s.runMigrations(ctx)
|
|
}
|
|
|
|
type migration struct {
|
|
version int
|
|
name string
|
|
sql string
|
|
}
|
|
|
|
func (s *Database) runMigrations(ctx context.Context) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version INTEGER PRIMARY KEY,
|
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)`)
|
|
if err != nil {
|
|
return fmt.Errorf("create schema_migrations table: %w", err)
|
|
}
|
|
|
|
migrations, err := s.loadMigrations()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, m := range migrations {
|
|
var exists int
|
|
err := s.db.QueryRowContext(ctx,
|
|
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
|
m.version,
|
|
).Scan(&exists)
|
|
if err != nil {
|
|
return fmt.Errorf("check migration %d: %w", m.version, err)
|
|
}
|
|
if exists > 0 {
|
|
continue
|
|
}
|
|
|
|
s.log.Info("applying migration", "version", m.version, "name", m.name)
|
|
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("begin tx for migration %d: %w", m.version, err)
|
|
}
|
|
|
|
_, err = tx.ExecContext(ctx, m.sql)
|
|
if err != nil {
|
|
_ = tx.Rollback()
|
|
return fmt.Errorf("apply migration %d (%s): %w", m.version, m.name, err)
|
|
}
|
|
|
|
_, err = tx.ExecContext(ctx,
|
|
"INSERT INTO schema_migrations (version) VALUES (?)",
|
|
m.version,
|
|
)
|
|
if err != nil {
|
|
_ = tx.Rollback()
|
|
return fmt.Errorf("record migration %d: %w", m.version, err)
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
return fmt.Errorf("commit migration %d: %w", m.version, err)
|
|
}
|
|
}
|
|
|
|
s.log.Info("database migrations complete")
|
|
return nil
|
|
}
|
|
|
|
func (s *Database) loadMigrations() ([]migration, error) {
|
|
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read schema dir: %w", err)
|
|
}
|
|
|
|
var migrations []migration
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
|
continue
|
|
}
|
|
|
|
parts := strings.SplitN(entry.Name(), "_", minMigrationParts)
|
|
if len(parts) < minMigrationParts {
|
|
continue
|
|
}
|
|
|
|
version, err := strconv.Atoi(parts[0])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read migration %s: %w", entry.Name(), err)
|
|
}
|
|
|
|
migrations = append(migrations, migration{
|
|
version: version,
|
|
name: entry.Name(),
|
|
sql: string(content),
|
|
})
|
|
}
|
|
|
|
sort.Slice(migrations, func(i, j int) bool {
|
|
return migrations[i].version < migrations[j].version
|
|
})
|
|
|
|
return migrations, nil
|
|
}
|