1

I am attempting to create a PostgreSQL 12.1 database (not a schema) using the CREATE DATABASE statement from a Python 3.7.5 program connecting to a PostgreSQL 12.1 instance as user postgres over UnixODBC and using the PyODBC module, all running on Ubuntu 19.10. My program runs a loop that reads lines from a SQL DDL script, splitting SQL statements on the semicolon character. It logs the following errors:

16:15:20 ERROR    Error executing statement 'CREATE DATABASE "TestV1" WITH OWNER = postgres': ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')
16:15:20 CRITICAL Unable to create objects: ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')

My SQL DDL script begins with the following line: CREATE DATABASE "TestV1" WITH OWNER = postgres;

I've had success with CREATE SCHEMA in the same context, but not with CREATE DATABASE. As well, I cannot seem to find any answers here related to CREATE DATABASE on PostgreSQL specifically. I can create a database from the shell command line using createdb. I have tried setting AUTOCOMMIT on within the SQL DDL script, but that does not work.

4
  • 3
    Can you try setting autocommit=True in pyodbc.connect()? Commented Feb 14, 2020 at 0:45
  • I've tried setting AutoCommit=True in the connection string and it turns out to be the default, so the result is the same as if I left it out. Commented Feb 14, 2020 at 23:14
  • "[autocommit=True] turns out to be the default" - No. The Python DBAPI clearly specifies that the default must be autocommit=False. Commented Feb 14, 2020 at 23:33
  • 1
    @GordThompson Thanks for that. I was able to verify that autocommit is false by default when I tried removing my calls to the commit() and rollback() methods and was subsequently surprised to find my data missing. Commented Feb 15, 2020 at 0:37

1 Answer 1

1

It seems it is best to issue the createdb command from the Bash shell and be done with it. I can then connect to the newly created database from ODBC. Rinse and repeat for each database to be created and populated.

Sign up to request clarification or add additional context in comments.

1 Comment

Good on you for the workaround. Shame this doesn't work through the interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.