Re: Insert NULL for ''

From: Jonathan Bartlett <johnnyb(at)eskimo(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Daniel Gehrke <dgehrke(at)neusta(dot)de>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Insert NULL for ''
Date: 2003-06-13 14:55:18
Message-ID: Pine.GSU.4.44.0306130754250.26801-100000@eskimo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Could you instead have a function around it?

into foo (bar) values (myfunction(''))

Where myfunction maps '' to null.

On Fri, 13 Jun 2003, Tom Lane wrote:

> "Daniel Gehrke" <dgehrke(at)neusta(dot)de> writes:
> > Is there any possibility to get postgresql to insert NULL when I do "insert
> > into foo (bar) values ('')?
>
> There's no easy way. '' simply is not a legal value of type date.
> Therefore, the only way to make the above work is to make the string be
> initially considered of type text, and postpone the conversion to date
> until after you've checked for the empty-string case.
>
> AFAICS this means you can't fix it with a simple method like a BEFORE
> trigger that replaces the value with NULL. The value has to get
> converted to type date to form the candidate row that the trigger
> receives, so you're too late, the error has already been raised.
>
> I can think of a couple of possible approaches:
>
> * Define a view in which the corresponding column is actually text not
> date, say
> CREATE VIEW v AS SELECT datecol::text, ...everything else... FROM t;
> and then make an ON INSERT rule that transforms an attempted insert
> into the view into an insert on the table proper. In this rule you
> can put
> CASE WHEN NEW.datecol = '' THEN NULL ELSE NEW.datecol::date END
> Of course you're also going to need ON UPDATE and ON DELETE rules.
>
> * Give up and make the column be actually type text. Then you just need
> an insert/update trigger along the lines of
> IF new.datecol is null or new.datecol = '' then
> new.datecol = null;
> else
> new.datecol = new.datecol::date::text;
> to ensure that the contents of the column always look like a date.
>
> But both of these answers suck from a maintenance point of view.
> I'd honestly recommend that you fix your application. It'll be
> less pain in the long run.
>
> regards, tom lane
>
> ---------------------------(end of broadcast)---------------------------
> TIP 4: Don't 'kill -9' the postmaster
>

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2003-06-13 14:56:22 Re: [HACKERS] SAP and MySQL ... [and Benchmark]
Previous Message Lincoln Yeoh 2003-06-13 14:52:19 Re: Postgres performance comments from a MySQL user