erd.sketch

SQL에서 TypeORM으로: DDL 스크립트로 모델 만들기

아래는 예시 그림이 아니라 왼쪽 스크립트에 대한 생성기의 실제 출력입니다. 편집기에서 「Codegen → TypeORM」을 누르면 같은 코드가 나옵니다.

입력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
);
결과entities.ts
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn } from "typeorm";

@Entity("users")
export class Users {
  @PrimaryColumn({ type: "bigint" })
  id!: string;

  @Column({ type: "varchar", length: 255, unique: true })
  email!: string;

  @Column({ type: "varchar", length: 120, nullable: true, name: "full_name" })
  fullName!: string | null;

  @Column({ type: "boolean", name: "is_active" })
  isActive!: boolean;

  @Column({ type: "timestamp", name: "created_at" })
  createdAt!: Date;
}

@Entity("orders")
export class Orders {
  @PrimaryColumn({ type: "bigint" })
  id!: string;

  @Column({ type: "bigint", name: "user_id" })
  userId!: string;

  @Column({ type: "decimal", precision: 12, scale: 2 })
  total!: number;

  @Column({ type: "text", nullable: true })
  note!: string | null;

  @Column({ type: "timestamp", name: "placed_at" })
  placedAt!: Date;

  @ManyToOne(() => Users)
  @JoinColumn({ name: "user_id" })
  users!: Users;
}
편집기 열기

스크립트는 브라우저에 남습니다. 해석도 생성도 사용자의 기기에서 이뤄지고 서버로는 아무것도 가지 않습니다.

타입이 어떻게 대응되나

SQL에서모델에서
BIGINTstring
VARCHAR(255)string
BOOLEANboolean
TIMESTAMPDate
DECIMAL(12,2)number
TEXTstring | null
널 허용 필드
nullable: true
컬럼 이름
name: "full_name"
관계
@ManyToOne(() => Users)