-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_db.py
More file actions
45 lines (35 loc) · 1.1 KB
/
init_db.py
File metadata and controls
45 lines (35 loc) · 1.1 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
38
39
40
41
42
43
44
45
import os
import psycopg2
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Get the DATABASE_URL from environment variables
DATABASE_URL = os.getenv('DATABASE_URL')
# Check if the URL is set
if not DATABASE_URL:
print("DATABASE_URL not found in environment variables. Please check your .env file.")
exit()
def create_tables():
"""Connects to the database and creates the tables from schema.sql."""
conn = None
try:
# Connect to your PostgreSQL database
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
# Read the SQL file
with open('schema.sql', 'r') as f:
sql_commands = f.read()
# Execute the SQL commands
cur.execute(sql_commands)
# Commit the changes
conn.commit()
print("Tables created successfully!")
except psycopg2.Error as e:
print(f"Database error: {e}")
if conn:
conn.rollback() # Rollback in case of error
finally:
if conn:
conn.close()
if __name__ == '__main__':
create_tables()