File size: 5,066 Bytes
2ed8996 | 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | """
Simple Database Setup for AegisLM
Creates all necessary tables using existing working patterns.
"""
import asyncio
import sys
import os
# Add to backend directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
async def setup_database():
"""Setup database tables."""
try:
from core.database import AsyncSessionLocal
from db_models import User, Evaluation, ApiKey, Role, Permission
print("🔧 Setting up database tables...")
# Create tables using the same pattern as main.py
async with AsyncSessionLocal() as db:
# Create tables one by one to avoid issues
from sqlalchemy import text
# Create roles table first
try:
await db.execute(text("""
CREATE TABLE IF NOT EXISTS roles (
id SERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL,
slug VARCHAR(50) UNIQUE NOT NULL,
description TEXT,
level INTEGER DEFAULT 1,
is_active BOOLEAN DEFAULT TRUE,
is_system BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)
"""))
print("✅ Created roles table")
except Exception as e:
print(f"⚠️ Roles table already exists: {str(e)}")
# Create users table enhancements
try:
await db.execute(text("""
ALTER TABLE users
ADD COLUMN IF NOT EXISTS verified_at TIMESTAMP WITH TIME ZONE,
ADD COLUMN IF NOT EXISTS is_superuser BOOLEAN DEFAULT FALSE
"""))
print("✅ Enhanced users table")
except Exception as e:
print(f"⚠️ Users table enhancement failed: {str(e)}")
# Create api_keys table
try:
await db.execute(text("""
CREATE TABLE IF NOT EXISTS api_keys (
id SERIAL PRIMARY KEY,
key_name VARCHAR(100) NOT NULL,
key_prefix VARCHAR(10) NOT NULL,
key_hash VARCHAR(255) NOT NULL,
user_id INTEGER REFERENCES users(id),
is_active BOOLEAN DEFAULT TRUE,
expires_at TIMESTAMP WITH TIME ZONE,
last_used_at TIMESTAMP WITH TIME ZONE,
usage_count INTEGER DEFAULT 0,
rate_limit_per_minute INTEGER DEFAULT 60,
permissions TEXT,
scope VARCHAR(50) DEFAULT 'evaluation',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)
"""))
print("✅ Created api_keys table")
except Exception as e:
print(f"⚠️ API keys table already exists: {str(e)}")
# Create evaluations table
try:
await db.execute(text("""
CREATE TABLE IF NOT EXISTS evaluations (
id SERIAL PRIMARY KEY,
job_id VARCHAR(255) UNIQUE NOT NULL,
user_id INTEGER REFERENCES users(id),
model_name VARCHAR(100) NOT NULL,
model_type VARCHAR(50) NOT NULL,
api_endpoint VARCHAR(255),
api_key VARCHAR(255),
dataset_name VARCHAR(100),
status VARCHAR(50) DEFAULT 'pending',
progress INTEGER DEFAULT 0,
current_phase VARCHAR(100),
config_snapshot JSONB,
result_summary JSONB,
prompt_count INTEGER DEFAULT 0,
created_by VARCHAR(255),
tags TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE
)
"""))
print("✅ Created evaluations table")
except Exception as e:
print(f"⚠️ Evaluations table already exists: {str(e)}")
print("✅ Database setup completed successfully!")
except Exception as e:
print(f"❌ Database setup failed: {str(e)}")
return False
return True
if __name__ == "__main__":
asyncio.run(setup_database())
|