cvcdocdb 1.0.0__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.
cvcdocdb/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ __version__ = "1.0.0"
2
+
3
+ from .base import *
4
+ from .drm_entities import *
5
+ from .graph_store import GraphStore
6
+
7
+
8
+ def __getattr__(name):
9
+ """Lazy import for optional backend modules.
10
+
11
+ Neo4jGraph and NetworkXGraph require optional dependencies (neo4j and
12
+ networkx respectively) that may not be installed in all environments.
13
+ """
14
+ if name == "Neo4jGraph":
15
+ from .neo4j_graph import Neo4jGraph
16
+
17
+ return Neo4jGraph
18
+ if name == "NetworkXGraph":
19
+ from .networkx_graph import NetworkXGraph
20
+
21
+ return NetworkXGraph
22
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
cvcdocdb/base.py ADDED
@@ -0,0 +1,566 @@
1
+ """Core data structures: Node, Relation, WeakNode, WeakRelation.
2
+
3
+ These classes represent the graph primitives used by both Neo4jGraph
4
+ and NetworkXGraph. Nodes carry a primary key (``pk``), a main label,
5
+ optional alternative labels, and optional parent relationships for
6
+ WeakNode hierarchies. Relations connect two nodes with a typed edge.
7
+ """
8
+
9
+ from typing import Any, Dict, List, Optional, Tuple, Union
10
+
11
+ # Sentinel per distingir "pk no proporcionat" de "pk=None explícit"
12
+ _UNSET = object()
13
+
14
+
15
+ def _single_pk(pk: Dict[str, Union[int, str]], version: int = 5) -> Dict[str, Union[int, str]]:
16
+ """Merge multi-field PK into a single-field PK for Neo4j 3.x compatibility.
17
+
18
+ Args:
19
+ pk: Primary key dictionary.
20
+ version: Neo4j protocol version (3 or 5).
21
+
22
+ Returns:
23
+ A single-field PK dict for version 3, or the original dict for version 5.
24
+ """
25
+ if version == 3 and len(pk) > 1:
26
+ return {"_".join(pk.keys()): "_".join([str(x) for x in pk.values()])}
27
+ return pk
28
+
29
+
30
+ def _new_key(old_key: str, list_keys: set) -> str:
31
+ """Generate a unique key by appending _0, _1, ... until a free name is found.
32
+
33
+ Args:
34
+ old_key: The original key to modify.
35
+ list_keys: Set of existing keys to avoid.
36
+
37
+ Returns:
38
+ A unique key name.
39
+ """
40
+ n = 0
41
+ while old_key + "_" + str(n) in list_keys:
42
+ n += 1
43
+ return old_key + "_" + str(n)
44
+
45
+
46
+ def _mergePK(
47
+ pk_a: Dict[str, Union[int, str]],
48
+ pk_b: Optional[Dict[str, Union[int, str]]],
49
+ version: int = 5,
50
+ ) -> Dict[str, Union[int, str]]:
51
+ """Merge two PK dicts into a composite PK.
52
+
53
+ If pk_b is None, return pk_a as-is (the child inherits the parent's PK).
54
+ """
55
+ if pk_b is None:
56
+ return pk_a
57
+ pk_b = dict(pk_b)
58
+ k = set(pk_a.keys()).intersection(set(pk_b.keys()))
59
+
60
+ for v in k:
61
+ new_key = _new_key(v, set(pk_a.keys()).union(pk_b.keys()))
62
+ pk_b[new_key] = pk_b.pop(v)
63
+
64
+ pk = {**pk_a, **pk_b}
65
+
66
+ return _single_pk(pk, version)
67
+
68
+
69
+ def _setNodePK(value: Dict[str, Any]) -> Dict[str, Any]:
70
+ """Extract main_label and pk from a dict without mutating the original.
71
+
72
+ Args:
73
+ value: dict containing 'main_label' and 'pk' keys.
74
+
75
+ Returns:
76
+ A new dict with 'main_label' and 'pk'. Returns empty values
77
+ if the keys are missing.
78
+ """
79
+ main_label = value.get("main_label")
80
+ pk = value.get("pk")
81
+ return {"main_label": main_label, "pk": pk}
82
+
83
+
84
+ class Node:
85
+ """A graph node with a primary key, labels, and optional parent.
86
+
87
+ Nodes are the fundamental building blocks of the DRM graph. Each node
88
+ has a ``main_label`` (the primary Cypher label), optional ``alternative_labels``,
89
+ and a ``pk`` (primary key) that uniquely identifies it within its label.
90
+
91
+ When a ``parent`` is provided the node becomes a **WeakNode**: its primary
92
+ key is merged with the parent's key to form a composite key, and a typed
93
+ edge is created when the node is inserted into a graph store.
94
+
95
+ By default a node **must** have a ``pk`` or a ``neo4j_id`` (or both).
96
+ If the caller passes ``pk=None`` explicitly, the node is created with
97
+ ``_primary_key = None`` and the backend is expected to assign a real
98
+ ID later (e.g. Neo4j generates an internal node ID, which is then
99
+ stored as ``_primary_key``). If the backend never assigns one,
100
+ ``_primary_key`` remains ``None``.
101
+
102
+ Args:
103
+ pk: Primary key — an int is converted to ``{"id": pk}``, a dict is used
104
+ as-is. Must be provided (or explicitly ``None``) unless
105
+ ``neo4j_id`` is given.
106
+ main_label: The primary label used in Cypher queries.
107
+ alternative_labels: Additional labels attached to the node.
108
+ version: Neo4j protocol version (default 5).
109
+ neo4j_id: Internal Neo4j node ID (used when reconstructing a node
110
+ from a database result).
111
+ **kwargs: Arbitrary additional attributes stored on the node.
112
+ Special kwargs: ``parent`` (Node), ``parent_relation`` (str),
113
+ ``is_weak`` (bool), ``_propagate`` (bool), ``dependencies``.
114
+
115
+ Raises:
116
+ ValueError: If ``pk`` is not provided at all (not even as ``None``)
117
+ and ``neo4j_id`` is also absent.
118
+ TypeError: If ``pk`` is neither an ``int`` nor a ``dict`` (when
119
+ ``pk`` is provided but not ``None``).
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ pk: Union[Dict[str, Union[int, str]], None, object] = _UNSET,
125
+ main_label: str = "",
126
+ alternative_labels: Optional[Union[str, List[str]]] = None,
127
+ version: int = 5,
128
+ neo4j_id: Optional[int] = None,
129
+ **kwargs: Any,
130
+ ):
131
+ # Definim les propietats
132
+ self._neo4j_id = neo4j_id
133
+ self._version = version
134
+
135
+ # Distingim entre "pk no passat" i "pk=None explícit"
136
+ if pk is _UNSET:
137
+ if neo4j_id is not None:
138
+ self._primary_key = {"id": neo4j_id}
139
+ else:
140
+ raise ValueError(
141
+ "Node must have either a primary key (pk) or a neo4j_id. "
142
+ "A node without either cannot be inserted or referenced."
143
+ )
144
+ elif pk is None:
145
+ # pk=None explícit: si hi ha neo4j_id, el fem servir com a PK;
146
+ # si no, el backend generarà un ID després (pk queda None).
147
+ if neo4j_id is not None:
148
+ self._primary_key = {"id": neo4j_id}
149
+ else:
150
+ self._primary_key = None
151
+ elif isinstance(pk, int):
152
+ self._primary_key = {"id": pk}
153
+ elif isinstance(pk, Dict):
154
+ self._primary_key = _single_pk(pk, version)
155
+ else:
156
+ raise TypeError(
157
+ f"pk must be an int, dict, or None, got {type(pk).__name__}"
158
+ )
159
+
160
+ self._main_label = main_label # main_label.lower().capitalize()
161
+
162
+ if isinstance(alternative_labels, str):
163
+ self._label = [
164
+ alternative_labels
165
+ ] # [alternative_labels.lower().capitalize()]
166
+ else:
167
+ self._label = (
168
+ alternative_labels
169
+ if alternative_labels is None
170
+ else [x for x in alternative_labels] # x.lower().capitalize()
171
+ )
172
+
173
+ self._is_weak = kwargs.pop("is_weak", False)
174
+ self._propagate = kwargs.pop("_propagate", False)
175
+ parent_relation = kwargs.pop("parent_relation", None)
176
+ self._parent = kwargs.pop("parent", None)
177
+ if self._parent is not None:
178
+ assert isinstance(self._parent, Node), "parent must be a Node"
179
+ self._is_weak = True
180
+ if self._parent._primary_key is None:
181
+ raise ValueError(
182
+ "WeakNode parent must have a primary key. "
183
+ "Transient nodes (no pk) cannot be parents."
184
+ )
185
+ self._primary_key = _mergePK(self._parent._primary_key, self._primary_key)
186
+ self._parent_relation = (
187
+ parent_relation if parent_relation is not None else "HAS"
188
+ )
189
+
190
+ dependencies = kwargs.pop("dependencies", False)
191
+ if dependencies:
192
+ self._dependencies = dependencies
193
+ else:
194
+ self._dependencies = None
195
+
196
+ if kwargs is not None:
197
+ for k in kwargs:
198
+ self.__setattr__(k, kwargs[k])
199
+
200
+ # ------------------------------------------------------------------
201
+ # Dunder methods
202
+ # ------------------------------------------------------------------
203
+
204
+ def __repr__(self):
205
+ main_label = ":" + self._main_label if len(self._main_label) > 0 else ""
206
+ id = " <Id>: " + str(self._neo4j_id) if self._neo4j_id is not None else ""
207
+ mess = "(a" + main_label + id + ")"
208
+ pk_repr = self._primary_key.__repr__() if self._primary_key is not None else "None"
209
+ mess += """, pk:""" + pk_repr
210
+ mess += (
211
+ (", attributes:" + self.attributes[1].__repr__())
212
+ if len(self.attributes[1]) > 0
213
+ else ""
214
+ )
215
+ return mess
216
+
217
+ def __getitem__(self, key: str) -> Any:
218
+ def get_pk():
219
+ if hasattr(self,'_primary_key'):
220
+ return self._primary_key
221
+ if hasattr(self,'_neo4j_id'):
222
+ return { 'neo4j_id': self._neo4j_id}
223
+
224
+ return 0
225
+
226
+ if key == "pk":
227
+ return {"main_label": self._main_label, "pk": get_pk() }
228
+
229
+ if key == "main_label":
230
+ return self._main_label
231
+
232
+ if key == "labels":
233
+ if self._label is None:
234
+ return [self._main_label]
235
+ else:
236
+ return [self._main_label] + self._label
237
+
238
+ if key == "pk_attributes":
239
+ return get_pk()
240
+
241
+ attr = self.__dict__.copy()
242
+ if key == "attributes":
243
+ attr.pop("_label", None)
244
+ attr.pop("_main_label")
245
+ attr.pop("_neo4j_id", None)
246
+ pk = attr.pop("_primary_key", None)
247
+
248
+ return pk, attr
249
+
250
+ if "_" + key in attr:
251
+ return attr["_" + key]
252
+ elif key in attr:
253
+ return attr[key]
254
+ else:
255
+ raise Exception(key + " is not a node attribute")
256
+
257
+ def __setitem__(self, key, value):
258
+ if key == "pk":
259
+ aux = _setNodePK(value)
260
+ self._main_label, self._primary_key = aux["main_label"], aux["pk"]
261
+ return
262
+
263
+ if key == "main_label":
264
+ self._main_label = value
265
+ return
266
+
267
+ if key == "labels":
268
+ self._label = value
269
+ return
270
+
271
+ if key == "pk_attributes":
272
+ if isinstance(value, dict):
273
+ self._primary_key = value
274
+ else:
275
+ raise Exception("dictionary expected")
276
+
277
+ return
278
+
279
+ self.__setattr__(key, value)
280
+
281
+ def __delitem__(self, key: str) -> None:
282
+ del self.__dict__[key]
283
+
284
+ def __contains__(self, key: str) -> bool:
285
+ return key in self.__dict__ or "_" + key in self.__dict__
286
+
287
+ def get(self, key: str, default: Any = None) -> Any:
288
+ """Dict-like access: return the value for *key*, or *default* if missing.
289
+
290
+ This method provides a compatibility shim so that code written
291
+ with ``node.get("key", default)`` works on Node objects even
292
+ though they are not full ``dict`` subclasses.
293
+
294
+ Args:
295
+ key: The attribute key to retrieve.
296
+ default: Value returned when the key is not found.
297
+
298
+ Returns:
299
+ The attribute value, or *default* if the key is absent.
300
+ """
301
+ try:
302
+ return self[key]
303
+ except Exception:
304
+ return default
305
+
306
+ # ------------------------------------------------------------------
307
+ # Properties
308
+ # ------------------------------------------------------------------
309
+
310
+ @property
311
+ def version(self) -> int:
312
+ return self._version
313
+
314
+ @version.setter
315
+ def version(self, value: int) -> None:
316
+ self._version = value
317
+ if value == 3 and self._primary_key is not None:
318
+ self._primary_key = _single_pk(self._primary_key, value)
319
+
320
+ @property
321
+ def attributes(self) -> Tuple[Optional[Dict[str, Union[int, str]]], Dict[str, Any]]:
322
+ """Return (pk, attributes) tuple for this node.
323
+
324
+ Returns:
325
+ A tuple of (primary_key_dict_or_None, attributes_dict).
326
+ """
327
+ at = self.__dict__.copy()
328
+ pk = at.pop("_primary_key", None)
329
+ for x in list(at.keys()):
330
+ if x[0] == "_":
331
+ at.pop(x, None)
332
+ return pk, at
333
+
334
+ @property
335
+ def labels(self) -> List[str]:
336
+ """Return the full list of labels (main + alternative)."""
337
+ if self._label is None:
338
+ return [self._main_label]
339
+ return [self._main_label] + self._label
340
+
341
+ @property
342
+ def main_label(self) -> str:
343
+ """Return the primary Cypher label."""
344
+ return self._main_label
345
+
346
+ @property
347
+ def neo4j_id(self) -> Optional[int]:
348
+ """Return the internal Neo4j node id, if set."""
349
+ return self._neo4j_id
350
+
351
+ @neo4j_id.setter
352
+ def neo4j_id(self, value: Optional[int]) -> None:
353
+ self._neo4j_id = value
354
+
355
+ # ------------------------------------------------------------------
356
+ # Utility methods
357
+ # ------------------------------------------------------------------
358
+
359
+ def keys(self) -> List[str]:
360
+ """Return all public attribute names."""
361
+ return [k for k in self.__dict__.keys() if not k.startswith("_")]
362
+
363
+
364
+ # Class Relation denotes the relation of two nodes in the graph database
365
+ class Relation:
366
+ """A typed edge connecting two nodes in the graph.
367
+
368
+ Relations store the primary keys of their source and destination nodes
369
+ and can carry arbitrary edge properties.
370
+
371
+ Args:
372
+ src: Source node. Its ``pk`` is extracted and stored.
373
+ dst: Destination node. Its ``pk`` is extracted and stored.
374
+ type: Relation type (e.g. "HAS_NOM", "CONNECTS"). Stored uppercase.
375
+ **kwargs: Edge properties stored as attributes.
376
+ """
377
+
378
+ def __init__(self, src: Node, dst: Node, rel_type: str, **kwargs: Any) -> None:
379
+ """Initialize a Relation between two nodes.
380
+
381
+ Args:
382
+ src: Source node. Its ``pk`` is extracted and stored.
383
+ dst: Destination node. Its ``pk`` is extracted and stored.
384
+ rel_type: Relation type (e.g. "HAS_NOM", "CONNECTS"). Stored uppercase.
385
+ **kwargs: Edge properties stored as attributes.
386
+ """
387
+ self._type = rel_type.upper()
388
+ self._src = src["pk"]
389
+ self._dst = dst["pk"]
390
+
391
+ if kwargs is not None:
392
+ for k in kwargs:
393
+ self.__setattr__(k, kwargs[k])
394
+
395
+ # ------------------------------------------------------------------
396
+ # Dunder methods
397
+ # ------------------------------------------------------------------
398
+
399
+ def __repr__(self) -> str:
400
+ return (
401
+ "src:" + str(self._src) + ", dst:" + str(self._dst)
402
+ + " type:" + self._type
403
+ )
404
+
405
+ def __getitem__(self, key: str) -> Any:
406
+ if key == "src":
407
+ return {"main_label": self._src["main_label"], "pk": self._src["pk"]}
408
+
409
+ if key == "dst":
410
+ return {"main_label": self._dst["main_label"], "pk": self._dst["pk"]}
411
+
412
+ if key == "type":
413
+ return self._type
414
+
415
+ attr = self.__dict__.copy()
416
+ if key == "attributes":
417
+ # remove private attributes
418
+ attr.pop("_src", None)
419
+ attr.pop("_dst", None)
420
+ attr.pop("_type", None)
421
+
422
+ if attr == {}:
423
+ return None
424
+ else:
425
+ return attr
426
+
427
+ if key in attr:
428
+ return attr[key]
429
+ raise KeyError(key + " is not a relation attribute")
430
+
431
+ def __setitem__(self, key: str, value: Any) -> None:
432
+ if key == "src":
433
+ self._src = _setNodePK(value)
434
+ return
435
+
436
+ if key == "dst":
437
+ self._dst = _setNodePK(value)
438
+ return
439
+
440
+ if key == "type":
441
+ self._type = value
442
+ return
443
+
444
+ self.__setattr__(key, value)
445
+
446
+ # ------------------------------------------------------------------
447
+ # Properties
448
+ # ------------------------------------------------------------------
449
+
450
+ @property
451
+ def src(self) -> Tuple[str, Optional[Dict[str, Union[int, str]]]]:
452
+ """Return (main_label, pk) of the source node."""
453
+ return self._src["main_label"], self._src["pk"]
454
+
455
+ @src.setter
456
+ def src(self, value: Dict[str, Any]) -> None:
457
+ self._src = _setNodePK(value)
458
+
459
+ @property
460
+ def dst(self) -> Tuple[str, Optional[Dict[str, Union[int, str]]]]:
461
+ """Return (main_label, pk) of the destination node."""
462
+ return self._dst["main_label"], self._dst["pk"]
463
+
464
+ @dst.setter
465
+ def dst(self, value: Dict[str, Any]) -> None:
466
+ self._dst = _setNodePK(value)
467
+
468
+ @property
469
+ def type(self) -> str:
470
+ """Return the relation type (uppercase)."""
471
+ return self._type
472
+
473
+ @property
474
+ def attributes(self) -> Optional[Dict[str, Any]]:
475
+ """Return edge attributes, or None if empty."""
476
+ attr = {
477
+ k: v for k, v in self.__dict__.items()
478
+ if not k.startswith("_")
479
+ }
480
+ return attr if attr else None
481
+
482
+
483
+ class WeakNode(Node):
484
+ """A node whose identity is tied to its parent node.
485
+
486
+ WeakNodes form a parent-child hierarchy where the child's primary
487
+ key is **merged** with the parent's key to produce a composite key.
488
+ This models document structures such as *Document → Section → Page*
489
+ where a child cannot exist without its parent.
490
+
491
+ When a WeakNode is inserted into a graph store, a typed edge
492
+ (``WeakRelation``) is automatically created linking the parent to
493
+ the child. This edge carries the ``_propagate=TRUE`` flag, which
494
+ triggers cascade delete: deleting the parent automatically deletes
495
+ all descendants in the hierarchy.
496
+
497
+ Args:
498
+ parent: The parent ``Node``. Must not be None.
499
+ **kwargs: Forwarded to :class:`Node.__init__`. Common kwargs
500
+ include ``pk`` (child's primary key), ``main_label``,
501
+ ``alternative_labels``, ``parent_relation`` (default
502
+ ``"HAS"``), and ``_propagate``.
503
+
504
+ Raises:
505
+ AssertionError: If ``parent`` is not a ``Node`` instance.
506
+ """
507
+
508
+ def __init__(self, **kwargs: Any) -> None:
509
+ """Initialize a WeakNode tied to a parent node.
510
+
511
+ Args:
512
+ parent: The parent ``Node``. Required — must be passed as a
513
+ kwarg.
514
+ **kwargs: Passed to :class:`Node.__init__` (``pk``,
515
+ ``main_label``, ``alternative_labels``,
516
+ ``parent_relation``, ``_propagate``, etc.).
517
+
518
+ Raises:
519
+ AssertionError: If ``parent`` is not provided or is not a
520
+ ``Node`` instance.
521
+ """
522
+ parent = kwargs.pop("parent", None)
523
+ if parent is None:
524
+ raise ValueError(
525
+ "WeakNode requires a 'parent' argument. "
526
+ "Pass parent=<Node> to establish the parent-child relationship."
527
+ )
528
+ assert isinstance(parent, Node), "parent must be a Node"
529
+ kwargs.pop("is_weak", None)
530
+ super().__init__(is_weak=True, parent=parent, **kwargs)
531
+
532
+
533
+ class WeakRelation(Relation):
534
+ """A typed edge connecting a parent node to its child (WeakNode).
535
+
536
+ WeakRelations are automatically created when a WeakNode is inserted.
537
+ They carry the ``_propagate=TRUE`` flag, which signals to the graph
538
+ store that deleting the parent should cascade to the child node.
539
+
540
+ Args:
541
+ src: Source (parent) node.
542
+ dst: Destination (child / WeakNode).
543
+ rel_type: Relation type (e.g. ``"HAS_PAGE"``, ``"CONTAINS"``).
544
+ **kwargs: Edge properties. The ``propagate`` kwarg controls
545
+ whether the ``_propagate`` flag is set (default ``True``).
546
+
547
+ Attributes:
548
+ _propagate: Always ``True`` by default. Indicates that deleting
549
+ the source node should cascade delete to the destination node.
550
+ """
551
+
552
+ def __init__(
553
+ self, src: Node, dst: Node, rel_type: str, **kwargs: Any
554
+ ) -> None:
555
+ """Initialize a WeakRelation with cascade propagation.
556
+
557
+ Args:
558
+ src: Source (parent) node.
559
+ dst: Destination (child) node.
560
+ rel_type: Relation type.
561
+ propagate: If True (default), the edge carries the
562
+ ``_propagate=TRUE`` flag for cascade delete.
563
+ """
564
+ super().__init__(
565
+ src, dst, rel_type, _propagate=kwargs.pop("propagate", True), **kwargs
566
+ )