GitHub - sunary/sqlize: powerful SQL toolkit; offering parsing, building, and migration capabilities. (original) (raw)

SQLize

github action

English | 中文

SQLize is a powerful migration generation tool that detects differences between two SQL state sources. It simplifies migration creation by comparing an existing SQL schema with Go models, ensuring seamless database updates.

Designed for flexibility, SQLize supports MySQL, PostgreSQL, and SQLite and integrates well with popular Go ORM and migration tools like gorm (gorm tag), golang-migrate/migrate (migration version), and more.

Additionally, SQLize offers advanced features, including Avro Schema export (MySQL only) and ERD diagram generation (MermaidJS).

Conventions

Default Behaviors

SQL Tag Options

Indexing

Embedded Structs

Data Types

// your struct type Record struct { ID int DeletedAt *time.Time }

// => // the struct is declared with a value now := time.Now() Record{DeletedAt: &now}

// or predefined data type type Record struct { ID int DeletedAt *time.Time sql:"type:DATETIME" }

// or using struct supported by "database/sql" type Record struct { ID int DeletedAt sql.NullTime }

Usage

package main

import ( "fmt" "log" "os"

"github.com/sunary/sqlize"

)

func main() { migrationFolder := "migrations/" sqlLatest := sqlize.NewSqlize(sqlize.WithSqlTag("sql"), sqlize.WithMigrationFolder(migrationFolder), sqlize.WithCommentGenerate())

ms := YourModels() // TODO: implement YourModels() function
err := sqlLatest.FromObjects(ms...)
if err != nil {
    log.Fatal("sqlize FromObjects", err)
}
sqlVersion := sqlLatest.HashValue()

sqlMigrated := sqlize.NewSqlize(sqlize.WithMigrationFolder(migrationFolder))
err = sqlMigrated.FromMigrationFolder()
if err != nil {
    log.Fatal("sqlize FromMigrationFolder", err)
}

sqlLatest.Diff(*sqlMigrated)

fmt.Println("sql version", sqlVersion)

fmt.Println("\n\n### migration up")
migrationUp := sqlLatest.StringUp()
fmt.Println(migrationUp)

fmt.Println("\n\n### migration down")
fmt.Println(sqlLatest.StringDown())

initVersion := false
if initVersion {
    log.Println("write to init version")
    err = sqlLatest.WriteFilesVersion("new version", 0, false)
    if err != nil {
        log.Fatal("sqlize WriteFilesVersion", err)
    }
}

if len(os.Args) > 1 {
    log.Println("write to file", os.Args[1])
    err = sqlLatest.WriteFilesWithVersion(os.Args[1], sqlVersion, false)
    if err != nil {
        log.Fatal("sqlize WriteFilesWithVersion", err)
    }
}

}