tigrbl_engine_xlsx 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ from .engine import WorkbookCatalog, XlsxEngine, xlsx_capabilities, xlsx_engine
2
+ from .session import XlsxSession
3
+
4
+
5
+ class _Registration:
6
+ def build(self, *, mapping, spec, dsn):
7
+ return xlsx_engine(mapping=mapping, spec=spec, dsn=dsn)
8
+
9
+ def capabilities(self, *, spec, mapping=None):
10
+ return xlsx_capabilities()
11
+
12
+
13
+ def register() -> None:
14
+ """Entry-point hook invoked by tigrbl to register this engine."""
15
+ from tigrbl.engine.registry import register_engine
16
+
17
+ register_engine("xlsx", _Registration())
18
+
19
+
20
+ __all__ = [
21
+ "WorkbookCatalog",
22
+ "XlsxEngine",
23
+ "XlsxSession",
24
+ "xlsx_engine",
25
+ "xlsx_capabilities",
26
+ "register",
27
+ ]
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ import threading
6
+ from typing import Any, Callable
7
+
8
+ from openpyxl import load_workbook
9
+ from openpyxl.workbook import Workbook
10
+
11
+ from .session import XlsxSession
12
+
13
+
14
+ @dataclass
15
+ class WorkbookCatalog:
16
+ workbook: Workbook
17
+ path: str
18
+ tables: dict[str, list[dict[str, Any]]] = field(default_factory=dict)
19
+ pks: dict[str, str] = field(default_factory=dict)
20
+ table_ver: dict[str, int] = field(default_factory=dict)
21
+ lock: threading.RLock = field(default_factory=threading.RLock)
22
+
23
+ def get_live(self, name: str) -> list[dict[str, Any]]:
24
+ if name not in self.tables:
25
+ self.tables[name] = []
26
+ self.table_ver[name] = 0
27
+ self.pks.setdefault(name, "id")
28
+ self.table_ver.setdefault(name, 0)
29
+ return self.tables[name]
30
+
31
+ def bump(self, name: str) -> None:
32
+ self.table_ver[name] = self.table_ver.get(name, 0) + 1
33
+
34
+
35
+ def _sheet_to_rows(workbook: Workbook, sheet_name: str) -> list[dict[str, Any]]:
36
+ sheet = workbook[sheet_name]
37
+ values = list(sheet.iter_rows(values_only=True))
38
+ if not values:
39
+ return []
40
+ headers = [str(col) if col is not None else "" for col in values[0]]
41
+ rows: list[dict[str, Any]] = []
42
+ for row_values in values[1:]:
43
+ row = {
44
+ header: value
45
+ for header, value in zip(headers, row_values, strict=False)
46
+ if header
47
+ }
48
+ if any(value is not None for value in row.values()):
49
+ rows.append(row)
50
+ return rows
51
+
52
+
53
+ @dataclass
54
+ class XlsxEngine:
55
+ """Workbook-backed engine: workbook as DB, sheet names as tables."""
56
+
57
+ path: str
58
+ pk: str
59
+ workbook: Workbook
60
+ catalog: WorkbookCatalog
61
+
62
+
63
+ def xlsx_engine(
64
+ *, mapping: dict[str, Any] | None = None, **_: Any
65
+ ) -> tuple[XlsxEngine, Callable[[], XlsxSession]]:
66
+ config = dict(mapping or {})
67
+ path_value = config.get("path") or config.get("file")
68
+ if not isinstance(path_value, str) or not path_value:
69
+ raise TypeError("mapping['path'] (or 'file') must be a non-empty string")
70
+ path = str(Path(path_value))
71
+
72
+ pk = config.get("pk", "id")
73
+ if not isinstance(pk, str) or not pk:
74
+ raise TypeError("mapping['pk'] must be a non-empty string")
75
+
76
+ workbook = load_workbook(path)
77
+ if not workbook.sheetnames:
78
+ raise ValueError("workbook must contain at least one sheet")
79
+
80
+ catalog = WorkbookCatalog(
81
+ workbook=workbook,
82
+ path=path,
83
+ tables={name: _sheet_to_rows(workbook, name) for name in workbook.sheetnames},
84
+ pks={name: pk for name in workbook.sheetnames},
85
+ )
86
+ engine = XlsxEngine(path=path, pk=pk, workbook=workbook, catalog=catalog)
87
+
88
+ def session_factory() -> XlsxSession:
89
+ return XlsxSession(catalog)
90
+
91
+ return engine, session_factory
92
+
93
+
94
+ def xlsx_capabilities() -> dict[str, object]:
95
+ return {
96
+ "files": ["xlsx"],
97
+ "workbook_database": True,
98
+ "multi_table": True,
99
+ "workbook_api": ["load_workbook", "wb[...]", "wb.save(...)"],
100
+ "transactions": True,
101
+ "dialect": "xlsx",
102
+ }
@@ -0,0 +1,608 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import tempfile
5
+ import uuid
6
+
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Callable,
11
+ Dict,
12
+ List,
13
+ Mapping,
14
+ Optional,
15
+ Sequence,
16
+ Tuple,
17
+ )
18
+
19
+ from openpyxl.worksheet.worksheet import Worksheet
20
+
21
+ try:
22
+ from tigrbl.session.base import TigrblSessionBase
23
+ except Exception:
24
+ from abc import ABC, abstractmethod
25
+
26
+ class TigrblSessionBase(ABC): # pragma: no cover - fallback
27
+ def __init__(self, spec=None):
28
+ self._spec = spec
29
+
30
+ @abstractmethod
31
+ def _add_impl(self, obj): ...
32
+
33
+ @abstractmethod
34
+ async def _delete_impl(self, obj): ...
35
+
36
+ @abstractmethod
37
+ async def _flush_impl(self): ...
38
+
39
+ @abstractmethod
40
+ async def _refresh_impl(self, obj): ...
41
+
42
+ @abstractmethod
43
+ async def _get_impl(self, model, ident): ...
44
+
45
+ @abstractmethod
46
+ async def _execute_impl(self, stmt): ...
47
+
48
+ @abstractmethod
49
+ async def _tx_begin_impl(self): ...
50
+
51
+ @abstractmethod
52
+ async def _tx_commit_impl(self): ...
53
+
54
+ @abstractmethod
55
+ async def _tx_rollback_impl(self): ...
56
+
57
+ @abstractmethod
58
+ async def _close_impl(self): ...
59
+
60
+
61
+ try:
62
+ from tigrbl.session.spec import SessionSpec
63
+ except Exception:
64
+
65
+ class SessionSpec: # pragma: no cover - fallback
66
+ def __init__(self, isolation=None, read_only=None):
67
+ self.isolation = isolation
68
+ self.read_only = read_only
69
+
70
+
71
+ try:
72
+ from tigrbl.core.crud.helpers.model import _single_pk_name, _model_columns
73
+ except Exception:
74
+
75
+ def _single_pk_name(model): # pragma: no cover - fallback
76
+ return "id"
77
+
78
+ def _model_columns(model): # pragma: no cover - fallback
79
+ return getattr(model, "__annotations__", {}) or {"id": int}
80
+
81
+
82
+ try:
83
+ from tigrbl.core.crud.helpers import NoResultFound
84
+ except Exception:
85
+
86
+ class NoResultFound(Exception):
87
+ pass
88
+
89
+
90
+ if TYPE_CHECKING:
91
+ from .engine import WorkbookCatalog
92
+
93
+
94
+ class _ScalarResult:
95
+ def __init__(self, items: Sequence[Any]) -> None:
96
+ self._items = list(items)
97
+
98
+ def scalars(self) -> "_ScalarResult":
99
+ return self
100
+
101
+ def all(self) -> List[Any]:
102
+ return list(self._items)
103
+
104
+ def scalar_one(self) -> Any:
105
+ if len(self._items) != 1:
106
+ raise NoResultFound("expected exactly one row")
107
+ return self._items[0]
108
+
109
+
110
+ class _ExecuteResult(_ScalarResult):
111
+ rowcount: int = 0
112
+
113
+
114
+ class XlsxSession(TigrblSessionBase):
115
+ """Native transaction session over workbook sheets as tables."""
116
+
117
+ def __init__(
118
+ self, catalog: "WorkbookCatalog", spec: Optional[SessionSpec] = None
119
+ ) -> None:
120
+ super().__init__(spec)
121
+ self._cat = catalog
122
+ self._snap: Dict[str, list[dict[str, Any]]] = {}
123
+ self._snap_ver: Dict[str, int] = {}
124
+ self._puts: Dict[Tuple[type, Any], Dict[str, Any]] = {}
125
+ self._dels: set[Tuple[type, Any]] = set()
126
+ self._tracked: Dict[Tuple[type, Any], Any] = {}
127
+
128
+ def workbook(self):
129
+ return self._cat.workbook
130
+
131
+ def sheet(self, name: str) -> Worksheet:
132
+ return self._cat.workbook[name]
133
+
134
+ def table(self, name: str) -> list[dict[str, Any]]:
135
+ rows = [dict(row) for row in self._cat.get_live(name)]
136
+ pk = self._pk_of(name)
137
+ by_pk = {row.get(pk): row for row in rows}
138
+
139
+ for (model, ident), row in self._puts.items():
140
+ if self._table(model) == name:
141
+ by_pk[ident] = dict(row)
142
+
143
+ for model, ident in self._dels:
144
+ if self._table(model) == name:
145
+ by_pk.pop(ident, None)
146
+
147
+ return list(by_pk.values())
148
+
149
+ async def run_sync(self, fn: Callable[[Any], Any]) -> Any:
150
+ out = fn(self)
151
+ return await out if hasattr(out, "__await__") else out
152
+
153
+ async def begin(self) -> None:
154
+ await self._tx_begin_impl()
155
+
156
+ async def commit(self) -> None:
157
+ await self._tx_commit_impl()
158
+
159
+ async def rollback(self) -> None:
160
+ await self._tx_rollback_impl()
161
+
162
+ async def flush(self) -> None:
163
+ await self._flush_impl()
164
+
165
+ async def refresh(self, obj: Any) -> None:
166
+ await self._refresh_impl(obj)
167
+
168
+ async def get(self, model: type, ident: Any) -> Any | None:
169
+ return await self._get_impl(model, ident)
170
+
171
+ async def execute(self, stmt: Any) -> Any:
172
+ return await self._execute_impl(stmt)
173
+
174
+ async def close(self) -> None:
175
+ await self._close_impl()
176
+
177
+ async def _tx_begin_impl(self) -> None:
178
+ self._snap.clear()
179
+ self._snap_ver.clear()
180
+ self._puts.clear()
181
+ self._dels.clear()
182
+ self._tracked.clear()
183
+
184
+ async def _tx_commit_impl(self) -> None:
185
+ iso = (self._spec.isolation if self._spec else None) or "read_committed"
186
+ if iso in ("repeatable_read", "snapshot", "serializable"):
187
+ for table, version in self._snap_ver.items():
188
+ if self._cat.table_ver.get(table, 0) != version:
189
+ raise RuntimeError(f"transaction conflict on table '{table}'")
190
+
191
+ with self._cat.lock:
192
+ dels_by_table: Dict[str, List[Any]] = {}
193
+ for model, ident in self._dels:
194
+ dels_by_table.setdefault(self._table(model), []).append(ident)
195
+ for table, idents in dels_by_table.items():
196
+ pk = self._pk_of(table)
197
+ live = self._cat.get_live(table)
198
+ self._cat.tables[table] = [
199
+ row for row in live if row.get(pk) not in idents
200
+ ]
201
+ self._cat.bump(table)
202
+
203
+ puts_by_table: Dict[str, List[Dict[str, Any]]] = {}
204
+ for (model, _), row in self._puts.items():
205
+ puts_by_table.setdefault(self._table(model), []).append(dict(row))
206
+ for table, rows in puts_by_table.items():
207
+ pk = self._pk_of(table)
208
+ live = self._cat.get_live(table)
209
+ live_by_pk = {row.get(pk): dict(row) for row in live}
210
+ for row in rows:
211
+ if pk not in row:
212
+ raise RuntimeError(f"missing pk '{pk}' for table '{table}'")
213
+ live_by_pk[row[pk]] = row
214
+ self._cat.tables[table] = list(live_by_pk.values())
215
+ self._cat.bump(table)
216
+
217
+ self._persist_workbook()
218
+
219
+ self._puts.clear()
220
+ self._dels.clear()
221
+ self._tracked.clear()
222
+
223
+ async def _tx_rollback_impl(self) -> None:
224
+ self._snap.clear()
225
+ self._snap_ver.clear()
226
+ self._puts.clear()
227
+ self._dels.clear()
228
+ self._tracked.clear()
229
+
230
+ @staticmethod
231
+ def _pk_default(model: type, pk: str) -> Any:
232
+ table = getattr(model, "__table__", None)
233
+ if table is None:
234
+ return None
235
+ try:
236
+ column = table.columns.get(pk)
237
+ except Exception:
238
+ return None
239
+ if column is None:
240
+ return None
241
+ default = getattr(column, "default", None)
242
+ if default is None:
243
+ return None
244
+ arg = getattr(default, "arg", None)
245
+ if callable(arg):
246
+ try:
247
+ return arg()
248
+ except TypeError:
249
+ return arg(None)
250
+ return arg
251
+
252
+ def _add_impl(self, obj: Any) -> Any:
253
+ model = obj.__class__
254
+ pk = _single_pk_name(model)
255
+ ident = getattr(obj, pk)
256
+ if ident is None:
257
+ ident = self._pk_default(model, pk)
258
+ if ident is not None:
259
+ setattr(obj, pk, ident)
260
+ if ident is None:
261
+ raise ValueError(f"primary key {pk!r} must be set")
262
+ row = {column: getattr(obj, column, None) for column in _model_columns(model)}
263
+ self._puts[(model, ident)] = row
264
+ self._dels.discard((model, ident))
265
+ self._tracked[(model, ident)] = obj
266
+ return None
267
+
268
+ async def _delete_impl(self, obj: Any) -> None:
269
+ model = obj.__class__
270
+ pk = _single_pk_name(model)
271
+ ident = getattr(obj, pk)
272
+ self._puts.pop((model, ident), None)
273
+ self._dels.add((model, ident))
274
+ self._tracked.pop((model, ident), None)
275
+
276
+ async def _flush_impl(self) -> None:
277
+ for (model, ident), obj in list(self._tracked.items()):
278
+ if (model, ident) in self._dels:
279
+ continue
280
+ row = {
281
+ column: getattr(obj, column, None) for column in _model_columns(model)
282
+ }
283
+ self._puts[(model, ident)] = row
284
+ return
285
+
286
+ async def _refresh_impl(self, obj: Any) -> None:
287
+ pk = _single_pk_name(obj.__class__)
288
+ ident = getattr(obj, pk)
289
+ fresh = await self._get_impl(obj.__class__, ident)
290
+ if fresh is None:
291
+ return
292
+ for column in _model_columns(obj.__class__):
293
+ setattr(obj, column, getattr(fresh, column, None))
294
+
295
+ async def _get_impl(self, model: type, ident: Any) -> Any | None:
296
+ tracked = self._tracked.get((model, ident))
297
+ if tracked is not None:
298
+ return tracked
299
+ row = self._puts.get((model, ident))
300
+ if row is not None:
301
+ return self._inflate_tracked(model, ident, row)
302
+ if (model, ident) in self._dels:
303
+ return None
304
+ table_rows = self._rows_for(model)
305
+ pk = _single_pk_name(model)
306
+ for table_row in table_rows:
307
+ if table_row.get(pk) == ident:
308
+ return self._inflate_tracked(model, ident, table_row)
309
+ return None
310
+
311
+ async def _execute_impl(self, stmt: Any) -> Any:
312
+ kind = type(stmt).__name__.lower()
313
+ if "select" in kind:
314
+ model, where, order, limit, offset = self._decompose_select(stmt)
315
+ items = self._scan_model(model)
316
+ items = [obj for obj in items if self._matches_obj(obj, where)]
317
+ return _ExecuteResult(self._order_slice(items, order, limit, offset))
318
+ if "delete" in kind:
319
+ model, where = self._decompose_delete(stmt)
320
+ items = self._scan_model(model)
321
+ items = [obj for obj in items if self._matches_obj(obj, where)]
322
+ for obj in items:
323
+ pk = _single_pk_name(model)
324
+ ident = getattr(obj, pk)
325
+ self._puts.pop((model, ident), None)
326
+ self._dels.add((model, ident))
327
+ self._tracked.pop((model, ident), None)
328
+ result = _ExecuteResult([])
329
+ result.rowcount = len(items)
330
+ return result
331
+ raise NotImplementedError(f"Unsupported statement: {type(stmt)}")
332
+
333
+ async def _close_impl(self) -> None:
334
+ return
335
+
336
+ def _table(self, model: type) -> str:
337
+ return getattr(model, "__tablename__", None) or model.__name__
338
+
339
+ def _pk_of(self, table: str) -> str:
340
+ if table in self._cat.pks:
341
+ return self._cat.pks[table]
342
+ raise RuntimeError(f"primary key for table '{table}' is unknown")
343
+
344
+ def _rows_for(self, model: type) -> list[dict[str, Any]]:
345
+ table = self._table(model)
346
+ iso = (self._spec.isolation if self._spec else None) or "read_committed"
347
+ if (
348
+ iso in ("repeatable_read", "snapshot", "serializable")
349
+ and table not in self._snap
350
+ ):
351
+ live = self._cat.get_live(table)
352
+ self._snap[table] = [dict(row) for row in live]
353
+ self._snap_ver[table] = self._cat.table_ver.get(table, 0)
354
+ return self._snap.get(table, self._cat.get_live(table))
355
+
356
+ def _inflate(self, model: type, data: Mapping[str, Any]) -> Any:
357
+ obj = model()
358
+ for column in _model_columns(model):
359
+ if column in data:
360
+ setattr(obj, column, data[column])
361
+ return obj
362
+
363
+ def _inflate_tracked(self, model: type, ident: Any, data: Mapping[str, Any]) -> Any:
364
+ obj = self._tracked.get((model, ident))
365
+ if obj is None:
366
+ obj = self._inflate(model, data)
367
+ self._tracked[(model, ident)] = obj
368
+ return obj
369
+
370
+ def _scan_model(self, model: type) -> List[Any]:
371
+ pk = _single_pk_name(model)
372
+ by_id: Dict[Any, Any] = {}
373
+ for row in self._rows_for(model):
374
+ ident = row.get(pk)
375
+ if ident is None:
376
+ continue
377
+ tracked = self._tracked.get((model, ident))
378
+ if tracked is not None:
379
+ by_id[ident] = tracked
380
+ else:
381
+ by_id[ident] = self._inflate_tracked(model, ident, row)
382
+ for (known_model, ident), row in self._puts.items():
383
+ if known_model is model:
384
+ by_id[ident] = self._inflate_tracked(model, ident, row)
385
+ for known_model, ident in self._dels:
386
+ if known_model is model:
387
+ by_id.pop(ident, None)
388
+ return list(by_id.values())
389
+
390
+ def _persist_workbook(self) -> None:
391
+ workbook = self._cat.workbook
392
+ for table, rows in self._cat.tables.items():
393
+ if table in workbook.sheetnames:
394
+ sheet = workbook[table]
395
+ sheet.delete_rows(1, sheet.max_row)
396
+ else:
397
+ sheet = workbook.create_sheet(table)
398
+ columns: list[str] = []
399
+ for row in rows:
400
+ for key in row:
401
+ if key not in columns:
402
+ columns.append(key)
403
+ if not columns:
404
+ columns = [self._pk_of(table)]
405
+ sheet.append(columns)
406
+ for row in rows:
407
+ sheet.append([self._excel_value(row.get(col)) for col in columns])
408
+ self._atomic_save_workbook(workbook, self._cat.path)
409
+
410
+ @staticmethod
411
+ def _excel_value(value: Any) -> Any:
412
+ if isinstance(value, uuid.UUID):
413
+ return str(value)
414
+ return value
415
+
416
+ def _atomic_save_workbook(self, workbook: Any, path: str) -> None:
417
+ directory = os.path.dirname(path) or "."
418
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix=".tmp_", suffix=".xlsx")
419
+ os.close(fd)
420
+ try:
421
+ workbook.save(tmp)
422
+ os.replace(tmp, path)
423
+ finally:
424
+ if os.path.exists(tmp):
425
+ os.remove(tmp)
426
+
427
+ def _decompose_select(
428
+ self, stmt: Any
429
+ ) -> Tuple[
430
+ type,
431
+ list[Tuple[str, str, Any]],
432
+ list[Tuple[str, str]],
433
+ Optional[int],
434
+ Optional[int],
435
+ ]:
436
+ return (
437
+ self._extract_model(stmt),
438
+ self._extract_predicates(stmt),
439
+ self._extract_order_by(stmt),
440
+ self._extract_int(stmt, ["_limit", "_limit_clause", "limit"]),
441
+ self._extract_int(stmt, ["_offset", "_offset_clause", "offset"]),
442
+ )
443
+
444
+ def _decompose_delete(self, stmt: Any) -> Tuple[type, list[Tuple[str, str, Any]]]:
445
+ return self._extract_model(stmt), self._extract_predicates(stmt)
446
+
447
+ def _extract_model(self, stmt: Any) -> type:
448
+ descs = getattr(stmt, "column_descriptions", None) or []
449
+ for desc in descs:
450
+ entity = desc.get("entity") if isinstance(desc, dict) else None
451
+ if isinstance(entity, type):
452
+ return entity
453
+
454
+ def _all_subclasses(base: type) -> list[type]:
455
+ def _safe_subclasses(cls: type) -> list[type]:
456
+ try:
457
+ return list(cls.__subclasses__())
458
+ except TypeError:
459
+ return []
460
+
461
+ out: list[type] = []
462
+ stack = _safe_subclasses(base)
463
+ while stack:
464
+ cls = stack.pop()
465
+ out.append(cls)
466
+ stack.extend(_safe_subclasses(cls))
467
+ return out
468
+
469
+ def _find_by_table(name: str) -> type | None:
470
+ for cls in _all_subclasses(object):
471
+ if getattr(cls, "__tablename__", None) == name:
472
+ return cls
473
+ return None
474
+
475
+ for attr_name in ("_from_objects", "_froms", "froms"):
476
+ value = getattr(stmt, attr_name, None)
477
+ if value is not None:
478
+ if isinstance(value, (list, tuple)) and not value:
479
+ continue
480
+ table = value[0] if isinstance(value, (list, tuple)) else value
481
+ name = getattr(table, "name", None)
482
+ if isinstance(name, str):
483
+ found = _find_by_table(name)
484
+ if found is not None:
485
+ return found
486
+ table = getattr(stmt, "table", None)
487
+ name = getattr(table, "name", None)
488
+ if isinstance(name, str):
489
+ found = _find_by_table(name)
490
+ if found is not None:
491
+ return found
492
+
493
+ rc = getattr(stmt, "_raw_columns", None) or getattr(stmt, "columns", None)
494
+ if rc is not None:
495
+ if isinstance(rc, (list, tuple)) and not rc:
496
+ raise RuntimeError("Cannot resolve model from statement")
497
+ entity = rc[0]
498
+ table = getattr(entity, "table", None)
499
+ name = getattr(table, "name", None)
500
+ if isinstance(name, str):
501
+ found = _find_by_table(name)
502
+ if found is not None:
503
+ return found
504
+ raise RuntimeError("Cannot resolve model from statement")
505
+
506
+ def _extract_predicates(self, stmt: Any) -> list[Tuple[str, str, Any]]:
507
+ where = getattr(stmt, "whereclause", None) or getattr(
508
+ stmt, "_whereclause", None
509
+ )
510
+ if where is None:
511
+ return []
512
+ parts = (
513
+ getattr(where, "clauses", None)
514
+ or getattr(where, "get_children", lambda: [])()
515
+ )
516
+ nodes = list(parts) if parts else [where]
517
+ out: list[Tuple[str, str, Any]] = []
518
+ for node in nodes:
519
+ left = getattr(node, "left", None)
520
+ right = getattr(node, "right", None)
521
+ op = getattr(node, "operator", None)
522
+ if left is None or right is None:
523
+ continue
524
+ name = getattr(left, "key", None) or getattr(left, "name", None)
525
+ if name is None:
526
+ continue
527
+ opname = getattr(op, "__name__", str(op))
528
+ if "eq" in opname:
529
+ value = (
530
+ getattr(right, "value", None)
531
+ if hasattr(right, "value")
532
+ else getattr(right, "literal", None)
533
+ )
534
+ out.append((str(name), "eq", value))
535
+ continue
536
+ right_clauses = getattr(right, "clauses", None)
537
+ if right_clauses is not None and "in" in opname:
538
+ vals = [
539
+ getattr(lit, "value", None)
540
+ if hasattr(lit, "value")
541
+ else getattr(lit, "literal", None)
542
+ for lit in right_clauses
543
+ ]
544
+ out.append((str(name), "in", vals))
545
+ return out
546
+
547
+ def _extract_order_by(self, stmt: Any) -> list[Tuple[str, str]]:
548
+ order = getattr(stmt, "_order_by_clause", None)
549
+ if order is None:
550
+ order = getattr(stmt, "_order_by_clauses", None)
551
+ if order is None:
552
+ return []
553
+ clauses = getattr(order, "clauses", None) or order
554
+ clauses = clauses if isinstance(clauses, (list, tuple)) else [clauses]
555
+ for ob in clauses:
556
+ col = (
557
+ getattr(ob, "element", None)
558
+ or getattr(ob, "this", None)
559
+ or getattr(ob, "expr", None)
560
+ )
561
+ name = getattr(col, "key", None) or getattr(col, "name", None)
562
+ direction = "desc" if "desc" in type(ob).__name__.lower() else "asc"
563
+ if name:
564
+ return [(str(name), direction)]
565
+ return []
566
+
567
+ def _extract_int(self, stmt: Any, names: Sequence[str]) -> Optional[int]:
568
+ for name in names:
569
+ value = getattr(stmt, name, None)
570
+ if value is None:
571
+ continue
572
+ try:
573
+ return int(value)
574
+ except Exception:
575
+ lit = getattr(value, "value", None)
576
+ if lit is not None:
577
+ try:
578
+ return int(lit)
579
+ except Exception:
580
+ pass
581
+ return None
582
+
583
+ def _matches_obj(self, obj: Any, where: list[Tuple[str, str, Any]]) -> bool:
584
+ for name, op, value in where:
585
+ datum = getattr(obj, name, None)
586
+ if op == "eq" and datum != value:
587
+ return False
588
+ if op == "in" and datum not in set(value):
589
+ return False
590
+ return True
591
+
592
+ def _order_slice(
593
+ self,
594
+ items: List[Any],
595
+ order: list[Tuple[str, str]],
596
+ limit: Optional[int],
597
+ offset: Optional[int],
598
+ ) -> List[Any]:
599
+ if order:
600
+ col, direction = order[0]
601
+ items.sort(
602
+ key=lambda obj: getattr(obj, col, None), reverse=(direction == "desc")
603
+ )
604
+ if isinstance(offset, int):
605
+ items = items[max(0, offset) :]
606
+ if isinstance(limit, int):
607
+ items = items[: max(0, limit)]
608
+ return items
@@ -0,0 +1,277 @@
1
+ Metadata-Version: 2.4
2
+ Name: tigrbl_engine_xlsx
3
+ Version: 0.1.1
4
+ Summary: XLSX engine plugin for tigrbl where each workbook is a database and each sheet is a table.
5
+ Project-URL: Homepage, https://github.com/swarmauri/swarmauri-sdk
6
+ Author-email: Jacob Stewart <jacob@swarmauri.com>
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "[]"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright [2025] [Swarmauri Team]
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+ License-File: LICENSE
209
+ Keywords: dataframe,engine,excel,experimental,tigrbl,xlsx
210
+ Classifier: Development Status :: 1 - Planning
211
+ Classifier: License :: OSI Approved :: Apache Software License
212
+ Classifier: Programming Language :: Python :: 3.10
213
+ Classifier: Programming Language :: Python :: 3.11
214
+ Classifier: Programming Language :: Python :: 3.12
215
+ Requires-Python: <3.13,>=3.10
216
+ Requires-Dist: openpyxl>=3.1
217
+ Requires-Dist: tigrbl>=0.3.0.dev4
218
+ Description-Content-Type: text/markdown
219
+
220
+ ![Tigrbl Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/tigrbl_full_logo.png)
221
+
222
+ <p align="center">
223
+ <a href="https://pypi.org/project/tigrbl_engine_xlsx/">
224
+ <img src="https://img.shields.io/pypi/v/tigrbl_engine_xlsx?label=tigrbl_engine_xlsx&color=green" alt="PyPI - tigrbl_engine_xlsx"/>
225
+ </a>
226
+ <a href="https://pypi.org/project/tigrbl_engine_xlsx/">
227
+ <img src="https://img.shields.io/pypi/dm/tigrbl_engine_xlsx" alt="PyPI - Downloads"/>
228
+ </a>
229
+ <a href="https://pypi.org/project/tigrbl_engine_xlsx/">
230
+ <img src="https://img.shields.io/pypi/pyversions/tigrbl_engine_xlsx" alt="PyPI - Python Version"/>
231
+ </a>
232
+ <a href="https://pypi.org/project/tigrbl_engine_xlsx/">
233
+ <img src="https://img.shields.io/pypi/l/tigrbl_engine_xlsx" alt="PyPI - License"/>
234
+ </a>
235
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/tigrbl_engine_xlsx/">
236
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/tigrbl_engine_xlsx.svg"/>
237
+ </a>
238
+ </p>
239
+
240
+ # tigrbl_engine_xlsx
241
+
242
+ A tigrbl engine plugin where each workbook is a database-like object and each sheet is a table.
243
+
244
+ ## Features
245
+
246
+ - Registers `kind="xlsx"` through the `tigrbl.engine` entry-point group.
247
+ - Uses `load_workbook`, `wb[...]`, and `wb.save(...)` directly for workbook operations.
248
+ - Treats each sheet as a table with transactional table semantics.
249
+
250
+ ## Installation
251
+
252
+ ### uv
253
+
254
+ ```bash
255
+ uv add tigrbl_engine_xlsx
256
+ ```
257
+
258
+ ### pip
259
+
260
+ ```bash
261
+ pip install tigrbl_engine_xlsx
262
+ ```
263
+
264
+ ## Usage
265
+
266
+ ```python
267
+ from tigrbl.engine import EngineSpec
268
+
269
+ spec = EngineSpec(kind="xlsx", mapping={"path": "./workbook.xlsx", "pk": "id"})
270
+ provider = spec.provider()
271
+ engine, session_factory = provider.build()
272
+
273
+ session = session_factory()
274
+ wb = session.workbook()
275
+ print(wb["Sheet1"])
276
+ print(session.table("Sheet1"))
277
+ ```
@@ -0,0 +1,8 @@
1
+ tigrbl_engine_xlsx/__init__.py,sha256=9yk65aLyE0KYRSJAuz_3Eqj93ayFJJifZDtiWoB5XD0,664
2
+ tigrbl_engine_xlsx/engine.py,sha256=sHNfwMI_yXmBWIzMZ88AX-N8YLhPzjtbdyFWIrRTqNk,3138
3
+ tigrbl_engine_xlsx/session.py,sha256=FHceAu8RHlqxjBvvwEj0tZEzov6L3k6n0JEHX45Gl9E,21016
4
+ tigrbl_engine_xlsx-0.1.1.dist-info/METADATA,sha256=O0r7rGICGb44JV8WjkHrocdPPvuAw1bq_vEwX2XsabY,15141
5
+ tigrbl_engine_xlsx-0.1.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
6
+ tigrbl_engine_xlsx-0.1.1.dist-info/entry_points.txt,sha256=rR7gnMBbkzbRbpClCTOcBzfPCRnxy2-CduR8LQZxaaE,51
7
+ tigrbl_engine_xlsx-0.1.1.dist-info/licenses/LICENSE,sha256=708mvS2G_dkXGD6DVfUDngIUW4HW-T14Ws-q7shsacA,10880
8
+ tigrbl_engine_xlsx-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [tigrbl.engine]
2
+ xlsx = tigrbl_engine_xlsx:register
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Swarmauri Team]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.