此上下文错误中不允许使用DEFAULT



我试图向数据库添加索引,但一直收到一个错误:

PG::SyntaxError: ERROR: DEFAULT is not allowed in this context

在阅读文档数小时后,我似乎无法解决这个问题。

我正在运行这个:

"CREATE UNIQUE INDEX index_uniq_service_models_default ON service_models(zone_id) WHERE default"

我的桌子是这样的:

create_table :service_models do |t|
t.string :name, null: false
t.jsonb :configuration, null: false, default: "{}"
t.boolean :default, null: false
t.json :metadata, null: false, default: "{}"
t.references :zone, foreign_key: true, null: false, index: { name: idx_name(:service_models, :zones) }
t.timestamps
end

我想做的是让ServiceModel在一个区域中只有一个默认值。

一个区域可以有许多ServiceModel,但它只能有一个默认的ServiceModel。

创建仅包括列"default"true的行的部分索引:

CREATE UNIQUE INDEX index_uniq_service_models_default ON service_models(zone_id)
WHERE "default";

default是一个保留字,在用作标识符时必须使用双引号。

更好的是,一开始就不要使用保留字作为标识符。

我想做的是让ServiceModel在一个区域中只有一个默认值。

由于您使用的是Rails,因此验证可能会更好。

class ServiceModel
belongs_to :zone
validates_uniqueness_of :zone, conditions: -> { where(default: true) }
end

where子句可以添加到索引中,以仅创建匹配行的部分索引。但是where default不是有效的where子句,因为default是SQL关键字。由于default是SQL关键字,因此必须将其作为列引用。

create unique index service_models_default_zone_idx
on service_models("zone_id")
where "default"

或者在您的create_table块中。。。

t.index(:zone_id, unique: true, where: '"default"')

最新更新