package db import ( "database/sql" "embed" "os" "codeberg.org/u1f320/filer/db/queries" "codeberg.org/u1f320/filer/store" "codeberg.org/u1f320/filer/store/local" "emperror.dev/errors" "github.com/joho/godotenv" "github.com/rs/zerolog/log" migrate "github.com/rubenv/sql-migrate" // sqlite driver _ "modernc.org/sqlite" ) func init() { godotenv.Load() } const defaultDBName = "filer.db?_pragma=foreign_keys(1)" type DB struct { *queries.Queries db *sql.DB Store store.Store } func New() (*DB, error) { sqldb, err := sql.Open("sqlite", defaultDBName) if err != nil { return nil, errors.Wrap(err, "creating database") } err = migrateDB(sqldb, defaultDBName) if err != nil { return nil, errors.Wrap(err, "migrating database") } db := &DB{ Queries: queries.New(sqldb), db: sqldb, } switch os.Getenv("STORAGE") { case local.StoreKey: db.Store, err = local.New(os.Getenv("LOCAL_PATH")) default: err = store.ErrInvalidStoreKey } if err != nil { return nil, errors.Wrap(err, "creating store") } return db, nil } //go:embed migrations var migrateFS embed.FS func migrateDB(db *sql.DB, dbName string) error { migrations := &migrate.EmbedFileSystemMigrationSource{ FileSystem: migrateFS, Root: "migrations", } n, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up) if err != nil { return errors.Wrap(err, "executing migrations") } log.Info().Int("count", n).Msg("Performed migrations!") return nil }