-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_db_temp.py
More file actions
37 lines (30 loc) · 1.2 KB
/
create_db_temp.py
File metadata and controls
37 lines (30 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import os
from dotenv import load_dotenv
load_dotenv()
def create_database():
user = os.getenv("POSTGRES_USER", "postgres")
password = os.getenv("POSTGRES_PASSWORD", "postgres")
host = os.getenv("POSTGRES_HOST", "localhost")
port = os.getenv("POSTGRES_PORT", "5432")
dbname = os.getenv("POSTGRES_DB", "silo_db")
try:
# Connect to default postgres database to create a new one
con = psycopg2.connect(dbname='postgres', user=user, host=host, password=password, port=port)
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
# Check if database exists
cur.execute(f"SELECT 1 FROM pg_catalog.pg_database WHERE datname='{dbname}'")
exists = cur.fetchone()
if not exists:
cur.execute(f"CREATE DATABASE {dbname}")
print(f"Database {dbname} created successfully.")
else:
print(f"Database {dbname} already exists.")
cur.close()
con.close()
except Exception as e:
print(f"Error creating database: {e}")
if __name__ == "__main__":
create_database()