rubenv / sql-migrate

SQL schema migration tool for Go.
MIT License
3.18k stars 273 forks source link

Add hook support #120

Open diegobernardes opened 6 years ago

diegobernardes commented 6 years ago

Today the package already know some special comments, I'm proposing to add hook points as special comments where plain Go code could execute along the migration. This is very useful during transformations caused by the migration.

-- +migrate Up
ALTER TABLE users ADD COLUMN confirmation BOOLEAN;
-- +hook addConfirmation

-- +migrate Down
ALTER TABLE users DROP COLUMN confirmation BOOLEAN;

Using the standalone cli, don't know how this could work, but, using the library is kinda easy:

type hook func(db *sql.DB, tx *sql.Tx) error

migrations := &migrate.MemoryMigrationSource{
    Migrations: []*migrate.Migration{
        &migrate.Migration{
            Id:   "123",
            Up:   []string{"CREATE TABLE people (id int)"},
            Down: []string{"DROP TABLE people"},
            Hook: map[string]hook{"addConfirmation": addConfirmation},
        },
    },
}

func addConfirmation(db *sql.DB, tx *sql.Tx) error {
  // custom logic here
  return nil
}
rubenv commented 6 years ago

Hi, could you explain what you mean by this?

diegobernardes commented 6 years ago

Yes, sorry, clicked in the create by mistake, 1 sec, writing the message.

rubenv commented 6 years ago

I like the idea of hooks and I don't mind that they might not be available through the CLI.

If we do add them it's probably best to scan for them when using the CLI and refuse to operate when a hook is detected. Just to make sure things either happen correctly or not at all.

There's a real danger for abuse though, so they should be used sparingly.