Search code examples
python-3.xsqlalchemysqlalchemy-utils

Why can't "create database if not exists" using sqlalchemy?


I wrote some lines to create database if not exists according to the sample:

https://www.programcreek.com/python/example/98164/sqlalchemy_utils.database_exists

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
db_user = 'postgres'
db_pass = 'xxxxxx'
db_ip = '127.0.0.1'
db_name = 'mydb'
engine = create_engine('postgresql://{}:{}@{}/{}/'.format(db_user,db_pass,db_ip,db_name))
if not database_exists(engine.url): create_database(engine.url)

It encounter the error:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/database.py", line 569, in create_database
    quote(engine, database),
  File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/orm.py", line 528, in quote
    dialect = get_bind(mixed).dialect
  File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/orm.py", line 339, in get_bind
    raise TypeError(
TypeError: This method accepts only Session, Engine, Connection and declarative model objects.

How to fix it then?


Solution

  • Solved by upgrading:

    pip  install  --upgrade  sqlalchemy-utils
    Found existing installation: SQLAlchemy-Utils 0.39.0
    Uninstalling SQLAlchemy-Utils-0.39.0:
      Successfully uninstalled SQLAlchemy-Utils-0.39.0
    Successfully installed sqlalchemy-utils-0.41.1
    

    Re-run the previous if not database_exists(engine.url): create_database(engine.url),success!