DrizzleORM v0.27.2 发布
Jul 12, 2023

🎉 在 PostgreSQL、MySQL、SQLite 中添加对 UNIQUE 约束的支持

对于 PostgreSQL,唯一约束可以在单列约束的列级别定义,也可以在多列约束的第三个参数中定义。在两种情况下,都可以为约束定义一个自定义名称。此外,PostgreSQL 将接收 NULLS NOT DISTINCT 选项,以限制表中超过一个 NULL 值。参考链接

以下示例仅演示不同的 unique 用法。请不要搜索这些表的真实用途。

// 单列
const table = pgTable('table', {
  id: serial('id').主键(),
  name: text('name').不能为空().唯一(),
  state: char('state', { length: 2 }).唯一('custom'),
  field: char('field', { length: 2 }).唯一('custom_field', { nulls: 'not distinct' }),
});
// 多列
const table = pgTable('table', {
  id: serial('id').主键(),
  name: text('name').不能为空(),
  state: char('state', { length: 2 }),
}, (t) => ({
  first: 唯一('custom_name').在(t.name, t.state).不同的空值(),
  second: 唯一('custom_name1').在(t.name, t.state),
}));

对于 MySQL,除了 NULLS NOT DISTINCT 选项之外,其他都相同。似乎 MySQL 不支持此选项。

以下示例仅演示不同的 unique 用法。请不要搜索这些表的真实用途。

// 单列
const table = mysqlTable('table', {
    id: serial('id').主键(),
    name: text('name').不能为空().唯一(),
    state: text('state').唯一('custom'),
    field: text('field').唯一('custom_field'),
});
// 多列
const table = mysqlTable('cities1', {
    id: serial('id').主键(),
    name: text('name').不能为空(),
    state: text('state'),
}, (t) => ({
    first: 唯一().在(t.name, t.state),
    second: 唯一('custom_name1').在(t.name, t.state),
}));

在 SQLite 中,唯一约束与唯一索引相同。只要您可以为唯一索引指定一个名称,在内部实现中,我们将把所有唯一约束视为唯一索引。

// 单列
const table = sqliteTable('table', {
    id: int('id').主键(),
    name: text('name').不能为空().唯一(),
    state: text('state').唯一('custom'),
    field: text('field').唯一(),
});
// 多列
const table = sqliteTable('table', {
    id: int('id').主键(),
    name: text('name').不能为空(),
    state: text('state'),
}, (t) => ({
    first: 唯一().在(t.name, t.state),
    second: 唯一('custom').在(t.name, t.state),
}));
Become a Gold Sponsor