Skip site navigation (1) Skip section navigation (2)

Re: Truncate if exists

From: Christopher Browne <cbbrowne(at)gmail(dot)com>
To: Robert Haas <robertmhaas(at)gmail(dot)com>
Cc: Simon Riggs <simon(at)2ndquadrant(dot)com>, Josh Berkus <josh(at)agliodbs(dot)com>, pgsql-hackers(at)postgresql(dot)org
Subject: Re: Truncate if exists
Date: 2012-10-12 21:05:56
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-hackers
On Fri, Oct 12, 2012 at 3:04 PM, Robert Haas <robertmhaas(at)gmail(dot)com> wrote:
> On Thu, Oct 11, 2012 at 3:22 PM, Simon Riggs <simon(at)2ndquadrant(dot)com> wrote:
>> So we just need a function called pg_if_table_exists(table, SQL) which
>> wraps a test in a subtransaction.
>> And you write
>> SELECT pg_if_table_exists('foo', 'TRUNCATE TABLE foo');
>> and we can even get rid of all that other DDL crud that's been added....
>> and we can have pg_if_table_not_exists() also.
> You could make this more composable by having pg_table_exists() and
> pg_execute_sql_from_string().  Then you can write: SELECT CASE WHEN
> pg_table_exists(...) THEN pg_execute_sql_from_string(...) END.  And if
> you want the if-not-exists case then just stick a NOT in there.  And
> if you want a more complicated condition, you can easily write that as
> well.

While that certainly has the merit of being compact, it mixes kinds of
evaluation (e.g. - parts of it are parsed at different times) and
requires quoting that isn't true for the other sorts of "IF EXISTS"

To be sure, you can do anything you like inside a DO $$ $$ language
plpgsql; block, but it's not nice to have to do a lot of work
involving embedding code between languages.  Makes it harder to
manipulate, analyze, and verify.

Let me observe that Perl has, as one of its conditional concepts, the
notion of a "statement modifier"
<>, which
corresponds pretty much to the IF EXISTS/IF NOT EXISTS modifiers that
have gotten added to Postgres over the last few versions.  (I *think*
statement modifiers are attributable to SNOBOL, not 100% sure.  I'm
pretty sure it predates Perl.)

I suggest the though of embracing statement modifiers in DDL, with
some options possible:

where CONDITION has several possible forms:
  i) {IF|UNLESS} ( SQL expression returning T/F )

That feels like a cleaner extension than what we have had, with the IF
EXISTS/IF NOT EXISTS clauses that have been added to various
When confronted by a difficult problem, solve it by reducing it to the
question, "How would the Lone Ranger handle this?"

In response to


pgsql-hackers by date

Next:From: Alvaro HerreraDate: 2012-10-12 21:09:45
Subject: Re: foreign key locks
Previous:From: Stephen FrostDate: 2012-10-12 20:42:46
Subject: Re: Improving the performance of psql tab completion

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group