Download cases/cloud_data_warehouse/raw/mcp_servers/state/database.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 6.07 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/cloud_data_warehouse/raw/mcp_servers/state/database.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/cloud_data_warehouse/raw/mcp_servers/state/database.py
-
curl -L -o database.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/cloud_data_warehouse/raw/mcp_servers/state/database.py
6.07 kB
| """Generic JSON file-backed database for isolated runtime state.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from typing import Any, Callable, Dict, List, Optional | |
| from mcp_servers.utils import safe_copy | |
| class Database: | |
| PK_FIELDS = { | |
| "organization": "org_id", | |
| "user": "user_id", | |
| "warehouse": "warehouse_id", | |
| "dataset": "dataset_id", | |
| "table": "table_id", | |
| "column": "column_id", | |
| "access_grant": "grant_id", | |
| "query_job": "query_job_id", | |
| "import_job": "import_job_id", | |
| "export_job": "export_job_id", | |
| "cost_usage_record": "usage_id", | |
| "quota_policy": "quota_id", | |
| } | |
| FILE_STEMS = { | |
| "organization": "organizations", | |
| "user": "users", | |
| "warehouse": "warehouses", | |
| "dataset": "datasets", | |
| "table": "tables", | |
| "column": "columns", | |
| "access_grant": "access_grants", | |
| "query_job": "query_jobs", | |
| "import_job": "import_jobs", | |
| "export_job": "export_jobs", | |
| "cost_usage_record": "cost_usage_records", | |
| "quota_policy": "quota_policies", | |
| } | |
| SINGULAR_NAMES = {value: key for key, value in FILE_STEMS.items()} | |
| def __init__(self, db_dir: str) -> None: | |
| self.db_dir = Path(db_dir) | |
| self._data: Dict[str, List[Dict[str, Any]]] = {} | |
| def _file(self, entity_type: str) -> Path: | |
| return self.db_dir / f"{self.FILE_STEMS.get(entity_type, entity_type + 's')}.json" | |
| def _pk_field(self, entity_type: str) -> str: | |
| return self.PK_FIELDS.get(entity_type, f"{entity_type}_id") | |
| def _ensure_loaded(self, entity_type: str) -> None: | |
| if entity_type in self._data: | |
| return | |
| path = self._file(entity_type) | |
| if path.exists(): | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| self._data[entity_type] = payload if isinstance(payload, list) else [] | |
| else: | |
| self._data[entity_type] = [] | |
| def _flush(self, entity_type: str) -> None: | |
| self.db_dir.mkdir(parents=True, exist_ok=True) | |
| path = self._file(entity_type) | |
| tmp = path.with_suffix(path.suffix + ".tmp") | |
| tmp.write_text(json.dumps(self._data.get(entity_type, []), indent=2, ensure_ascii=False), encoding="utf-8") | |
| tmp.replace(path) | |
| def _ref(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| pk = self._pk_field(entity_type) | |
| for record in self._data[entity_type]: | |
| if record.get(pk) == entity_id or record.get("id") == entity_id: | |
| return record | |
| return None | |
| def get_all(self, entity_type: str) -> List[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| return safe_copy(self._data[entity_type]) | |
| def get_by_id(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| ref = self._ref(entity_type, entity_id) | |
| return safe_copy(ref) if ref is not None else None | |
| def get_one(self, entity_type: str, id_field: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| found = self.get_by_id(entity_type, entity_id) | |
| if found is not None: | |
| return found | |
| matches = self.query(entity_type, lambda row: row.get(id_field) == entity_id) | |
| return matches[0] if matches else None | |
| def query(self, entity_type: str, predicate: Callable[[Dict[str, Any]], bool]) -> List[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| return safe_copy([record for record in self._data[entity_type] if predicate(record)]) | |
| def insert(self, entity_type: str, record: Dict[str, Any]) -> Dict[str, Any]: | |
| self._ensure_loaded(entity_type) | |
| stored = safe_copy(record) | |
| self._data[entity_type].append(stored) | |
| self._flush(entity_type) | |
| return safe_copy(stored) | |
| def upsert(self, entity_type: str, arg1: Any, arg2: Any = None) -> Dict[str, Any]: | |
| if isinstance(arg1, dict): | |
| record = safe_copy(arg1) | |
| entity_id = record.get(self._pk_field(entity_type)) | |
| else: | |
| entity_id = str(arg1) | |
| record = safe_copy(arg2 if isinstance(arg2, dict) else {}) | |
| ref = self._ref(entity_type, str(entity_id)) | |
| if ref is None: | |
| return self.insert(entity_type, record) | |
| ref.update(record) | |
| self._flush(entity_type) | |
| return safe_copy(ref) | |
| def update(self, entity_type: str, entity_id: str, patch: Dict[str, Any]) -> Optional[Dict[str, Any]]: | |
| ref = self._ref(entity_type, entity_id) | |
| if ref is None: | |
| return None | |
| ref.update(safe_copy(patch)) | |
| self._flush(entity_type) | |
| return safe_copy(ref) | |
| def delete(self, entity_type: str, entity_id: str) -> bool: | |
| self._ensure_loaded(entity_type) | |
| pk = self._pk_field(entity_type) | |
| before = len(self._data[entity_type]) | |
| self._data[entity_type] = [row for row in self._data[entity_type] if row.get(pk) != entity_id and row.get("id") != entity_id] | |
| if len(self._data[entity_type]) != before: | |
| self._flush(entity_type) | |
| return True | |
| return False | |
| def delete_many(self, entity_type: str, predicate: Callable[[Dict[str, Any]], bool]) -> int: | |
| self._ensure_loaded(entity_type) | |
| before = len(self._data[entity_type]) | |
| self._data[entity_type] = [row for row in self._data[entity_type] if not predicate(row)] | |
| removed = before - len(self._data[entity_type]) | |
| if removed: | |
| self._flush(entity_type) | |
| return removed | |
| def save(self, entity_type: str, records: List[Dict[str, Any]]) -> None: | |
| self._data[entity_type] = safe_copy(records) | |
| self._flush(entity_type) | |
| def snapshot(self) -> Dict[str, List[Dict[str, Any]]]: | |
| if self.db_dir.exists(): | |
| for path in self.db_dir.glob("*.json"): | |
| self._ensure_loaded(self.SINGULAR_NAMES.get(path.stem, path.stem)) | |
| return safe_copy(self._data) | |