sqldb: separate migration execution from construction

This commit separates the execution of SQL and in-code migrations
from their construction. This change is necessary because,
currently, the SQL schema is migrated during the construction
phase in the lncfg package. However, migrations are typically
executed when individual stores are constructed within the
configuration builder.
This commit is contained in:
Andras Banki-Horvath
2024-11-25 20:29:08 +01:00
parent b789fb2db3
commit 91c3e1496f
8 changed files with 137 additions and 57 deletions

View File

@@ -36,6 +36,9 @@ var (
// Make sure PostgresStore implements the MigrationExecutor interface.
_ MigrationExecutor = (*PostgresStore)(nil)
// Make sure PostgresStore implements the DB interface.
_ DB = (*PostgresStore)(nil)
)
// replacePasswordInDSN takes a DSN string and returns it with the password
@@ -89,9 +92,7 @@ type PostgresStore struct {
// NewPostgresStore creates a new store that is backed by a Postgres database
// backend.
func NewPostgresStore(cfg *PostgresConfig, migrations []MigrationConfig) (
*PostgresStore, error) {
func NewPostgresStore(cfg *PostgresConfig) (*PostgresStore, error) {
sanitizedDSN, err := replacePasswordInDSN(cfg.Dsn)
if err != nil {
return nil, err
@@ -130,25 +131,32 @@ func NewPostgresStore(cfg *PostgresConfig, migrations []MigrationConfig) (
queries := sqlc.New(db)
s := &PostgresStore{
return &PostgresStore{
cfg: cfg,
BaseDB: &BaseDB{
DB: db,
Queries: queries,
},
}
}, nil
}
// GetBaseDB returns the underlying BaseDB instance for the Postgres store.
// It is a trivial helper method to comply with the sqldb.DB interface.
func (s *PostgresStore) GetBaseDB() *BaseDB {
return s.BaseDB
}
// ApplyAllMigrations applies both the SQLC and custom in-code migrations to the
// Postgres database.
func (s *PostgresStore) ApplyAllMigrations(ctx context.Context,
migrations []MigrationConfig) error {
// Execute migrations unless configured to skip them.
if !cfg.SkipMigrations {
err := ApplyMigrations(
context.Background(), s.BaseDB, s, migrations,
)
if err != nil {
return nil, err
}
if s.cfg.SkipMigrations {
return nil
}
return s, nil
return ApplyMigrations(ctx, s.BaseDB, s, migrations)
}
// ExecuteMigrations runs migrations for the Postgres database, depending on the