2024-02-27 11:04:05 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
2024-02-29 22:42:56 +00:00
|
|
|
"fmt"
|
2024-02-27 11:04:05 +00:00
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
2024-05-18 20:18:28 +00:00
|
|
|
"github.com/pkg/errors"
|
2024-02-27 11:04:05 +00:00
|
|
|
migrate "github.com/rubenv/sql-migrate"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed sqlite/migrations/*
|
|
|
|
var sqliteMigrations embed.FS
|
|
|
|
|
|
|
|
func ConnectToDatabase(logger *slog.Logger, path string) (*sqlx.DB, error) {
|
2024-02-29 22:42:56 +00:00
|
|
|
db, err := sqlx.Connect("sqlite3", fmt.Sprintf("%s?_journal=WAL&_timeout=5000&_fk=true", path))
|
2024-02-27 11:04:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
logger.Info("Connected to database")
|
|
|
|
|
|
|
|
migrations := migrate.EmbedFileSystemMigrationSource{
|
|
|
|
FileSystem: sqliteMigrations,
|
|
|
|
Root: "sqlite/migrations",
|
|
|
|
}
|
|
|
|
n, err := migrate.Exec(db.DB, "sqlite3", migrations, migrate.Up)
|
|
|
|
if err != nil {
|
2024-05-18 20:18:28 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to run migrations")
|
2024-02-27 11:04:05 +00:00
|
|
|
}
|
|
|
|
logger.Info("Applied migrations", "number", n)
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
}
|