Added migration mgmt with goose.
This commit is contained in:
@ -3,7 +3,6 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@ -14,9 +13,6 @@ import (
|
||||
"github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
//go:embed schema.sql
|
||||
var ddl string
|
||||
|
||||
// DBConfig holds database configuration.
|
||||
type DBConfig struct {
|
||||
DSN string // Data Source Name for SQLite
|
||||
@ -126,8 +122,9 @@ func openAndConfigureDB(config *DBConfig) (*sql.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// NewDB initializes and returns a new database connection pool and runs migrations.
|
||||
func NewDB(ctx context.Context, logger *slog.Logger, config *DBConfig) (*sql.DB, error) {
|
||||
// Connect initializes and returns a new database connection pool.
|
||||
// This is the basic connection function without any automatic operations.
|
||||
func Connect(ctx context.Context, logger *slog.Logger, config *DBConfig) (*sql.DB, error) {
|
||||
db, err := openAndConfigureDB(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -147,16 +144,26 @@ func NewDB(ctx context.Context, logger *slog.Logger, config *DBConfig) (*sql.DB,
|
||||
slog.Int("max_open_conns", config.MaxOpenConns),
|
||||
slog.Int("max_idle_conns", config.MaxIdleConns))
|
||||
|
||||
// Execute schema with retry logic
|
||||
err = retryOperation(ctx, logger, config, "schema execution", func() error {
|
||||
_, err := db.ExecContext(ctx, ddl)
|
||||
return err
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// ConnectAndMigrate initializes a database connection and automatically runs migrations.
|
||||
// This is the main function for application startup.
|
||||
func ConnectAndMigrate(ctx context.Context, logger *slog.Logger, config *DBConfig) (*sql.DB, error) {
|
||||
db, err := Connect(ctx, logger, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run migrations with retry logic
|
||||
err = retryOperation(ctx, logger, config, "migrations", func() error {
|
||||
return RunMigrations(db)
|
||||
})
|
||||
if err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Info("database schema applied")
|
||||
logger.Info("database migrations applied")
|
||||
return db, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user