File size: 6,069 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

"""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)