SQL to GORM: models from a DDL script
What follows is not a mock-up: it is the real output of the generator for the script on the left. You get the same code in the editor under “Codegen → GORM”.
The inputschema.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
);What comes outmodels.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" }Open the editor
The script stays in the browser: both parsing and generation run on your machine, nothing goes to a server.
How the types land
| in SQL | in the model |
|---|---|
BIGINT | int64 |
VARCHAR(255) | type:varchar(255) |
BOOLEAN | bool |
TIMESTAMP | time.Time |
DECIMAL(12,2) | float64 |
TEXT | *string |
- Optional field
*string- Column name
column:full_name- Relation
foreignKey:UserID;references:ID