connect.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package db
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "log/slog"
  7. "path/filepath"
  8. "github.com/pressly/goose/v3"
  9. )
  10. var pragmas = map[string]string{
  11. "foreign_keys": "ON",
  12. "journal_mode": "WAL",
  13. "page_size": "4096",
  14. "cache_size": "-8000",
  15. "synchronous": "NORMAL",
  16. "secure_delete": "ON",
  17. "busy_timeout": "30000",
  18. }
  19. // Connect opens a SQLite database connection and runs migrations.
  20. func Connect(ctx context.Context, dataDir string) (*sql.DB, error) {
  21. if dataDir == "" {
  22. return nil, fmt.Errorf("data.dir is not set")
  23. }
  24. dbPath := filepath.Join(dataDir, "crush.db")
  25. db, err := openDB(dbPath)
  26. if err != nil {
  27. return nil, err
  28. }
  29. if err = db.PingContext(ctx); err != nil {
  30. db.Close()
  31. return nil, fmt.Errorf("failed to connect to database: %w", err)
  32. }
  33. goose.SetBaseFS(FS)
  34. if err := goose.SetDialect("sqlite3"); err != nil {
  35. slog.Error("Failed to set dialect", "error", err)
  36. return nil, fmt.Errorf("failed to set dialect: %w", err)
  37. }
  38. if err := goose.Up(db, "migrations"); err != nil {
  39. slog.Error("Failed to apply migrations", "error", err)
  40. return nil, fmt.Errorf("failed to apply migrations: %w", err)
  41. }
  42. return db, nil
  43. }