이 페이지는 drizzle 버전 1.0.0-beta.2 이상에서 사용 가능한 개념을 설명합니다.
CockroachDB 컬럼 타입
npm i drizzle-orm@beta
npm i drizzle-kit@beta -D
모든 타입에 대한 네이티브 지원을 제공하지만, 충분하지 않다면 **커스텀 타입**을 생성할 수 있습니다.
이 문서의 모든 예제는 데이터베이스 컬럼명 별칭을 사용하지 않으며, 컬럼명은 TypeScript 키로부터 생성됩니다.
원한다면 컬럼명에 데이터베이스 별칭을 사용할 수 있으며, casing 파라미터를 사용하여 Drizzle의 매핑 전략을 정의할 수도 있습니다.
자세한 내용은 여기에서 확인할 수 있습니다.
bigint
int int8 int64 integer
부호 있는 8바이트 정수
2^31보다 크지만 2^53보다 작은 값을 예상한다면, mode: 'number'를 사용하여 bigint 대신 JavaScript number로 처리할 수 있습니다.
import { bigint, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
bigint: bigint({ mode: 'number' })
});
// will be inferred as `number`
bigint: bigint({ mode: 'number' })
// will be inferred as `bigint`
bigint: bigint({ mode: 'bigint' })CREATE TABLE "table" (
"bigint" bigint
);import { sql } from "drizzle-orm";
import { bigint, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
bigint1: bigint().default(10),
bigint2: bigint().default(sql`'10'::bigint`)
});CREATE TABLE "table" (
"bigint1" bigint DEFAULT 10,
"bigint2" bigint DEFAULT '10'::bigint
);smallint
smallint int2
작은 범위의 부호 있는 2바이트 정수
import { smallint, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
smallint: smallint()
});CREATE TABLE "table" (
"smallint" smallint
);import { sql } from "drizzle-orm";
import { smallint, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
smallint1: smallint().default(10),
smallint2: smallint().default(sql`'10'::smallint`)
});CREATE TABLE "table" (
"smallint1" smallint DEFAULT 10,
"smallint2" smallint DEFAULT '10'::smallint
);int4
부호 있는 4바이트 정수
import { int4, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
int4: int4()
});
CREATE TABLE "table" (
"int4" int4
);import { sql } from "drizzle-orm";
import { int4, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
int1: int4().default(10),
int2: int4().default(sql`'10'::int4`)
});CREATE TABLE "table" (
"int1" int4 DEFAULT 10,
"int2" int4 DEFAULT '10'::int4
);int8
**bigint**의 별칭입니다.
int2
**smallint**의 별칭입니다.
---
bool
Cockroach는 표준 SQL 타입 bool을 제공합니다.
자세한 정보는 공식 Cockroach **문서**를 참조하세요.
import { bool, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
boolean: bool()
});
CREATE TABLE "table" (
"boolean" bool
);---
string
text varchar, char
STRING 데이터 타입은 유니코드 문자열을 저장합니다.
PostgreSQL 호환성을 위해 CockroachDB는 다음 STRING 관련 타입과 별칭을 지원합니다:
VARCHAR (별칭 CHARACTER VARYING)
CHAR (별칭 CHARACTER)
NAME
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
{ enum: ["value1", "value2"] } 설정을 정의하여 insert와 select 타입을 추론할 수 있으며, 이는 런타임 값을 검사하지 않습니다.
import { string, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
stringColumn: string(), // equivalent to `text` PostgreSQL type
stringColumn1: string({ length: 256 }), // equivalent to `varchar(256)` PostgreSQL type
});
// will be inferred as text: "value1" | "value2" | null
stringColumn: string({ enum: ["value1", "value2"] })CREATE TABLE "table" (
"stringColumn" string,
"stringColumn1" string(256),
);text
CockroachDB의 STRING 별칭입니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
{ enum: ["value1", "value2"] } 설정을 정의하여 insert와 select 타입을 추론할 수 있으며, 이는 런타임 값을 검사하지 않습니다.
import { text, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
text: text()
});
// will be inferred as text: "value1" | "value2" | null
text: text({ enum: ["value1", "value2"] })CREATE TABLE "table" (
"text" text
);varchar
character varying(n) varchar(n)
PostgreSQL 호환성을 위해 사용되는 STRING 별칭입니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
{ enum: ["value1", "value2"] } 설정을 정의하여 insert와 select 타입을 추론할 수 있으며, 이는 런타임 값을 검사하지 않습니다.
PostgreSQL 문서에 따르면 length 파라미터는 선택사항입니다.
import { varchar, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
varchar1: varchar(),
varchar2: varchar({ length: 256 }),
});
// will be inferred as text: "value1" | "value2" | null
varchar: varchar({ enum: ["value1", "value2"] }),CREATE TABLE "table" (
"varchar1" varchar,
"varchar2" varchar(256)
);char
character(n) char(n)
PostgreSQL 호환성을 위해 사용되는 STRING 별칭입니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
{ enum: ["value1", "value2"] } 설정을 정의하여 insert와 select 타입을 추론할 수 있으며, 이는 런타임 값을 검사하지 않습니다.
PostgreSQL 문서에 따르면 length 파라미터는 선택사항입니다.
import { char, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
char1: char(),
char2: char({ length: 256 }),
});
// will be inferred as text: "value1" | "value2" | null
char: char({ enum: ["value1", "value2"] }),CREATE TABLE "table" (
"char1" char,
"char2" char(256)
);---
https://www.cockroachlabs.com/docs/stable/float
decimal
numeric decimal dec
DECIMAL 데이터 타입은 정확한 고정 소수점 숫자를 저장합니다. 이 타입은 금전 데이터와 같이 정확한 정밀도를 유지하는 것이 중요할 때 사용됩니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { decimal, cockroachTable } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
decimal1: decimal(),
decimal2: decimal({ precision: 100 }),
decimal3: decimal({ precision: 100, scale: 20 }),
decimalNum: decimal({ mode: 'number' }),
decimalBig: decimal({ mode: 'bigint' }),
});CREATE TABLE "table" (
"decimal1" decimal,
"decimal2" decimal(100),
"decimal3" decimal(100, 20),
"decimalNum" decimal,
"decimalBig" decimal
);numeric
**decimal**의 별칭입니다.
float
float float8 double precision
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { sql } from "drizzle-orm";
import { float, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
float1: float(),
float2: float().default(10.10),
float3: float().default(sql`'10.10'::float`),
});CREATE TABLE "table" (
"float1" float,
"float2" float default 10.10,
"float3" float default '10.10'::float
);real
real float4
단정밀도 부동소수점 숫자 (4바이트)
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { sql } from "drizzle-orm";
import { real, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
real1: real(),
real2: real().default(10.10),
real3: real().default(sql`'10.10'::real`),
});CREATE TABLE "table" (
"real1" real,
"real2" real default 10.10,
"real3" real default '10.10'::real
);double precision
**float**의 별칭입니다.
---
jsonb
jsonb
JSONB 데이터 타입은 JSON (JavaScript Object Notation) 데이터를 JSONB 값의 바이너리 표현으로 저장하며, 공백, 중복 키, 키 순서를 제거합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { jsonb, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
jsonb1: jsonb(),
jsonb2: jsonb().default({ foo: "bar" }),
jsonb3: jsonb().default(sql`'{foo: "bar"}'::jsonb`),
});CREATE TABLE "table" (
"jsonb1" jsonb,
"jsonb2" jsonb default '{"foo": "bar"}'::jsonb,
"jsonb3" jsonb default '{"foo": "bar"}'::jsonb
);json 객체 추론을 위해 .$type<..>()을 지정할 수 있으며, 이는 런타임 값을 검사하지 않습니다.
기본값, 삽입 및 조회 스키마에 대한 컴파일 타임 보호를 제공합니다.
// will be inferred as { foo: string }
jsonb: jsonb().$type<{ foo: string }>();
// will be inferred as string[]
jsonb: jsonb().$type<string[]>();
// won't compile
jsonb: jsonb().$type<string[]>().default({});---
bit
bit
BIT 데이터 타입은 비트 배열을 저장합니다. BIT는 길이가 고정되어 있습니다.
크기
BIT 값의 비트 수는 다음과 같이 결정됩니다:
| Type declaration | Logical size |
|---|---|
| BIT | 1 bit |
| BIT(N) | N bits |
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { sql } from "drizzle-orm";
import { cockroachTable, bit } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
bit1: bit(),
bit2: bit({ length: 15 }),
bit3: bit({ length: 15 }).default('10011'),
bit4: bit({ length: 15 }).default(sql`'10011'`)
});CREATE TABLE "table" (
"bit1" bit,
"bit2" bit(15),
"bit3" bit(15) DEFAULT '10011',
"bit4" bit(15) DEFAULT '10011'
);
varbit
varbit
VARBIT 데이터 타입은 비트 배열을 저장합니다. VARBIT는 길이가 가변적입니다.
크기
VARBIT 값의 비트 수는 다음과 같이 결정됩니다:
| Type declaration | Logical size |
|---|---|
| VARBIT | variable with no maximum |
| VARBIT(N) | variable with a maximum of N bits |
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { sql } from "drizzle-orm";
import { cockroachTable, bit } from "drizzle-orm/cockroach-core";
export const table = cockroachTable('table', {
varbit1: varbit(),
varbit2: varbit({ length: 15 }),
varbit3: varbit({ length: 15 }).default('10011'),
varbit4: varbit({ length: 15 }).default(sql`'10011'`)
});CREATE TABLE "table" (
"varbit1" varbit,
"varbit2" varbit(15),
"varbit3" varbit(15) DEFAULT '10011',
"varbit4" varbit(15) DEFAULT '10011'
);---
uuid
uuid
UUID (Universally Unique Identifier) 데이터 타입은 공간과 시간에 걸쳐 고유한 128비트 값을 저장합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { uuid, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
uuid1: uuid(),
uuid2: uuid().defaultRandom(),
uuid3: uuid().default('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11')
});CREATE TABLE "table" (
"uuid1" uuid,
"uuid2" uuid default gen_random_uuid(),
"uuid3" uuid default 'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11'
);---
time
time timetz time with timezone time without timezone
TIME 데이터 타입은 UTC 기준 하루 중 시각을 저장합니다.
TIMETZ 데이터 타입은 UTC로부터의 시간대 오프셋을 포함한 하루 중 시각을 저장합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { time, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
time1: time(),
time2: time({ withTimezone: true }),
time3: time({ precision: 6 }),
time4: time({ precision: 6, withTimezone: true })
});CREATE TABLE "table" (
"time1" time,
"time2" time with timezone,
"time3" time(6),
"time4" time(6) with timezone
);timestamp
timestamp timestamptz timestamp with time zone timestamp without time zone
TIMESTAMP와 TIMESTAMPTZ 데이터 타입은 UTC 기준 날짜와 시간 쌍을 저장합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { sql } from "drizzle-orm";
import { timestamp, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
timestamp1: timestamp(),
timestamp2: timestamp({ precision: 6, withTimezone: true }),
timestamp3: timestamp().defaultNow(),
timestamp4: timestamp().default(sql`now()`),
});CREATE TABLE "table" (
"timestamp1" timestamp,
"timestamp2" timestamp (6) with time zone,
"timestamp3" timestamp default now(),
"timestamp4" timestamp default now()
);date 또는 string 추론 모드를 지정할 수 있습니다:
// will infer as date
timestamp: timestamp({ mode: "date" }),
// will infer as string
timestamp: timestamp({ mode: "string" }),
string모드는 어떠한 매핑도 수행하지 않습니다. 이 모드는 개발자가 필요에 따라 날짜와 날짜 매핑을 직접 처리할 수 있도록 Drizzle ORM에 추가되었습니다. Drizzle은 원시 날짜를 문자열로 데이터베이스에그리고 데이터베이스로부터전달하므로, 동작은 가능한 한 예측 가능하고 데이터베이스 동작과 100% 일치해야 합니다.
date모드는 날짜를 다루는 일반적인 방법입니다. Drizzle이 데이터베이스와 JS Date 객체 간의 모든 매핑을 처리합니다.
date
date
DATE 데이터 타입은 연도, 월, 일을 저장합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { date, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
date: date(),
});CREATE TABLE "table" (
"date" date
);date 또는 string 추론 모드를 지정할 수 있습니다:
// will infer as date
date: date({ mode: "date" }),
// will infer as string
date: date({ mode: "string" }),interval
interval
시간 범위를 나타내는 값을 저장합니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { interval, cockroachTable } from "drizzle-orm/cockroach-core";
const table = cockroachTable('table', {
interval1: interval(),
interval2: interval({ fields: 'day' }),
interval3: interval({ fields: 'month' , precision: 6 }),
});
CREATE TABLE "table" (
"interval1" interval,
"interval2" interval day,
"interval3" interval(6) month
);---
enum
enum enumerated types
열거형(enum) 타입은 정적이고 순서가 있는 값들의 집합으로 구성된 데이터 타입입니다.
여러 프로그래밍 언어에서 지원하는 enum 타입과 동일합니다.
enum 타입의 예로는 요일이나 데이터의 상태 값 집합이 있습니다.
자세한 정보는 공식 CockroachDB **문서**를 참조하세요.
import { cockroachEnum, cockroachTable } from "drizzle-orm/cockroach-core";
export const moodEnum = cockroachEnum('mood', ['sad', 'ok', 'happy']);
export const table = cockroachTable('table', {
mood: moodEnum(),
});CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
CREATE TABLE "table" (
"mood" mood
);---
Customizing data type
모든 컬럼 빌더는 .$type() 메서드를 제공하며, 이를 통해 컬럼의 데이터 타입을 커스터마이징할 수 있습니다.
이는 예를 들어 unknown 또는 브랜드 타입과 함께 사용할 때 유용합니다:
type UserId = number & { __brand: 'user_id' };
type Data = {
foo: string;
bar: number;
};
const users = cockroachTable('users', {
id: int().$type<UserId>().primaryKey(),
jsonField: json().$type<Data>(),
});Identity Columns
이 기능을 사용하려면 drizzle-orm@0.32.0 이상과 drizzle-kit@0.23.0 이상이 필요합니다.
PostgreSQL과 CockroachDB는 컬럼에 대해 고유한 정수 값을 자동으로 생성하는 방법으로 identity 컬럼을 지원합니다. 이 값들은 시퀀스를 사용하여 생성되며 GENERATED AS IDENTITY 절을 사용하여 정의할 수 있습니다.
Identity 컬럼 타입
GENERATED ALWAYS AS IDENTITY: 데이터베이스가 항상 컬럼 값을 생성합니다. OVERRIDING SYSTEM VALUE 절을 사용하지 않는 한 이 컬럼에 수동 삽입이나 업데이트는 허용되지 않습니다.GENERATED BY DEFAULT AS IDENTITY: 데이터베이스가 기본적으로 값을 생성하지만, 수동 값도 삽입하거나 업데이트할 수 있습니다. 수동 값이 제공되면 시스템 생성 값 대신 해당 값이 사용됩니다.
사용 예제
import { pgTable, integer, text } from 'drizzle-orm/pg-core'
export const ingredients = pgTable("ingredients", {
id: integer().primaryKey().generatedAlwaysAsIdentity({ startWith: 1000 }),
name: text().notNull(),
description: text(),
});.generatedAlwaysAsIdentity() 함수에서 시퀀스에 사용 가능한 모든 속성을 지정할 수 있습니다. 또한 이러한 시퀀스에 대한 커스텀 이름도 지정할 수 있습니다.
PostgreSQL 문서 레퍼런스.
Default value
DEFAULT 절은 INSERT 수행 시 사용자가 명시적으로 값을 제공하지 않을 경우 컬럼에 사용할 기본값을 지정합니다.
컬럼 정의에 명시적인 DEFAULT 절이 없으면, 컬럼의 기본값은 NULL입니다.
명시적인 DEFAULT 절은 기본값을 NULL, 문자열 상수, blob 상수, 부호 있는 숫자, 또는 괄호로 묶인 상수 표현식으로 지정할 수 있습니다.
import { sql } from "drizzle-orm";
import { integer, pgTable, uuid } from "drizzle-orm/pg-core";
const table = pgTable('table', {
integer1: integer().default(42),
integer2: integer().default(sql`'42'::integer`),
uuid1: uuid().defaultRandom(),
uuid2: uuid().default(sql`gen_random_uuid()`),
});CREATE TABLE IF NOT EXISTS "table" (
"integer1" integer DEFAULT 42,
"integer2" integer DEFAULT '42'::integer,
"uuid1" uuid DEFAULT gen_random_uuid(),
"uuid2" uuid DEFAULT gen_random_uuid()
);$default() 또는 $defaultFn()을 사용하면 (동일한 함수의 다른 별칭입니다), 런타임에 기본값을 생성하고 모든 삽입 쿼리에서 이 값을 사용할 수 있습니다.
이 함수들은 uuid, cuid, cuid2 등 다양한 구현을 활용하는 데 도움이 됩니다.
참고: 이 값은 drizzle-kit 동작에 영향을 주지 않으며, drizzle-orm에서 런타임에만 사용됩니다.
import { text, pgTable } from "drizzle-orm/pg-core";
import { createId } from '@paralleldrive/cuid2';
const table = pgTable('table', {
id: text().$defaultFn(() => createId()),
});$onUpdate() 또는 $onUpdateFn()을 사용하면 (동일한 함수의 다른 별칭입니다), 런타임에 기본값을 생성하고 모든 업데이트 쿼리에서 이 값을 사용할 수 있습니다.
컬럼에 동적 업데이트 값을 추가합니다. 행이 업데이트될 때 함수가 호출되며, 값이 제공되지 않으면 반환된 값이 컬럼 값으로 사용됩니다. 기본값(또는 $defaultFn)이 제공되지 않으면, 행이 삽입될 때도 함수가 호출되고 반환된 값이 컬럼 값으로 사용됩니다.
참고: 이 값은 drizzle-kit 동작에 영향을 주지 않으며, drizzle-orm에서 런타임에만 사용됩니다.
import { integer, timestamp, text, pgTable } from "drizzle-orm/pg-core";
const table = pgTable('table', {
updateCounter: integer().default(sql`1`).$onUpdateFn((): SQL => sql`${table.update_counter} + 1`),
updatedAt: timestamp({ mode: 'date', precision: 3 }).$onUpdate(() => new Date()),
alwaysNull: text().$type<string | null>().$onUpdate(() => null),
});Not null
NOT NULL 제약조건은 연결된 컬럼이 NULL 값을 포함할 수 없음을 지정합니다.
import { integer, pgTable } from "drizzle-orm/pg-core";
const table = pgTable('table', {
integer: integer().notNull(),
});CREATE TABLE IF NOT EXISTS "table" (
"integer" integer NOT NULL
);Primary key
기본 키 제약조건은 컬럼 또는 컬럼 그룹이 테이블의 행에 대한 고유 식별자로 사용될 수 있음을 나타냅니다. 이는 값이 고유하고 null이 아니어야 함을 요구합니다.
import { serial, pgTable } from "drizzle-orm/pg-core";
const table = pgTable('table', {
id: serial().primaryKey(),
});CREATE TABLE IF NOT EXISTS "table" (
"id" serial PRIMARY KEY NOT NULL
);