diff options
| -rw-r--r-- | .gitignore | 4 | ||||
| -rw-r--r-- | README.md | 272 | ||||
| -rw-r--r-- | internal/commands/down.go (renamed from internal/commands/downgrade.go) | 42 | ||||
| -rw-r--r-- | internal/commands/list.go | 74 | ||||
| -rw-r--r-- | internal/commands/new.go (renamed from internal/commands/create.go) | 42 | ||||
| -rw-r--r-- | internal/commands/status.go | 100 | ||||
| -rw-r--r-- | internal/commands/up.go (renamed from internal/commands/migrate.go) | 41 | ||||
| -rw-r--r-- | internal/output/console.go | 60 | ||||
| -rw-r--r-- | internal/output/console_test.go | 76 | ||||
| -rw-r--r-- | internal/output/output.go | 7 | ||||
| -rw-r--r-- | internal/repositories/migration_db_repo.go | 10 | ||||
| -rw-r--r-- | internal/repositories/migration_db_repo_test.go | 5 | ||||
| -rw-r--r-- | internal/repositories/migration_fs_repo.go | 8 | ||||
| -rw-r--r-- | internal/repositories/migration_fs_repo_test.go | 10 | ||||
| -rw-r--r-- | internal/services/migration.go | 48 | ||||
| -rw-r--r-- | pkg/cli/cli.go | 9 |
16 files changed, 665 insertions, 143 deletions
@@ -3,3 +3,7 @@ # Editors /.vscode + +# Bolt CLI config/output +/migrations +/bolt.toml @@ -3,20 +3,280 @@ <h1>Bolt</h1> </div> -Bolt is a command-line tool that helps you manage your database migrations. -It allows you to write your database migrations in plain SQL, and Bolt will -handle ensuring they are applied and executed in the correct order. +Bolt is a command-line tool designed to simplify and streamline your database migration process. -:warning: This project is in early development. +🌟 Key Features: +- **SQL-Powered Flexibility**: 🧩 - Write your migration scripts in plain SQL. This gives you the full power and familiarity of SQL, ensuring that you're not limited by the constraints of a specific DSL (Domain Specific Language). + +- **Bidirectional Migrations**: 🔀 - With support for both 'up' (migrating) and 'down' (downgrading) migrations, Bolt provides complete control over your database versions. This feature is essential for maintaining database integrity and for executing seamless rollbacks whenever necessary. + +- **Time-Travel with Ease**: ⏳ - Migrate or downgrade to any specific point in time. Bolt allows you to specify a specific migration version to migrate or downgrade to, allowing you to easily time-travel to any point in your database's history. + +- **Safe and Reliable**: 🛡️ - Built with safety and reliability in mind, Bolt ensures your migrations are executed smoothly, with clear logging and error handling. + +## Table of Contents + +- [Installation](#installation) +- [Tutorial](#tutorial) + - [Creating your first migration](#creating-your-first-migration) + - [Writing your migration scripts](#writing-your-migration-scripts) + - [Starting up a Database Container](#starting-up-a-database-container) + - [Configuring Bolt](#configuring-bolt) + - [Applying your migration](#applying-your-migration) + - [Checking Migration Status](#checking-migration-status) + - [Verifying the Migration](#verifying-the-migration) + - [Downgrading Your Migration](#downgrading-your-migration) + - [Verifying Migration Reversion](#verifying-migration-reversion) + - [Next Steps](#next-steps) +- [Reference](#reference) + - [Database Compatibility](#database-compatibility) + - [Configuration](#configuration) + - [Configuration File](#configuration-file) + - [Environment Variables](#environment-variables) +- [Explanation](#explanation) + - [How Are Migration Scripts Executed?](#how-are-migration-scripts-executed) + - [How Does Bolt Know What Migrations Have Been Applied?](#how-does-bolt-know-what-migrations-have-been-applied) + - [How Are Migrations Applied?](#how-are-migrations-applied) + - [How Are Migrations Reverted?](#how-are-migrations-reverted) ## Installation -You may install Bolt using the following command: +To install Bolt, run the following command: ```bash $ go install github.com/eugenetriguba/bolt@latest ``` -## Database Compatibility +This will install Bolt to your `$GOBIN` directory. Make sure that `$GOBIN` is in your `$PATH`. + +## Tutorial + +In this tutorial, we'll guide you through the basics of using Bolt by running through how you can create a migration, apply it, revert it, and see the status of your migrations. + +### Creating your first migration + +Run the following command to create your first migration: + +```bash +$ bolt new -m "my first migration" +``` + +Upon completion, a migrations directory will be created with the following structure: + +```bash +migrations/ +└── 20240113162817_my_first_migration + ├── downgrade.sql + └── upgrade.sql + +1 directories, 2 files +``` + +Bolt automatically creates the migrations directory and your migration scripts inside it. + +### Writing your migration scripts + +Bolt utilizes plain SQL for migration scripts. Each migration directory contains `upgrade.sql` for applying migrations and `downgrade.sql` for reverting them. + +1. Write the Upgrade Script + +Edit `upgrade.sql` with the following SQL command to create a new table: + +```sql +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); +``` + +2. Write the Downgrade Script + +Edit `downgrade.sql` with the following SQL command to remove the table: + +```sql +DROP TABLE users; +``` + +### Starting up a Database Container + +We'll use Docker to run a PostgreSQL database container for this tutorial: + +1. Install Docker + +If you don't have docker installed, view the installation instructions [here](https://docs.docker.com/get-docker/). + +2. Startup the PostgreSQL container + +```bash +$ docker run --name bolt-postgres -e POSTGRES_USER=bolt_user -e POSTGRES_PASSWORD=bolt_password -e POSTGRES_DB=bolt_tutorial_db -p 5432:5432 --detach postgres:16.1-alpine3.19 +``` + +### Configuring Bolt + +Bolt can be configured with a `bolt.toml` file or environment variables. For simplicity, we'll use a `bolt.toml` file in this tutorial. + +1. Create a `bolt.toml` file: + +```bash +$ touch bolt.toml +``` + +2. Add the following contents to the file: + +```toml +[connection] +host = "localhost" +port = 5432 +user = "bolt_user" +password = "bolt_password" +dbname = "bolt_tutorial_db" +driver = "postgres" +``` + +### Applying your migration + +Apply your migration, which will execute the `upgrade.sql` script: + +```bash +$ bolt up +Applying migration 20240113162817_my_first_migration.. +Successfully applied migration 20240113162817_my_first_migration! +``` + +### Checking Migration Status + +To view the status of your migration: + +```bash +$ bolt status +Version Message Applied +20240113162817 my_first_migration X +``` + +This command displays the migration's version, name, and whether the migration was applied or not. + +### Verifying the Migration + +Connect to the database container to confirm the users table was created: + +```bash +$ docker exec -it bolt-postgres psql -U bolt_user -d bolt_tutorial_db +``` + +```psql +bolt_tutorial_db=# \dt + List of relations + Schema | Name | Type | Owner +--------+-----------------+-------+----------- + public | bolt_migrations | table | bolt_user + public | users | table | bolt_user +(2 rows) +``` + +We can see that our `users` table was created successfully. We also see another table that we didn't explicitly create called `bolt_migrations`. This table is used by Bolt to keep track of which migrations have been applied to your database. You should not modify this table manually. + +### Downgrading Your Migration + +To revert your migration: + +```bash +$ bolt down +Reverting migration 20240113162817_my_first_migration.. +Successfully reverted migration 20240113162817_my_first_migration! +``` + +### Verifying Migration Reversion + +Reconnect to the database container and check that the users table has been removed: + +```bash +$ docker exec -it bolt-postgres psql -U bolt_user -d bolt_tutorial_db +``` + +```psql +bolt_tutorial_db=# \dt + List of relations + Schema | Name | Type | Owner +--------+-----------------+-------+----------- + public | bolt_migrations | table | bolt_user +(1 row) +``` + +### Next Steps + +Congrats! You've learned the core features of Bolt. If you want learn more, see the [Reference](#reference) or [Explanation](#explanation) section. + +## Reference + +### Database Compatibility At the moment, only PostgreSQL is supported. You're welcome to contribute support for other databases. + +### Configuration + +There are two ways to configure Bolt: via a `bolt.toml` file or via environment variables. If you use both methods, the environment variables will take precedence. + +#### Configuration File + +Bolt attempts to find a `bolt.toml` file in your current working directory +or in any parent directory. + +```toml +# The directory where your migration scripts are located. +# Defaults to "migrations". This directory is relative to +# the current working directory. You may also use an absolute +# path. +migrations_dir = "migrations" + +# Connection parameters for the database Bolt will be +# applying migrations to. All connection parameters are +# required. +[connection] +# The host to use to connect to your database. +host = +# The port to use to connect to your database. +# Note: This should be an integer. +port = +# The user to use to connect to your database. +user = +# The password to use to connect to your database. +password = +# The name of the database within your DBMS. +dbname = +# The name of the database driver to use to connect to +# the database. At the moment, only "postgres" is supported. +driver = +``` + +#### Environment Variables + +All configuration file settings have corresponding environment variables. + +- `BOLT_MIGRATIONS_DIR` +- `BOLT_CONNECTION_HOST` +- `BOLT_CONNECTION_PORT` +- `BOLT_CONNECTION_USER` +- `BOLT_CONNECTION_PASSWORD` +- `BOLT_CONNECTION_DBNAME` +- `BOLT_CONNECTION_DRIVER` + +## Explanation + +### How Are Migration Scripts Executed? + +Bolt executes upgrade and downgrade migration scripts in a transaction. This ensures that if any errors occur during the execution of any migration script, the transaction will be rolled back and the migration will be marked as failed. Bolt will then exit with an error code and output what error has occurred to standard error. + +### How Does Bolt Know What Migrations Have Been Applied? + +Bolt keeps track of which migrations have been applied to your database by creating a table called `bolt_migrations`. This table contains a single column called `version` which is the version of the migration that was applied. That version is compared to the versions you have locally. + +### How Are Migrations Applied? + +When you run `bolt up`, Bolt will look at your local migration scripts and compares the version part of the migration directory names to the versions that have been inserted into the `bolt_migrations` table. Any versions that aren't in the table will be applied in order, starting with the oldest migration. + +### How Are Migrations Reverted? + +When you run `bolt down`, Bolt will look at the `bolt_migrations` table and compare the versions to the versions of your local migration scripts. Any versions that are in the table but not in your local migration scripts will be reverted in order, starting with the newest migration. diff --git a/internal/commands/downgrade.go b/internal/commands/down.go index f953286..0a9ca99 100644 --- a/internal/commands/downgrade.go +++ b/internal/commands/down.go @@ -3,37 +3,43 @@ package commands import ( "context" "flag" - "fmt" - "os" "github.com/eugenetriguba/bolt/internal/configloader" + "github.com/eugenetriguba/bolt/internal/output" "github.com/eugenetriguba/bolt/internal/repositories" "github.com/eugenetriguba/bolt/internal/services" "github.com/eugenetriguba/bolt/internal/storage" "github.com/google/subcommands" ) -type DowngradeCmd struct{} +type DownCmd struct{} -func (*DowngradeCmd) Name() string { return "downgrade" } +func (*DownCmd) Name() string { + return "down" +} + +func (*DownCmd) Synopsis() string { + return "downgrade migrations against the database" +} -func (*DowngradeCmd) Synopsis() string { return "Downgrade all migrations against the database." } -func (*DowngradeCmd) Usage() string { - return `downgrade: - Downgrade all migrations against the database. +func (*DownCmd) Usage() string { + return `down: + Downgrade migrations against the database. ` } -func (m *DowngradeCmd) SetFlags(f *flag.FlagSet) {} +func (m *DownCmd) SetFlags(f *flag.FlagSet) {} -func (m *DowngradeCmd) Execute( +func (m *DownCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, ) subcommands.ExitStatus { + consoleOutputter := output.ConsoleOutputter{} + cfg, err := configloader.NewConfig() if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } @@ -42,27 +48,31 @@ func (m *DowngradeCmd) Execute( storage.DBConnectionString(&cfg.Connection), ) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } defer db.Close() migrationDBRepo, err := repositories.NewMigrationDBRepo(db) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } - migrationService := services.NewMigrationService(migrationDBRepo, migrationFsRepo) + migrationService := services.NewMigrationService( + migrationDBRepo, + migrationFsRepo, + consoleOutputter, + ) err = migrationService.RevertAllMigrations() if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } diff --git a/internal/commands/list.go b/internal/commands/list.go deleted file mode 100644 index 8224820..0000000 --- a/internal/commands/list.go +++ /dev/null @@ -1,74 +0,0 @@ -package commands - -import ( - "context" - "flag" - "fmt" - "os" - - "github.com/eugenetriguba/bolt/internal/configloader" - "github.com/eugenetriguba/bolt/internal/repositories" - "github.com/eugenetriguba/bolt/internal/services" - "github.com/eugenetriguba/bolt/internal/storage" - "github.com/google/subcommands" -) - -type ListCmd struct{} - -func (*ListCmd) Name() string { return "list" } - -func (*ListCmd) Synopsis() string { return "List the database migrations and their statuses." } -func (*ListCmd) Usage() string { - return `list: - List the database migrations and their statuses. - ` -} - -func (m *ListCmd) SetFlags(f *flag.FlagSet) {} - -func (m *ListCmd) Execute( - _ context.Context, - f *flag.FlagSet, - _ ...interface{}, -) subcommands.ExitStatus { - cfg, err := configloader.NewConfig() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return subcommands.ExitFailure - } - - db, err := storage.DBConnect( - cfg.Connection.Driver, - storage.DBConnectionString(&cfg.Connection), - ) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return subcommands.ExitFailure - } - defer db.Close() - - migrationDBRepo, err := repositories.NewMigrationDBRepo(db) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return subcommands.ExitFailure - } - - migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return subcommands.ExitFailure - } - - migrationService := services.NewMigrationService(migrationDBRepo, migrationFsRepo) - migrations, err := migrationService.ListMigrations(services.SortOrderAsc) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return subcommands.ExitFailure - } - - for _, migration := range migrations { - fmt.Println(migration) - } - - return subcommands.ExitSuccess -} diff --git a/internal/commands/create.go b/internal/commands/new.go index 57f4c69..be1f49c 100644 --- a/internal/commands/create.go +++ b/internal/commands/new.go @@ -3,67 +3,77 @@ package commands import ( "context" "flag" - "fmt" - "os" "time" "github.com/eugenetriguba/bolt/internal/configloader" "github.com/eugenetriguba/bolt/internal/models" + "github.com/eugenetriguba/bolt/internal/output" "github.com/eugenetriguba/bolt/internal/repositories" "github.com/eugenetriguba/bolt/internal/services" "github.com/google/subcommands" ) -type CreateCmd struct { +type NewCmd struct { message string } -func (*CreateCmd) Name() string { return "create" } -func (*CreateCmd) Synopsis() string { - return "Create a new database migration." +func (*NewCmd) Name() string { + return "new" } -func (*CreateCmd) Usage() string { - return `create [-message]: - Create a new database migration. + +func (*NewCmd) Synopsis() string { + return "create a new database migration" +} + +func (*NewCmd) Usage() string { + return `create [-message|-m]: + Create a new database migration ` } -func (cmd *CreateCmd) SetFlags(f *flag.FlagSet) { +func (cmd *NewCmd) SetFlags(f *flag.FlagSet) { f.StringVar( &cmd.message, "message", "autogenerated", "Message to use for the migration", ) + f.StringVar(&cmd.message, "m", cmd.message, "alias for -message") } -func (cmd *CreateCmd) Execute( +func (cmd *NewCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, ) subcommands.ExitStatus { + consoleOutputter := output.ConsoleOutputter{} + cfg, err := configloader.NewConfig() if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } - migrationService := services.NewMigrationService(nil, migrationFsRepo) + migrationService := services.NewMigrationService( + nil, + migrationFsRepo, + consoleOutputter, + ) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } migration := models.NewMigration(time.Now(), cmd.message) err = migrationService.CreateMigration(migration) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } diff --git a/internal/commands/status.go b/internal/commands/status.go new file mode 100644 index 0000000..c20abd3 --- /dev/null +++ b/internal/commands/status.go @@ -0,0 +1,100 @@ +package commands + +import ( + "context" + "flag" + + "github.com/eugenetriguba/bolt/internal/configloader" + "github.com/eugenetriguba/bolt/internal/output" + "github.com/eugenetriguba/bolt/internal/repositories" + "github.com/eugenetriguba/bolt/internal/services" + "github.com/eugenetriguba/bolt/internal/storage" + "github.com/google/subcommands" +) + +type StatusCmd struct{} + +func (*StatusCmd) Name() string { + return "status" +} + +func (*StatusCmd) Synopsis() string { + return "list the database migrations and their statuses" +} + +func (*StatusCmd) Usage() string { + return `status: + List the database migrations and their statuses + ` +} + +func (m *StatusCmd) SetFlags(f *flag.FlagSet) {} + +func (m *StatusCmd) Execute( + _ context.Context, + f *flag.FlagSet, + _ ...interface{}, +) subcommands.ExitStatus { + consoleOutputter := output.ConsoleOutputter{} + + cfg, err := configloader.NewConfig() + if err != nil { + consoleOutputter.Error(err.Error()) + return subcommands.ExitFailure + } + + db, err := storage.DBConnect( + cfg.Connection.Driver, + storage.DBConnectionString(&cfg.Connection), + ) + if err != nil { + consoleOutputter.Error(err.Error()) + return subcommands.ExitFailure + } + defer db.Close() + + migrationDBRepo, err := repositories.NewMigrationDBRepo(db) + if err != nil { + consoleOutputter.Error(err.Error()) + return subcommands.ExitFailure + } + + migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir) + if err != nil { + consoleOutputter.Error(err.Error()) + return subcommands.ExitFailure + } + + migrationService := services.NewMigrationService( + migrationDBRepo, + migrationFsRepo, + consoleOutputter, + ) + migrations, err := migrationService.ListMigrations(services.SortOrderAsc) + if err != nil { + consoleOutputter.Error(err.Error()) + return subcommands.ExitFailure + } + + if len(migrations) == 0 { + consoleOutputter.Output( + "No migrations have been created.\n" + + "Run 'bolt create' to create your first migration.", + ) + return subcommands.ExitSuccess + } + + headers := []string{"Version", "Message", "Applied"} + rows := make([][]string, len(migrations)) + for i, migration := range migrations { + applied := "" + if migration.Applied { + applied = "X" + } + + rows[i] = []string{migration.Version, migration.Message, applied} + } + + consoleOutputter.Table(headers, rows) + return subcommands.ExitSuccess +} diff --git a/internal/commands/migrate.go b/internal/commands/up.go index 8c86291..c207a83 100644 --- a/internal/commands/migrate.go +++ b/internal/commands/up.go @@ -3,37 +3,42 @@ package commands import ( "context" "flag" - "fmt" - "os" "github.com/eugenetriguba/bolt/internal/configloader" + "github.com/eugenetriguba/bolt/internal/output" "github.com/eugenetriguba/bolt/internal/repositories" "github.com/eugenetriguba/bolt/internal/services" "github.com/eugenetriguba/bolt/internal/storage" "github.com/google/subcommands" ) -type UpgradeCmd struct{} +type UpCmd struct{} -func (*UpgradeCmd) Name() string { return "upgrade" } +func (*UpCmd) Name() string { + return "up" +} + +func (*UpCmd) Synopsis() string { + return "apply migrations against the database" +} -func (*UpgradeCmd) Synopsis() string { return "Upgrade the database to the latest migration." } -func (*UpgradeCmd) Usage() string { - return `upgrade: - Upgrade the database to the latest migration. +func (*UpCmd) Usage() string { + return `up: + Apply migrations against the database ` } -func (m *UpgradeCmd) SetFlags(f *flag.FlagSet) {} +func (m *UpCmd) SetFlags(f *flag.FlagSet) {} -func (m *UpgradeCmd) Execute( +func (m *UpCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, ) subcommands.ExitStatus { + consoleOutputter := output.ConsoleOutputter{} cfg, err := configloader.NewConfig() if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } @@ -42,27 +47,31 @@ func (m *UpgradeCmd) Execute( storage.DBConnectionString(&cfg.Connection), ) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } defer db.Close() migrationDBRepo, err := repositories.NewMigrationDBRepo(db) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(cfg.MigrationsDir) if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } - migrationService := services.NewMigrationService(migrationDBRepo, migrationFsRepo) + migrationService := services.NewMigrationService( + migrationDBRepo, + migrationFsRepo, + consoleOutputter, + ) err = migrationService.ApplyAllMigrations() if err != nil { - fmt.Fprintln(os.Stderr, err) + consoleOutputter.Error(err.Error()) return subcommands.ExitFailure } diff --git a/internal/output/console.go b/internal/output/console.go new file mode 100644 index 0000000..d2946ed --- /dev/null +++ b/internal/output/console.go @@ -0,0 +1,60 @@ +package output + +import ( + "fmt" + "io" + "os" + "text/tabwriter" +) + +type ConsoleOutputter struct { + stdout io.Writer + stderr io.Writer +} + +func NewConsoleOutputter() ConsoleOutputter { + return ConsoleOutputter{stdout: os.Stdout, stderr: os.Stderr} +} + +func (c ConsoleOutputter) Output(message string) error { + _, err := fmt.Fprintln(c.stdout, message) + return err +} + +func (c ConsoleOutputter) Error(message string) error { + _, err := fmt.Fprintln(c.stderr, message) + return err +} + +func (c ConsoleOutputter) Table(headers []string, rows [][]string) error { + w := tabwriter.NewWriter(c.stdout, 4, 4, 4, ' ', 0) + + for _, header := range headers { + _, err := fmt.Fprintf(w, "%s\t", header) + if err != nil { + return err + } + } + if len(headers) > 0 { + _, err := fmt.Fprint(w, "\n") + if err != nil { + return err + } + } + + for _, row := range rows { + for _, cell := range row { + _, err := fmt.Fprintf(w, "%s\t", cell) + if err != nil { + return err + } + } + _, err := fmt.Fprint(w, "\n") + if err != nil { + return err + } + } + + w.Flush() + return nil +} diff --git a/internal/output/console_test.go b/internal/output/console_test.go new file mode 100644 index 0000000..be369ab --- /dev/null +++ b/internal/output/console_test.go @@ -0,0 +1,76 @@ +package output + +import ( + "bytes" + "io" + "testing" + + "gotest.tools/v3/assert" +) + +func NewConsoleOutputterWithWriters(stdout io.Writer, stderr io.Writer) ConsoleOutputter { + return ConsoleOutputter{stdout: stdout, stderr: stderr} +} + +func TestConsoleOutputter_Output(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + consoleOutputter := NewConsoleOutputterWithWriters(&stdout, &stderr) + + consoleOutputter.Output("test string") + + assert.Equal(t, stdout.String(), "test string\n") + assert.Equal(t, stderr.String(), "") +} + +func TestConsoleOutputter_Error(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + consoleOutputter := NewConsoleOutputterWithWriters(&stdout, &stderr) + + consoleOutputter.Error("test string") + + assert.Equal(t, stdout.String(), "") + assert.Equal(t, stderr.String(), "test string\n") +} + +func TestConsoleOutputter_Table(t *testing.T) { + type test struct { + headers []string + rows [][]string + expectedStdout string + } + + tests := []test{ + { + headers: []string{}, + rows: make([][]string, 0), + expectedStdout: "", + }, + { + headers: []string{"Version"}, + rows: [][]string{{"test1"}, {"test2"}}, + expectedStdout: "Version \n" + + "test1 \n" + + "test2 \n", + }, + { + headers: []string{"Version", "Message"}, + rows: [][]string{{"v1", "m1"}, {"v1", "m2"}}, + expectedStdout: "Version Message \n" + + "v1 m1 \n" + + "v1 m2 \n", + }, + } + + for _, tc := range tests { + var stdout bytes.Buffer + var stderr bytes.Buffer + consoleOutputter := NewConsoleOutputterWithWriters(&stdout, &stderr) + + consoleOutputter.Table(tc.headers, tc.rows) + + assert.Equal(t, stdout.String(), tc.expectedStdout) + assert.Equal(t, stderr.String(), "") + } +} diff --git a/internal/output/output.go b/internal/output/output.go new file mode 100644 index 0000000..c51553b --- /dev/null +++ b/internal/output/output.go @@ -0,0 +1,7 @@ +package output + +type Outputter interface { + Output(message string) error + Error(message string) error + Table(header []string, rows [][]string) error +} diff --git a/internal/repositories/migration_db_repo.go b/internal/repositories/migration_db_repo.go index 7f8fc10..6a37e7b 100644 --- a/internal/repositories/migration_db_repo.go +++ b/internal/repositories/migration_db_repo.go @@ -83,7 +83,10 @@ func (mr *MigrationDBRepo) IsApplied(version string) (applied bool, err error) { // and adding the applied migration version into the migrations table. When // successfully applied, the `migration` model's `Applied` field will be set // to true. -func (mr *MigrationDBRepo) Apply(upgradeScript string, migration *models.Migration) error { +func (mr *MigrationDBRepo) Apply( + upgradeScript string, + migration *models.Migration, +) error { tx, err := mr.db.Begin() if err != nil { return err @@ -114,7 +117,10 @@ func (mr *MigrationDBRepo) Apply(upgradeScript string, migration *models.Migrati // Revert reverts a migration by executing the corresponding downgrade script // and deleting the migration version from the migrations table. When successfully // reverted, the `migration` model's `Applied` field will be set to false. -func (mr *MigrationDBRepo) Revert(downgradeScript string, migration *models.Migration) error { +func (mr *MigrationDBRepo) Revert( + downgradeScript string, + migration *models.Migration, +) error { tx, err := mr.db.Begin() if err != nil { return err diff --git a/internal/repositories/migration_db_repo_test.go b/internal/repositories/migration_db_repo_test.go index 264b3be..a38875f 100644 --- a/internal/repositories/migration_db_repo_test.go +++ b/internal/repositories/migration_db_repo_test.go @@ -159,7 +159,10 @@ func TestMigrationDBRepo_Revert(t *testing.T) { assert.NilError(t, err) migration := models.NewMigration(time.Now(), "test") - _, err = db.Exec(`INSERT INTO bolt_migrations(version) VALUES ($1);`, migration.Version) + _, err = db.Exec( + `INSERT INTO bolt_migrations(version) VALUES ($1);`, + migration.Version, + ) assert.NilError(t, err) migration.Applied = true diff --git a/internal/repositories/migration_fs_repo.go b/internal/repositories/migration_fs_repo.go index d347176..8a7ec8a 100644 --- a/internal/repositories/migration_fs_repo.go +++ b/internal/repositories/migration_fs_repo.go @@ -88,7 +88,9 @@ func (mr *MigrationFsRepo) List() (map[string]*models.Migration, error) { return migrations, nil } -func (mr *MigrationFsRepo) ReadUpgradeScript(migration *models.Migration) (string, error) { +func (mr *MigrationFsRepo) ReadUpgradeScript( + migration *models.Migration, +) (string, error) { upgradeScriptPath := filepath.Join( mr.migrationsDirPath, mr.migrationDirname(migration), @@ -97,7 +99,9 @@ func (mr *MigrationFsRepo) ReadUpgradeScript(migration *models.Migration) (strin return mr.readScriptContents(upgradeScriptPath) } -func (mr *MigrationFsRepo) ReadDowngradeScript(migration *models.Migration) (string, error) { +func (mr *MigrationFsRepo) ReadDowngradeScript( + migration *models.Migration, +) (string, error) { downgradeScriptPath := filepath.Join( mr.migrationsDirPath, mr.migrationDirname(migration), diff --git a/internal/repositories/migration_fs_repo_test.go b/internal/repositories/migration_fs_repo_test.go index a0448a5..bb12097 100644 --- a/internal/repositories/migration_fs_repo_test.go +++ b/internal/repositories/migration_fs_repo_test.go @@ -88,8 +88,14 @@ func TestMigrationFsRepo_List(t *testing.T) { repo, err := repositories.NewMigrationFsRepo(tempDir) assert.NilError(t, err) - migration1 := models.NewMigration(time.Date(2020, 10, 12, 1, 1, 1, 1, time.UTC), "migration_1") - migration2 := models.NewMigration(time.Date(2022, 10, 12, 1, 1, 1, 1, time.UTC), "migration_2") + migration1 := models.NewMigration( + time.Date(2020, 10, 12, 1, 1, 1, 1, time.UTC), + "migration_1", + ) + migration2 := models.NewMigration( + time.Date(2022, 10, 12, 1, 1, 1, 1, time.UTC), + "migration_2", + ) err = repo.Create(migration1) assert.NilError(t, err) repo.Create(migration2) diff --git a/internal/services/migration.go b/internal/services/migration.go index de03d3c..ef6a509 100644 --- a/internal/services/migration.go +++ b/internal/services/migration.go @@ -1,22 +1,26 @@ package services import ( + "fmt" "sort" "github.com/eugenetriguba/bolt/internal/models" + "github.com/eugenetriguba/bolt/internal/output" "github.com/eugenetriguba/bolt/internal/repositories" ) type MigrationService struct { - dbRepo *repositories.MigrationDBRepo - fsRepo *repositories.MigrationFsRepo + dbRepo *repositories.MigrationDBRepo + fsRepo *repositories.MigrationFsRepo + outputter output.Outputter } func NewMigrationService( dbRepo *repositories.MigrationDBRepo, fsRepo *repositories.MigrationFsRepo, + outputter output.Outputter, ) *MigrationService { - return &MigrationService{dbRepo: dbRepo, fsRepo: fsRepo} + return &MigrationService{dbRepo: dbRepo, fsRepo: fsRepo, outputter: outputter} } type sortOrder int @@ -42,6 +46,14 @@ func (ms *MigrationService) ApplyAllMigrations() error { } func (ms *MigrationService) ApplyMigration(migration *models.Migration) error { + ms.outputter.Output( + fmt.Sprintf( + "Applying migration %s_%s..", + migration.Version, + migration.Message, + ), + ) + scriptContents, err := ms.fsRepo.ReadUpgradeScript(migration) if err != nil { return err @@ -51,6 +63,13 @@ func (ms *MigrationService) ApplyMigration(migration *models.Migration) error { if err != nil { return err } + ms.outputter.Output( + fmt.Sprintf( + "Successfully applied migration %s_%s!", + migration.Version, + migration.Message, + ), + ) return nil } @@ -71,6 +90,13 @@ func (ms *MigrationService) RevertAllMigrations() error { } func (ms *MigrationService) RevertMigration(migration *models.Migration) error { + ms.outputter.Output( + fmt.Sprintf( + "Reverting migration %s_%s..", + migration.Version, + migration.Message, + ), + ) scriptContents, err := ms.fsRepo.ReadDowngradeScript(migration) if err != nil { return err @@ -80,12 +106,26 @@ func (ms *MigrationService) RevertMigration(migration *models.Migration) error { if err != nil { return err } + ms.outputter.Output( + fmt.Sprintf( + "Successfully reverted migration %s_%s!", + migration.Version, + migration.Message, + ), + ) return nil } func (ms *MigrationService) CreateMigration(migration *models.Migration) error { - return ms.fsRepo.Create(migration) + err := ms.fsRepo.Create(migration) + if err != nil { + return err + } + ms.outputter.Output( + fmt.Sprintf("Created migration %s - %s.", migration.Version, migration.Message), + ) + return nil } func (ms *MigrationService) ListMigrations(order sortOrder) ([]*models.Migration, error) { diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index ba4ae0d..fb9d1f3 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -8,14 +8,15 @@ import ( "github.com/google/subcommands" ) +// Run runs the Bolt CLI and returns the exit code. func Run() int { subcommands.Register(subcommands.HelpCommand(), "") subcommands.Register(subcommands.FlagsCommand(), "") subcommands.Register(subcommands.CommandsCommand(), "") - subcommands.Register(&commands.CreateCmd{}, "") - subcommands.Register(&commands.UpgradeCmd{}, "") - subcommands.Register(&commands.DowngradeCmd{}, "") - subcommands.Register(&commands.ListCmd{}, "") + subcommands.Register(&commands.NewCmd{}, "") + subcommands.Register(&commands.UpCmd{}, "") + subcommands.Register(&commands.DownCmd{}, "") + subcommands.Register(&commands.StatusCmd{}, "") flag.Parse() ctx := context.Background() |