[Wellington-pm] Perl database stuff....

Cliff Pratt enkidu at cliffp.com
Sat Dec 23 17:29:44 PST 2006


I want to write a row, using Perl, to a PostgreSQL database, *but only 
if the row does not already exist*. If I add a row, I need to know the 
ID of the row.

Currently what I have is:

1) Select the row using a WHERE clause to select the row I want to add, 
to see if it is already there.

2) If the row does exist return an error (details don't matter).

3) If the row doesn't exist insert it, defaulting the ID which is 
generated by a sequence.

4) Read it again to find the ID which was generated during the insert.

Blah! This works but is long-winded, untidy and generally blah!

Is there a smarter way to do it, either on the Perl side or on the 
database side?

Currently the code is plastered with '...or die....' but having just 
read Grant's piece on error handling I think I can tidy THAT up. I 
intend to wrap it up as a transaction eventually, so that will be tidied 
up too, and that just leaves the select, insert, select as the remaining 
nastiness.

Any ideas?

Cheers,

Cliff


More information about the Wellington-pm mailing list