Incrementing A Very Important None-numeric Field

From: cn <cn(at)mail(dot)sinyih(dot)com(dot)tw>
To: pgsql-novice(at)postgresql(dot)org
Subject: Incrementing A Very Important None-numeric Field
Date: 2000-10-30 08:31:04
Message-ID: 39FD31C8.57517C4D@mail.sinyih.com.tw
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Hi!

I want to increment the value of field SocialSecurityNo for a centrally
controlled table SocialSecurityTable. SocialSecurityTable contains only
one row and one field - SocialSecurityNo. Because, I think,
SocialSecurityNo in the table should not be seen by any other user when
it is being incremented by a function (or the number will duplicate), I
use table lock as follows:

CREATE FUNCTION GetAndSetNextNumber () RETURNS TEXT AS '
DECLARE
UsedNumber TEXT;
BEGIN
BEGIN WORK;
LOCK SocialSecurityTable IN ROW EXCLUSIVE MODE;
SELECT SocialSecurityNo INTO UsedNumber FROM SocialSecurityTable;
--Do a lot calculation on UsedNumber and then generate the next free
SocialSecurityNo
-- and assign the value to UsedNumber.
UPDATE SocialSecurityTable SET SocialSecurityNo=UsedNumber;
COMMIT WORK;
RETURN UsedNumber;
END;' LANGUAGE 'plpgsql';

Question A: Is this above function apporpriately designed, or are there
more efficient ways than table locking?

Question B: What problem will happen and how to fix it when statement
"LOCK SocialSecurityTable IN ROW EXCLUSIVE MODE;" fails because this
user (user A) started this transaction AFTER another user (user B) and
user B has not yet COMMITed the transaction?

Regards,

CN

Browse pgsql-novice by date

  From Date Subject
Next Message James Snelling 2000-10-30 13:09:01 Installation of Postgres + PHP
Previous Message The Hermit Hacker 2000-10-30 00:11:15 pgsql-novice list should be live again ...