Re: uniquely indexing Celko's nested set model

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: Richard Broersma Jr <rabroersma(at)yahoo(dot)com>
Cc: General PostgreSQL List <pgsql-general(at)postgresql(dot)org>
Subject: Re: uniquely indexing Celko's nested set model
Date: 2007-10-20 03:15:45
Message-ID: 0B9C3386-46C0-4EAE-B4E2-B02D78F28B0F@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Oct 19, 2007, at 16:42 , Richard Broersma Jr wrote:

> Is it possible to constraint both the LEFT and RIGHT fields of a
> record to use the same index? I am looking for a way to ensure for
> all LEFTs and RIGHTs in a table, that is it is impossible for any
> LEFT or RIGHT to have to same value.

You can define a check constraint to handle this:

CREATE OR REPLACE FUNCTION strict_nested_set_node_check(INTEGER,
INTEGER)
RETURNS BOOLEAN
STRICT IMMUTABLE SECURITY DEFINER
LANGUAGE SQL AS $_$
SELECT ((abs($1) < abs($2))
AND ($2 - $1 - 1) % 2 = 0)
$_$;
COMMENT ON FUNCTION strict_nested_set_node_check(INTEGER, INTEGER) IS
'Convenience function to encapsulate the check conditions for the
lower and '
' upper bounds (often called ''left'' and ''right'') for strict
nested set '
'implementations.';

CREATE TABLE nodes
(
node_id SERIAL PRIMARY KEY
, node_lower INTEGER NOT NULL
, node_upper INTEGER NOT NULL
, UNIQUE (query_plan_id, node_lower)
, UNIQUE (query_plan_id, node_upper)
, CHECK (strict_nested_set_node_check(node_lower, node_upper))
);

To actually guarantee that each lower and upper value is only used
once, I think you'd need to write a trigger that checks that each
value is only used once. I haven't used such trigger when I've used
nested sets, however. If you handle your table modifications through
functions and test your functions thoroughly, you can be pretty sure
that your table updates aren't going to cause any duplication of this
time. Then again, maybe I should add the trigger to be on the safe
side :)

Michael Glaesemann
grzm seespotcode net

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2007-10-20 03:25:21 Re: Connection & logging Problems
Previous Message Richard Broersma Jr 2007-10-20 03:14:00 Re: uniquely indexing Celko's nested set model