Database Migrations
The migrate package provides a simple, file-based schema migration tool. It reads .cql files from a directory or fs.FS and applies them in lexicographical order.
Migration Files
Create a folder (e.g., cql/) and add your CQL files. Naming them with a numeric prefix is recommended to control order.
cql/001_init.cql
CREATE TABLE users (id uuid PRIMARY KEY, name text);
cql/002_add_email.cql
ALTER TABLE users ADD email text;
Running Migrations
Use migrate.FromFS to apply the migrations. This will create a gocqlx_migrate table in your keyspace to track applied versions.
import (
"embed"
"github.com/scylladb/gocqlx/v3/migrate"
)
//go:embed cql/*.cql
var cqlFiles embed.FS
func main() {
// ... session setup ...
if err := migrate.FromFS(ctx, session, cqlFiles); err != nil {
log.Fatal("Migrate:", err)
}
}
Callbacks
You can execute Go code during migrations (e.g., for data backfills that are hard to do in CQL) using special comments in your CQL files.
CQL File:
-- CALL my_custom_callback;
Go Code:
func myCallback(ctx context.Context, session gocqlx.Session, ev migrate.CallbackEvent, name string) error {
// Execute custom logic
return nil
}
// Register the callback
reg := migrate.CallbackRegister{}
reg.Add(migrate.CallComment, "my_custom_callback", myCallback)
migrate.Callback = reg.Callback