Re: Constraint: string length must be 32 chars

From: Darren Duncan <darren(at)darrenduncan(dot)net>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Constraint: string length must be 32 chars
Date: 2010-10-16 22:48:36
Message-ID: 4CBA2BC4.9030105@darrenduncan.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alexander Farber wrote:
> I'm trying to create a table, where md5 strings will serve as primary keys.
> So I'd like to add a constraing that the key length should be 32 chars long
> (and contain [a-fA-F0-9] only):
>
> create table gps (
> id varchar(32) primary key CONSTRAINT char_length(id)==32,
> stamp timestamp DEFAULT current_timestamp,
> pos point);

If you want to use a text type for this and you are restricting the character
repertoire anyway, which presumably you'd need a regex for, then use the same
regex to restrict the length too.

Adjusting your example:

create table gps (
id text primary key CONSTRAINT id ~ '^[a-fA-F0-9]{32}$',
stamp timestamp DEFAULT current_timestamp,
pos point
);

But I would further restrict this to just upper or just lowercase, so that the
values compare correctly as text; you then have to upper/lower your inputs:

create table gps (
id text primary key CONSTRAINT id ~ '^[A-F0-9]{32}$',
stamp timestamp DEFAULT current_timestamp,
pos point
);

I would further recommend turning the above into a separate data type,
especially if you'd otherwise be using that constraint in several places, like this:

CREATE DOMAIN md5text
AS text
CHECK (
VALUE IS NOT NULL
AND
VALUE ~ '^[A-F0-9]{32}$'
)
DEFAULT '00000000000000000000000000000000';

create table gps (
id md5text primary key,
stamp timestamp DEFAULT current_timestamp,
pos point
);

This all being said, I would go with the other advice you mentioned and use a
bitstring or numeric type to represent the md5 rather than using text.

-- Darren Duncan

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Rob Sargent 2010-10-17 00:37:43 Re: Constraint: string length must be 32 chars
Previous Message Alexander Farber 2010-10-16 22:29:46 Re: Constraint: string length must be 32 chars