DBML-go is a Go parser for DBML syntax.
Go get
go get github.com/duythinht/dbml-go/...
package main
import (
"fmt"
"os"
"github.com/duythinht/dbml-go/parser"
"github.com/duythinht/dbml-go/scanner"
)
func main() {
f, _ := os.Open("test.dbml")
s := scanner.NewScanner(f)
parser := parser.NewParser(s)
dbml, err := parser.Parse()
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}
// process dbml here
}
go get github.com/duythinht/dbml-go/cmd/dbml-go-gen-model
Usage:
dbml-gen-go-model [flags]
Flags:
-E, --exclude string regex for exclude "from" files. Only applied if "from" is a directory
-t, --fieldtags stringArray go field tags (default [db,json,mapstructure])
-f, --from string source of dbml, can be https://dbdiagram.io/... | fire_name.dbml (default "database.dbml")
--gen-table-name should generate "TableName" function
-h, --help help for dbml-gen-go-model
-o, --out string output folder (default "model")
-p, --package string single for multiple files (default "model")
--recursive recursive search directory. Only applied if "from" is a directory
--remember-alias should remember table alias. Only applied if "from" is a directory
input:
// database.dbml
Table users as user {
id int [pk, unique, increment] // auto-increment
full_name varchar [not null, unique, default: 1]
created_at timestamp
country_code int
Note: 'This is simple note'
}
Run:
mkdir -p model
dbml-gen-go-model -f database.dbml -o model -p model
output: model/users.table.go
// Code generated by dbml-gen-gorm. DO NOT EDIT.
package model
type User struct {
ID int `gorm:"column:id" json:"id" mapstructure:"id"`
FullName string `gorm:"column:full_name" json:"full_name" mapstructure:"full_name"`
CreatedAt int `gorm:"column:created_at" json:"created_at" mapstructure:"created_at"`
CountryCode int `gorm:"column:country_code" json:"country_code" mapstructure:"country_code"`
}
// table 'user' columns list struct
type userTableColumns struct {
ID string
FullName string
CreatedAt string
CountryCode string
}
// table 'user' columns list info
var UserTableColumns = userTableColumns{
CountryCode: "user.country_code",
CreatedAt: "user.created_at",
FullName: "user.full_name",
ID: "user.id",
}
// AllColumns return list columns name for table 'user'
func (*User) AllColumns() []string {
return []string{"id", "full_name", "created_at", "country_code"}
}
// TableName return table name
func (*User) TableName() string {
return "user"
}
type UserSlice []User