Created
July 18, 2020 02:04
-
-
Save matutter/36bd1e2226e20fbe7bbf5b4aa23807de to your computer and use it in GitHub Desktop.
A python script to create a database if it does not exist with psycopg2 & Postgres.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from psycopg2 import connect, extensions, sql, OperationalError | |
import re | |
POSTGRES_PASSWORD = 'mypasswd' | |
POSTGRES_USER = 'myuser' | |
POSTGRES_DB = 'mytest12' | |
connect_string = f"postgres://{POSTGRES_USER}:{POSTGRES_PASSWORD}@localhost" | |
db_connect_string = f"{connect_string}/{POSTGRES_DB}" | |
try: | |
engine = connect(db_connect_string) | |
except OperationalError as e: | |
if e.args: | |
msg = e.args[0] | |
m = re.match('^FATAL:.*database.*does not exist\s', e.args[0], re.IGNORECASE) | |
if m and m.endpos == len(msg): | |
engine = connect(f'{connect_string}/postgres') | |
engine.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) | |
cursor = engine.cursor() | |
cursor.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(POSTGRES_DB))) | |
cursor.close() | |
engine.close() | |
engine = connect(db_connect_string) | |
else: | |
raise | |
print(f'Connected to: {db_connect_string}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment