erd.sketch

SQL 转 GORM:从 DDL 脚本生成模型

下面不是示意图:这是生成器对左边脚本的真实输出。在编辑器里点「Codegen → GORM」得到的就是同一份代码。

输入schema.sql
CREATE TABLE users (
    id BIGINT NOT NULL PRIMARY KEY,
    email       VARCHAR(255) NOT NULL UNIQUE,
    full_name   VARCHAR(120),
    is_active   BOOLEAN NOT NULL,
    created_at  TIMESTAMP NOT NULL
);

CREATE TABLE orders (
    id BIGINT NOT NULL PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users(id),
    total       DECIMAL(12,2) NOT NULL,
    note        TEXT,
    placed_at   TIMESTAMP NOT NULL
);
输出models.go
import (
	"time"
)

type Users struct {
	ID        int64     `gorm:"column:id;primaryKey"`
	Email     string    `gorm:"column:email;type:varchar(255);not null;unique"`
	FullName  *string   `gorm:"column:full_name;type:varchar(120)"`
	IsActive  bool      `gorm:"column:is_active;not null"`
	CreatedAt time.Time `gorm:"column:created_at;not null"`
}

func (Users) TableName() string { return "users" }

type Orders struct {
	ID       int64     `gorm:"column:id;primaryKey"`
	UserID   int64     `gorm:"column:user_id;not null"`
	Total    float64   `gorm:"column:total;not null"`
	Note     *string   `gorm:"column:note"`
	PlacedAt time.Time `gorm:"column:placed_at;not null"`
	Users    *Users    `gorm:"foreignKey:UserID;references:ID"`
}

func (Orders) TableName() string { return "orders" }
打开编辑器

脚本留在浏览器里:解析和生成都在您的机器上进行,不会上传到服务器。

类型如何对应

在 SQL 里在模型里
BIGINTint64
VARCHAR(255)type:varchar(255)
BOOLEANbool
TIMESTAMPtime.Time
DECIMAL(12,2)float64
TEXT*string
可空字段
*string
列名
column:full_name
关系
foreignKey:UserID;references:ID