Psycopg2 : Create a table in a stored procedure Postgres

Question:

Stored Procedure :

CREATE OR REPLACE FUNCTION try_create() RETURNS INT AS $$

  BEGIN
      CREATE TABLE hello(id SERIAL PRIMARY KEY, name TEXT);
      RETURN 1;
  END ;

$$ LANGUAGE plpgsql;

test.py

import psycopg2

conn = psycopg2.connect(user='a', password='a', dbname='a')
cur = conn.cursor()
cur.callproc('try_create', ())
print cur.fetchall()

I am trying to create a stored procedure which will create a table named hello. I am invoking the same using a python script. Upon running the above script I see the following output

[root@localhost partitioning]# python test.py
[(1,)]

But the table is not created at the db. Am I making something wrong here? Thanks.

Asked By: wonder

||

Answers:

You should commit the transaction, add the commands:

...
conn.commit()
conn.close()

Alternatively, you can set the connection in autocommit mode:

conn = psycopg2.connect(user='a', password='a', dbname='a')
conn.autocommit = True
cur = conn.cursor()
cur.callproc('try_create', ())
conn.close()

Read more about transactions in psycopg2.

Answered By: klin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.