Added Cassandra URL flag to enable multi statement migrations

This commit is contained in:
Alan Graham 2018-07-20 13:27:54 +00:00
parent c4b81d1210
commit 327822c29a
2 changed files with 17 additions and 6 deletions

View File

@ -3,6 +3,7 @@
* Drop command will not work on Cassandra 2.X because it rely on
system_schema table which comes with 3.X
* Other commands should work properly but are **not tested**
* The Cassandra driver (gocql) does not natively support executing multipe statements in a single query. To allow for multiple statements in a single migration, you can use the `x-multi-statement` param. Note that this simply splits the migration into separately-executed statements by a semi-colon ';'. The queries are also not executed in any sort of transaction/batch, meaning you are responsible for fixing partial migrations.
## Usage
@ -12,6 +13,7 @@ system_schema table which comes with 3.X
| URL Query | Default value | Description |
|------------|-------------|-----------|
| `x-migrations-table` | schema_migrations | Name of the migrations table |
| `x-multi-statement` | false | Enable multiple statements to be ran in a single migration (See note above) |
| `port` | 9042 | The port to bind to |
| `consistency` | ALL | Migration consistency
| `protocol` | | Cassandra protocol version (3 or 4)

View File

@ -31,6 +31,7 @@ var (
type Config struct {
MigrationsTable string
KeyspaceName string
MultiStatementEnabled bool
}
type Cassandra struct {
@ -127,6 +128,7 @@ func (c *Cassandra) Open(url string) (database.Driver, error) {
return WithInstance(session, &Config{
KeyspaceName: strings.TrimPrefix(u.Path, "/"),
MigrationsTable: u.Query().Get("x-migrations-table"),
MultiStatementEnabled: u.Query().Get("x-multi-statement") == "true",
})
}
@ -156,13 +158,20 @@ func (c *Cassandra) Run(migration io.Reader) error {
// run migration
query := string(migr[:])
// split query by semi-colon
queries := strings.Split(query, ";\n")
if c.config.MultiStatementEnabled {
// split query by semi-colon
queries := strings.Split(query, ";")
for _, q := range(queries) {
tq := strings.TrimSpace(q)
if (tq == "") { continue }
if err := c.session.Query(tq).Exec(); err != nil {
for _, q := range(queries) {
tq := strings.TrimSpace(q)
if (tq == "") { continue }
if err := c.session.Query(tq).Exec(); err != nil {
// TODO: cast to Cassandra error and get line number
return database.Error{OrigErr: err, Err: "migration failed", Query: migr}
}
}
} else {
if err := c.session.Query(query).Exec(); err != nil {
// TODO: cast to Cassandra error and get line number
return database.Error{OrigErr: err, Err: "migration failed", Query: migr}
}