Question

I use psycopg2 for accessing my postgres database in python. My function should create a new database, the code looks like this:

def createDB(host, username, dbname):
  adminuser = settings.DB_ADMIN_USER
  adminpass = settings.DB_ADMIN_PASS

  try:
    conn=psycopg2.connect(user=adminuser, password=adminpass, host=host)
    cur = conn.cursor()
    cur.execute("CREATE DATABASE %s OWNER %s" % (nospecial(dbname), nospecial(username)))
    conn.commit()
  except Exception, e:
    raise e
  finally:
    cur.close()
    conn.close()

def nospecial(s):
  pattern = re.compile('[^a-zA-Z0-9_]+')
  return pattern.sub('', s)

When I call createDB my postgres server throws an error: CREATE DATABASE cannot run inside a transaction block with the errorcode 25001 which stands for "ACTIVE SQL TRANSACTION".

I'm pretty sure that there is no other connection running at the same time and every connection I used before calling createDB is shut down.

Was it helpful?

Solution

It looks like your cursor() is actually a transaction: http://initd.org/psycopg/docs/cursor.html#cursor

Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors. Cursors created from different connections can or can not be isolated, depending on the connections’ isolation level. See also rollback() and commit() methods.

Skip the cursor and just execute your query. Drop commit() as well, you can't commit when you don't have a transaction open.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top