pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Harald Fuchs <hari.fuchs@gmail.com>
To: pgsql-sql@postgresql.org
Subject: Re: exclusion constraint for ranges of IP
Date: Mon, 22 Aug 2011 17:20:30 +0200
Message-ID: <86hb595v7l.fsf@mgm.protecting.net> (raw)
References: <CAF36091-203E-4C10-AA53-7D9087114D35@unicell.co.il>
	<86ty9a5rw6.fsf@mgm.protecting.net>
	<1343D11C-6F58-4653-8EA8-837C01E6184F@unicell.co.il>

In article <1343D11C-6F58-4653-8EA8-837C01E6184F@unicell.co.il>,
Herouth Maoz <herouth@unicell.co.il> writes:

> On 22/08/2011, at 01:19, Harald Fuchs wrote:

>> In article <CAF36091-203E-4C10-AA53-7D9087114D35@unicell.co.il>,
>> Herouth Maoz <herouth@unicell.co.il> writes:
>> 
>>> Hi,
>>> I'm designing a new database. One of the table contains allowed IP ranges for a customer (Fields: customer_id, from_ip, to_ip) which is intended to check - if  an incoming connection's originating IP number falls within the range, it is identified as a particular customer.
>> 
>>> Naturally, I'd like to have constraints on the table that prevent entering of ip ranges that overlap. Is there a way to do that with exclusion constraints? Or do I have to define a new type for this?
>> 
>> This "new type" already exists: ip4r, which can be found in pgfoundry.
>> With it you can do
>> 
>> CREATE TABLE mytbl (
>> iprange ip4r NOT NULL,
>> ...,
>> CONSTRAINT range_check CHECK ((NOT overlap(iprange)))
>> );


> Thank you.

> I assume you can't use a CHECK constraint for between-rows constraints. Wouldn't this  be

> CONSTRAINT EXCLUDE ( iprange WITH && )

> ?

You're right.  In the old PostgreSQL version I had to use I defined a
helper function

  CREATE FUNCTION overlap(ip4r) RETURNS boolean
      LANGUAGE sql
      AS $_$
    SELECT count(*) > 0
    FROM mytbl
    WHERE iprange != $1 AND iprange && $1
  $_$;

for the CHECK CONSTRAINT, but in more recent PostgreSQL versions you can
just say
  EXCLUDE (iprange WITH &&)
(without CONSTRAINT).




view thread (11+ messages)  latest in thread

Message-ID: <86hb595v7l.fsf@mgm.protecting.net>
Permalink:  ../86hb595v7l.fsf@mgm.protecting.net/
Also on:    postgresql.org/message-id/86hb595v7l.fsf@mgm.protecting.net

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: hari.fuchs@gmail.com
  Subject: Re: exclusion constraint for ranges of IP
  In-Reply-To: <86hb595v7l.fsf@mgm.protecting.net>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox