| | import psycopg2 |
| | from app import settings as config |
| | from app.db import Base |
| | from app.user.models import User |
| | from psycopg2.errors import DuplicateDatabase |
| | from sqlalchemy import create_engine |
| | from sqlalchemy.orm import sessionmaker |
| |
|
| | |
| | DATABASE_USERNAME = config.DATABASE_USERNAME |
| | DATABASE_PASSWORD = config.DATABASE_PASSWORD |
| | DATABASE_HOST = config.DATABASE_HOST |
| | DATABASE_NAME = config.DATABASE_NAME |
| |
|
| | |
| | initial_connection_url = ( |
| | f"postgresql://{DATABASE_USERNAME}:{DATABASE_PASSWORD}@{DATABASE_HOST}/postgres" |
| | ) |
| |
|
| | print(initial_connection_url) |
| |
|
| | conn = None |
| |
|
| | |
| | try: |
| | conn = psycopg2.connect(initial_connection_url) |
| | conn.autocommit = True |
| | cursor = conn.cursor() |
| |
|
| | |
| | cursor.execute(f"CREATE DATABASE {DATABASE_NAME}") |
| | print(f"Database '{DATABASE_NAME}' created successfully") |
| |
|
| | except DuplicateDatabase as e: |
| | if "already exists" in str(e): |
| | print(f"Database '{DATABASE_NAME}' already exists.") |
| | else: |
| | print(f"Error creating database: {e}") |
| | finally: |
| | if conn: |
| | cursor.close() |
| | conn.close() |
| |
|
| | |
| | SQLALCHEMY_DATABASE_URL = f"postgresql://{DATABASE_USERNAME}:{DATABASE_PASSWORD}@{DATABASE_HOST}/{DATABASE_NAME}" |
| | print(SQLALCHEMY_DATABASE_URL) |
| |
|
| | |
| | engine = create_engine(SQLALCHEMY_DATABASE_URL) |
| |
|
| | |
| | Base.metadata.drop_all(engine) |
| | print("Tables dropped") |
| |
|
| | |
| | Base.metadata.create_all(engine) |
| | print("Tables created") |
| |
|
| | |
| | print("Populating database with default user") |
| | Session = sessionmaker(bind=engine) |
| | session = Session() |
| |
|
| | user = User( |
| | name="Admin User", |
| | password="admin", |
| | email="admin@example.com", |
| | ) |
| |
|
| | session.add(user) |
| | session.commit() |
| | print("Default user added") |
| |
|