[Django]-Psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block

6👍

Use the autocommit property of the connection:

from psycopg2 import sql

def create_database(tenant_id):
  conn = psycopg2.connect(database="mydb", user="dbuser", password="mypass", host="db")
  cursor = conn.cursor()
  conn.autocommit = True #!
#  transaction.set_autocommit(True) #?
  dbname = sql.Identifier(f'tenant_{tenant_id}')
  create_cmd = sql.SQL('CREATE DATABASE {}').format(dbname)
  grant_cmd = sql.SQL('GRANT ALL PRIVILEGES ON DATABASE {} TO dbuser').format(dbname)
  cursor.execute(create_cmd)
  cursor.execute(grant_cmd)
  cursor.close()
  conn.close()

Read in the docs about connection.autocommit.

Note also the use of the SQL string composition to avoid SQL injection.

👤klin

Leave a comment