473,804 Members | 2,280 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PostgreSQL, psycopg2 and OID-less tables

Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?

I've tried three Python client libraries, including psycopg2, and where they
support cursor attribute 'lastrowid' (Python DB API 2.0), it is always
zero.

Anyone figured this out?

Thanks.
--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

Sep 15 '06 #1
12 5183

Dale Strickland-Clark wrote:
Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?

I've tried three Python client libraries, including psycopg2, and where they
support cursor attribute 'lastrowid' (Python DB API 2.0), it is always
zero.

Anyone figured this out?
Hi,

It's of course strictly a PostgreSQL question, but have you tried

select lastval();

?

According to my reading of the postgress manuals, that should do the
trick.

Cheers,

--Tim

Thanks.
--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk
Sep 15 '06 #2
Dale,
Now that OIDs have been deprecated in PostgreSQL, how do you find the keyof
a newly inserted record?
using OIDs as primary key was no good idea for some PostgreSQL versions
allready ... i.e. they really make dump & restore much more
challenging.

So usually us have something along:

CREATE TABLE feuser
(
id_user serial NOT NULL,
name text,
CONSTRAINT feuser_pkey PRIMARY KEY (id_user),
CONSTRAINT feuser_name_key UNIQUE (name)
)
WITHOUT OIDS;

which automatically creates a sequence for you and rewrites the serial
"id_user" with a default of

nextval('feuser _id_user_seq':: regclass)

So, to get the key of a record inserted, basically there are two
methods. (from now on "cs" is a DB-API 2.0 compliant cursor object,
i.e. from psycopg2

cn=psycopg2.con nect(....)
cs=cn.cursor()

a) get id first, then insert
cs.execute("sel ect nextval('feuser _id_user_seq':: regclass)")
newid=cs.fetcho ne()[0]

cs.execute("ins ert into feuser (id_user, name) values (%(id_user)s,
%(name)s)",
dict(id_user=ne wid, name="Karl Napf")

cs.commit()
-now newid contains your new id.

b) create a serverside function on PostgreSQL:
CREATE OR REPLACE FUNCTION insfeuser (text)
RETURNS integer AS
$BODY$
DECLARE
result int4;
BEGIN

select nextval('feuser _id_user_seq':: regclass) into result;
insert into feuser (id_user, name) values (result, $1);

RETURN result;
END;

$BODY$
LANGUAGE 'plpgsql' VOLATILE;

within python:
cs.execute("sel ect insfeuser(%(nam e)s)", dict(name="Karl Napf"))
newid=cs.fetcho ne()[0]

Hope that helps,

Harald

--
GHUM Harald Massa
persuadere et programmare
Harald Armin Massa
Reinsburgstraße 202b
70197 Stuttgart
0173/9409607

Sep 15 '06 #3
Hi Harald

Thanks for that, somewhat comprehensive, answer.

--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

Sep 15 '06 #4
Tim N. van der Leeuw wrote:
>
Hi,

select lastval();
Thanks, that was useful.
--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

Sep 15 '06 #5

Dale Strickland-Clark wrote:
Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?

I've tried three Python client libraries, including psycopg2, and where they
support cursor attribute 'lastrowid' (Python DB API 2.0), it is always
zero.

Anyone figured this out?

Thanks.
--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk
I used to use 'select lastval()', but I hit a problem. If I insert a
row into table A, I want the id of the row inserted. If it is a complex
insert, which triggers inserts into various other tables, some of which
may also be auto-incrementing, lastval() returns the id of the row last
inserted into any auto-incrementing table.

I therefore use the following -
cur.execute("se lect currval('%s_%s_ Seq')" % (tableid, columnid)

where tableid is the specific table I want (in this example, table A),
and columnid is the column specified as the auto-incrementing one.
>From the PostgreSQL docs - "Notice that because this is returning a
session-local value, it gives a predictable answer whether or not other
sessions have executed nextval since the current session did."

Frank Millman

Sep 16 '06 #6
Jim
Frank Millman wrote:
I therefore use the following -
cur.execute("se lect currval('%s_%s_ Seq')" % (tableid, columnid)
I use this also (although isn't it right that sometimes the name of the
sequence is not so straightforward ? for instance, isn't there a limit
on the number of chars?).

Can anyone say what is an advantage of the two nextval() solutions
described earlier in this thread over the currval() solution listed
here?

Jim

Sep 16 '06 #7
Frank Millman wrote:
Dale Strickland-Clark wrote:
Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?
>
I used to use 'select lastval()', but I hit a problem. If I insert a
row into table A, I want the id of the row inserted. If it is a complex
insert, which triggers inserts into various other tables, some of which
may also be auto-incrementing, lastval() returns the id of the row last
inserted into any auto-incrementing table.

I therefore use the following -
cur.execute("se lect currval('%s_%s_ Seq')" % (tableid, columnid)
Aren't both of these inherently racey? It seems to me like you need
some kind of atomic insert-and-return-id value; otherwise you don't
know if another thread/process has inserted something else in the table
in between when you call insert and when you select lastval/currval.

Or does postgres have some transactional atomicity here?

I'm very interested in an answer to the OP's question as well. As far
as I can tell, the best you can do is make the ID a primary key, select
the nextval _before you insert, explicitly set it on insert, and then
you'll get an error if you lost a race and you can select nextval, set
it, and try again (repeat until success).

That's nasty and I'm sure there's a real solution but I haven't found
it yet.

Sep 16 '06 #8
sj*******@yahoo .com wrote:
Frank Millman wrote:
>>Dale Strickland-Clark wrote:
>>>Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?

>>I used to use 'select lastval()', but I hit a problem. If I insert a
row into table A, I want the id of the row inserted. If it is a complex
insert, which triggers inserts into various other tables, some of which
may also be auto-incrementing, lastval() returns the id of the row last
inserted into any auto-incrementing table.

I therefore use the following -
cur.execute("se lect currval('%s_%s_ Seq')" % (tableid, columnid)


Aren't both of these inherently racey? It seems to me like you need
some kind of atomic insert-and-return-id value; otherwise you don't
know if another thread/process has inserted something else in the table
in between when you call insert and when you select lastval/currval.

Or does postgres have some transactional atomicity here?
currval(sequenc e) is alleged to be connection-specific in the PostgreSQL
documentation for currval: """Return the value most recently obtained by
nextval for this sequence in the current session. (An error is reported
if nextval has never been called for this sequence in this session.)
Notice that because this is returning a session-local value, it gives a
predictable answer whether or not other sessions have executed nextval
since the current session did."""
I'm very interested in an answer to the OP's question as well. As far
as I can tell, the best you can do is make the ID a primary key, select
the nextval _before you insert, explicitly set it on insert, and then
you'll get an error if you lost a race and you can select nextval, set
it, and try again (repeat until success).

That's nasty and I'm sure there's a real solution but I haven't found
it yet.
The real solution has been given already: you just haven't brought
yourself to believe it yet ;-)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 16 '06 #9

sj*******@yahoo .com wrote:
Frank Millman wrote:
Dale Strickland-Clark wrote:
Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?
>

I used to use 'select lastval()', but I hit a problem. If I insert a
row into table A, I want the id of the row inserted. If it is a complex
insert, which triggers inserts into various other tables, some of which
may also be auto-incrementing, lastval() returns the id of the row last
inserted into any auto-incrementing table.

I therefore use the following -
cur.execute("se lect currval('%s_%s_ Seq')" % (tableid, columnid)

Aren't both of these inherently racey? It seems to me like you need
some kind of atomic insert-and-return-id value; otherwise you don't
know if another thread/process has inserted something else in the table
in between when you call insert and when you select lastval/currval.
Did you read my extract from the PostgreSQL docs -

"Notice that because this is returning a session-local value, it gives
a predictable answer whether or not other sessions have executed
nextval since the current session did."

For some reason Google Groups stuck a '>' at the beginning, so you may
have thought that it related to a previous message, but it was actually
part of my reply and refers specifically to 'select currval()'.

Frank

Sep 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2276
by: Graeme Matthew | last post by:
Hi All I have noticed that there are a numbe rof client libraries for connecting to Postgres. Can anyone tell me what is the recommended Python library for database connections many thanks
11
2949
by: Errol Neal | last post by:
Hi all, Not sure if this is a question for a php list or this one, but I'll give it a shot and if I am wrong, please do not crucify me. :-) There is a php based sourceforge project called mailwatch. (http://www.sourceforge.net/projects/mailwatch) It logs data from the excellent Mailscanner security product into a mysql database. Now, I am not a php programmer,
14
4126
by: Manuel Tejada | last post by:
Hi My box: RedHat 9.0, Pentium III Recently I upgraded from PostgreSQL 7.3.2 to PostgreSQL 7.4.1. The PostgreSQL 7.3.2's rpms were installed from RehHat CDs The PostgreSQL 7.4.1's rpms I used to upgrade were downloaded from RHEL3 subdirectory (of the mirror ftp://ftp4.ar.postgresql.org/pub/mirrors/postgresql/binary/v7.4.1/redhat/rhel3). The upgrade is working well, even I can connect to PostgreSQL from a PHP
2
1716
by: Klaus Harbo | last post by:
Does anyone have experiences using PostgreSQL for storing Microsoft Project data? MS Access, SQL Server and Oracle are supported according to the manual. A simple test with PostgreSQL results in an error something like 'Unknown data type "lo"'. I have been unable to find any useful info on this issue on www.google.com. Any help much appreciated.
3
1550
by: Keen Anthony | last post by:
Hello, I am currently using psycopg 2 as my db adapter for a mod_python & PostgreSQL web app. It's works fine, and I haven't any complaints. I would appreciate some input on what other pythonistas like in an adapter. There were several different options available to me, but there was no particular informed reason for me to choose psycopg. Am I missing anything? ~ Anthony
2
1746
by: Paolo | last post by:
Ciao a tutti, sto cercando di implementare un applicazione che si interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente windows (python versione 2.5). Ho installato Psycopg2 e provando solamente fare: import psycopg mi ritorna il seguente errore: import psycopg ImportError: No module named psycopg come mai? va settata qualche path oltre a quella di postgresql ?
4
1523
by: Ben Sizer | last post by:
I've been looking for a Windows version of a library to interface to PostgreSQL, but can only find ones compiled under Python version 2.4. Is there a 2.5 build out there? -- Ben Sizer
0
1624
by: David Michael Schruth, | last post by:
Hi, I am sort of in a jam here. I am using the PsycoPG2 library to read data out of a windows XP based PostGIS / PostGreSQL database but I am apparently unable to write (update or insert) even though I am able to read (select) I am using PsycoPG2 2.0.6 (psycopg2-2.0.6.win32-py2.5-pg8.2.4- release.exe ) with Python 2.5 (python-2.5.msi)
0
1676
by: badaboum84 | last post by:
I have to migrate a current PostgreSQL database to MSSQL. For doing this task I uses Python to create script for doing this task. Now, I want to extract the data from the current PostgreSQL database, but I need a API. I decided to go with PSYCOPG2, but it seem to have a problem with the BYTEA datatype. I use these lines of code : self.cursor.execute('SELECT * FROM electronicassembly WHERE id_pk = 2') list = self.cursor.fetchall()...
1
5695
by: Pradip | last post by:
Hello every body. I am new to this forum and also in Python. Read many things about multi threading in python. But still having problem. I am using Django Framework with Python having PostgreSQL as backend database with Linux OS. My applications are long running. I am using threading. The problem I am facing is that the connections that are being created for database(postgres) update are not getting closed even though my threads had...
0
10346
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.