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에서 | 모델에서 |
|---|---|
BIGINT | int64 |
VARCHAR(255) | type:varchar(255) |
BOOLEAN | bool |
TIMESTAMP | time.Time |
DECIMAL(12,2) | float64 |
TEXT | *string |
- 널 허용 필드
*string- 컬럼 이름
column:full_name- 관계
foreignKey:UserID;references:ID