adding verbose output for statement execution (#138)

* adding verbose output for statement execution

* fixing lint and redefined v flag

* changing name due to inherited verbose flag and updating README

* linting

* moving verbose flag to subcommand, removing driver verbose, adding tests

* fixing README, cleaning up spacing
This commit is contained in:
Viswesh Periyasamy 2020-06-25 12:26:09 -07:00 committed by GitHub
parent 5e128ae6a6
commit 24705c5d01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 65 additions and 3 deletions

View file

@ -30,6 +30,7 @@ type DB struct {
DatabaseURL *url.URL
MigrationsDir string
SchemaFile string
Verbose bool
WaitBefore bool
WaitInterval time.Duration
WaitTimeout time.Duration
@ -304,8 +305,11 @@ func (db *DB) Migrate() error {
execMigration := func(tx Transaction) error {
// run actual migration
if _, err := tx.Exec(up.Contents); err != nil {
result, err := tx.Exec(up.Contents)
if err != nil {
return err
} else if db.Verbose {
printVerbose(result)
}
// record migration
@ -425,8 +429,11 @@ func (db *DB) Rollback() error {
execMigration := func(tx Transaction) error {
// rollback migration
if _, err := tx.Exec(down.Contents); err != nil {
result, err := tx.Exec(down.Contents)
if err != nil {
return err
} else if db.Verbose {
printVerbose(result)
}
// remove migration record

View file

@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/kami-zh/go-capturer"
"github.com/stretchr/testify/require"
)
@ -161,9 +162,10 @@ func checkWaitCalled(t *testing.T, u *url.URL, command func() error) {
u.Host = oldHost
}
func TestWaitBefore(t *testing.T) {
func testWaitBefore(t *testing.T, verbose bool) {
u := postgresTestURL(t)
db := newTestDB(t, u)
db.Verbose = verbose
db.WaitBefore = true
// so that checkWaitCalled returns quickly
db.WaitInterval = time.Millisecond
@ -200,6 +202,24 @@ func TestWaitBefore(t *testing.T) {
checkWaitCalled(t, u, db.DumpSchema)
}
func TestWaitBefore(t *testing.T) {
testWaitBefore(t, false)
}
func TestWaitBeforeVerbose(t *testing.T) {
output := capturer.CaptureOutput(func() {
testWaitBefore(t, true)
})
require.Contains(t, output,
`Applying: 20151129054053_test_migration.sql
Rows affected: 1
Applying: 20200227231541_test_posts.sql
Rows affected: 0`)
require.Contains(t, output,
`Rolling back: 20200227231541_test_posts.sql
Rows affected: 0`)
}
func testURLs(t *testing.T) []*url.URL {
return []*url.URL{
postgresTestURL(t),

View file

@ -127,3 +127,14 @@ func queryColumn(db *sql.DB, query string) ([]string, error) {
return result, nil
}
func printVerbose(result sql.Result) {
lastInsertId, err := result.LastInsertId()
if err == nil {
fmt.Printf("Last insert ID: %d\n", lastInsertId)
}
rowsAffected, err := result.RowsAffected()
if err == nil {
fmt.Printf("Rows affected: %d\n", rowsAffected)
}
}