Using SELECT FOR UPDATE in PostgresDAC

One of our clients once asked: “How can I use SELECT … FOR UPDATE functionality in conjunction with PostgresDAC?”

As stated in server manual:

FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends.

The solution is obvious. Start transaction before call TPSQLQuery.Open, so the code might look like this:

PSQLDatabase1.StartTransaction;
try
 PSQLQuery1.SQL.Clear;
 PSQLQuery1.SQL.Add('SELECT * FROM tablename');
 PSQLQuery1.SQL.Add('WHERE id = 12345');
 PSQLQuery1.SQL.Add('FOR UPDATE NOWAIT');
 PSQLQuery1.Open;
 <your actions here>
 PSQLDatabase1.Commit;
except
 PSQLDatabase1.Rollback;
end;

So simple!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s