DrizzleORM v0.27.2 发布
2023年7月12日
🎉 已在 PostgreSQL、MySQL、SQLite 中添加对 UNIQUE
约束的支持
对于 PostgreSQL,单列约束可以在列级别定义唯一约束,多列约束则在第三个参数中定义。在这两种情况下,都可以为约束定义一个自定义名称。此外,PostgreSQL 还将支持 NULLS NOT DISTINCT
选项,以限制表中出现多个 NULL 值。 参考
这些示例仅展示了 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 中,唯一约束与唯一索引相同。只要您可以在 SQLite 中为唯一索引指定名称,我们将在内部实现中将所有唯一约束视为唯一索引
// 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),
}));