File size: 10,071 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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | """
SQLite compatibility utilities for AegisLM SaaS Backend.
Provides compatibility layer for database models to work seamlessly
with both PostgreSQL and SQLite databases.
"""
import logging
from typing import Any, Dict
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.sql import func
logger = logging.getLogger(__name__)
class SQLiteCompatibilityMixin:
"""
Mixin class to provide SQLite compatibility for database models.
Handles differences between PostgreSQL and SQLite such as:
- JSON field types
- DateTime timezone handling
- Boolean field handling
- Auto-incrementing IDs
"""
@classmethod
def get_sqlite_compatible_table_args(cls):
"""Get table arguments compatible with SQLite."""
from sqlalchemy import Index
# SQLite-specific indexes and constraints
table_args = []
# Add indexes for performance
if hasattr(cls, '__table__'):
for column in cls.__table__.columns:
if column.index and not column.primary_key:
table_args.append(Index(f"idx_{cls.__tablename__}_{column.name}", column.name))
return tuple(table_args) if table_args else None
def get_database_type(session: AsyncSession) -> str:
"""
Determine the current database type.
Args:
session: Database session
Returns:
str: "postgresql" or "sqlite"
"""
try:
result = session.execute(text("SELECT sqlite_version()"))
return "sqlite"
except Exception:
try:
result = session.execute(text("SELECT version()"))
return "postgresql"
except Exception:
return "unknown"
def is_sqlite_session(session: AsyncSession) -> bool:
"""
Check if the current session is using SQLite.
Args:
session: Database session
Returns:
bool: True if using SQLite
"""
return get_database_type(session) == "sqlite"
def is_postgresql_session(session: AsyncSession) -> bool:
"""
Check if the current session is using PostgreSQL.
Args:
session: Database session
Returns:
bool: True if using PostgreSQL
"""
return get_database_type(session) == "postgresql"
def get_compatible_now(session: AsyncSession):
"""
Get database-compatible current timestamp function.
Args:
session: Database session
Returns:
SQL function for current timestamp
"""
if is_sqlite_session(session):
return func.datetime('now', 'localtime')
else:
return func.now()
def get_json_field_compatible_value(value: Any, session: AsyncSession) -> Any:
"""
Convert JSON field value to be compatible with current database.
Args:
value: JSON value to convert
session: Database session
Returns:
Any: Database-compatible JSON value
"""
if is_sqlite_session(session):
# SQLite stores JSON as text
import json
return json.dumps(value) if value is not None else None
else:
# PostgreSQL handles JSON natively
return value
def parse_json_field_value(value: Any, session: AsyncSession) -> Any:
"""
Parse JSON field value from database.
Args:
value: JSON value from database
session: Database session
Returns:
Any: Parsed JSON value
"""
if is_sqlite_session(session):
# SQLite stores JSON as text
import json
if isinstance(value, str):
try:
return json.loads(value)
except json.JSONDecodeError:
return value
return value
else:
# PostgreSQL handles JSON natively
return value
async def migrate_postgres_to_sqlite(pg_session: AsyncSession, sqlite_session: AsyncSession) -> bool:
"""
Migrate data from PostgreSQL to SQLite.
Args:
pg_session: PostgreSQL session
sqlite_session: SQLite session
Returns:
bool: True if migration successful
"""
try:
logger.info("Starting PostgreSQL to SQLite migration...")
# Get all table names
from core.database import Base
tables = Base.metadata.tables.keys()
for table_name in tables:
if table_name in ['alembic_version']: # Skip migration tables
continue
logger.info(f"Migrating table: {table_name}")
# Get data from PostgreSQL
pg_result = await pg_session.execute(text(f"SELECT * FROM {table_name}"))
rows = pg_result.fetchall()
if not rows:
continue
# Get column names
columns = [desc[0] for desc in pg_result.cursor.description]
# Insert into SQLite
for row in rows:
# Convert row to dictionary
row_dict = dict(zip(columns, row))
# Handle JSON fields for SQLite
for key, value in row_dict.items():
if isinstance(value, dict) or isinstance(value, list):
row_dict[key] = get_json_field_compatible_value(value, sqlite_session)
# Build insert query
placeholders = ', '.join([':' + col for col in columns])
insert_query = text(f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({placeholders})")
await sqlite_session.execute(insert_query, row_dict)
await sqlite_session.commit()
logger.info("PostgreSQL to SQLite migration completed successfully")
return True
except Exception as e:
logger.error(f"Migration failed: {e}")
await sqlite_session.rollback()
return False
async def sync_sqlite_to_postgresql(sqlite_session: AsyncSession, pg_session: AsyncSession) -> bool:
"""
Sync data from SQLite back to PostgreSQL.
Args:
sqlite_session: SQLite session
pg_session: PostgreSQL session
Returns:
bool: True if sync successful
"""
try:
logger.info("Starting SQLite to PostgreSQL sync...")
# Get all table names
from core.database import Base
tables = Base.metadata.tables.keys()
for table_name in tables:
if table_name in ['alembic_version']: # Skip migration tables
continue
logger.info(f"Syncing table: {table_name}")
# Get data from SQLite
sqlite_result = await sqlite_session.execute(text(f"SELECT * FROM {table_name}"))
rows = sqlite_result.fetchall()
if not rows:
continue
# Get column names
columns = [desc[0] for desc in sqlite_result.cursor.description]
# Insert into PostgreSQL
for row in rows:
# Convert row to dictionary
row_dict = dict(zip(columns, row))
# Handle JSON fields for PostgreSQL
for key, value in row_dict.items():
if isinstance(value, str):
try:
import json
parsed = json.loads(value)
row_dict[key] = parsed
except json.JSONDecodeError:
pass
# Build insert query with ON CONFLICT handling
placeholders = ', '.join([':' + col for col in columns])
insert_query = text(f"""
INSERT INTO {table_name} ({', '.join(columns)})
VALUES ({placeholders})
ON CONFLICT (id) DO UPDATE SET
{', '.join([f"{col} = EXCLUDED.{col}" for col in columns if col != 'id'])}
""")
await pg_session.execute(insert_query, row_dict)
await pg_session.commit()
logger.info("SQLite to PostgreSQL sync completed successfully")
return True
except Exception as e:
logger.error(f"Sync failed: {e}")
await pg_session.rollback()
return False
class DatabaseTypeDetector:
"""Utility class for detecting and managing database types."""
def __init__(self, session: AsyncSession):
self.session = session
self._db_type = None
@property
def is_sqlite(self) -> bool:
"""Check if using SQLite."""
if self._db_type is None:
self._db_type = get_database_type(self.session)
return self._db_type == "sqlite"
@property
def is_postgresql(self) -> bool:
"""Check if using PostgreSQL."""
if self._db_type is None:
self._db_type = get_database_type(self.session)
return self._db_type == "postgresql"
@property
def db_type(self) -> str:
"""Get database type."""
if self._db_type is None:
self._db_type = get_database_type(self.session)
return self._db_type
def get_now_function(self):
"""Get appropriate now function for database."""
return get_compatible_now(self.session)
def process_json_value(self, value: Any) -> Any:
"""Process JSON value for database compatibility."""
if self.is_sqlite:
return get_json_field_compatible_value(value, self.session)
return value
def parse_json_value(self, value: Any) -> Any:
"""Parse JSON value from database."""
if self.is_sqlite:
return parse_json_field_value(value, self.session)
return value
|