dbtypegen is a tool that generates Go structures from a database schema.
go install github.com/johejo/dbtypegen/cmd/dbtypegen
mkdir example
cd example/
go mod init example
Create schema DDL
schema.sql
CREATE TABLE `user` (
id BIGINT PRIMARY KEY,
created_at DATETIME(3) NOT NULL,
active BOOLEAN DEFAULT NULL,
name VARCHAR(36) NOT NULL
);
dbtypegen -schema schema.sql -out ./db_types_gen.go -package example
Generated file
// Code generated by dbtypegen, DO NOT EDIT.
package example
import (
"time"
)
// User is the type that represents table `user`.
type User struct {
Id int64 `db:"id"`
CreatedAt time.Time `db:"created_at"`
Active bool `db:"active"`
Name string `db:"name"`
}
// Columns returns all columns as joined string
func (t *User) Columns() string {
return "id,created_at,active,name"
}
// ColumnList returns all columns as slice of string.
func (t *User) ColumnList() []string {
return []string{"id", "created_at", "active", "name"}
}
// TableName returns the name of table.
func (t *User) TableName() string {
return "user"
}
// SelectAll returns a part of query like `SELECT id,name FROM people`.
func (t *User) SelectAll() string {
return "SELECT id,created_at,active,name FROM user"
}
// ScanAll returns field's pointers for row.Scan.
func (t *User) ScanAll() []interface{} {
return []interface{}{&t.Id, &t.CreatedAt, &t.Active, &t.Name}
}
INSERT and SELECT
var u User
var b strings.Builder
b.WriteString("INSERT INTO ")
b.WriteString(u.TableName())
b.WriteString(" (")
b.WriteString(u.Columns())
b.WriteString(") ")
b.WriteString("VALUES (?,?,?,?)")
q := b.String()
now := time.Now()
args := []interface{}{1, now, true, "Gopher"}
if _, err := db.ExecContext(ctx, q, args...); err != nil {
panic(err)
}
if err := db.QueryRowContext(ctx, u.SelectAll()+" WHERE id=?", 1).Scan(u.ScanAll()...); err != nil {
panic(err)
}
fmt.Println(u)
// {1 20xx-xx-xx xx:xx:xx.xxx +0000 UTC true Gopher}
MIT
Mitsuo Heijo