prograph 1.3.3__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.
- prograph/__init__.py +36 -0
- prograph/__main__.py +5 -0
- prograph/_version.py +375 -0
- prograph/cli/__init__.py +1 -0
- prograph/cli/_iri_utils.py +124 -0
- prograph/cli/emit_genie_space.py +107 -0
- prograph/cli/generate_views.py +140 -0
- prograph/cli/main.py +420 -0
- prograph/cli/schema_inferrer.py +746 -0
- prograph/cli/ttl_loader.py +289 -0
- prograph/cli/upload_genie_space.py +84 -0
- prograph/config/__init__.py +27 -0
- prograph/config/yaml_config.py +848 -0
- prograph/demos/__init__.py +14 -0
- prograph/demos/turbofan/README.md +74 -0
- prograph/demos/turbofan/SCENARIO.md +209 -0
- prograph/demos/turbofan/__init__.py +75 -0
- prograph/demos/turbofan/create_tables.sql +206 -0
- prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
- prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
- prograph/demos/turbofan/demo.py +162 -0
- prograph/demos/turbofan/genie_qa_notebook.py +434 -0
- prograph/demos/turbofan/graph.yaml +1098 -0
- prograph/demos/turbofan/instance_graph_demo.py +32 -0
- prograph/demos/turbofan/load.py +223 -0
- prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
- prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
- prograph/demos/turbofan/payload-shapes.ttl +33 -0
- prograph/demos/turbofan/queries/example-queries.sparql +215 -0
- prograph/demos/turbofan/shapes.ttl +75 -0
- prograph/demos/turbofan/tables.py +106 -0
- prograph/demos/turbofan/turbofan_schema.py +393 -0
- prograph/demos/turbofan/validation_demo.py +153 -0
- prograph/describe.py +231 -0
- prograph/endpoint/__init__.py +12 -0
- prograph/endpoint/app.py +722 -0
- prograph/endpoint/cli.py +280 -0
- prograph/endpoint/credentials.py +240 -0
- prograph/endpoint/engines.py +418 -0
- prograph/endpoint/negotiate.py +101 -0
- prograph/endpoint/results.py +181 -0
- prograph/endpoint/service.py +31 -0
- prograph/engine.py +2718 -0
- prograph/execution.py +455 -0
- prograph/executors/__init__.py +6 -0
- prograph/executors/base.py +11 -0
- prograph/executors/databricks_sql_executor.py +51 -0
- prograph/executors/duckdb_executor.py +24 -0
- prograph/executors/mysql_executor.py +20 -0
- prograph/executors/oracle_executor.py +24 -0
- prograph/executors/pandas_executor.py +72 -0
- prograph/executors/postgresql_executor.py +35 -0
- prograph/executors/spark_executor.py +88 -0
- prograph/executors/sqlserver_executor.py +35 -0
- prograph/extras/__init__.py +1 -0
- prograph/extras/graphql/__init__.py +33 -0
- prograph/extras/graphql/execute.py +25 -0
- prograph/extras/graphql/schema.py +314 -0
- prograph/extras/instance_graph.py +559 -0
- prograph/genie/__init__.py +83 -0
- prograph/genie/databricks_uploader.py +306 -0
- prograph/genie/deploy.py +393 -0
- prograph/genie/formats.py +414 -0
- prograph/genie/instruction_generator.py +375 -0
- prograph/genie/sample_query_generator.py +256 -0
- prograph/genie/shacl_views.py +318 -0
- prograph/genie/space_emitter.py +329 -0
- prograph/genie/view_generator.py +628 -0
- prograph/genie/view_writer.py +172 -0
- prograph/graph/__init__.py +1 -0
- prograph/graph/ansi_session.py +348 -0
- prograph/graph/databricks_sql_graph.py +300 -0
- prograph/graph/drivers.py +143 -0
- prograph/graph/duckdb_graph.py +68 -0
- prograph/graph/mysql_graph.py +38 -0
- prograph/graph/oracle_graph.py +285 -0
- prograph/graph/pandas_graph.py +343 -0
- prograph/graph/postgresql_graph.py +644 -0
- prograph/graph/spark_graph.py +556 -0
- prograph/graph/sql_graph.py +83 -0
- prograph/graph/sqlserver_graph.py +72 -0
- prograph/hints.py +95 -0
- prograph/logging.py +550 -0
- prograph/mcp/__init__.py +29 -0
- prograph/mcp/__main__.py +180 -0
- prograph/mcp/bootstrap.py +98 -0
- prograph/mcp/server.py +601 -0
- prograph/mcp/sparql.py +397 -0
- prograph/mcp/tools.py +504 -0
- prograph/nlp/__init__.py +79 -0
- prograph/nlp/client.py +305 -0
- prograph/nlp/databricks_tools.py +369 -0
- prograph/nlp/graph_context.py +313 -0
- prograph/nlp/interface.py +652 -0
- prograph/nlp/prompts/__init__.py +19 -0
- prograph/nlp/prompts/examples.py +258 -0
- prograph/nlp/prompts/system.py +239 -0
- prograph/nlp/providers/__init__.py +14 -0
- prograph/nlp/providers/anthropic.py +274 -0
- prograph/nlp/providers/databricks.py +312 -0
- prograph/nlp/providers/openai.py +203 -0
- prograph/nlp/schema_context.py +78 -0
- prograph/ontology/__init__.py +53 -0
- prograph/ontology/alignment.py +542 -0
- prograph/ontology/hierarchy.py +310 -0
- prograph/ontology/imports.py +587 -0
- prograph/ontology/layer.py +991 -0
- prograph/ontology/skos.py +61 -0
- prograph/owl/__init__.py +27 -0
- prograph/owl/defined_classes.py +323 -0
- prograph/parameters.py +242 -0
- prograph/parser/__init__.py +1 -0
- prograph/parser/cypher/CypherLexer.py +836 -0
- prograph/parser/cypher/CypherListener.py +966 -0
- prograph/parser/cypher/CypherParser.py +10854 -0
- prograph/parser/cypher/CypherVisitor.py +543 -0
- prograph/parser/cypher/__init__.py +1 -0
- prograph/parser/sparql/SparqlLexer.py +801 -0
- prograph/parser/sparql/SparqlParser.py +10146 -0
- prograph/parser/sparql/SparqlParserListener.py +1056 -0
- prograph/parser/sparql/SparqlParserVisitor.py +593 -0
- prograph/parser/sparql/__init__.py +8 -0
- prograph/plan/__init__.py +3 -0
- prograph/plan/ir/__init__.py +1 -0
- prograph/plan/ir/casts.py +338 -0
- prograph/plan/ir/consistency.py +397 -0
- prograph/plan/ir/construct.py +90 -0
- prograph/plan/ir/cost.py +234 -0
- prograph/plan/ir/cypher_answer.py +1081 -0
- prograph/plan/ir/cypher_apoc.py +717 -0
- prograph/plan/ir/cypher_apoc_convert.py +505 -0
- prograph/plan/ir/cypher_apoc_date.py +845 -0
- prograph/plan/ir/cypher_apoc_map.py +496 -0
- prograph/plan/ir/cypher_apoc_meta.py +384 -0
- prograph/plan/ir/cypher_apoc_path.py +597 -0
- prograph/plan/ir/cypher_apoc_procedures.py +163 -0
- prograph/plan/ir/cypher_apoc_text.py +785 -0
- prograph/plan/ir/cypher_front.py +5474 -0
- prograph/plan/ir/cypher_functions.py +565 -0
- prograph/plan/ir/cypher_lists.py +935 -0
- prograph/plan/ir/cypher_maps.py +370 -0
- prograph/plan/ir/cypher_mixed.py +604 -0
- prograph/plan/ir/cypher_ontology.py +226 -0
- prograph/plan/ir/cypher_procedures.py +191 -0
- prograph/plan/ir/cypher_runtime_errors.py +107 -0
- prograph/plan/ir/cypher_temporal.py +1357 -0
- prograph/plan/ir/cypher_temporal_arith.py +339 -0
- prograph/plan/ir/cypher_values.py +546 -0
- prograph/plan/ir/cypher_write.py +612 -0
- prograph/plan/ir/dataset.py +643 -0
- prograph/plan/ir/dates.py +102 -0
- prograph/plan/ir/entry.py +992 -0
- prograph/plan/ir/expr.py +260 -0
- prograph/plan/ir/facts.py +1171 -0
- prograph/plan/ir/fresh.py +291 -0
- prograph/plan/ir/freshness.py +625 -0
- prograph/plan/ir/identity.py +797 -0
- prograph/plan/ir/java_datetime.py +265 -0
- prograph/plan/ir/java_regex.py +391 -0
- prograph/plan/ir/join_order.py +39 -0
- prograph/plan/ir/key_checks.py +433 -0
- prograph/plan/ir/keys.py +454 -0
- prograph/plan/ir/lower.py +5323 -0
- prograph/plan/ir/ops.py +619 -0
- prograph/plan/ir/owl_rl.py +1119 -0
- prograph/plan/ir/owl_rl_rules.py +725 -0
- prograph/plan/ir/profiles.py +694 -0
- prograph/plan/ir/ql.py +987 -0
- prograph/plan/ir/rdfs.py +342 -0
- prograph/plan/ir/rewrite.py +1782 -0
- prograph/plan/ir/saturate.py +339 -0
- prograph/plan/ir/semantics.py +103 -0
- prograph/plan/ir/slot.py +509 -0
- prograph/plan/ir/sparql_front.py +3418 -0
- prograph/plan/ir/strings.py +534 -0
- prograph/plan/ir/term_functions.py +274 -0
- prograph/plan/ir/terms.py +84 -0
- prograph/plan/ir/xpath_regex.py +264 -0
- prograph/plan/run_record.py +65 -0
- prograph/plan/sql/__init__.py +21 -0
- prograph/plan/sql/dialect.py +3726 -0
- prograph/plan/sql/mysql_serializer.py +103 -0
- prograph/plan/sql/names.py +65 -0
- prograph/plan/sql/oracle_serializer.py +306 -0
- prograph/plan/sql/pg_serializer.py +501 -0
- prograph/plan/sql/rel_algebra.py +781 -0
- prograph/plan/sql/sql_serializer.py +1419 -0
- prograph/plan/sql/sqlserver_serializer.py +603 -0
- prograph/provenance.py +222 -0
- prograph/r2rml/__init__.py +48 -0
- prograph/r2rml/catalog.py +259 -0
- prograph/r2rml/compile.py +372 -0
- prograph/r2rml/direct.py +140 -0
- prograph/r2rml/export.py +495 -0
- prograph/r2rml/model.py +180 -0
- prograph/r2rml/parser.py +546 -0
- prograph/r2rml/schema.py +120 -0
- prograph/read_only.py +122 -0
- prograph/results.py +157 -0
- prograph/rules/__init__.py +168 -0
- prograph/rules/__main__.py +32 -0
- prograph/schema/__init__.py +60 -0
- prograph/schema/change_set.py +50 -0
- prograph/schema/collations.py +198 -0
- prograph/schema/compile_schema.py +388 -0
- prograph/schema/context.py +845 -0
- prograph/schema/examples.py +234 -0
- prograph/schema/iri.py +817 -0
- prograph/schema/literals.py +94 -0
- prograph/schema/lpg_view.py +617 -0
- prograph/schema/mapping.py +1803 -0
- prograph/schema/maps_schema.py +40 -0
- prograph/schema/naming.py +77 -0
- prograph/schema/query_sources.py +59 -0
- prograph/schema/rows.py +215 -0
- prograph/schema/source_map.py +1103 -0
- prograph/schema/store_view.py +459 -0
- prograph/schema/types.py +569 -0
- prograph/schema/xsd.py +569 -0
- prograph/shacl/__init__.py +30 -0
- prograph/shacl/dqv.py +58 -0
- prograph/shacl/generate.py +255 -0
- prograph/shacl/report.py +138 -0
- prograph/shacl/validator.py +164 -0
- prograph/store.py +1737 -0
- prograph/utils/__init__.py +6 -0
- prograph/utils/exceptions.py +308 -0
- prograph/utils/helpers.py +126 -0
- prograph/warnings.py +46 -0
- prograph/writes.py +369 -0
- prograph-1.3.3.dist-info/METADATA +281 -0
- prograph-1.3.3.dist-info/RECORD +237 -0
- prograph-1.3.3.dist-info/WHEEL +5 -0
- prograph-1.3.3.dist-info/entry_points.txt +3 -0
- prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
- prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
- prograph-1.3.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
"""The property-graph view of the source maps (one-plan 2.5): the labels, property keys
|
|
2
|
+
and relationship types the Cypher front end reads, and an element's identity, from the one model every
|
|
3
|
+
mapping compiles to. YAML, Python, R2RML and generated maps (the owned store, the TCK's typed tables) all
|
|
4
|
+
give a view; the Cypher front end reads nothing else.
|
|
5
|
+
|
|
6
|
+
Names (one-plan 2.5; decided 2026-11-12):
|
|
7
|
+
- A node map's labels are its property-graph label (YAML, Python, a generated map), else the local names
|
|
8
|
+
of its classes (R2RML). A map with neither gives nodes with no label, as openCypher allows. Over an
|
|
9
|
+
ontology the maps are saturated (`saturate`): a class saturation added is an inferred label, named by
|
|
10
|
+
every label a mapping declares it under, else as an R2RML class is.
|
|
11
|
+
- A property key is a literal-valued predicate-object map's property name, else its predicate's local
|
|
12
|
+
name. A relationship type is an edge map's type, else its predicate's local name as a type
|
|
13
|
+
(`rel_type_from_local_name`).
|
|
14
|
+
- Two IRIs of one local name in one namespace of names (labels, property keys, relationship types: three
|
|
15
|
+
namespaces) take their prefixed names (`foaf_name`, `schema_name`); where a name still clashes, the
|
|
16
|
+
view refuses it by name (`ViewNameClashError`).
|
|
17
|
+
|
|
18
|
+
Identity: a node is its map's subject term, as SPARQL's subject is (A): maps whose subjects give
|
|
19
|
+
one term give one node, and its labels and properties are the union of theirs. `node_identity` is that
|
|
20
|
+
one function; a relationship is a row of its edge map, its ends the nodes its end terms give.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from dataclasses import dataclass, field, replace
|
|
26
|
+
from typing import Any, Dict, FrozenSet, List, Optional, Sequence, Set, Tuple
|
|
27
|
+
|
|
28
|
+
from prograph.rules import home, module_home
|
|
29
|
+
from prograph.schema.naming import local_name, rel_type_from_local_name
|
|
30
|
+
from prograph.schema.source_map import (LITERAL, EdgeMap, NodeMap, PredicateObject, SourceMaps, TermMap,
|
|
31
|
+
key_property, row_identity_term, triple_identity_term)
|
|
32
|
+
|
|
33
|
+
module_home("lpg-view", "The property-graph view of the source maps",
|
|
34
|
+
terms=("LPG view", "label", "property key", "relationship type", "node identity", "elementId",
|
|
35
|
+
"local name", "Cypher schema", "key column", "node key property", "id_column", "id()"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ViewNameClashError(ValueError):
|
|
39
|
+
"""Two IRIs give one name in the property-graph view even with their prefixes (one-plan 2.5)."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class LPGView:
|
|
44
|
+
"""The view of one set of source maps. Built once per maps (`view_of`)."""
|
|
45
|
+
maps: SourceMaps
|
|
46
|
+
labels: Dict[str, Tuple[NodeMap, ...]] = field(default_factory=dict)
|
|
47
|
+
unlabelled: Tuple[NodeMap, ...] = ()
|
|
48
|
+
node_labels: Dict[str, Tuple[str, ...]] = field(default_factory=dict) # map id -> its labels
|
|
49
|
+
# map id -> key -> its literal predicate-object maps (more than one where the map gives the key
|
|
50
|
+
# twice: the cardinality-one rule decides how Cypher reads them, not the view)
|
|
51
|
+
properties: Dict[str, Dict[str, Tuple[PredicateObject, ...]]] = field(default_factory=dict)
|
|
52
|
+
rel_types: Dict[str, Tuple[EdgeMap, ...]] = field(default_factory=dict)
|
|
53
|
+
# The owned store's view (`store_view.StoreView`), where the engine has a store: its generic maps are
|
|
54
|
+
# read beside these, through `store_node` and `store_edge`. Its generated R2RML maps are SPARQL's, not
|
|
55
|
+
# this view's: `nodes` and `edges` are the maps without them.
|
|
56
|
+
store: Any = None
|
|
57
|
+
nodes: Tuple[NodeMap, ...] = ()
|
|
58
|
+
edges: Tuple[EdgeMap, ...] = ()
|
|
59
|
+
# Relationship types the ontology reads through an inverse (`with_inverses`), each with the type it is read
|
|
60
|
+
# through: a write of one to the store would not be seen by that other type's reversed read.
|
|
61
|
+
inverse_partners: Dict[str, Tuple[str, ...]] = field(default_factory=dict)
|
|
62
|
+
# Reversed edge maps of a symmetric property (`with_inverses`): a self-loop row is its own reverse, read once.
|
|
63
|
+
mirrored: frozenset = frozenset()
|
|
64
|
+
# Labels the ontology gives by rdfs:domain or rdfs:range (`with_typing`): each with its typing edges, (edge
|
|
65
|
+
# map, True where its start is typed, False its end).
|
|
66
|
+
typed: Dict[str, Tuple[Tuple[EdgeMap, bool], ...]] = field(default_factory=dict)
|
|
67
|
+
# Properties with a domain or range whose typed end no node map holds: Cypher has no node there to label.
|
|
68
|
+
typing_lost: Tuple[str, ...] = ()
|
|
69
|
+
# Labels a stored RL fact gives (`with_derived`): read like `typed`, a derived rdf:type row's subject.
|
|
70
|
+
derived_labels: FrozenSet[str] = frozenset()
|
|
71
|
+
# Property keys stored RL facts with a literal object give (`with_derived`): key -> the stored facts' maps (one
|
|
72
|
+
# datatype per key), read beside the mapped value where a query reads the key (`cypher_front.stored_values`).
|
|
73
|
+
stored_values: Dict[str, Tuple[NodeMap, ...]] = field(default_factory=dict)
|
|
74
|
+
# Those keys no node map gives: a write of one is refused, as a derived label's is.
|
|
75
|
+
derived_keys: FrozenSet[str] = frozenset()
|
|
76
|
+
# Predicates of stored RL facts whose object is a literal that Cypher cannot read as a property (a datatype the
|
|
77
|
+
# view does not read, two datatypes of one key, a local name another predicate's key holds): warned.
|
|
78
|
+
derived_values: Tuple[str, ...] = ()
|
|
79
|
+
# Labels every node has under profile ql (`with_everything`): owl:Thing's, and each class C with ⊤ ⊑ C.
|
|
80
|
+
everything: FrozenSet[str] = frozenset()
|
|
81
|
+
|
|
82
|
+
def node_maps(self, label: Optional[str] = None) -> Tuple[NodeMap, ...]:
|
|
83
|
+
"""The node maps a node pattern of `label` reads (every node map for no label); the store's
|
|
84
|
+
generic map is apart (`store_node`)."""
|
|
85
|
+
if label is None:
|
|
86
|
+
return tuple(self.nodes)
|
|
87
|
+
return self.labels.get(label, ())
|
|
88
|
+
|
|
89
|
+
def edge_maps(self, rel_type: Optional[str] = None) -> Tuple[EdgeMap, ...]:
|
|
90
|
+
"""The edge maps a relationship pattern of `rel_type` reads (every edge map for none); the store's
|
|
91
|
+
generic map is apart (`store_edge`)."""
|
|
92
|
+
if rel_type is None:
|
|
93
|
+
return tuple(self.edges)
|
|
94
|
+
return self.rel_types.get(rel_type, ())
|
|
95
|
+
|
|
96
|
+
def store_node(self, label: Optional[str], keys: Sequence[str], labels: Sequence[str],
|
|
97
|
+
extra: Optional[Dict[str, str]] = None, force: bool = False) -> Optional[NodeMap]:
|
|
98
|
+
"""The store's generic node map for a pattern of `label`, reading `keys` and a flag per label of
|
|
99
|
+
`labels` (`store_view.StoreView.node_map`); None without a store, or where it holds no such node."""
|
|
100
|
+
found = None if self.store is None else self.store.node_map(label, keys, labels, extra, force)
|
|
101
|
+
if found is None:
|
|
102
|
+
return None
|
|
103
|
+
m, props = found
|
|
104
|
+
self.properties[m.id] = props
|
|
105
|
+
self.node_labels[m.id] = (label,) if label is not None else ()
|
|
106
|
+
return m
|
|
107
|
+
|
|
108
|
+
def store_edge(self, rel_type: Optional[str], keys: Sequence[str], extra: Optional[Dict[str, str]] = None,
|
|
109
|
+
force: bool = False) -> Optional[EdgeMap]:
|
|
110
|
+
"""The store's generic relationship map for a pattern of `rel_type`; None without a store."""
|
|
111
|
+
return None if self.store is None else self.store.edge_map(rel_type, keys, extra, force)
|
|
112
|
+
|
|
113
|
+
def all_node_keys(self) -> Set[str]:
|
|
114
|
+
"""Every property key a node may have: the maps' and the store's."""
|
|
115
|
+
return {k for ps in self.properties.values() for k in ps} | set(self.stored_values) | \
|
|
116
|
+
set(self.store.keys("node") if self.store else ())
|
|
117
|
+
|
|
118
|
+
def all_rel_keys(self) -> Set[str]:
|
|
119
|
+
"""Every property key a relationship may have: the maps' and the store's."""
|
|
120
|
+
return {k for e in self.edges for k, _ in e.property_columns} | set(self.store.keys("rel") if self.store else ())
|
|
121
|
+
|
|
122
|
+
def property_of(self, m: NodeMap, key: str) -> Tuple[PredicateObject, ...]:
|
|
123
|
+
"""The map's predicate-object maps giving property `key`; () where the map gives none (the
|
|
124
|
+
node's property is then null for the rows of that map)."""
|
|
125
|
+
return self.properties.get(m.id, {}).get(key, ())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def node_identity(m: NodeMap) -> TermMap:
|
|
129
|
+
"""A node's identity: its map's subject term (A). Two maps whose subjects give one term give
|
|
130
|
+
one node. The one place Cypher reads identity from."""
|
|
131
|
+
return m.subject
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def with_key_properties(m: NodeMap, held: Dict[str, Tuple[PredicateObject, ...]]
|
|
135
|
+
) -> Dict[str, Tuple[PredicateObject, ...]]:
|
|
136
|
+
"""`held` (a map's property keys) with each of its key's columns a property under the column's name, for a
|
|
137
|
+
YAML or Python node mapping (`NodeMap.key_properties`: its `id_column`, each column of a composite key its own
|
|
138
|
+
property): `m.movie_id` reads the key column the subject is made from, so a filter on it is a filter on that
|
|
139
|
+
column. A property the mapping maps under that name wins. The property has no predicate: it is no triple, so
|
|
140
|
+
SPARQL does not see it (SPARQL reads the key through the subject's IRI, or a property the mapping maps)."""
|
|
141
|
+
if not m.key_properties:
|
|
142
|
+
return held
|
|
143
|
+
out = dict(held)
|
|
144
|
+
for column in m.key.columns:
|
|
145
|
+
out.setdefault(column, (key_property(column),))
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
ORDINAL = "#ordinal"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@home("cypher-relationship-identity", "A Cypher relationship's identity, from its map",
|
|
153
|
+
terms=("relationship identity", "relationship uniqueness", "elementId", "edge key", "parallel relationships",
|
|
154
|
+
"row ordinal", "id_column of a relationship"))
|
|
155
|
+
def relationship_identity(m: EdgeMap, trusted: Sequence[Sequence[str]] = ()) -> TermMap:
|
|
156
|
+
"""A relationship's identity, the one place Cypher reads it from (openCypher's relationship
|
|
157
|
+
uniqueness, `elementId`, `count(r)`):
|
|
158
|
+
- from R2RML (no relationship type, a predicate, both ends IRI templates): the triple itself, its
|
|
159
|
+
start IRI, predicate and end IRI as written, so one triple two triples maps give is one
|
|
160
|
+
relationship;
|
|
161
|
+
- else its map's declared id (stable when maps are reordered) and its row's key: the map's
|
|
162
|
+
`id_column` (`EdgeMap.row_key`), else a key of its table `trusted` holds (`keys.trusted_keys`: a
|
|
163
|
+
constraint the database enforces, a RELY key, or `keys: trusted`, the start and end columns);
|
|
164
|
+
- else, each row being one relationship (docs/conformance/choices.md), its start and end columns
|
|
165
|
+
and its number among the rows of that start and end (`ORDINAL`, an `O.Ordinal` the scan adds).
|
|
166
|
+
Rows that agree on every mapped column are numbered in any order: they are interchangeable for
|
|
167
|
+
every query, so the answers are the same; the id itself is stable only while the table is.
|
|
168
|
+
Two maps' identities never meet."""
|
|
169
|
+
from prograph.schema.store_view import is_store_map, store_identity
|
|
170
|
+
if is_store_map(m):
|
|
171
|
+
return store_identity(m) # a created relationship: its minted edge id
|
|
172
|
+
start, end = m.start.term, m.end.term
|
|
173
|
+
if m.rel_type is None and m.predicate is not None and start is not None and end is not None \
|
|
174
|
+
and start.template is not None and end.template is not None:
|
|
175
|
+
return triple_identity_term(start, m.predicate, end)
|
|
176
|
+
ends = tuple(dict.fromkeys(tuple(start.columns()) + tuple(end.columns())))
|
|
177
|
+
if m.row_key:
|
|
178
|
+
columns = tuple(m.row_key)
|
|
179
|
+
elif m.rel_type is None:
|
|
180
|
+
columns = ends # an RDF triples map's rows: one triple each
|
|
181
|
+
elif m.trust == "trusted":
|
|
182
|
+
columns = ends # asserted: one row per start and end
|
|
183
|
+
else:
|
|
184
|
+
key = next((tuple(k) for k in trusted if k), None)
|
|
185
|
+
columns = key if key is not None else ends + (ORDINAL,)
|
|
186
|
+
return row_identity_term(f"relationship:{m.id}", columns)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _named(iris: Sequence[str], prefixes: Dict[str, str], what: str,
|
|
190
|
+
spell: Any = lambda name: name) -> Dict[str, str]:
|
|
191
|
+
"""Each IRI's name in one namespace of names: its local name as `spell` writes it, or its prefixed
|
|
192
|
+
name where another IRI's spells the same (`foaf_Person`; `isPartOf` and `is_part_of` are one
|
|
193
|
+
relationship type, `IS_PART_OF`); a name that still clashes is refused."""
|
|
194
|
+
by_local: Dict[str, List[str]] = {}
|
|
195
|
+
for iri in dict.fromkeys(iris):
|
|
196
|
+
by_local.setdefault(spell(local_name(iri)), []).append(iri)
|
|
197
|
+
names: Dict[str, str] = {}
|
|
198
|
+
for local, group in by_local.items():
|
|
199
|
+
if len(group) == 1:
|
|
200
|
+
names[group[0]] = local
|
|
201
|
+
continue
|
|
202
|
+
for iri in group:
|
|
203
|
+
own = local_name(iri)
|
|
204
|
+
prefix = next((p for p, ns in prefixes.items() if iri.startswith(ns) and iri[len(ns):] == own), None)
|
|
205
|
+
if prefix is None:
|
|
206
|
+
raise ViewNameClashError(
|
|
207
|
+
f"the {what} name {local!r} is given by {', '.join(sorted(group))}, and <{iri}> has no "
|
|
208
|
+
f"prefix to tell it apart: bind a prefix to its namespace, or map it under a name")
|
|
209
|
+
names[iri] = spell(f"{prefix}_{own}")
|
|
210
|
+
clash = [n for n in set(names.values()) if list(names.values()).count(n) > 1]
|
|
211
|
+
if clash:
|
|
212
|
+
raise ViewNameClashError(f"two of the mapping's classes or predicates would both be the {what} {clash[0]!r}: "
|
|
213
|
+
f"map one of them under a name of its own")
|
|
214
|
+
return names
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# The classes every node is of (`inferred`).
|
|
218
|
+
_EVERY_NODE = frozenset({"http://www.w3.org/2000/01/rdf-schema#Resource", "http://www.w3.org/2002/07/owl#Thing"})
|
|
219
|
+
|
|
220
|
+
def _inferred_names(iris: Sequence[str], declared: Dict[str, Tuple[str, ...]], taken: Set[str],
|
|
221
|
+
prefixes: Dict[str, str], spell: Any = lambda name: name) -> Dict[str, Tuple[str, ...]]:
|
|
222
|
+
"""The names of the classes or predicates an ontology added (`saturate`): an IRI the mapping names keeps
|
|
223
|
+
those names (`declared`); another takes its local name as `spell` writes it, else its prefixed name where
|
|
224
|
+
that is taken (`taken`: the mapping's own names) or shared with another such IRI, else the IRI itself
|
|
225
|
+
(a Cypher name in backticks). It never refuses: an inferred name cannot make a query fail."""
|
|
226
|
+
out: Dict[str, Tuple[str, ...]] = {}
|
|
227
|
+
rest = [i for i in dict.fromkeys(iris) if i not in declared]
|
|
228
|
+
by_local: Dict[str, List[str]] = {}
|
|
229
|
+
for iri in rest:
|
|
230
|
+
by_local.setdefault(spell(local_name(iri)), []).append(iri)
|
|
231
|
+
for name, group in by_local.items():
|
|
232
|
+
for iri in group:
|
|
233
|
+
if len(group) == 1 and name not in taken:
|
|
234
|
+
out[iri] = (name,)
|
|
235
|
+
continue
|
|
236
|
+
own = local_name(iri)
|
|
237
|
+
prefix = next((p for p, ns in prefixes.items() if iri.startswith(ns) and iri[len(ns):] == own), None)
|
|
238
|
+
alt = spell(f"{prefix}_{own}") if prefix is not None else None
|
|
239
|
+
out[iri] = (alt,) if alt is not None and alt not in taken else (iri,)
|
|
240
|
+
out.update({i: declared[i] for i in iris if i in declared})
|
|
241
|
+
return out
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def build(maps: SourceMaps) -> LPGView:
|
|
245
|
+
attached = maps.__dict__.get("owned_store")
|
|
246
|
+
if attached is not None:
|
|
247
|
+
# The store's generated R2RML maps are SPARQL's; this view reads the store's generic maps.
|
|
248
|
+
own = attached[2]
|
|
249
|
+
declared = maps.__dict__.get("saturated_from")
|
|
250
|
+
maps = replace(maps, nodes=tuple(m for m in maps.nodes if m.id not in own),
|
|
251
|
+
edges=tuple(e for e in maps.edges if e.id not in own))
|
|
252
|
+
if declared is not None:
|
|
253
|
+
maps.__dict__["saturated_from"] = declared # the maps as declared, for inferred labels (`_build`)
|
|
254
|
+
view = _build(maps)
|
|
255
|
+
if attached is None:
|
|
256
|
+
return view
|
|
257
|
+
from prograph.schema.store_view import StoreView
|
|
258
|
+
store = StoreView(attached[0], attached[1])
|
|
259
|
+
for m in maps.nodes:
|
|
260
|
+
if m.label is not None and m.classes:
|
|
261
|
+
store.classes.setdefault(m.label, m.classes[0])
|
|
262
|
+
for key, pos in view.properties.get(m.id, {}).items():
|
|
263
|
+
for po in pos:
|
|
264
|
+
if po.predicate is not None: # a key column's property has no predicate (`with_key_properties`)
|
|
265
|
+
store.key_predicates.setdefault(key, []).append((m.label, po.predicate))
|
|
266
|
+
for name, edges in view.rel_types.items():
|
|
267
|
+
given = next((e.predicate for e in edges if e.predicate), None)
|
|
268
|
+
if given:
|
|
269
|
+
store.rel_predicates[name] = given
|
|
270
|
+
labels = dict(view.labels)
|
|
271
|
+
for label in store.labels():
|
|
272
|
+
labels.setdefault(label, ())
|
|
273
|
+
return replace(view, labels=labels, store=store)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _build(maps: SourceMaps) -> LPGView:
|
|
277
|
+
prefixes = dict(maps.settings.prefixes or ())
|
|
278
|
+
# Maps an ontology saturated (`saturate.saturate`) keep the maps as declared (`saturated_from`). What
|
|
279
|
+
# saturation added is named by `_inferred_names`: a class a map gains is an inferred label (MATCH
|
|
280
|
+
# (n:Employee) finds a Manager, labels(n) lists Employee), named by every label a mapping declares that
|
|
281
|
+
# class under; a predicate-object or edge map copied under a super-property gives that predicate's key or
|
|
282
|
+
# relationship type, the one the mapping declares for it where it does.
|
|
283
|
+
declared = maps.__dict__.get("saturated_from")
|
|
284
|
+
own = {m.id: set(m.classes) for m in declared.nodes} if declared is not None else {}
|
|
285
|
+
|
|
286
|
+
def own_classes(m: NodeMap) -> List[str]:
|
|
287
|
+
return [c for c in m.classes if c in own.get(m.id, set(m.classes))]
|
|
288
|
+
|
|
289
|
+
def inferred(m: NodeMap) -> List[str]:
|
|
290
|
+
# rdfs:Resource and owl:Thing (the RDFS core, OWL 2 RL's scm-cls) hold of every node: no label.
|
|
291
|
+
return [c for c in m.classes if c not in own.get(m.id, set(m.classes)) and c not in _EVERY_NODE]
|
|
292
|
+
|
|
293
|
+
declared_classes: Dict[str, Tuple[str, ...]] = {
|
|
294
|
+
c: (name,) for c, name in _named([c for m in maps.nodes if m.label is None for c in own_classes(m)],
|
|
295
|
+
prefixes, "label").items()}
|
|
296
|
+
for m in (declared.nodes if declared is not None else ()):
|
|
297
|
+
if m.label is not None:
|
|
298
|
+
for c in m.classes:
|
|
299
|
+
declared_classes[c] = tuple(dict.fromkeys(declared_classes.get(c, ()) + (m.label,)))
|
|
300
|
+
label_taken = {m.label for m in maps.nodes if m.label is not None} | \
|
|
301
|
+
{n for names in declared_classes.values() for n in names}
|
|
302
|
+
class_names = _inferred_names([c for m in maps.nodes for c in inferred(m)], declared_classes, label_taken,
|
|
303
|
+
prefixes)
|
|
304
|
+
labels: Dict[str, List[NodeMap]] = {}
|
|
305
|
+
node_labels: Dict[str, Tuple[str, ...]] = {}
|
|
306
|
+
unlabelled: List[NodeMap] = []
|
|
307
|
+
for m in maps.nodes:
|
|
308
|
+
names = ((m.label,) if m.label is not None else
|
|
309
|
+
tuple(n for c in own_classes(m) for n in declared_classes.get(c, ())))
|
|
310
|
+
names = tuple(dict.fromkeys(names + tuple(n for c in inferred(m) for n in class_names[c])))
|
|
311
|
+
node_labels[m.id] = names
|
|
312
|
+
if not names:
|
|
313
|
+
unlabelled.append(m)
|
|
314
|
+
for name in names:
|
|
315
|
+
labels.setdefault(name, []).append(m)
|
|
316
|
+
# Property keys: the maps' own as before; a copy (not among its map's declared predicate-object maps)
|
|
317
|
+
# by its predicate, and only where its map declares no such key itself; copies of one value give it once.
|
|
318
|
+
declared_pos = {m.id: m.predicate_objects for m in declared.nodes} if declared is not None else {}
|
|
319
|
+
|
|
320
|
+
def is_copy(m: NodeMap, po: PredicateObject) -> bool:
|
|
321
|
+
return m.id in declared_pos and po not in declared_pos[m.id]
|
|
322
|
+
|
|
323
|
+
literal = [(m, po) for m in maps.nodes for po in m.predicate_objects
|
|
324
|
+
if po.object.term_type == LITERAL and po.predicate is not None]
|
|
325
|
+
prop_names = _named([po.predicate for m, po in literal if po.property_name is None and not is_copy(m, po)],
|
|
326
|
+
prefixes, "property key")
|
|
327
|
+
key_of: Dict[str, Tuple[str, ...]] = {}
|
|
328
|
+
for m, po in literal:
|
|
329
|
+
if not is_copy(m, po):
|
|
330
|
+
key_of.setdefault(po.predicate, (po.property_name or prop_names[po.predicate],))
|
|
331
|
+
copy_keys = _inferred_names([po.predicate for m, po in literal if is_copy(m, po)], key_of,
|
|
332
|
+
{k for ks in key_of.values() for k in ks}, prefixes)
|
|
333
|
+
properties: Dict[str, Dict[str, Tuple[PredicateObject, ...]]] = {}
|
|
334
|
+
for m in maps.nodes:
|
|
335
|
+
held: Dict[str, Tuple[PredicateObject, ...]] = {}
|
|
336
|
+
copies: Dict[str, Tuple[PredicateObject, ...]] = {}
|
|
337
|
+
for po in m.predicate_objects:
|
|
338
|
+
if po.object.term_type != LITERAL or po.predicate is None:
|
|
339
|
+
continue
|
|
340
|
+
if is_copy(m, po):
|
|
341
|
+
key = copy_keys[po.predicate][0]
|
|
342
|
+
if not any(c.object == po.object for c in copies.get(key, ())):
|
|
343
|
+
copies[key] = copies.get(key, ()) + (po,)
|
|
344
|
+
continue
|
|
345
|
+
key = po.property_name or prop_names[po.predicate]
|
|
346
|
+
held[key] = held.get(key, ()) + (po,)
|
|
347
|
+
for key, pos in copies.items():
|
|
348
|
+
held.setdefault(key, pos)
|
|
349
|
+
held = with_key_properties(m, held)
|
|
350
|
+
if held:
|
|
351
|
+
properties[m.id] = held
|
|
352
|
+
# Relationship types: the maps' own as before; a copied edge map (not among the declared ones) by its
|
|
353
|
+
# predicate.
|
|
354
|
+
declared_edges = {e.id for e in declared.edges} if declared is not None else None
|
|
355
|
+
|
|
356
|
+
def edge_copy(e: EdgeMap) -> bool:
|
|
357
|
+
return declared_edges is not None and e.id not in declared_edges
|
|
358
|
+
|
|
359
|
+
rel_names = _named([e.predicate for e in maps.edges if e.rel_type is None and e.predicate is not None
|
|
360
|
+
and not edge_copy(e)], prefixes, "relationship type", spell=rel_type_from_local_name)
|
|
361
|
+
type_of: Dict[str, Tuple[str, ...]] = {}
|
|
362
|
+
for e in maps.edges:
|
|
363
|
+
if not edge_copy(e) and e.predicate is not None:
|
|
364
|
+
type_of.setdefault(e.predicate, (e.rel_type or rel_names[e.predicate],))
|
|
365
|
+
copy_types = _inferred_names([e.predicate for e in maps.edges if edge_copy(e)], type_of,
|
|
366
|
+
{t for ts in type_of.values() for t in ts} |
|
|
367
|
+
{e.rel_type for e in maps.edges if e.rel_type and not edge_copy(e)},
|
|
368
|
+
prefixes, spell=rel_type_from_local_name)
|
|
369
|
+
rel_types: Dict[str, List[EdgeMap]] = {}
|
|
370
|
+
for e in maps.edges:
|
|
371
|
+
if edge_copy(e):
|
|
372
|
+
name = copy_types[e.predicate][0]
|
|
373
|
+
else:
|
|
374
|
+
name = e.rel_type or (rel_names[e.predicate] if e.predicate else None)
|
|
375
|
+
if name is not None:
|
|
376
|
+
rel_types.setdefault(name, []).append(e)
|
|
377
|
+
return LPGView(maps, {k: tuple(v) for k, v in labels.items()}, tuple(unlabelled), node_labels, properties,
|
|
378
|
+
{k: tuple(v) for k, v in rel_types.items()}, nodes=tuple(maps.nodes), edges=tuple(maps.edges))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
@home("cypher-inverse-types", "A Cypher relationship type read through owl:inverseOf",
|
|
382
|
+
terms=("owl:inverseOf", "inverse property", "symmetric property", "inverse_subs", "reversed edge map",
|
|
383
|
+
"relationship type from the ontology"))
|
|
384
|
+
def with_inverses(view: LPGView, inverse_subs: Dict[str, Any]) -> LPGView:
|
|
385
|
+
"""`view` where a relationship type also reads its inverses' edges reversed: for each property p and each
|
|
386
|
+
q the ontology puts under p's inverse (`ql.QLTBox.inverse_subs`: owl:inverseOf, a symmetric property, a
|
|
387
|
+
sub-property of an inverse), every edge map of q with its start and end swapped, as p's. p's type is its
|
|
388
|
+
maps' type, else its local name spelled as a type (`rel_type_from_local_name`). A reversed map is a map of
|
|
389
|
+
its own (its id `<id>~<type>`), so its relationships are not the edges it reverses (its row under its own
|
|
390
|
+
id, `relationship_identity`), and it has no properties: a property of the stated edge is not one of the
|
|
391
|
+
inferred one. For a symmetric property (q is p) a self-loop row is its own reverse, read once (`mirrored`).
|
|
392
|
+
Only a named type reads them: a pattern of no type reads the mapped edges once (`edges` is unchanged)."""
|
|
393
|
+
if not inverse_subs:
|
|
394
|
+
return view
|
|
395
|
+
name_of: Dict[str, str] = {}
|
|
396
|
+
for name, edges in view.rel_types.items():
|
|
397
|
+
for e in edges:
|
|
398
|
+
if e.predicate is not None:
|
|
399
|
+
name_of.setdefault(e.predicate, name)
|
|
400
|
+
rel_types = {k: list(v) for k, v in view.rel_types.items()}
|
|
401
|
+
partners: Dict[str, Set[str]] = {}
|
|
402
|
+
mirrored: Set[str] = set()
|
|
403
|
+
|
|
404
|
+
def type_name(iri: str) -> str:
|
|
405
|
+
return name_of.get(iri) or rel_type_from_local_name(local_name(iri))
|
|
406
|
+
|
|
407
|
+
for p in sorted(inverse_subs):
|
|
408
|
+
name = type_name(p)
|
|
409
|
+
for q in inverse_subs[p]:
|
|
410
|
+
partners.setdefault(name, set()).add(type_name(q))
|
|
411
|
+
partners.setdefault(type_name(q), set()).add(name)
|
|
412
|
+
if name in rel_types and any(e.predicate not in (None, p) for e in rel_types[name]):
|
|
413
|
+
raise ViewNameClashError(f"the relationship type {name} names {p} (an inverse in the ontology) and "
|
|
414
|
+
f"another predicate: name one of them in the mapping")
|
|
415
|
+
for q in sorted(inverse_subs[p]):
|
|
416
|
+
for e in view.edges:
|
|
417
|
+
if e.predicate == q and e.join is None:
|
|
418
|
+
reversed_ = replace(e, id=f"{e.id}~{name}", predicate=p,
|
|
419
|
+
rel_type=name if e.rel_type is not None else None,
|
|
420
|
+
start=e.end, end=e.start, property_columns=(), row_key=None)
|
|
421
|
+
rel_types.setdefault(name, []).append(reversed_)
|
|
422
|
+
if q == p:
|
|
423
|
+
mirrored.add(reversed_.id)
|
|
424
|
+
return replace(view, rel_types={k: tuple(v) for k, v in rel_types.items()},
|
|
425
|
+
inverse_partners={k: tuple(sorted(v)) for k, v in partners.items()}, mirrored=frozenset(mirrored))
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
@home("cypher-typed-labels", "A Cypher label from rdfs:domain and rdfs:range",
|
|
429
|
+
terms=("rdfs:domain", "rdfs:range", "typed by a property", "derived label", "labels(n)", "typing edge"))
|
|
430
|
+
def with_typing(view: LPGView, typing: Sequence[Tuple[str, Any, bool]]) -> LPGView:
|
|
431
|
+
"""`view` where a class the ontology gives a property's starts (rdfs:domain) or ends (rdfs:range) is a label
|
|
432
|
+
of the nodes at that end of the property's edges, where such an edge exists: `typing` as SPARQL reads it
|
|
433
|
+
(`saturate.typing_properties`: (property, classes, True for its starts)), rdfs:Resource and owl:Thing aside
|
|
434
|
+
(every node's). The label is the one the view names the class by (a node map's label that has the class),
|
|
435
|
+
else the class's local name. The scan reads a typed label's nodes from the node map at the edge's end,
|
|
436
|
+
kept where an edge exists (`cypher_front._Translator.scan`)."""
|
|
437
|
+
if not typing:
|
|
438
|
+
return view
|
|
439
|
+
# A class's label: the label a node map declares it under (its own class, not one saturation added), else
|
|
440
|
+
# the label the view infers for it (its local name, on the maps saturation gave it), else its local name.
|
|
441
|
+
declared = view.maps.__dict__.get("saturated_from") or view.maps
|
|
442
|
+
own = {m.id: set(m.classes) for m in declared.nodes}
|
|
443
|
+
named: Dict[str, List[str]] = {} # every label that declares the class
|
|
444
|
+
for m in view.nodes:
|
|
445
|
+
if m.label is not None:
|
|
446
|
+
for c in m.classes:
|
|
447
|
+
if c in own.get(m.id, ()) and m.label not in named.get(c, []):
|
|
448
|
+
named.setdefault(c, []).append(m.label)
|
|
449
|
+
typed: Dict[str, List[Tuple[EdgeMap, bool]]] = {}
|
|
450
|
+
lost: Set[str] = set()
|
|
451
|
+
for prop, classes, as_subject in typing:
|
|
452
|
+
for cls in sorted(classes):
|
|
453
|
+
if cls in _EVERY_NODE:
|
|
454
|
+
continue
|
|
455
|
+
names = named.get(cls) or [local_name(cls)]
|
|
456
|
+
if cls not in named and any(cls not in m.classes for m in view.labels.get(names[0], ())):
|
|
457
|
+
raise ViewNameClashError(f"the label {names[0]} names {cls} (a class the ontology gives by "
|
|
458
|
+
"rdfs:domain or rdfs:range) and another class: name one of them in the mapping")
|
|
459
|
+
for e in view.edges:
|
|
460
|
+
if e.predicate == prop and e.join is None:
|
|
461
|
+
for name in names:
|
|
462
|
+
typed.setdefault(name, []).append((e, as_subject))
|
|
463
|
+
if (e.start if as_subject else e.end).map_id is None:
|
|
464
|
+
lost.add(prop)
|
|
465
|
+
labels = dict(view.labels)
|
|
466
|
+
for name in typed:
|
|
467
|
+
labels.setdefault(name, ())
|
|
468
|
+
return replace(view, labels=labels, typed={k: tuple(v) for k, v in typed.items()},
|
|
469
|
+
typing_lost=tuple(sorted(lost)))
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
@home("cypher-every-node-labels", "A Cypher label every node has: owl:Thing under profile ql",
|
|
473
|
+
terms=("owl:Thing", "every individual", "⊤ ⊑ C", "everything", "Thing label"))
|
|
474
|
+
def with_everything(view: LPGView, classes: Sequence[str]) -> LPGView:
|
|
475
|
+
"""`view` where owl:Thing's label (`Thing`) and the label of each class every individual is (`classes`:
|
|
476
|
+
`ql.QLTBox.everything`, ⊤ ⊑ C) hold of every node, as SPARQL types every individual under profile ql: a
|
|
477
|
+
pattern of such a label reads every node map, and a label test of one is true of any node. Such a label
|
|
478
|
+
says nothing of a node, so `labels(n)` does not list it (a node's labels are the mapping's labels and the
|
|
479
|
+
classes it has by its data). A label a mapping declares keeps its own nodes."""
|
|
480
|
+
from prograph.plan.ir.ql import THING
|
|
481
|
+
names: Set[str] = set()
|
|
482
|
+
for cls in [THING] + sorted(classes):
|
|
483
|
+
name = local_name(cls)
|
|
484
|
+
if name not in view.labels:
|
|
485
|
+
names.add(name)
|
|
486
|
+
return replace(view, everything=frozenset(names))
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def typed_end_maps(e: EdgeMap, as_subject: bool) -> Tuple[str, ...]:
|
|
490
|
+
"""The node maps that may hold the typed end of `e` (its start where `as_subject`): its own and its peers."""
|
|
491
|
+
end = e.start if as_subject else e.end
|
|
492
|
+
return ((end.map_id,) if end.map_id is not None else ()) + tuple(end.peers)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
@home("cypher-derived-labels", "A Cypher label, relationship and property from the stored OWL RL facts",
|
|
496
|
+
terms=("RL-derived type", "stored facts", "derived label", "profile rl", "materialized type",
|
|
497
|
+
"stored literal fact", "derived property", "hasValue property", "derived key"))
|
|
498
|
+
def with_derived(view: LPGView, stored: Any, superclasses: Dict[str, Any], held: Sequence[str] = (),
|
|
499
|
+
superproperties: Optional[Dict[str, Any]] = None) -> LPGView:
|
|
500
|
+
"""`view` where each of the ontology's named classes (the keys of `superclasses`, each class's superclasses
|
|
501
|
+
with itself) is also a label of the nodes a stored OWL RL fact types so or types by one of its subclasses
|
|
502
|
+
(`stored`: the store's derived maps, `dataset.maps_seen`, read only where SPARQL reads them; a subclass's
|
|
503
|
+
type gives the superclass as SPARQL's rewriting does): read as a typed label (`with_typing`), from the stored
|
|
504
|
+
rdf:type facts of those classes, their subject a node of any node map that holds it (a derived fact's
|
|
505
|
+
subject is an IRI the data gave). The label is the class's mapped label, else its local name; a class no
|
|
506
|
+
stored fact holds adds no row. `held`: the classes the stored rdf:type facts hold (read once per store
|
|
507
|
+
version, `cypher_front._view`): a label is made only for them and their superclasses, each read from its held
|
|
508
|
+
subclasses' facts, so the plan grows with the data's derived classes, not the ontology's. A stored fact whose
|
|
509
|
+
object is a literal is a property of its subject's node (`_with_stored_values`; `superproperties`, each property's
|
|
510
|
+
super-properties with itself, give it to a mapped key of a super-property too, as SPARQL's rewriting does)."""
|
|
511
|
+
from prograph.plan.ir.ql import RDF as _RDF
|
|
512
|
+
typing = [e for e in stored.edges if e.predicate == _RDF + "type" and e.join is None]
|
|
513
|
+
view = _with_stored_values(view, stored, superproperties or {})
|
|
514
|
+
# A stored fact of another predicate with an IRI object is a relationship of that predicate's type (its row
|
|
515
|
+
# its identity), in a pattern of the type and in one of no type: it is data the store holds.
|
|
516
|
+
name_of: Dict[str, str] = {}
|
|
517
|
+
for name, edges in view.rel_types.items():
|
|
518
|
+
for e in edges:
|
|
519
|
+
if e.predicate is not None:
|
|
520
|
+
name_of.setdefault(e.predicate, name)
|
|
521
|
+
# Each stored map under an id of its predicate's, not the generated mapping's (whose IRI holds the store's
|
|
522
|
+
# base IRI, a local path where it is a file): a relationship's id (`relationship_identity`) is its row under it.
|
|
523
|
+
facts = [replace(e, id=f"stored-fact:{e.predicate}") for e in stored.edges
|
|
524
|
+
if e.predicate not in (None, _RDF + "type") and e.join is None
|
|
525
|
+
and e.end.term is not None and e.end.term.term_type == "iri"]
|
|
526
|
+
if facts:
|
|
527
|
+
rel_types = {k: list(v) for k, v in view.rel_types.items()}
|
|
528
|
+
for e in facts:
|
|
529
|
+
rel_types.setdefault(name_of.get(e.predicate) or rel_type_from_local_name(local_name(e.predicate)),
|
|
530
|
+
[]).append(e)
|
|
531
|
+
view = replace(view, rel_types={k: tuple(v) for k, v in rel_types.items()}, edges=view.edges + tuple(facts))
|
|
532
|
+
if not typing:
|
|
533
|
+
return view
|
|
534
|
+
declared = view.maps.__dict__.get("saturated_from") or view.maps
|
|
535
|
+
own = {m.id: set(m.classes) for m in declared.nodes}
|
|
536
|
+
named: Dict[str, List[str]] = {}
|
|
537
|
+
for m in view.nodes:
|
|
538
|
+
if m.label is not None:
|
|
539
|
+
for c in m.classes:
|
|
540
|
+
if c in own.get(m.id, ()) and m.label not in named.get(c, []):
|
|
541
|
+
named.setdefault(c, []).append(m.label)
|
|
542
|
+
everyone = tuple(m.id for m in view.nodes)
|
|
543
|
+
typed = {k: list(v) for k, v in view.typed.items()}
|
|
544
|
+
derived: Set[str] = set()
|
|
545
|
+
wanted = set(held) | {c for h in held for c in superclasses.get(h, (h,))}
|
|
546
|
+
for cls in sorted(wanted - _EVERY_NODE):
|
|
547
|
+
names = named.get(cls) or [local_name(cls)]
|
|
548
|
+
if cls not in named and any(cls not in m.classes for m in view.labels.get(names[0], ())):
|
|
549
|
+
continue # the local name is another class's label: that class keeps it
|
|
550
|
+
subclasses = sorted(h for h in held if cls in superclasses.get(h, (h,)))
|
|
551
|
+
for e in typing:
|
|
552
|
+
column = e.end.term.column
|
|
553
|
+
if column is None:
|
|
554
|
+
continue
|
|
555
|
+
for sub in subclasses:
|
|
556
|
+
one = replace(e, id=f"stored-type:{sub}", source=replace(e.source, filter=((column, sub),)),
|
|
557
|
+
start=replace(e.start, peers=everyone))
|
|
558
|
+
for name in names:
|
|
559
|
+
typed.setdefault(name, []).append((one, True))
|
|
560
|
+
derived.add(name)
|
|
561
|
+
labels = dict(view.labels)
|
|
562
|
+
for name in derived:
|
|
563
|
+
labels.setdefault(name, ())
|
|
564
|
+
return replace(view, labels=labels, typed={k: tuple(v) for k, v in typed.items()},
|
|
565
|
+
derived_labels=frozenset(derived))
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _with_stored_values(view: LPGView, stored: Any, superproperties: Dict[str, Any]) -> LPGView:
|
|
569
|
+
"""`view` where each stored RL fact with a literal object (`stored`'s node maps: a hasValue, a sub-property or an
|
|
570
|
+
equivalent property onto a data property) is a property of the node its subject is (`cypher-derived-labels`). Its
|
|
571
|
+
key is the key a node map gives its predicate (the mapped value's key), else the predicate's local name; and the
|
|
572
|
+
key a node map gives each of its super-properties (`superproperties`), whose value it is too. A key's
|
|
573
|
+
facts are read in one datatype the store view reads (`store_view.fact_map`); a predicate of another datatype, of
|
|
574
|
+
two datatypes for one key, or whose local name a mapped key of another predicate holds, is left unread (warned,
|
|
575
|
+
`derived_values`)."""
|
|
576
|
+
from prograph.schema.store_view import readable_datatype
|
|
577
|
+
keys_of: Dict[str, Set[str]] = {}
|
|
578
|
+
mapped: Set[str] = set()
|
|
579
|
+
for m in view.nodes:
|
|
580
|
+
for key, pos in view.properties.get(m.id, {}).items():
|
|
581
|
+
mapped.add(key)
|
|
582
|
+
for po in pos:
|
|
583
|
+
if po.predicate is not None:
|
|
584
|
+
keys_of.setdefault(po.predicate, set()).add(key)
|
|
585
|
+
found: Dict[str, List[NodeMap]] = {}
|
|
586
|
+
lost: Set[str] = set()
|
|
587
|
+
for m in stored.nodes:
|
|
588
|
+
for po in m.predicate_objects:
|
|
589
|
+
if po.predicate is None or po.object.term_type != LITERAL:
|
|
590
|
+
continue
|
|
591
|
+
own = keys_of.get(po.predicate) or {local_name(po.predicate)}
|
|
592
|
+
if not keys_of.get(po.predicate) and next(iter(own)) in mapped or not readable_datatype(po.object.datatype):
|
|
593
|
+
lost.add(po.predicate)
|
|
594
|
+
continue
|
|
595
|
+
keys = set(own) | {k for sup in superproperties.get(po.predicate, ()) if sup != po.predicate
|
|
596
|
+
for k in keys_of.get(sup, ())}
|
|
597
|
+
for key in sorted(keys):
|
|
598
|
+
if m not in found.setdefault(key, []):
|
|
599
|
+
found[key].append(m)
|
|
600
|
+
for key, ms in list(found.items()):
|
|
601
|
+
if len({po.object.datatype for m in ms for po in m.predicate_objects}) > 1:
|
|
602
|
+
lost |= {po.predicate for m in ms for po in m.predicate_objects}
|
|
603
|
+
del found[key]
|
|
604
|
+
if not found and not lost:
|
|
605
|
+
return view
|
|
606
|
+
return replace(view, stored_values={k: tuple(v) for k, v in sorted(found.items())},
|
|
607
|
+
derived_keys=frozenset(set(found) - mapped), derived_values=tuple(sorted(lost)))
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def view_of(maps: SourceMaps) -> LPGView:
|
|
611
|
+
"""The view of `maps`, built the first time a Cypher query needs it and kept on the maps object
|
|
612
|
+
itself, so it goes with them (a mapping that changes compiles new maps, so a new view)."""
|
|
613
|
+
view = maps.__dict__.get("_lpg_view")
|
|
614
|
+
if view is None:
|
|
615
|
+
view = build(maps)
|
|
616
|
+
maps.__dict__["_lpg_view"] = view
|
|
617
|
+
return view
|