mirror of
https://github.com/coder/coder.git
synced 2025-07-12 00:14:10 +00:00
chore: Initial database scaffolding (#2)
* chore: Initial database scaffolding This implements migrations and code generation for interfacing with a PostgreSQL database. A dependency is added for the "postgres" binary on the host, but that seems like an acceptable requirement considering it's our primary database. An in-memory database object can be created for simple cross-OS and fast testing. * Run tests in CI * Use Docker instead of binaries on the host * Skip database tests on non-Linux operating systems * chore: Add golangci-lint and codecov * Use consistent file names
This commit is contained in:
48
database/migrate.go
Normal file
48
database/migrate.go
Normal file
@ -0,0 +1,48 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrations embed.FS
|
||||
|
||||
// Migrate runs SQL migrations to ensure the database schema is up-to-date.
|
||||
func Migrate(ctx context.Context, dbName string, db *sql.DB) error {
|
||||
sourceDriver, err := iofs.New(migrations, "migrations")
|
||||
if err != nil {
|
||||
return xerrors.Errorf("create iofs: %w", err)
|
||||
}
|
||||
dbDriver, err := postgres.WithInstance(db, &postgres.Config{})
|
||||
if err != nil {
|
||||
return xerrors.Errorf("wrap postgres connection: %w", err)
|
||||
}
|
||||
m, err := migrate.NewWithInstance("", sourceDriver, dbName, dbDriver)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("migrate: %w", err)
|
||||
}
|
||||
err = m.Up()
|
||||
if err != nil {
|
||||
if errors.Is(err, migrate.ErrNoChange) {
|
||||
// It's OK if no changes happened!
|
||||
return nil
|
||||
}
|
||||
return xerrors.Errorf("up: %w", err)
|
||||
}
|
||||
srcErr, dbErr := m.Close()
|
||||
if srcErr != nil {
|
||||
return xerrors.Errorf("close source: %w", err)
|
||||
}
|
||||
if dbErr != nil {
|
||||
return xerrors.Errorf("close database: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user