views:

37

answers:

1

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.

+2  A: 

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.

Frank Heikens
Thanks for putting me into the right direction. The solution is described here:http://lists.initd.org/pipermail/psycopg/2002-February/000758.html
Kai
Sorry, that was the solution if you use psycopg1, for psycopg2 instead of conn.autocommit() you do conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) and it should work.
Kai