S115 PG驱动兼容
这个提交存在于:
父节点
c7937c099a
当前提交
0ca51f95a1
共有 2 个文件被更改,包括 114 次插入 和 4 次删除
|
|
@ -126,9 +126,7 @@ class Database:
|
||||||
import psycopg
|
import psycopg
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
raise RuntimeError(
|
return self._connect_postgresql_psycopg2(exc)
|
||||||
"PostgreSQL backend requires the optional 'psycopg' package."
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
pg = self.settings.postgresql
|
pg = self.settings.postgresql
|
||||||
if pg.dsn:
|
if pg.dsn:
|
||||||
|
|
@ -142,6 +140,29 @@ class Database:
|
||||||
row_factory=dict_row,
|
row_factory=dict_row,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _connect_postgresql_psycopg2(self, original_error: ImportError):
|
||||||
|
try:
|
||||||
|
import psycopg2
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
except ImportError as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
"PostgreSQL backend requires the optional 'psycopg' or 'psycopg2' package."
|
||||||
|
) from original_error if original_error else exc
|
||||||
|
|
||||||
|
pg = self.settings.postgresql
|
||||||
|
if pg.dsn:
|
||||||
|
return _Psycopg2ConnectionAdapter(psycopg2.connect(pg.dsn, cursor_factory=RealDictCursor))
|
||||||
|
return _Psycopg2ConnectionAdapter(
|
||||||
|
psycopg2.connect(
|
||||||
|
host=pg.host,
|
||||||
|
port=pg.port,
|
||||||
|
dbname=pg.database,
|
||||||
|
user=pg.user,
|
||||||
|
password=pg.password,
|
||||||
|
cursor_factory=RealDictCursor,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def _ensure_schema_migrations(self, conn) -> None:
|
def _ensure_schema_migrations(self, conn) -> None:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
|
|
@ -194,6 +215,22 @@ def load_database_settings(config_path: str | Path = "config.yaml") -> DatabaseS
|
||||||
return DatabaseSettings.from_mapping(payload)
|
return DatabaseSettings.from_mapping(payload)
|
||||||
|
|
||||||
|
|
||||||
|
class _Psycopg2ConnectionAdapter:
|
||||||
|
def __init__(self, connection):
|
||||||
|
self.connection = connection
|
||||||
|
|
||||||
|
def execute(self, query: str, params: tuple[Any, ...] | list[Any] | None = None):
|
||||||
|
cursor = self.connection.cursor()
|
||||||
|
cursor.execute(query, tuple(params or ()))
|
||||||
|
return cursor
|
||||||
|
|
||||||
|
def commit(self) -> None:
|
||||||
|
self.connection.commit()
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.connection.close()
|
||||||
|
|
||||||
|
|
||||||
def _as_bool(value: Any) -> bool:
|
def _as_bool(value: Any) -> bool:
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
return value
|
return value
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,14 @@ from pathlib import Path
|
||||||
from backend.dto.common import ErrorCode, error_response, success_response
|
from backend.dto.common import ErrorCode, error_response, success_response
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from database.db_helper import Database, DatabaseSettings, PostgresSettings, SqliteSettings, _load_yaml_subset
|
from database.db_helper import (
|
||||||
|
Database,
|
||||||
|
DatabaseSettings,
|
||||||
|
PostgresSettings,
|
||||||
|
SqliteSettings,
|
||||||
|
_Psycopg2ConnectionAdapter,
|
||||||
|
_load_yaml_subset,
|
||||||
|
)
|
||||||
from database.models import table_spec
|
from database.models import table_spec
|
||||||
from database.seed import DEFAULT_MATERIAL_CATEGORIES, seed_default_material_categories
|
from database.seed import DEFAULT_MATERIAL_CATEGORIES, seed_default_material_categories
|
||||||
|
|
||||||
|
|
@ -112,6 +119,72 @@ class DatabaseMetadataTests(unittest.TestCase):
|
||||||
|
|
||||||
self.assertEqual(settings.selected_backend, "sqlite")
|
self.assertEqual(settings.selected_backend, "sqlite")
|
||||||
|
|
||||||
|
def test_postgres_migration_runner_executes_split_statements(self):
|
||||||
|
class FakeConnection:
|
||||||
|
def __init__(self):
|
||||||
|
self.statements = []
|
||||||
|
|
||||||
|
def execute(self, statement):
|
||||||
|
self.statements.append(statement)
|
||||||
|
|
||||||
|
database = Database(
|
||||||
|
DatabaseSettings(
|
||||||
|
backend="postgresql",
|
||||||
|
postgresql=PostgresSettings(enabled=True, dsn="postgresql://example"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
conn = FakeConnection()
|
||||||
|
|
||||||
|
database._execute_script(
|
||||||
|
conn,
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS demo (id TEXT PRIMARY KEY);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_demo_id ON demo(id);
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(len(conn.statements), 2)
|
||||||
|
self.assertTrue(conn.statements[0].startswith("CREATE TABLE"))
|
||||||
|
self.assertTrue(conn.statements[1].startswith("CREATE INDEX"))
|
||||||
|
|
||||||
|
def test_psycopg2_adapter_exposes_connection_execute_shape(self):
|
||||||
|
class FakeCursor:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def execute(self, query, params):
|
||||||
|
self.calls.append((query, params))
|
||||||
|
|
||||||
|
def fetchone(self):
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
class FakeConnection:
|
||||||
|
def __init__(self):
|
||||||
|
self.cursor_instance = FakeCursor()
|
||||||
|
self.committed = False
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
def cursor(self):
|
||||||
|
return self.cursor_instance
|
||||||
|
|
||||||
|
def commit(self):
|
||||||
|
self.committed = True
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
raw = FakeConnection()
|
||||||
|
adapter = _Psycopg2ConnectionAdapter(raw)
|
||||||
|
|
||||||
|
cursor = adapter.execute("SELECT * FROM demo WHERE id = %s", ("demo_1",))
|
||||||
|
adapter.commit()
|
||||||
|
adapter.close()
|
||||||
|
|
||||||
|
self.assertEqual(cursor.fetchone(), {"ok": True})
|
||||||
|
self.assertEqual(raw.cursor_instance.calls, [("SELECT * FROM demo WHERE id = %s", ("demo_1",))])
|
||||||
|
self.assertTrue(raw.committed)
|
||||||
|
self.assertTrue(raw.closed)
|
||||||
|
|
||||||
|
|
||||||
class AuditServiceTests(unittest.TestCase):
|
class AuditServiceTests(unittest.TestCase):
|
||||||
def test_record_writes_audit_log_to_sqlite(self):
|
def test_record_writes_audit_log_to_sqlite(self):
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用