AGENTS.md: no direct commits to main, all changes via feature branches

This commit is contained in:
clawbot
2026-02-09 12:31:14 -08:00
parent e9b6eb862e
commit 7b0ff178d4
14 changed files with 247 additions and 100 deletions

View File

@@ -1,3 +1,4 @@
// Package db provides database access and migration management.
package db
import (
@@ -5,38 +6,47 @@ import (
"database/sql"
"embed"
"fmt"
"time"
"io/fs"
"log/slog"
"sort"
"strconv"
"strings"
"time"
"git.eeqj.de/sneak/chat/internal/config"
"git.eeqj.de/sneak/chat/internal/logger"
"git.eeqj.de/sneak/chat/internal/models"
"go.uber.org/fx"
_ "github.com/joho/godotenv/autoload"
_ "modernc.org/sqlite"
_ "github.com/joho/godotenv/autoload" // loads .env file
_ "modernc.org/sqlite" // SQLite driver
)
//go:embed schema/*.sql
var SchemaFiles embed.FS
const (
minMigrationParts = 2
)
// SchemaFiles contains embedded SQL migration files.
//
//go:embed schema/*.sql
var SchemaFiles embed.FS //nolint:gochecknoglobals
// DatabaseParams defines the dependencies for creating a Database.
type DatabaseParams 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 *DatabaseParams
}
// GetDB implements models.db so Database can be embedded in model structs.
// GetDB returns the underlying sql.DB connection.
func (s *Database) GetDB() *sql.DB {
return s.db
}
@@ -52,9 +62,11 @@ func (s *Database) NewChannel(id int64, name, topic, modes string, createdAt, up
UpdatedAt: updatedAt,
}
c.SetDB(s)
return c
}
// New creates a new Database instance and registers lifecycle hooks.
func New(lc fx.Lifecycle, params DatabaseParams) (*Database, error) {
s := new(Database)
s.params = &params
@@ -65,16 +77,20 @@ func New(lc fx.Lifecycle, params DatabaseParams) (*Database, error) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
s.log.Info("Database OnStart Hook")
return s.connect(ctx)
},
OnStop: func(ctx context.Context) error {
s.log.Info("Database OnStop Hook")
if s.db != nil {
return s.db.Close()
}
return nil
},
})
return s, nil
}
@@ -89,11 +105,14 @@ func (s *Database) connect(ctx context.Context) error {
d, err := sql.Open("sqlite", dbURL)
if err != nil {
s.log.Error("failed to open database", "error", err)
return err
}
if err := d.PingContext(ctx); err != nil {
err = d.PingContext(ctx)
if err != nil {
s.log.Error("failed to ping database", "error", err)
return err
}
@@ -110,8 +129,27 @@ type migration struct {
}
func (s *Database) runMigrations(ctx context.Context) error {
// Bootstrap: create schema_migrations table directly (migration 001 also does this,
// but we need it to exist before we can check which migrations have run)
err := s.bootstrapMigrationsTable(ctx)
if err != nil {
return err
}
migrations, err := s.loadMigrations()
if err != nil {
return err
}
err = s.applyMigrations(ctx, migrations)
if err != nil {
return err
}
s.log.Info("database migrations complete")
return nil
}
func (s *Database) bootstrapMigrationsTable(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
@@ -120,23 +158,27 @@ func (s *Database) runMigrations(ctx context.Context) error {
return fmt.Errorf("failed to create schema_migrations table: %w", err)
}
// Read all migration files
return nil
}
func (s *Database) loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(SchemaFiles, "schema")
if err != nil {
return fmt.Errorf("failed to read schema dir: %w", err)
return nil, fmt.Errorf("failed to read schema dir: %w", err)
}
var migrations []migration
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
// Parse version from filename (e.g. "001_initial.sql" -> 1)
parts := strings.SplitN(entry.Name(), "_", 2)
if len(parts) < 2 {
parts := strings.SplitN(entry.Name(), "_", minMigrationParts)
if len(parts) < minMigrationParts {
continue
}
version, err := strconv.Atoi(parts[0])
if err != nil {
continue
@@ -144,7 +186,7 @@ func (s *Database) runMigrations(ctx context.Context) error {
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
if err != nil {
return fmt.Errorf("failed to read migration %s: %w", entry.Name(), err)
return nil, fmt.Errorf("failed to read migration %s: %w", entry.Name(), err)
}
migrations = append(migrations, migration{
@@ -158,26 +200,34 @@ func (s *Database) runMigrations(ctx context.Context) error {
return migrations[i].version < migrations[j].version
})
return migrations, nil
}
func (s *Database) applyMigrations(ctx context.Context, migrations []migration) error {
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("failed to check migration %d: %w", m.version, err)
}
if exists > 0 {
continue
}
s.log.Info("applying migration", "version", m.version, "name", m.name)
if _, err := s.db.ExecContext(ctx, m.sql); err != nil {
_, err = s.db.ExecContext(ctx, m.sql)
if err != nil {
return fmt.Errorf("failed to apply migration %d (%s): %w", m.version, m.name, err)
}
if _, err := s.db.ExecContext(ctx, "INSERT INTO schema_migrations (version) VALUES (?)", m.version); err != nil {
_, err = s.db.ExecContext(ctx, "INSERT INTO schema_migrations (version) VALUES (?)", m.version)
if err != nil {
return fmt.Errorf("failed to record migration %d: %w", m.version, err)
}
}
s.log.Info("database migrations complete")
return nil
}