DrizzleORM v0.27.2 릴리스
Jul 12, 2023

🎉 PostgreSQL, MySQL, SQLite에서 UNIQUE 제약조건 지원 추가

PostgreSQL의 경우, unique 제약조건은 단일 컬럼 제약조건에는 컬럼 레벨에서 정의할 수 있고, 다중 컬럼 제약조건에는 세 번째 파라미터에서 정의할 수 있습니다. 두 경우 모두 제약조건에 대한 사용자 정의 이름을 지정할 수 있습니다. 또한 PostgreSQL은 테이블에 두 개 이상의 NULL 값을 제한하는 NULLS NOT DISTINCT 옵션을 지원합니다. 참고

다양한 unique 사용법을 보여주는 예제입니다. 이 테이블들에서 실제 사용 사례를 찾으려 하지 마세요

// single column
const table = pgTable('table', {
  id: serial('id').primaryKey(),
  name: text('name').notNull().unique(),
  state: char('state', { length: 2 }).unique('custom'),
  field: char('field', { length: 2 }).unique('custom_field', { nulls: 'not distinct' }),
});
// multiple columns
const table = pgTable('table', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  state: char('state', { length: 2 }),
}, (t) => ({
  first: unique('custom_name').on(t.name, t.state).nullsNotDistinct(),
  second: unique('custom_name1').on(t.name, t.state),
}));

MySQL의 경우, NULLS NOT DISTINCT 옵션을 제외하고는 모든 것이 동일합니다. MySQL은 이 옵션을 지원하지 않는 것으로 보입니다

다양한 unique 사용법을 보여주는 예제입니다. 이 테이블들에서 실제 사용 사례를 찾으려 하지 마세요

// single column
const table = mysqlTable('table', {
    id: serial('id').primaryKey(),
    name: text('name').notNull().unique(),
    state: text('state').unique('custom'),
    field: text('field').unique('custom_field'),
});
// multiple columns
const table = mysqlTable('cities1', {
    id: serial('id').primaryKey(),
    name: text('name').notNull(),
    state: text('state'),
}, (t) => ({
    first: unique().on(t.name, t.state),
    second: unique('custom_name1').on(t.name, t.state),
}));

SQLite에서 unique 제약조건은 unique 인덱스와 동일합니다. SQLite에서 unique 인덱스에 이름을 지정할 수 있는 한, 내부 구현에서는 모든 unique 제약조건을 unique 인덱스로 처리합니다

// single column
const table = sqliteTable('table', {
    id: int('id').primaryKey(),
    name: text('name').notNull().unique(),
    state: text('state').unique('custom'),
    field: text('field').unique(),
});
// multiple columns
const table = sqliteTable('table', {
    id: int('id').primaryKey(),
    name: text('name').notNull(),
    state: text('state'),
}, (t) => ({
    first: unique().on(t.name, t.state),
    second: unique('custom').on(t.name, t.state),
}));