Pretor/pretor/core/database/postgres.py

69 lines
2.9 KiB
Python

# Copyright 2026 zhaoxi826
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import asyncio
import ray
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel
from pretor.core.database.module.individual import IndividualDatabase
from pretor.core.database.module.user import AuthDatabase
from pretor.core.database.module.provider import ProviderDatabase
@ray.remote
class PostgresDatabase:
def __init__(self):
user = os.environ.get('POSTGRES_USER')
password = os.environ.get('POSTGRES_PASSWORD')
host = os.environ.get('POSTGRES_HOST')
port = os.environ.get('POSTGRES_PORT')
database = os.environ.get('POSTGRES_DB')
database_url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{database}"
self.async_engine = create_async_engine(database_url, echo=True)
self.async_session_maker = sessionmaker(self.async_engine, class_=AsyncSession, expire_on_commit=False)
self._auth_database = AuthDatabase(self.async_session_maker)
self._provider_database = ProviderDatabase(self.async_session_maker)
self._individual_database = IndividualDatabase(self.async_session_maker)
self.ready_event = asyncio.Event()
async def init_db(self) -> None:
try:
async with self.async_engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
except Exception as e:
# Provide a warning if the database is not accessible, allowing
# the app to start up for development/UI tests without crashing immediately.
print(f"Warning: Failed to initialize PostgreSQL database: {e}")
finally:
self.ready_event.set()
async def auth_database(self, method_name: str, *args, **kwargs):
await self.ready_event.wait()
method = getattr(self._auth_database, method_name)
return await method(*args, **kwargs)
async def provider_database(self, method_name: str, *args, **kwargs):
await self.ready_event.wait()
method = getattr(self._provider_database, method_name)
return await method(*args, **kwargs)
async def individual_database(self, method_name: str, *args, **kwargs):
await self.ready_event.wait()
method = getattr(self._individual_database, method_name)
return await method(*args, **kwargs)