cpg2py 1.1.0__tar.gz → 1.2.1__tar.gz
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.
- {cpg2py-1.1.0 → cpg2py-1.2.1}/LICENSE +1 -1
- cpg2py-1.2.1/PKG-INFO +179 -0
- cpg2py-1.2.1/README.md +124 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/__init__.py +25 -2
- cpg2py-1.2.1/cpg2py/_abc/edge.py +96 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_abc/graph.py +10 -15
- cpg2py-1.2.1/cpg2py/_abc/node.py +75 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_abc/storage.py +69 -1
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_cpg/edge.py +2 -3
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_cpg/graph.py +7 -7
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_cpg/node.py +2 -3
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_exceptions.py +11 -9
- cpg2py-1.2.1/cpg2py.egg-info/PKG-INFO +179 -0
- cpg2py-1.2.1/cpg2py.egg-info/requires.txt +11 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/pyproject.toml +19 -9
- cpg2py-1.2.1/tests/test_edge.py +208 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/tests/test_exceptions.py +39 -10
- {cpg2py-1.1.0 → cpg2py-1.2.1}/tests/test_generics.py +47 -41
- {cpg2py-1.1.0 → cpg2py-1.2.1}/tests/test_graph.py +277 -63
- {cpg2py-1.1.0 → cpg2py-1.2.1}/tests/test_node.py +113 -19
- cpg2py-1.2.1/tests/test_storage.py +854 -0
- cpg2py-1.1.0/PKG-INFO +0 -407
- cpg2py-1.1.0/README.md +0 -358
- cpg2py-1.1.0/cpg2py/_abc/edge.py +0 -96
- cpg2py-1.1.0/cpg2py/_abc/node.py +0 -62
- cpg2py-1.1.0/cpg2py.egg-info/PKG-INFO +0 -407
- cpg2py-1.1.0/cpg2py.egg-info/requires.txt +0 -6
- cpg2py-1.1.0/tests/test_edge.py +0 -139
- cpg2py-1.1.0/tests/test_storage.py +0 -472
- {cpg2py-1.1.0 → cpg2py-1.2.1}/MANIFEST.in +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_abc/__init__.py +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_cpg/__init__.py +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py/_logger.py +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py.egg-info/SOURCES.txt +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py.egg-info/dependency_links.txt +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/cpg2py.egg-info/top_level.txt +0 -0
- {cpg2py-1.1.0 → cpg2py-1.2.1}/setup.cfg +0 -0
cpg2py-1.2.1/PKG-INFO
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: cpg2py
|
|
3
|
+
Version: 1.2.1
|
|
4
|
+
Summary: A graph-based data structure designed for querying CSV files in Joern format in Python
|
|
5
|
+
Author-email: samhsu-dev <yxu166@jhu.edu>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 samhsu-dev
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/samhsu-dev/cpg2py
|
|
29
|
+
Project-URL: Repository, https://github.com/samhsu-dev/cpg2py
|
|
30
|
+
Project-URL: Documentation, https://github.com/samhsu-dev/cpg2py
|
|
31
|
+
Keywords: Joern,CPG,Graph,CSV
|
|
32
|
+
Classifier: Development Status :: 4 - Beta
|
|
33
|
+
Classifier: Intended Audience :: Developers
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Programming Language :: Python :: 3
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
42
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
43
|
+
Requires-Python: >=3.8
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
License-File: LICENSE
|
|
46
|
+
Provides-Extra: test
|
|
47
|
+
Requires-Dist: pytest>=7.4.0; extra == "test"
|
|
48
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
|
|
49
|
+
Provides-Extra: dev
|
|
50
|
+
Requires-Dist: pytest>=7.4.0; extra == "dev"
|
|
51
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
52
|
+
Requires-Dist: black>=23.0.0; extra == "dev"
|
|
53
|
+
Requires-Dist: isort>=5.12.0; extra == "dev"
|
|
54
|
+
Requires-Dist: pylint>=2.17.0; extra == "dev"
|
|
55
|
+
|
|
56
|
+
# cpg2py
|
|
57
|
+
|
|
58
|
+
Python graph query engine for Code Property Graphs from Joern CSV exports. Directed multi-graph with generic ABCs for custom node/edge/graph types.
|
|
59
|
+
|
|
60
|
+
**Features**: Load from `nodes.csv` + `rels.csv`; query/update nodes and edges (`get_property`, `set_property`, `set_properties`); traverse succ/prev/children/parent/flow_to/flow_from; JSON persistence (`save_json`, `load_json`, `storage_from_json`). Concrete types: `CpgGraph`, `CpgNode`, `CpgEdge`.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install cpg2py
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
From source (e.g. with [uv](https://github.com/astral-sh/uv)):
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
git clone https://github.com/samhsu-dev/cpg2py.git && cd cpg2py
|
|
74
|
+
uv sync --dev
|
|
75
|
+
uv run pytest tests/
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Input format
|
|
81
|
+
|
|
82
|
+
- **nodes.csv**: tab-delimited; must include node id (e.g. `id:int` or `id`). Other columns become node properties.
|
|
83
|
+
- **rels.csv**: tab-delimited; columns `start`, `end`, `type` (or `start:str`, `end:str`, `type:str`).
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## Usage
|
|
88
|
+
|
|
89
|
+
**Load from CSV**
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from pathlib import Path
|
|
93
|
+
from cpg2py import cpg_graph, CpgGraph, CpgNode, CpgEdge
|
|
94
|
+
|
|
95
|
+
graph: CpgGraph = cpg_graph(Path("nodes.csv"), Path("rels.csv"))
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
**Nodes and edges** (edge identified by `(from_id, to_id, edge_type)`; `edge_type` is string)
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
node: CpgNode = graph.node("2")
|
|
102
|
+
node.name
|
|
103
|
+
node.set_property("name", "x")
|
|
104
|
+
node.set_properties({"k": "v"})
|
|
105
|
+
|
|
106
|
+
edge: CpgEdge = graph.edge("2", "3", "ENTRY")
|
|
107
|
+
edge.from_nid, edge.to_nid, edge.type
|
|
108
|
+
edge.set_property("weight", 0.5)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Traversal**
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
graph.succ(node) # successors
|
|
115
|
+
graph.prev(node) # predecessors
|
|
116
|
+
graph.children(node)
|
|
117
|
+
graph.parent(node)
|
|
118
|
+
graph.flow_to(node)
|
|
119
|
+
graph.flow_from(node)
|
|
120
|
+
graph.topfile_node("5") # top-level file node for given node ID
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
**Filtered iteration** (optional predicate)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
graph.nodes(lambda n: n.type == "Function")
|
|
127
|
+
graph.edges(lambda e: e.edge_type == "FLOWS_TO")
|
|
128
|
+
graph.succ(node, who_satisifies=lambda e: e.edge_type == "PARENT_OF")
|
|
129
|
+
graph.descendants(node, condition=...)
|
|
130
|
+
graph.ancestors(node, condition=...)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
**JSON persistence**
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
graph.storage.save_json("graph.json")
|
|
137
|
+
|
|
138
|
+
storage = Storage()
|
|
139
|
+
storage.load_json("graph.json")
|
|
140
|
+
graph2 = CpgGraph(storage)
|
|
141
|
+
|
|
142
|
+
# or
|
|
143
|
+
storage = storage_from_json(Path("graph.json"))
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
JSON schema: `{"nodes": { "<id>": { "<key>": <value>, ... }, ... }, "edges": [ {"from": str, "to": str, "type": str, "props": {...} }, ... ]}`. See [design.md](docs/design.md).
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## Extending (ABCs)
|
|
151
|
+
|
|
152
|
+
Implement `AbcGraphQuerier[MyNode, MyEdge]`, `AbcNodeQuerier`, `AbcEdgeQuerier`; inject `Storage`. Full interface and contracts: [docs/design.md](docs/design.md).
|
|
153
|
+
|
|
154
|
+
Minimal custom graph:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from cpg2py import AbcGraphQuerier, AbcNodeQuerier, AbcEdgeQuerier, Storage
|
|
158
|
+
from typing import Optional
|
|
159
|
+
|
|
160
|
+
class MyNode(AbcNodeQuerier): pass
|
|
161
|
+
class MyEdge(AbcEdgeQuerier): pass
|
|
162
|
+
|
|
163
|
+
class MyGraph(AbcGraphQuerier[MyNode, MyEdge]):
|
|
164
|
+
def node(self, whose_id_is: str) -> Optional[MyNode]:
|
|
165
|
+
return MyNode(self.storage, whose_id_is)
|
|
166
|
+
def edge(self, fid: str, tid: str, eid: str) -> Optional[MyEdge]:
|
|
167
|
+
return MyEdge(self.storage, fid, tid, eid)
|
|
168
|
+
|
|
169
|
+
g = MyGraph(Storage())
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
Interface specifications (classes, methods, signatures, validation): [docs/design.md](docs/design.md).
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
MIT.
|
cpg2py-1.2.1/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# cpg2py
|
|
2
|
+
|
|
3
|
+
Python graph query engine for Code Property Graphs from Joern CSV exports. Directed multi-graph with generic ABCs for custom node/edge/graph types.
|
|
4
|
+
|
|
5
|
+
**Features**: Load from `nodes.csv` + `rels.csv`; query/update nodes and edges (`get_property`, `set_property`, `set_properties`); traverse succ/prev/children/parent/flow_to/flow_from; JSON persistence (`save_json`, `load_json`, `storage_from_json`). Concrete types: `CpgGraph`, `CpgNode`, `CpgEdge`.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install cpg2py
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
From source (e.g. with [uv](https://github.com/astral-sh/uv)):
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
git clone https://github.com/samhsu-dev/cpg2py.git && cd cpg2py
|
|
19
|
+
uv sync --dev
|
|
20
|
+
uv run pytest tests/
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Input format
|
|
26
|
+
|
|
27
|
+
- **nodes.csv**: tab-delimited; must include node id (e.g. `id:int` or `id`). Other columns become node properties.
|
|
28
|
+
- **rels.csv**: tab-delimited; columns `start`, `end`, `type` (or `start:str`, `end:str`, `type:str`).
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
**Load from CSV**
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from cpg2py import cpg_graph, CpgGraph, CpgNode, CpgEdge
|
|
39
|
+
|
|
40
|
+
graph: CpgGraph = cpg_graph(Path("nodes.csv"), Path("rels.csv"))
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Nodes and edges** (edge identified by `(from_id, to_id, edge_type)`; `edge_type` is string)
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
node: CpgNode = graph.node("2")
|
|
47
|
+
node.name
|
|
48
|
+
node.set_property("name", "x")
|
|
49
|
+
node.set_properties({"k": "v"})
|
|
50
|
+
|
|
51
|
+
edge: CpgEdge = graph.edge("2", "3", "ENTRY")
|
|
52
|
+
edge.from_nid, edge.to_nid, edge.type
|
|
53
|
+
edge.set_property("weight", 0.5)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Traversal**
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
graph.succ(node) # successors
|
|
60
|
+
graph.prev(node) # predecessors
|
|
61
|
+
graph.children(node)
|
|
62
|
+
graph.parent(node)
|
|
63
|
+
graph.flow_to(node)
|
|
64
|
+
graph.flow_from(node)
|
|
65
|
+
graph.topfile_node("5") # top-level file node for given node ID
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Filtered iteration** (optional predicate)
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
graph.nodes(lambda n: n.type == "Function")
|
|
72
|
+
graph.edges(lambda e: e.edge_type == "FLOWS_TO")
|
|
73
|
+
graph.succ(node, who_satisifies=lambda e: e.edge_type == "PARENT_OF")
|
|
74
|
+
graph.descendants(node, condition=...)
|
|
75
|
+
graph.ancestors(node, condition=...)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
**JSON persistence**
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
graph.storage.save_json("graph.json")
|
|
82
|
+
|
|
83
|
+
storage = Storage()
|
|
84
|
+
storage.load_json("graph.json")
|
|
85
|
+
graph2 = CpgGraph(storage)
|
|
86
|
+
|
|
87
|
+
# or
|
|
88
|
+
storage = storage_from_json(Path("graph.json"))
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
JSON schema: `{"nodes": { "<id>": { "<key>": <value>, ... }, ... }, "edges": [ {"from": str, "to": str, "type": str, "props": {...} }, ... ]}`. See [design.md](docs/design.md).
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Extending (ABCs)
|
|
96
|
+
|
|
97
|
+
Implement `AbcGraphQuerier[MyNode, MyEdge]`, `AbcNodeQuerier`, `AbcEdgeQuerier`; inject `Storage`. Full interface and contracts: [docs/design.md](docs/design.md).
|
|
98
|
+
|
|
99
|
+
Minimal custom graph:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from cpg2py import AbcGraphQuerier, AbcNodeQuerier, AbcEdgeQuerier, Storage
|
|
103
|
+
from typing import Optional
|
|
104
|
+
|
|
105
|
+
class MyNode(AbcNodeQuerier): pass
|
|
106
|
+
class MyEdge(AbcEdgeQuerier): pass
|
|
107
|
+
|
|
108
|
+
class MyGraph(AbcGraphQuerier[MyNode, MyEdge]):
|
|
109
|
+
def node(self, whose_id_is: str) -> Optional[MyNode]:
|
|
110
|
+
return MyNode(self.storage, whose_id_is)
|
|
111
|
+
def edge(self, fid: str, tid: str, eid: str) -> Optional[MyEdge]:
|
|
112
|
+
return MyEdge(self.storage, fid, tid, eid)
|
|
113
|
+
|
|
114
|
+
g = MyGraph(Storage())
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
Interface specifications (classes, methods, signatures, validation): [docs/design.md](docs/design.md).
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
MIT.
|
|
@@ -1,14 +1,36 @@
|
|
|
1
1
|
from csv import DictReader
|
|
2
2
|
from pathlib import Path
|
|
3
|
+
from typing import Union
|
|
3
4
|
|
|
4
|
-
from ._abc import
|
|
5
|
-
from .
|
|
5
|
+
from ._abc import Storage
|
|
6
|
+
from ._abc import AbcEdgeQuerier, AbcGraphQuerier, AbcNodeQuerier
|
|
7
|
+
from ._cpg import CpgEdge, CpgGraph, CpgNode
|
|
6
8
|
from ._exceptions import CPGError, EdgeNotFoundError, NodeNotFoundError, TopFileNotFoundError
|
|
7
9
|
from ._logger import get_logger
|
|
8
10
|
|
|
9
11
|
logger = get_logger(__name__)
|
|
10
12
|
|
|
11
13
|
|
|
14
|
+
def storage_from_json(path: Union[Path, str]) -> Storage:
|
|
15
|
+
"""
|
|
16
|
+
Creates a Storage instance populated from a JSON file.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
path: Path to JSON file (Path or str).
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
New Storage instance containing the graph.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
OSError: If the file cannot be read.
|
|
26
|
+
ValueError: If JSON structure is invalid (missing "nodes" or "edges").
|
|
27
|
+
KeyError: If an edge object is missing "from", "to", or "type".
|
|
28
|
+
"""
|
|
29
|
+
storage = Storage()
|
|
30
|
+
storage.load_json(path)
|
|
31
|
+
return storage
|
|
32
|
+
|
|
33
|
+
|
|
12
34
|
def cpg_graph(node_csv: Path, edge_csv: Path, verbose: bool = False) -> CpgGraph:
|
|
13
35
|
"""
|
|
14
36
|
Creates a CPG graph from CSV files.
|
|
@@ -66,6 +88,7 @@ def cpg_graph(node_csv: Path, edge_csv: Path, verbose: bool = False) -> CpgGraph
|
|
|
66
88
|
|
|
67
89
|
__all__ = [
|
|
68
90
|
"cpg_graph",
|
|
91
|
+
"storage_from_json",
|
|
69
92
|
"CpgGraph",
|
|
70
93
|
"CpgNode",
|
|
71
94
|
"CpgEdge",
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
from typing import Any, Dict, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
from .._exceptions import EdgeNotFoundError
|
|
7
|
+
from .storage import Storage
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AbcEdgeQuerier(abc.ABC):
|
|
11
|
+
"""
|
|
12
|
+
Abstract base class for edge property access, queries, and updates.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, graph: Storage, f_nid: str, t_nid: str, e_type: str) -> None:
|
|
16
|
+
"""
|
|
17
|
+
Initializes edge querier and validates edge existence.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
graph: Storage instance containing the graph.
|
|
21
|
+
f_nid: Source node ID.
|
|
22
|
+
t_nid: Target node ID.
|
|
23
|
+
e_type: Edge type string.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
EdgeNotFoundError: If edge does not exist in the graph.
|
|
27
|
+
"""
|
|
28
|
+
self.__graph: Storage = graph
|
|
29
|
+
self.__edge_id: Tuple[str, str, str] = (str(f_nid), str(t_nid), str(e_type))
|
|
30
|
+
if not graph.contains_edge(self.__edge_id):
|
|
31
|
+
raise EdgeNotFoundError(f_nid, t_nid, e_type)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def edge_id(self) -> Tuple[str, str, str]:
|
|
35
|
+
"""
|
|
36
|
+
Returns the edge identifier tuple (from_nid, to_nid, edge_type).
|
|
37
|
+
"""
|
|
38
|
+
return self.__edge_id
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def from_nid(self) -> str:
|
|
42
|
+
"""Returns the source node identifier."""
|
|
43
|
+
return self.__edge_id[0]
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def to_nid(self) -> str:
|
|
47
|
+
"""Returns the target node identifier."""
|
|
48
|
+
return self.__edge_id[1]
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def edge_type(self) -> str:
|
|
52
|
+
"""Returns the edge type string."""
|
|
53
|
+
return self.__edge_id[2]
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def properties(self) -> Optional[Dict[str, Any]]:
|
|
57
|
+
"""Returns all edge properties dictionary, or None if not found."""
|
|
58
|
+
return self.__graph.get_edge_props(self.__edge_id)
|
|
59
|
+
|
|
60
|
+
def get_property(self, *prop_names: str) -> Optional[Any]:
|
|
61
|
+
"""
|
|
62
|
+
Returns first found property value trying multiple name alternatives.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
prop_names: Property name alternatives to try.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
First found value, or None if none found.
|
|
69
|
+
"""
|
|
70
|
+
prop_values = (self.__graph.get_edge_prop(self.__edge_id, p_name) for p_name in prop_names)
|
|
71
|
+
return next((value for value in prop_values if value is not None), None)
|
|
72
|
+
|
|
73
|
+
def set_property(self, key: str, value: Any) -> bool:
|
|
74
|
+
"""
|
|
75
|
+
Sets single edge property value.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
key: Property key.
|
|
79
|
+
value: Property value.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
True if property was set, False if edge does not exist.
|
|
83
|
+
"""
|
|
84
|
+
return self.__graph.set_edge_prop(self.__edge_id, key, value)
|
|
85
|
+
|
|
86
|
+
def set_properties(self, props: Dict[str, Any]) -> bool:
|
|
87
|
+
"""
|
|
88
|
+
Updates multiple edge properties at once.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
props: Dictionary of property key-value pairs.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
True if properties were updated, False if edge does not exist.
|
|
95
|
+
"""
|
|
96
|
+
return self.__graph.set_edge_props(self.__edge_id, props)
|
|
@@ -16,6 +16,8 @@ _EdgeType = TypeVar("_EdgeType", bound=AbcEdgeQuerier, covariant=True)
|
|
|
16
16
|
# Type variables for concrete implementations (invariant)
|
|
17
17
|
_ConcreteNodeType = TypeVar("_ConcreteNodeType", bound=AbcNodeQuerier)
|
|
18
18
|
_ConcreteEdgeType = TypeVar("_ConcreteEdgeType", bound=AbcEdgeQuerier)
|
|
19
|
+
_NodeCondition = Callable[[_NodeType], bool]
|
|
20
|
+
_EdgeCondition = Callable[[_EdgeType], bool]
|
|
19
21
|
|
|
20
22
|
|
|
21
23
|
class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
@@ -36,15 +38,8 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
36
38
|
_ConcreteNodeType: The concrete node type returned by node() and related methods
|
|
37
39
|
_ConcreteEdgeType: The concrete edge type returned by edge() and used in conditions
|
|
38
40
|
"""
|
|
39
|
-
|
|
40
|
-
__NodeCondition = Callable[[_NodeType], bool]
|
|
41
|
-
__EdgeCondition = Callable[[_EdgeType], bool]
|
|
42
|
-
|
|
43
41
|
__always_true = lambda _: True
|
|
44
42
|
|
|
45
|
-
__NodesResult = Iterable[_ConcreteNodeType]
|
|
46
|
-
__EdgesResult = Iterable[_ConcreteEdgeType]
|
|
47
|
-
|
|
48
43
|
def __init__(self, target: Storage, maxdepth: int = -1) -> None:
|
|
49
44
|
"""
|
|
50
45
|
Initializes a graph querier.
|
|
@@ -95,7 +90,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
95
90
|
raise NotImplementedError
|
|
96
91
|
|
|
97
92
|
def nodes(
|
|
98
|
-
self, who_satisifies:
|
|
93
|
+
self, who_satisifies: _NodeCondition = __always_true
|
|
99
94
|
) -> Iterable[_ConcreteNodeType]:
|
|
100
95
|
"""
|
|
101
96
|
Returns all nodes matching the condition.
|
|
@@ -112,7 +107,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
112
107
|
yield cur_node
|
|
113
108
|
|
|
114
109
|
def first_node(
|
|
115
|
-
self, who_satisifies:
|
|
110
|
+
self, who_satisifies: _NodeCondition = __always_true
|
|
116
111
|
) -> Optional[_ConcreteNodeType]:
|
|
117
112
|
"""
|
|
118
113
|
Returns the first node matching the condition.
|
|
@@ -126,7 +121,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
126
121
|
return next(self.nodes(who_satisifies), None)
|
|
127
122
|
|
|
128
123
|
def edges(
|
|
129
|
-
self, who_satisifies:
|
|
124
|
+
self, who_satisifies: _EdgeCondition = __always_true
|
|
130
125
|
) -> Iterable[_ConcreteEdgeType]:
|
|
131
126
|
"""
|
|
132
127
|
Returns all edges matching the condition.
|
|
@@ -143,7 +138,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
143
138
|
yield cur_edge
|
|
144
139
|
|
|
145
140
|
def succ(
|
|
146
|
-
self, of: _ConcreteNodeType, who_satisifies:
|
|
141
|
+
self, of: _ConcreteNodeType, who_satisifies: _EdgeCondition = __always_true
|
|
147
142
|
) -> Iterable[_ConcreteNodeType]:
|
|
148
143
|
"""
|
|
149
144
|
Returns successor nodes connected to the input node.
|
|
@@ -163,7 +158,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
163
158
|
yield node
|
|
164
159
|
|
|
165
160
|
def prev(
|
|
166
|
-
self, of: _ConcreteNodeType, who_satisifies:
|
|
161
|
+
self, of: _ConcreteNodeType, who_satisifies: _EdgeCondition = __always_true
|
|
167
162
|
) -> Iterable[_ConcreteNodeType]:
|
|
168
163
|
"""
|
|
169
164
|
Returns predecessor nodes connected to the input node.
|
|
@@ -183,7 +178,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
183
178
|
yield node
|
|
184
179
|
|
|
185
180
|
def __bfs_search(
|
|
186
|
-
self, root: _ConcreteNodeType, condition:
|
|
181
|
+
self, root: _ConcreteNodeType, condition: _EdgeCondition, reverse: bool
|
|
187
182
|
) -> Iterable[_ConcreteNodeType]:
|
|
188
183
|
"""
|
|
189
184
|
Returns nodes from src node by BFS order (src node not included).
|
|
@@ -217,7 +212,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
217
212
|
yield cur_node
|
|
218
213
|
|
|
219
214
|
def descendants(
|
|
220
|
-
self, src: _ConcreteNodeType, condition:
|
|
215
|
+
self, src: _ConcreteNodeType, condition: _EdgeCondition = __always_true
|
|
221
216
|
) -> Iterable[_ConcreteNodeType]:
|
|
222
217
|
"""
|
|
223
218
|
Returns descendants from src node by BFS order (src node not included).
|
|
@@ -232,7 +227,7 @@ class AbcGraphQuerier(abc.ABC, Generic[_ConcreteNodeType, _ConcreteEdgeType]):
|
|
|
232
227
|
return self.__bfs_search(src, condition, reverse=False)
|
|
233
228
|
|
|
234
229
|
def ancestors(
|
|
235
|
-
self, src: _ConcreteNodeType, condition:
|
|
230
|
+
self, src: _ConcreteNodeType, condition: _EdgeCondition = __always_true
|
|
236
231
|
) -> Iterable[_ConcreteNodeType]:
|
|
237
232
|
"""
|
|
238
233
|
Returns ancestors from src node by BFS order (src node not included).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
from .._exceptions import NodeNotFoundError
|
|
5
|
+
from .storage import Storage
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AbcNodeQuerier(abc.ABC):
|
|
9
|
+
"""
|
|
10
|
+
Abstract base class for node property access, queries, and updates.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, graph: Storage, nid: str) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Initializes node querier and validates node existence.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
graph: Storage instance containing the graph.
|
|
19
|
+
nid: Node identifier.
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
NodeNotFoundError: If node does not exist in the graph.
|
|
23
|
+
"""
|
|
24
|
+
self.__nid: str = str(nid)
|
|
25
|
+
self.__graph: Storage = graph
|
|
26
|
+
if not graph.contains_node(self.__nid):
|
|
27
|
+
raise NodeNotFoundError(str(nid))
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def node_id(self) -> str:
|
|
31
|
+
"""Returns the node identifier."""
|
|
32
|
+
return self.__nid
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def properties(self) -> Optional[Dict[str, Any]]:
|
|
36
|
+
"""Returns all node properties dictionary, or None if not found."""
|
|
37
|
+
return self.__graph.get_node_props(self.__nid)
|
|
38
|
+
|
|
39
|
+
def get_property(self, *prop_names: str) -> Optional[Any]:
|
|
40
|
+
"""
|
|
41
|
+
Returns first found property value trying multiple name alternatives.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
prop_names: Property name alternatives to try.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
First found value, or None if none found.
|
|
48
|
+
"""
|
|
49
|
+
prop_values = (self.__graph.get_node_prop(self.__nid, p_name) for p_name in prop_names)
|
|
50
|
+
return next((value for value in prop_values if value is not None), None)
|
|
51
|
+
|
|
52
|
+
def set_property(self, key: str, value: Any) -> bool:
|
|
53
|
+
"""
|
|
54
|
+
Sets single node property value.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
key: Property key.
|
|
58
|
+
value: Property value.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
True if property was set, False if node does not exist.
|
|
62
|
+
"""
|
|
63
|
+
return self.__graph.set_node_prop(self.__nid, key, value)
|
|
64
|
+
|
|
65
|
+
def set_properties(self, props: Dict[str, Any]) -> bool:
|
|
66
|
+
"""
|
|
67
|
+
Updates multiple node properties at once.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
props: Dictionary of property key-value pairs.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
True if properties were updated, False if node does not exist.
|
|
74
|
+
"""
|
|
75
|
+
return self.__graph.set_node_props(self.__nid, props)
|