Drizzle | 빈 배열을 기본값으로 사용하기
This guide assumes familiarity with:
- PostgreSQL, MySQL, SQLite 시작하기
- PostgreSQL, MySQL, SQLite 컬럼 데이터 타입에 대해 알아보기
- sql 연산자
PostgreSQL
PostgreSQL에서 빈 배열을 기본값으로 설정하려면 sql 연산자를 '{}' 또는 ARRAY[] 문법과 함께 사용할 수 있습니다:
import { sql } from 'drizzle-orm';
import { pgTable, serial, text } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
tags1: text('tags1')
.array()
.notNull()
.default(sql`'{}'::text[]`),
tags2: text('tags2')
.array()
.notNull()
.default(sql`ARRAY[]::text[]`),
});CREATE TABLE IF NOT EXISTS "users" (
"id" serial PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"tags1" text[] DEFAULT '{}'::text[] NOT NULL,
"tags2" text[] DEFAULT ARRAY[]::text[] NOT NULL
);MySQL
MySQL은 배열 데이터 타입을 제공하지 않지만, 같은 목적으로 json 데이터 타입을 사용할 수 있습니다. MySQL에서 빈 배열을 기본값으로 설정하려면 JSON_ARRAY() 함수나 sql 연산자를 ('[]') 문법과 함께 사용할 수 있습니다:
import { sql } from 'drizzle-orm';
import { json, mysqlTable, serial, varchar } from 'drizzle-orm/mysql-core';
export const users = mysqlTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 255 }).notNull(),
tags1: json('tags1').$type<string[]>().notNull().default([]),
tags2: json('tags2')
.$type<string[]>()
.notNull()
.default(sql`('[]')`), // the same as default([])
tags3: json('tags3')
.$type<string[]>()
.notNull()
.default(sql`(JSON_ARRAY())`),
});CREATE TABLE `users` (
`id` serial AUTO_INCREMENT NOT NULL,
`name` varchar(255) NOT NULL,
`tags1` json NOT NULL DEFAULT ('[]'),
`tags2` json NOT NULL DEFAULT ('[]'),
`tags3` json NOT NULL DEFAULT (JSON_ARRAY()),
CONSTRAINT `users_id` PRIMARY KEY(`id`)
);mode 옵션은 애플리케이션에서 값을 처리하는 방식을 정의합니다. json 모드를 사용하면 값이 JSON 객체 리터럴로 처리됩니다.
.$type<..>()을 사용하여 JSON 객체의 타입을 추론할 수 있으며, 런타임 값은 검사하지 않습니다. 이는 기본값, insert 및 select 스키마에 대한 컴파일 타임 보호를 제공합니다.
SQLite
SQLite는 배열 데이터 타입을 제공하지 않지만, 같은 목적으로 text 데이터 타입을 사용할 수 있습니다. SQLite에서 빈 배열을 기본값으로 설정하려면 json_array() 함수나 sql 연산자를 '[]' 문법과 함께 사용할 수 있습니다:
import { sql } from 'drizzle-orm';
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
export const users = sqliteTable('users', {
id: integer('id').primaryKey(),
tags1: text('tags1', { mode: 'json' })
.notNull()
.$type<string[]>()
.default(sql`(json_array())`),
tags2: text('tags2', { mode: 'json' })
.notNull()
.$type<string[]>()
.default(sql`'[]'`),
});CREATE TABLE `users` (
`id` integer PRIMARY KEY NOT NULL,
`tags1` text DEFAULT (json_array()) NOT NULL,
`tags2` text DEFAULT '[]' NOT NULL
);mode 옵션은 애플리케이션에서 값을 처리하는 방식을 정의합니다. json 모드를 사용하면 값이 JSON 객체 리터럴로 처리됩니다.
.$type<..>()을 사용하여 JSON 객체의 타입을 추론할 수 있으며, 런타임 값은 검사하지 않습니다. 이는 기본값, insert 및 select 스키마에 대한 컴파일 타임 보호를 제공합니다.