from typing import Protocol

from sqlalchemy import create_engine, text


class LegacySource(Protocol):
    def rows(self, table: str) -> list[dict]: ...


class MemorySource:
    def __init__(self, tables: dict[str, list[dict]]):
        self.tables = tables

    def rows(self, table: str) -> list[dict]:
        return [dict(r) for r in self.tables.get(table, [])]


class SqlServerSource:
    """只读访问旧 SQL Server 库（文档 12.3：只读核对，不在生产库写入）。"""

    def __init__(self, url: str):
        self.engine = create_engine(url)

    def rows(self, table: str) -> list[dict]:
        with self.engine.connect() as c:
            return [dict(r._mapping) for r in c.execute(text(f"SELECT * FROM [dbo].[{table}]"))]
