0

I would like to create a unique PostgreSQL index that contains operations. Does anyone know if this is possible?

CREATE UNIQUE INDEX ux_data ON table (name, color)

The operation that I would like to add is "num & new_num = 0", where num is an existing column and new_num is a value to be inserted.

Is this possible?

Update: Here's more detail regarding what I want to do.

Database:

name    color    num
one     red      5
two     green    5
one     red      8

What I want to do is to prevent the case where an entry is not unique, like:

New entry 1: name = one, color = red, num = 1.

We have matching names and colors and the first num check results in 101 & 001 = 1, this New entry 1 is not unique, and should be rejected, however, if the number was changed to 2.

New entry 2: name = one, color = red, num = 2

Now we have matching names and colors. For the num in all name/color matches 101 & 010 = 0, and 1000 & 0010 = 0, so we have a unique entry.

4

1 回答 1

0

这将是一个半项目。看起来没有一种非常简单的方法可以做到这一点,但使用 PostgreSQL 一切皆有可能。我认为您想要使用 GIST 的排除约束。不幸的是,排除约束不会是一件容易的事,因为没有简单的类型支持这一点。

我认为您的基本解决方案必须涉及:

  1. 转换为合适的数据类型(大概是 bit(n))

  2. 足够的运算符以允许位 (n) 的 GiST 索引。这意味着您必须为所有 GiST 操作类构建函数和运算符,创建运算符族等。

  3. 使用您的操作创建排除约束。

这并不容易,而且会很复杂,但只要付出一些努力和奉献,这是可能的。我预计会涉及一到两百行代码。您可能也想编写单元测试。

于 2013-04-25T15:35:11.453 回答