Files
Outpost/initdb.py
2025-11-09 21:12:43 +00:00

129 lines
3.6 KiB
Python

import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from dotenv import load_dotenv
from os import getenv
load_dotenv()
# Database connection parameters
DB_HOST = getenv("DB_HOST")+":"+getenv("DB_PORT")
DB_USER = getenv("DB_USER")
DB_PASSWORD = getenv("DB_PASSWORD")
DB_NAME = "outpost"
def create_database():
"""Create the outpost database if it doesn't exist"""
try:
# Connect to PostgreSQL server (default postgres database)
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database="postgres"
)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
# Check if database exists
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (DB_NAME,))
exists = cur.fetchone()
if not exists:
cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(DB_NAME)))
print(f"Database '{DB_NAME}' created successfully")
else:
print(f"Database '{DB_NAME}' already exists")
cur.close()
conn.close()
except Exception as e:
print(f"Error creating database: {e}")
raise
def create_tables():
try:
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
password_hash VARCHAR(255) NOT NULL
)
""")
print("Table 'users' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS logging (
id SERIAL PRIMARY KEY,
time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER REFERENCES users(id),
action TEXT NOT NULL
)
""")
print("Table 'logging' created or already exists")
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error creating tables: {e}")
raise
def create_user_table(id):
try:
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cur = conn.cursor()
table_name = f"userpermissions.{id.lower().replace(' ', '_').replace('-', '_').replace('.', '_')}"
cur.execute(sql.SQL("""
CREATE TABLE IF NOT EXISTS {} (
key VARCHAR(255) PRIMARY KEY,
value TEXT
)
""").format(sql.Identifier(table_name)))
print(f"Table '{table_name}' created or already exists")
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error creating user table: {e}")
raise
def main():
"""Main function to set up the database"""
print("Starting database setup...")
# Step 1: Create database
create_database()
# Step 2: Create tables
create_tables()
print("\nDatabase setup completed successfully!")
print("\nTo create a user-specific table, call:")
print("create_user_table('username')")
if __name__ == "__main__":
main()