golang-migrate / migrate

Database migrations. CLI and Golang library.
Other
15.21k stars 1.4k forks source link

Failed parsing go migration files from CLI #1177

Open emilianosantucci opened 1 week ago

emilianosantucci commented 1 week ago

Describe the Bug Failed to use .go files as migration files with CLI

Steps to Reproduce

  1. Create (or use) a clean PostgreSQL db (ex. mydb)
  2. Create this project structure:

    migrations/
    ├── 1_create_users_table.up.go
    ├── 1_create_users_table.down.go
    ├── 2_add_last_login_column.up.go
    └── 2_add_last_login_column.down.go

    Each file contains go code like below:

    package migrations
    
    import (
          "database/sql"
    )
    
    func Up(db *sql.DB) error {
          _, err := db.Exec(`
                  ALTER TABLE users
                  ADD COLUMN last_login TIMESTAMP WITH TIME ZONE;
          `)
          return err
    }
  3. Execute the migrate CLI:
    migrate -database "postgres://user:password@host:port/mydb" -path file://./migrations up

Expected Behavior Migrate interprets migration files and execute them appropriately

Migrate Version v4.18.1

Loaded Source Drivers file

Loaded Database Drivers postgres

Go Version go version go1.23.1 darwin/arm64

Stacktrace

error: migration failed: syntax error at or near "package" (column 1) in line 1: package migrations

import (

    "database/sql"

)

func Up(db *sql.DB) error {

    _, err := db.Exec(`

                select 1;

        `)

    return err

}

 (details: pq: syntax error at or near "package")

Additional context I don't know if really is it a bug, a wrong use of the CLI or my mistake. I have not found any official documentation on using go, instead of sql, for migration files.

My goal is using mapper integrated with GORM and Uber FX to automate db migrations process. The usage of SQL files is not a suitable options for my project 'cause I can't use GORM AutoMigrate (+ custom logic) to handle db versioning.

joschi commented 22 hours ago

Migrations typically have to contain valid SQL.

I am not aware that Go code would be used by any driver currently available in this project.

There are open issues and PRs for that, but nothing merged yet.

Where did you read that migrations can consist of Go code?