Create database if not exists.

See original GitHub issue

I’m using the multi-database configuration and I’m wondering if alembic is able to create new databases as they are added to the databases section in alembic.ini.

[alembic]
# path to migration scripts
script_location = ./db

databases = engine1, engine2  # do I need to manage this out of band from the migrations?

[engine1]
sqlalchemy.url = driver://user:pass@localhost/dbname

[engine2]
sqlalchemy.url = driver://user:pass@localhost/dbname2

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:4
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
zzzeekcommented, Oct 29, 2019

hi there -

Alembic doesn’t do anything with “CREATE DATABASE”, that part is normally run by the database administrator manually, or as part of your software install / build system if you are using something like that (e.g. ansible, docker, puppet, shell scripts, etc).

you can also add this step to your env.py if you’d like, basically as env.py runs through engines, you can emit "CREATE DATABASE " based on what the URL says it should be. you can parse the url using sqlalchemy.engine.url.make_url(url_string) then look at the “database” portion (if this is mysql or postgresql) and emit CREATE DATABASE from that given your “master” database connection.

1reaction
am17torrescommented, Oct 30, 2019

I ended up doing this which worked.

    for name in re.split(r",\s*", db_names):
        engines[name] = rec = {}
        rec["engine"] = engine = engine_from_config(
            context.config.get_section(name),
            prefix="sqlalchemy.",
            poolclass=pool.NullPool,
        )

        host_uri = re.sub(name + r"$", '', str(engine.url))
        if host_uri not in host_connections:
            host_connections[host_uri] = []

        host_connections[host_uri].append(name)

    for host, databases in host_connections.items():
        engine = create_engine(host)
        conn = engine.connect()
        try:
            for database in databases:
                logger.info(
                    "Ensuring database '%s' exists on host '%s'" % (database, host))
                    conn.execute("CREATE DATABASE IF NOT EXISTS %s" % database)
        except Exception as ex:
            logger.error(ex)
        finally:
            conn.close()

The only nice to have feature I’m missing is supressing the warning if the database already exists.

Read more comments on GitHub >

github_iconTop Results From Across the Web

MySQL 8.0 Reference Manual :: 13.1.12 CREATE DATABASE ...
Because there are no tables in a database when it is initially created, the CREATE DATABASE statement creates only a directory under the...
Read more >
MySQL create database if not exist - Stack Overflow
I'm not sure exactly how you'd check, but if you just want to create it if it doesn't exist, then you can do....
Read more >
Creating a New Database in MySQL
Introduction to the MySQL CREATE DATABASE statement · First, specify name of the database after the the CREATE DATABASE keywords. · Second, use...
Read more >
How to Create Database in MySQL (Create MySQL Tables)
1. In first step Open the ER model of MyFlix database that you created in earlier tutorial. 2. Now Click on the database...
Read more >
PostgreSQL Create Database if not Exists - Linux Hint
The “Create Database if not Exists” notation is supported by some of the programming languages. With the help of this notation, you can...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found