|
| 1 | +from abc import ABC |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import httpx |
| 5 | +from anyio import to_thread |
| 6 | +from pydantic import BaseModel, SecretStr |
| 7 | +from sqlalchemy.engine import Engine |
| 8 | +from sqlalchemy import create_engine |
| 9 | +from sqlalchemy.pool import StaticPool |
| 10 | +from sqlalchemy.orm import sessionmaker, Session |
| 11 | + |
| 12 | +from pysus import CACHEPATH |
| 13 | +from pysus.api import types |
| 14 | +from pysus.api.ducklake.functional import download_s3, upload_s3 |
| 15 | + |
| 16 | + |
| 17 | +class DuckLakeCredentials(BaseModel): |
| 18 | + access_key: SecretStr |
| 19 | + secret_key: SecretStr |
| 20 | + |
| 21 | + |
| 22 | +class BaseAdapter(ABC): |
| 23 | + cache_dir: Path = Path(CACHEPATH) / "ducklake" |
| 24 | + db_local: Path |
| 25 | + db_remote: Path |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, engine=None, credentials: DuckLakeCredentials | None = None, **data |
| 29 | + ) -> None: |
| 30 | + self._engine = engine |
| 31 | + self._session_factory = None |
| 32 | + self.cache_dir.mkdir(parents=True, exist_ok=True) |
| 33 | + self.credentials = credentials |
| 34 | + |
| 35 | + @property |
| 36 | + def remote_url(self) -> str: |
| 37 | + return f"https://{types.S3_ENDPOINT}/{types.S3_BUCKET}/{self.db_remote}" |
| 38 | + |
| 39 | + def get_session(self) -> Session: |
| 40 | + if not self._session_factory: |
| 41 | + raise RuntimeError("Database engine not initialized. Call connect() first.") |
| 42 | + return self._session_factory() |
| 43 | + |
| 44 | + async def connect(self, force: bool = False) -> None: |
| 45 | + if self._engine and not force: |
| 46 | + if not self._session_factory: |
| 47 | + self._session_factory = sessionmaker(bind=self._engine) |
| 48 | + return |
| 49 | + |
| 50 | + await self._download_catalog( |
| 51 | + self.db_local, |
| 52 | + str(self.db_remote), |
| 53 | + ) |
| 54 | + self._engine = await to_thread.run_sync(self.setup_engine) |
| 55 | + self._session_factory = sessionmaker(bind=self._engine) |
| 56 | + |
| 57 | + def setup_engine( |
| 58 | + self, access_key: str | None = None, secret_key: str | None = None |
| 59 | + ) -> Engine: |
| 60 | + engine: Engine = create_engine( |
| 61 | + f"duckdb:///{self.db_local}", |
| 62 | + poolclass=StaticPool, |
| 63 | + ) |
| 64 | + |
| 65 | + with engine.connect() as conn: |
| 66 | + conn.exec_driver_sql("INSTALL ducklake; LOAD ducklake;") |
| 67 | + |
| 68 | + has_pysus = conn.exec_driver_sql( |
| 69 | + "SELECT 1 FROM information_schema.schemata WHERE schema_name = 'pysus'" |
| 70 | + ).fetchone() |
| 71 | + |
| 72 | + if has_pysus: |
| 73 | + conn.exec_driver_sql("SET search_path='pysus,main';") |
| 74 | + else: |
| 75 | + conn.exec_driver_sql("SET search_path='main';") |
| 76 | + |
| 77 | + s3_cfg = { |
| 78 | + "s3_endpoint": types.S3_ENDPOINT, |
| 79 | + "s3_region": types.S3_REGION, |
| 80 | + "s3_url_style": "path", |
| 81 | + "s3_use_ssl": "true", |
| 82 | + } |
| 83 | + |
| 84 | + if access_key and secret_key: |
| 85 | + s3_cfg["s3_access_key_id"] = access_key |
| 86 | + s3_cfg["s3_secret_access_key"] = secret_key |
| 87 | + |
| 88 | + for key, value in s3_cfg.items(): |
| 89 | + conn.exec_driver_sql(f"SET {key}='{value}'") |
| 90 | + |
| 91 | + conn.commit() |
| 92 | + |
| 93 | + return engine |
| 94 | + |
| 95 | + async def _download_catalog(self, local_path: Path, remote_path: str) -> None: |
| 96 | + url = f"https://{types.S3_ENDPOINT}/{types.S3_BUCKET}/{remote_path}" |
| 97 | + |
| 98 | + if local_path.exists(): |
| 99 | + try: |
| 100 | + local_size = local_path.stat().st_size |
| 101 | + except OSError: |
| 102 | + local_size = -1 |
| 103 | + else: |
| 104 | + local_size = -1 |
| 105 | + |
| 106 | + async with httpx.AsyncClient(follow_redirects=True) as client: |
| 107 | + try: |
| 108 | + head = await client.head(url) |
| 109 | + head.raise_for_status() |
| 110 | + remote_size = int(head.headers.get("content-length", 0)) |
| 111 | + except Exception: |
| 112 | + remote_size = 0 |
| 113 | + |
| 114 | + if remote_size == local_size: |
| 115 | + return |
| 116 | + |
| 117 | + access_key = ( |
| 118 | + self.credentials.access_key.get_secret_value() if self.credentials else None |
| 119 | + ) |
| 120 | + secret_key = ( |
| 121 | + self.credentials.secret_key.get_secret_value() if self.credentials else None |
| 122 | + ) |
| 123 | + |
| 124 | + await download_s3( |
| 125 | + remote_path=remote_path, |
| 126 | + local_path=local_path, |
| 127 | + access_key=access_key, |
| 128 | + secret_key=secret_key, |
| 129 | + ) |
| 130 | + |
| 131 | + async def _upload_catalog(self) -> None: |
| 132 | + if not self.credentials: |
| 133 | + raise PermissionError( |
| 134 | + "Admin credentials required to upload catalog.", |
| 135 | + ) |
| 136 | + |
| 137 | + if not self.db_local.exists(): |
| 138 | + raise FileNotFoundError("catalog file not found") |
| 139 | + |
| 140 | + await upload_s3( |
| 141 | + local_path=self.db_local, |
| 142 | + remote_path=str(self.db_remote), |
| 143 | + access_key=self.credentials.access_key.get_secret_value(), |
| 144 | + secret_key=self.credentials.secret_key.get_secret_value(), |
| 145 | + ) |
| 146 | + |
| 147 | + async def close(self, update: bool = False) -> None: |
| 148 | + if update: |
| 149 | + await self._upload_catalog() |
| 150 | + |
| 151 | + if self._engine: |
| 152 | + await to_thread.run_sync(self._engine.dispose) |
| 153 | + self._engine = None |
| 154 | + self._session_factory = None |
| 155 | + |
| 156 | + |
| 157 | +class CatalogAdapter(BaseAdapter): |
| 158 | + def __init__(self, engine=None, **data) -> None: |
| 159 | + super().__init__(engine=engine, **data) |
| 160 | + self.db_local: Path = self.cache_dir / "catalog.duckdb" |
| 161 | + self.db_remote: str = "public/catalog.duckdb" |
| 162 | + |
| 163 | + |
| 164 | +class DatasetAdapter(BaseAdapter): |
| 165 | + def __init__(self, name: str, engine=None, **data) -> None: |
| 166 | + super().__init__(engine=engine, **data) |
| 167 | + self.dataset_name: str = name |
| 168 | + self.db_local: Path = self.cache_dir / f"catalog_{name}.duckdb" |
| 169 | + self.db_remote: str = f"datasets/catalog_{name}.duckdb" |
| 170 | + |
| 171 | + |
| 172 | +class ColumnsAdapter(BaseAdapter): |
| 173 | + def __init__(self, engine=None, **data) -> None: |
| 174 | + super().__init__(engine=engine, **data) |
| 175 | + self.db_local: Path = self.cache_dir / "columns.duckdb" |
| 176 | + self.db_remote: str = "public/columns.duckdb" |
0 commit comments