File size: 7,753 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 | """JSON file-backed database for isolated ticketing runtime data."""
from __future__ import annotations
import json
import os
from typing import Any, Callable, Dict, List, Optional
from mcp_servers.utils import generate_id, safe_copy
ENTITY_FILES = {
"operator": ("operators.json", "operator_id"),
"venue": ("venues.json", "venue_id"),
"venue_section": ("venue_sections.json", "venue_section_id"),
"seat": ("seats.json", "seat_id"),
"event": ("events.json", "event_id"),
"performance": ("performances.json", "performance_id"),
"price_tier": ("price_tiers.json", "price_tier_id"),
"ticket_type": ("ticket_types.json", "ticket_type_id"),
"discount_campaign": ("discount_campaigns.json", "discount_campaign_id"),
"customer": ("customers.json", "customer_id"),
"order": ("orders.json", "order_id"),
"order_line": ("order_lines.json", "order_line_id"),
"ticket": ("tickets.json", "ticket_id"),
"refund_request": ("refund_requests.json", "refund_request_id"),
"checkpoint": ("checkpoints.json", "checkpoint_id"),
"entry_scan": ("entry_scans.json", "entry_scan_id"),
"inventory_hold": ("inventory_holds.json", "inventory_hold_id"),
"entry_summary": ("entry_summaries.json", "entry_summary_id"),
"audit_log": ("audit_logs.json", "audit_log_id"),
}
class Database:
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 _info(self, entity_type: str) -> tuple[str, str]:
return ENTITY_FILES.get(entity_type, (f"{entity_type}s.json", f"{entity_type}_id"))
def _file(self, entity_type: str) -> str:
return os.path.join(self.db_dir, self._info(entity_type)[0])
def _pk_field(self, entity_type: str) -> str:
return self._info(entity_type)[1]
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:
rows = json.load(handle)
self._data[entity_type] = rows if isinstance(rows, list) else []
else:
self._data[entity_type] = []
self._id_counters.setdefault(entity_type, len(self._data[entity_type]))
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)
try:
os.unlink(path)
except FileNotFoundError:
pass
os.replace(tmp, path)
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_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 get_by_id(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]:
ref = self.get_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]]:
self._ensure_loaded(entity_type)
pk = self._pk_field(entity_type)
if id_field in {"id", pk}:
return self.get_by_id(entity_type, entity_id)
for row in self._data[entity_type]:
if row.get(id_field) == entity_id:
return safe_copy(row)
return 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 add(self, entity_type: str, record: Dict[str, Any]) -> Dict[str, Any]:
self._ensure_loaded(entity_type)
stored = safe_copy(record)
pk = self._pk_field(entity_type)
if not stored.get(pk):
self._id_counters[entity_type] = self._id_counters.get(entity_type, 0) + 1
stored[pk] = generate_id(entity_type, self._id_counters[entity_type])
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)
id_field = arg2 if isinstance(arg2, str) and arg2 else self._pk_field(entity_type)
entity_id = str(record.get(id_field) or record.get(self._pk_field(entity_type)) or record.get("id") or "")
else:
entity_id = str(arg1)
record = safe_copy(arg2 if isinstance(arg2, dict) else {})
id_field = self._pk_field(entity_type)
if not entity_id:
return self.add(entity_type, record)
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_field) == entity_id or row.get("id") == entity_id:
row.update(record)
if pk not in row:
row[pk] = entity_id
self._flush(entity_type)
return safe_copy(row)
if pk not in record:
record[pk] = entity_id
self._data[entity_type].append(record)
self._flush(entity_type)
return safe_copy(record)
def update(self, entity_type: str, entity_id: str, patch: Dict[str, Any]) -> 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:
row.update(safe_copy(patch))
self._flush(entity_type)
return safe_copy(row)
return None
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)
value = str(arg1)
else:
id_field = str(arg1)
value = str(arg2)
before = len(self._data[entity_type])
self._data[entity_type] = [row for row in self._data[entity_type] if str(row.get(id_field) or row.get(self._pk_field(entity_type)) or row.get("id")) != value]
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, *, loaded_only: bool = True) -> Dict[str, List[Dict[str, Any]]]:
if not loaded_only:
for entity_type in ENTITY_FILES:
self._ensure_loaded(entity_type)
return safe_copy(self._data)
def reset(self) -> None:
self._data.clear()
self._id_counters.clear()
|