Python – pygresql – insert and return serial

postgresqlpygresqlpython

I'm using PyGreSQL to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid… aka the value that the DB created for my ID field:

create table job_runners (
    id           SERIAL PRIMARY KEY,
    hostname     varchar(100) not null,
    is_available boolean default FALSE
    );

sql = "insert into job_runners (hostname) values ('localhost')"

When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.

Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?

Best Answer

INSERT INTO job_runners
    (hostname,is_available) VALUES ('localhost',true)
    RETURNING id

That said, I have no idea about pygresql, but by what you've already written, I guess it's db.query() that you want to use here.