Warning
This project is in beta. The API is subject to changes and may break.
dbx is a database schema migration library for Go that lets you manage database schemas using Go code instead of SQL.
- Database inspection: Introspect existing database schemas
- Schema comparison: Compare schemas and generate migration statements
- Built on
database/sql
: Works with standard Go database drivers - Automatic SQL generation: Automatically generate SQL statements for schema changes
Introspect an existing database schema:
import (
_ "github.com/lib/pq"
"github.com/swiftcarrot/dbx/postgresql"
"github.com/swiftcarrot/dbx/schema"
)
db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost:5432/dbx_test?sslmode=disable")
pg := postgresql.New()
source, err := pg.Inspect(db)
Define a target schema and compare with current schema:
target := schema.NewSchema()
target.CreateTable("user", func(t *schema.Table) {
t.Column("name", &schema.TextType{}, schema.NotNull)
t.Index("users_name_idx", []string{"name"})
})
changes, err := schema.Diff(source, target)
Generate and execute SQL from schema changes:
for _, change := range changes {
sql := pg.GenerateSQL(change)
_, err := db.Exec(sql)
}
You can define columns using convenient predefined helpers, or use the generic Column
method with any supported type. All types accept optional column options (e.g., NotNull
, Default(...)
).
Go Method | SQL Type | Example Usage |
---|---|---|
String |
VARCHAR(255) | t.String("name") |
Text |
TEXT | t.Text("bio") |
Integer |
INTEGER | t.Integer("age") |
BigInt |
BIGINT | t.BigInt("credit") |
Float |
FLOAT | t.Float("weight") |
Decimal |
DECIMAL | t.Decimal("balance") |
DateTime |
TIMESTAMP | t.DateTime("created_at") |
Time |
TIME | t.Time("time") |
Date |
DATE | t.Date("birthday") |
Binary |
BLOB/BINARY | t.Binary("bin") |
Boolean |
BOOLEAN | t.Boolean("verified") |
You can also use the generic method:
t.Column("column_name", &schema.TextType{}, schema.NotNull)
Example:
sch.CreateTable("users", func (t *schema.Table) {
t.String("name")
t.Text("bio")
t.Integer("age")
t.BigInt("credit")
t.Float("weight")
t.Decimal("balance")
t.DateTime("created_at")
t.Time("time")
t.Date("birthday")
t.Binary("bin")
t.Boolean("verified")
})
import (
_ "github.com/lib/pq"
"github.com/swiftcarrot/dbx/postgresql"
)
pg := postgresql.New()
import (
_ "github.com/go-sql-driver/mysql"
"github.com/swiftcarrot/dbx/mysql"
)
my := mysql.New()
import (
_ "github.com/mattn/go-sqlite3"
"github.com/swiftcarrot/dbx/sqlite"
)
s := sqlite.New()
For other dialect support, feel free to create an issue.
The official dbx documentation is currently in development. In the meantime, you can:
- Read and ask questions on the DeepWiki page
- Open an issue for bug reports or feature requests
- Join our Discord community for real-time discussions and support
This project is licensed under the Apache License - see the LICENSE file for details.