Re: Order-independent multi-field uniqueness constraint?

From: "Kynn Jones" <kynnjo(at)gmail(dot)com>
To: "Gregory Stark" <stark(at)enterprisedb(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Order-independent multi-field uniqueness constraint?
Date: 2007-10-20 17:25:52
Message-ID: c2350ba40710201025l6d4c3afu38c102eefba2d66c@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 10/19/07, Gregory Stark <stark(at)enterprisedb(dot)com> wrote:
> "Kynn Jones" <kynnjo(at)gmail(dot)com> writes:
>
> > CREATE OR REPLACE FUNCTION canonicalize( anyelement, anyelement )
> > RETURNS anyarray AS
> > $$
> > BEGIN
> > IF $1 < $2 THEN RETURN ARRAY[ $1, $2 ];
> > ELSE RETURN ARRAY[ $2, $1 ];
> > END IF;
> > END;
> > $$ LANGUAGE plpgsql;
>
> You need to add IMMUTABLE as well.
>
> > and this function works as expected, but when I try to use it in a
> > constraint I get the error:
> >
> > -> ALTER TABLE foo ADD CONSTRAINT foo_uniq_x_y UNIQUE(canonicalize(x,y));
> > ERROR: 42601: syntax error at or near "("
> > LINE 1: ...E foo ADD CONSTRAINT foo_uniq_x_y UNIQUE(canonicalize(x,y));
>
> What you need is:
>
> CREATE UNIQUE INDEX foo_uniq_x_y on foo (canonicalize(x,y));

Yep, that did the trick.

> > I found this puzzling; it's not clear to me why UNIQUE(UPPER(x)) is OK
> > syntax but not UNIQUE(my_function(x)).
>
> Really? It doesn't work for me in the ADD CONSTRAINT syntax.

My mistake, sorry. I was probably misremembering something I saw in a
CREATE INDEX statement.

Thanks!

kj

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Shelby Cain 2007-10-20 18:29:15 Re: 8.2.3: Server crashes on Windows using Eclipse/Junit
Previous Message Trevor Talbot 2007-10-20 16:53:03 Re: 8.2.3: Server crashes on Windows using Eclipse/Junit