File size: 7,301 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""JSON file-backed database for C_48_09_01."""
from __future__ import annotations

import json
import os
from typing import Any, Callable, Dict, List, Optional

from mcp_servers.utils import extract_id_sequence, generate_id, safe_copy


ENTITY_COLLECTION = {
    "audit_log": "audit_logs",
    "data_query": "data_queries",
    "dictionary_version": "dictionary_versions",
    "event": "events",
    "export_job": "export_jobs",
    "field_value": "field_values",
    "form_instance": "form_instances",
    "instrument": "instruments",
    "instrument_field": "instrument_fields",
    "project": "projects",
    "project_user": "project_users",
    "quality_rule_result": "quality_rule_results",
    "record": "records",
    "record_event": "record_events"
}
ENTITY_ID_FIELD = {
    "audit_log": "audit_id",
    "data_query": "query_id",
    "dictionary_version": "dictionary_version_id",
    "event": "event_id",
    "export_job": "export_id",
    "field_value": "value_id",
    "form_instance": "form_instance_id",
    "instrument": "instrument_id",
    "instrument_field": "field_id",
    "project": "project_id",
    "project_user": "user_id",
    "quality_rule_result": "quality_result_id",
    "record": "record_id",
    "record_event": "record_event_id"
}


class Database:
    """Small JSON database that writes only to the active runtime directory."""

    def __init__(self, db_dir: str) -> None:
        self.db_dir = os.path.abspath(db_dir)
        self._data: Dict[str, List[Dict[str, Any]]] = {}
        self._id_counters: Dict[str, int] = {}

    def _collection(self, entity_type: str) -> str:
        return ENTITY_COLLECTION.get(entity_type, f"{entity_type}s")

    def _file(self, entity_type: str) -> str:
        return os.path.join(self.db_dir, f"{self._collection(entity_type)}.json")

    def _pk_field(self, entity_type: str) -> str:
        return ENTITY_ID_FIELD.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 os.path.exists(path):
            with open(path, "r", encoding="utf-8") as handle:
                raw = json.load(handle)
            self._data[entity_type] = raw if isinstance(raw, list) else []
        else:
            self._data[entity_type] = []
        pk = self._pk_field(entity_type)
        max_seq = 0
        for row in self._data[entity_type]:
            seq = extract_id_sequence(row.get(pk) or row.get("id"), entity_type)
            if seq is not None:
                max_seq = max(max_seq, seq)
        self._id_counters.setdefault(entity_type, max_seq)

    def _flush(self, entity_type: str) -> None:
        os.makedirs(self.db_dir, exist_ok=True)
        path = self._file(entity_type)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as handle:
            json.dump(self._data.get(entity_type, []), handle, indent=2, ensure_ascii=False)
        os.replace(tmp, 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 row in self._data[entity_type]:
            if row.get(pk) == entity_id or row.get("id") == entity_id:
                return row
        return None

    def next_id(self, entity_type: str) -> str:
        self._ensure_loaded(entity_type)
        self._id_counters[entity_type] = self._id_counters.get(entity_type, 0) + 1
        return generate_id(entity_type, self._id_counters[entity_type])

    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]]:
        pk = self._pk_field(entity_type)
        if id_field in ("id", pk):
            row = self.get_by_id(entity_type, entity_id)
            if row is not None:
                return row
        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([row for row in self._data[entity_type] if predicate(row)])

    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 update(self, entity_type: str, entity_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        ref = self._ref(entity_type, entity_id)
        if ref is None:
            return None
        ref.update(safe_copy(updates))
        self._flush(entity_type)
        return safe_copy(ref)

    def upsert(self, entity_type: str, arg1: Any, arg2: Any = None) -> Dict[str, Any]:
        if isinstance(arg1, dict):
            record = safe_copy(arg1)
            id_field = arg2 if isinstance(arg2, str) and arg2 else self._pk_field(entity_type)
            entity_id = record.get(id_field) or record.get(self._pk_field(entity_type)) or record.get("id")
        else:
            entity_id = str(arg1)
            record = safe_copy(arg2 or {})
        if not entity_id:
            entity_id = self.next_id(entity_type)
            record[self._pk_field(entity_type)] = entity_id
        existing = self._ref(entity_type, str(entity_id))
        if existing is None:
            return self.insert(entity_type, record)
        existing.update(record)
        self._flush(entity_type)
        return safe_copy(existing)

    def delete(self, entity_type: str, arg1: Any, arg2: Any = None) -> bool:
        self._ensure_loaded(entity_type)
        if arg2 is None:
            id_field = self._pk_field(entity_type)
            entity_id = str(arg1)
        else:
            id_field = str(arg1)
            entity_id = str(arg2)
        before = len(self._data[entity_type])
        self._data[entity_type] = [row for row in self._data[entity_type] if row.get(id_field) != 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 snapshot(self) -> Dict[str, List[Dict[str, Any]]]:
        for entity_type in ENTITY_COLLECTION:
            self._ensure_loaded(entity_type)
        return safe_copy(self._data)

    def reset(self) -> None:
        self._data.clear()
        self._id_counters.clear()