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.
Files changed (237) hide show
  1. prograph/__init__.py +36 -0
  2. prograph/__main__.py +5 -0
  3. prograph/_version.py +375 -0
  4. prograph/cli/__init__.py +1 -0
  5. prograph/cli/_iri_utils.py +124 -0
  6. prograph/cli/emit_genie_space.py +107 -0
  7. prograph/cli/generate_views.py +140 -0
  8. prograph/cli/main.py +420 -0
  9. prograph/cli/schema_inferrer.py +746 -0
  10. prograph/cli/ttl_loader.py +289 -0
  11. prograph/cli/upload_genie_space.py +84 -0
  12. prograph/config/__init__.py +27 -0
  13. prograph/config/yaml_config.py +848 -0
  14. prograph/demos/__init__.py +14 -0
  15. prograph/demos/turbofan/README.md +74 -0
  16. prograph/demos/turbofan/SCENARIO.md +209 -0
  17. prograph/demos/turbofan/__init__.py +75 -0
  18. prograph/demos/turbofan/create_tables.sql +206 -0
  19. prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
  20. prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
  21. prograph/demos/turbofan/demo.py +162 -0
  22. prograph/demos/turbofan/genie_qa_notebook.py +434 -0
  23. prograph/demos/turbofan/graph.yaml +1098 -0
  24. prograph/demos/turbofan/instance_graph_demo.py +32 -0
  25. prograph/demos/turbofan/load.py +223 -0
  26. prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
  27. prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
  28. prograph/demos/turbofan/payload-shapes.ttl +33 -0
  29. prograph/demos/turbofan/queries/example-queries.sparql +215 -0
  30. prograph/demos/turbofan/shapes.ttl +75 -0
  31. prograph/demos/turbofan/tables.py +106 -0
  32. prograph/demos/turbofan/turbofan_schema.py +393 -0
  33. prograph/demos/turbofan/validation_demo.py +153 -0
  34. prograph/describe.py +231 -0
  35. prograph/endpoint/__init__.py +12 -0
  36. prograph/endpoint/app.py +722 -0
  37. prograph/endpoint/cli.py +280 -0
  38. prograph/endpoint/credentials.py +240 -0
  39. prograph/endpoint/engines.py +418 -0
  40. prograph/endpoint/negotiate.py +101 -0
  41. prograph/endpoint/results.py +181 -0
  42. prograph/endpoint/service.py +31 -0
  43. prograph/engine.py +2718 -0
  44. prograph/execution.py +455 -0
  45. prograph/executors/__init__.py +6 -0
  46. prograph/executors/base.py +11 -0
  47. prograph/executors/databricks_sql_executor.py +51 -0
  48. prograph/executors/duckdb_executor.py +24 -0
  49. prograph/executors/mysql_executor.py +20 -0
  50. prograph/executors/oracle_executor.py +24 -0
  51. prograph/executors/pandas_executor.py +72 -0
  52. prograph/executors/postgresql_executor.py +35 -0
  53. prograph/executors/spark_executor.py +88 -0
  54. prograph/executors/sqlserver_executor.py +35 -0
  55. prograph/extras/__init__.py +1 -0
  56. prograph/extras/graphql/__init__.py +33 -0
  57. prograph/extras/graphql/execute.py +25 -0
  58. prograph/extras/graphql/schema.py +314 -0
  59. prograph/extras/instance_graph.py +559 -0
  60. prograph/genie/__init__.py +83 -0
  61. prograph/genie/databricks_uploader.py +306 -0
  62. prograph/genie/deploy.py +393 -0
  63. prograph/genie/formats.py +414 -0
  64. prograph/genie/instruction_generator.py +375 -0
  65. prograph/genie/sample_query_generator.py +256 -0
  66. prograph/genie/shacl_views.py +318 -0
  67. prograph/genie/space_emitter.py +329 -0
  68. prograph/genie/view_generator.py +628 -0
  69. prograph/genie/view_writer.py +172 -0
  70. prograph/graph/__init__.py +1 -0
  71. prograph/graph/ansi_session.py +348 -0
  72. prograph/graph/databricks_sql_graph.py +300 -0
  73. prograph/graph/drivers.py +143 -0
  74. prograph/graph/duckdb_graph.py +68 -0
  75. prograph/graph/mysql_graph.py +38 -0
  76. prograph/graph/oracle_graph.py +285 -0
  77. prograph/graph/pandas_graph.py +343 -0
  78. prograph/graph/postgresql_graph.py +644 -0
  79. prograph/graph/spark_graph.py +556 -0
  80. prograph/graph/sql_graph.py +83 -0
  81. prograph/graph/sqlserver_graph.py +72 -0
  82. prograph/hints.py +95 -0
  83. prograph/logging.py +550 -0
  84. prograph/mcp/__init__.py +29 -0
  85. prograph/mcp/__main__.py +180 -0
  86. prograph/mcp/bootstrap.py +98 -0
  87. prograph/mcp/server.py +601 -0
  88. prograph/mcp/sparql.py +397 -0
  89. prograph/mcp/tools.py +504 -0
  90. prograph/nlp/__init__.py +79 -0
  91. prograph/nlp/client.py +305 -0
  92. prograph/nlp/databricks_tools.py +369 -0
  93. prograph/nlp/graph_context.py +313 -0
  94. prograph/nlp/interface.py +652 -0
  95. prograph/nlp/prompts/__init__.py +19 -0
  96. prograph/nlp/prompts/examples.py +258 -0
  97. prograph/nlp/prompts/system.py +239 -0
  98. prograph/nlp/providers/__init__.py +14 -0
  99. prograph/nlp/providers/anthropic.py +274 -0
  100. prograph/nlp/providers/databricks.py +312 -0
  101. prograph/nlp/providers/openai.py +203 -0
  102. prograph/nlp/schema_context.py +78 -0
  103. prograph/ontology/__init__.py +53 -0
  104. prograph/ontology/alignment.py +542 -0
  105. prograph/ontology/hierarchy.py +310 -0
  106. prograph/ontology/imports.py +587 -0
  107. prograph/ontology/layer.py +991 -0
  108. prograph/ontology/skos.py +61 -0
  109. prograph/owl/__init__.py +27 -0
  110. prograph/owl/defined_classes.py +323 -0
  111. prograph/parameters.py +242 -0
  112. prograph/parser/__init__.py +1 -0
  113. prograph/parser/cypher/CypherLexer.py +836 -0
  114. prograph/parser/cypher/CypherListener.py +966 -0
  115. prograph/parser/cypher/CypherParser.py +10854 -0
  116. prograph/parser/cypher/CypherVisitor.py +543 -0
  117. prograph/parser/cypher/__init__.py +1 -0
  118. prograph/parser/sparql/SparqlLexer.py +801 -0
  119. prograph/parser/sparql/SparqlParser.py +10146 -0
  120. prograph/parser/sparql/SparqlParserListener.py +1056 -0
  121. prograph/parser/sparql/SparqlParserVisitor.py +593 -0
  122. prograph/parser/sparql/__init__.py +8 -0
  123. prograph/plan/__init__.py +3 -0
  124. prograph/plan/ir/__init__.py +1 -0
  125. prograph/plan/ir/casts.py +338 -0
  126. prograph/plan/ir/consistency.py +397 -0
  127. prograph/plan/ir/construct.py +90 -0
  128. prograph/plan/ir/cost.py +234 -0
  129. prograph/plan/ir/cypher_answer.py +1081 -0
  130. prograph/plan/ir/cypher_apoc.py +717 -0
  131. prograph/plan/ir/cypher_apoc_convert.py +505 -0
  132. prograph/plan/ir/cypher_apoc_date.py +845 -0
  133. prograph/plan/ir/cypher_apoc_map.py +496 -0
  134. prograph/plan/ir/cypher_apoc_meta.py +384 -0
  135. prograph/plan/ir/cypher_apoc_path.py +597 -0
  136. prograph/plan/ir/cypher_apoc_procedures.py +163 -0
  137. prograph/plan/ir/cypher_apoc_text.py +785 -0
  138. prograph/plan/ir/cypher_front.py +5474 -0
  139. prograph/plan/ir/cypher_functions.py +565 -0
  140. prograph/plan/ir/cypher_lists.py +935 -0
  141. prograph/plan/ir/cypher_maps.py +370 -0
  142. prograph/plan/ir/cypher_mixed.py +604 -0
  143. prograph/plan/ir/cypher_ontology.py +226 -0
  144. prograph/plan/ir/cypher_procedures.py +191 -0
  145. prograph/plan/ir/cypher_runtime_errors.py +107 -0
  146. prograph/plan/ir/cypher_temporal.py +1357 -0
  147. prograph/plan/ir/cypher_temporal_arith.py +339 -0
  148. prograph/plan/ir/cypher_values.py +546 -0
  149. prograph/plan/ir/cypher_write.py +612 -0
  150. prograph/plan/ir/dataset.py +643 -0
  151. prograph/plan/ir/dates.py +102 -0
  152. prograph/plan/ir/entry.py +992 -0
  153. prograph/plan/ir/expr.py +260 -0
  154. prograph/plan/ir/facts.py +1171 -0
  155. prograph/plan/ir/fresh.py +291 -0
  156. prograph/plan/ir/freshness.py +625 -0
  157. prograph/plan/ir/identity.py +797 -0
  158. prograph/plan/ir/java_datetime.py +265 -0
  159. prograph/plan/ir/java_regex.py +391 -0
  160. prograph/plan/ir/join_order.py +39 -0
  161. prograph/plan/ir/key_checks.py +433 -0
  162. prograph/plan/ir/keys.py +454 -0
  163. prograph/plan/ir/lower.py +5323 -0
  164. prograph/plan/ir/ops.py +619 -0
  165. prograph/plan/ir/owl_rl.py +1119 -0
  166. prograph/plan/ir/owl_rl_rules.py +725 -0
  167. prograph/plan/ir/profiles.py +694 -0
  168. prograph/plan/ir/ql.py +987 -0
  169. prograph/plan/ir/rdfs.py +342 -0
  170. prograph/plan/ir/rewrite.py +1782 -0
  171. prograph/plan/ir/saturate.py +339 -0
  172. prograph/plan/ir/semantics.py +103 -0
  173. prograph/plan/ir/slot.py +509 -0
  174. prograph/plan/ir/sparql_front.py +3418 -0
  175. prograph/plan/ir/strings.py +534 -0
  176. prograph/plan/ir/term_functions.py +274 -0
  177. prograph/plan/ir/terms.py +84 -0
  178. prograph/plan/ir/xpath_regex.py +264 -0
  179. prograph/plan/run_record.py +65 -0
  180. prograph/plan/sql/__init__.py +21 -0
  181. prograph/plan/sql/dialect.py +3726 -0
  182. prograph/plan/sql/mysql_serializer.py +103 -0
  183. prograph/plan/sql/names.py +65 -0
  184. prograph/plan/sql/oracle_serializer.py +306 -0
  185. prograph/plan/sql/pg_serializer.py +501 -0
  186. prograph/plan/sql/rel_algebra.py +781 -0
  187. prograph/plan/sql/sql_serializer.py +1419 -0
  188. prograph/plan/sql/sqlserver_serializer.py +603 -0
  189. prograph/provenance.py +222 -0
  190. prograph/r2rml/__init__.py +48 -0
  191. prograph/r2rml/catalog.py +259 -0
  192. prograph/r2rml/compile.py +372 -0
  193. prograph/r2rml/direct.py +140 -0
  194. prograph/r2rml/export.py +495 -0
  195. prograph/r2rml/model.py +180 -0
  196. prograph/r2rml/parser.py +546 -0
  197. prograph/r2rml/schema.py +120 -0
  198. prograph/read_only.py +122 -0
  199. prograph/results.py +157 -0
  200. prograph/rules/__init__.py +168 -0
  201. prograph/rules/__main__.py +32 -0
  202. prograph/schema/__init__.py +60 -0
  203. prograph/schema/change_set.py +50 -0
  204. prograph/schema/collations.py +198 -0
  205. prograph/schema/compile_schema.py +388 -0
  206. prograph/schema/context.py +845 -0
  207. prograph/schema/examples.py +234 -0
  208. prograph/schema/iri.py +817 -0
  209. prograph/schema/literals.py +94 -0
  210. prograph/schema/lpg_view.py +617 -0
  211. prograph/schema/mapping.py +1803 -0
  212. prograph/schema/maps_schema.py +40 -0
  213. prograph/schema/naming.py +77 -0
  214. prograph/schema/query_sources.py +59 -0
  215. prograph/schema/rows.py +215 -0
  216. prograph/schema/source_map.py +1103 -0
  217. prograph/schema/store_view.py +459 -0
  218. prograph/schema/types.py +569 -0
  219. prograph/schema/xsd.py +569 -0
  220. prograph/shacl/__init__.py +30 -0
  221. prograph/shacl/dqv.py +58 -0
  222. prograph/shacl/generate.py +255 -0
  223. prograph/shacl/report.py +138 -0
  224. prograph/shacl/validator.py +164 -0
  225. prograph/store.py +1737 -0
  226. prograph/utils/__init__.py +6 -0
  227. prograph/utils/exceptions.py +308 -0
  228. prograph/utils/helpers.py +126 -0
  229. prograph/warnings.py +46 -0
  230. prograph/writes.py +369 -0
  231. prograph-1.3.3.dist-info/METADATA +281 -0
  232. prograph-1.3.3.dist-info/RECORD +237 -0
  233. prograph-1.3.3.dist-info/WHEEL +5 -0
  234. prograph-1.3.3.dist-info/entry_points.txt +3 -0
  235. prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
  236. prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
  237. prograph-1.3.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,628 @@
1
+ """Generate SQL views from a ProGraph schema (+ optional ontology, shapes, metrics).
2
+
3
+ W1 scope: schema-label views (one per NodeMapping) and subclass-closure
4
+ views (union of subclass tables when the ontology declares
5
+ ``rdfs:subClassOf`` relationships between mapped labels).
6
+
7
+ W2 scope (this commit): OWL-defined class views, one per restriction
8
+ pattern the RL+ reasoner recognizes:
9
+
10
+ - **Data-range** (e.g. ``HighWearComponent ≡ Component ⊓ (wearIndex ≥ 0.7)``)
11
+ → ``SELECT id FROM base_table WHERE prop_col >= 0.7``.
12
+ - **Min-cardinality** (e.g. ``CriticalPathComponent ≡ Component ⊓ (≥ 2 propagatesTo)``)
13
+ → ``SELECT src AS id FROM rel_table GROUP BY src HAVING COUNT(*) >= 2``.
14
+ - **Inverse-someValuesFrom** (e.g. ``MonitoredComponent ≡ Component ⊓ ∃ inverse(monitors) . Sensor``)
15
+ → ``SELECT DISTINCT dst AS id FROM rel_table WHERE src IN (SELECT id FROM sensor_table)``.
16
+
17
+ These views project the entailed instances **at query time** without
18
+ requiring the engine to have run ``materialize_entailments``. That's
19
+ the Category 3 (generated views) sweet spot from the operational-
20
+ artifacts principle: no new storage, always fresh, consistent by
21
+ construction.
22
+
23
+ W2 deliberately defers SHACL violation views. They require either an
24
+ operational store of past validation runs (Category 2 telemetry,
25
+ deferred until the operational-artifacts work) or a per-shape SQL
26
+ translation pass that's a bigger lift. Both land in a later week.
27
+
28
+ The generator is a pure function: given the same inputs, it returns
29
+ the same :class:`ViewDefinition` list. No side effects. Writing the
30
+ views to a SQL warehouse is :mod:`prograph.genie.view_writer`'s job
31
+ (W3); this module just builds the definitions.
32
+
33
+ Dialect: SQL produced here uses the existing
34
+ :class:`prograph.plan.sql.dialect.DialectConfig` system for
35
+ identifier quoting and limit syntax. Default dialect is the Databricks
36
+ SQL / Spark backtick form; pass another :class:`DialectConfig` for
37
+ Postgres / SQL Server / DuckDB output.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import re
43
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional
44
+
45
+ from prograph.genie.formats import ViewDefinition, ViewSource
46
+
47
+ if TYPE_CHECKING:
48
+ from prograph.ontology.layer import OntologyLayer
49
+ from prograph.plan.sql.dialect import DialectConfig
50
+ from prograph.schema import GraphSchema, NodeMapping
51
+
52
+
53
+ # ─── Public API ──────────────────────────────────────────────────────
54
+
55
+
56
+ def generate_views(
57
+ schema: "GraphSchema",
58
+ ontology: Optional["OntologyLayer"] = None,
59
+ dialect: Optional["DialectConfig"] = None,
60
+ include_labels: Optional[List[str]] = None,
61
+ exclude_labels: Optional[List[str]] = None,
62
+ ) -> List[ViewDefinition]:
63
+ """Generate :class:`ViewDefinition` instances for the schema.
64
+
65
+ Args:
66
+ schema: The :class:`GraphSchema` to derive views from.
67
+ ontology: Optional :class:`OntologyLayer`. When provided,
68
+ subclass-closure views are emitted for every parent class
69
+ whose subclasses are mapped in the schema. When ``None``,
70
+ only schema-label views are produced.
71
+ dialect: SQL dialect for identifier quoting. Defaults to the
72
+ Spark / Databricks SQL backtick form (matches the
73
+ ``databricks_sql`` backend's expectations).
74
+ include_labels: If set, restrict generation to NodeMappings
75
+ with these labels. Useful when only a few of the schema's
76
+ classes should be exposed to Genie.
77
+ exclude_labels: If set, drop NodeMappings with these labels.
78
+ Applied after ``include_labels``.
79
+
80
+ Returns:
81
+ A list of :class:`ViewDefinition` instances. Order: schema-
82
+ label views first (in schema declaration order), then
83
+ subclass-closure views (sorted by parent label name).
84
+
85
+ The returned definitions are pure data. To actually create the
86
+ views in a warehouse, pass them to
87
+ :func:`prograph.genie.view_writer.write_views` (W3).
88
+ """
89
+ from prograph.r2rml.schema import require_property_graph
90
+ require_property_graph(schema, "Genie views")
91
+ dialect = dialect or _default_dialect()
92
+ mappings = _filter_mappings(
93
+ schema.node_mappings,
94
+ include_labels=include_labels,
95
+ exclude_labels=exclude_labels,
96
+ )
97
+
98
+ views: List[ViewDefinition] = []
99
+
100
+ # ── Schema-label views (one per kept mapping) ──
101
+ for mapping in mappings:
102
+ if mapping.label is None:
103
+ continue # an unlabelled node mapping: no label to name a view by
104
+ views.append(_build_label_view(mapping, dialect))
105
+
106
+ # ── Subclass-closure views (one per parent class with mapped subclasses) ──
107
+ if ontology is not None:
108
+ closures = _find_subclass_closures(mappings, ontology)
109
+ for parent_label in sorted(closures):
110
+ child_mappings = closures[parent_label]
111
+ views.append(_build_closure_view(parent_label, child_mappings, dialect))
112
+
113
+ # ── OWL-defined class views (W2: RL+ restriction patterns) ──
114
+ if ontology is not None:
115
+ for view in _build_defined_class_views(schema, ontology, mappings, dialect):
116
+ views.append(view)
117
+
118
+ return views
119
+
120
+
121
+ # ─── Helpers ─────────────────────────────────────────────────────────
122
+
123
+
124
+ def _default_dialect() -> "DialectConfig":
125
+ """Lazy-import the existing Spark dialect as the default."""
126
+ from prograph.plan.sql.dialect import SPARK_DIALECT
127
+ return SPARK_DIALECT
128
+
129
+
130
+ def _filter_mappings(
131
+ mappings: List["NodeMapping"],
132
+ include_labels: Optional[List[str]],
133
+ exclude_labels: Optional[List[str]],
134
+ ) -> List["NodeMapping"]:
135
+ """Apply include/exclude filters; preserve schema order."""
136
+ if include_labels is not None:
137
+ include_set = set(include_labels)
138
+ mappings = [m for m in mappings if m.label in include_set]
139
+ if exclude_labels:
140
+ exclude_set = set(exclude_labels)
141
+ mappings = [m for m in mappings if m.label not in exclude_set]
142
+ return mappings
143
+
144
+
145
+ def _label_to_view_name(label: str) -> str:
146
+ """Convert a PascalCase or camelCase label to snake_case view name.
147
+
148
+ ``HighWearComponent`` → ``high_wear_component``.
149
+ ``Sensor`` → ``sensor``.
150
+ ``CarOwner`` → ``car_owner``.
151
+
152
+ Already-snake-cased labels pass through unchanged.
153
+ """
154
+ return _snake_case(label)
155
+
156
+
157
+ def _snake_case(name: str) -> str:
158
+ """Convert PascalCase or camelCase to snake_case. Idempotent.
159
+
160
+ ``wearIndex`` → ``wear_index``. ``HTTPSConnection`` → ``https_connection``.
161
+ """
162
+ s = re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", name)
163
+ s = re.sub(r"(?<=[A-Z])([A-Z][a-z])", r"_\1", s)
164
+ return s.lower()
165
+
166
+
167
+ def _quote(identifier: str, dialect: "DialectConfig") -> str:
168
+ """A name, quoted for the dialect; a dotted one (``catalog.schema.table``)
169
+ part by part, which Databricks needs (one quoted name with dots is
170
+ TABLE_OR_VIEW_NOT_FOUND)."""
171
+ from prograph.plan.sql.dialect import get_dialect_instance
172
+ return get_dialect_instance(dialect.name).quote_qualified(identifier)
173
+
174
+
175
+ def _format_literal(value: Any, dialect: "DialectConfig") -> str:
176
+ """A value as the dialect's SQL literal (Dialect.literal: Spark escapes
177
+ a quote with a backslash, SQL Server has no TRUE)."""
178
+ from prograph.plan.sql.dialect import get_dialect_instance
179
+ return get_dialect_instance(dialect.name).literal(value)
180
+
181
+
182
+ def _owned_clauses(mapping: Any, dialect: "DialectConfig") -> List[str]:
183
+ """A mapping's `filter_predicate` as SQL tests (`IS NULL` for a None):
184
+ `prograph.writes.column_condition` writes each."""
185
+ from prograph.schema.rows import column_condition
186
+ return [column_condition(_quote(col, dialect), val, lambda v: _format_literal(v, dialect))
187
+ for col, val in mapping.filter_predicate.items()]
188
+
189
+
190
+ def _build_label_view(mapping: "NodeMapping", dialect: "DialectConfig") -> ViewDefinition:
191
+ """Build a SCHEMA_LABEL view for one NodeMapping.
192
+
193
+ Output shape:
194
+
195
+ SELECT
196
+ `id_col` AS `id`,
197
+ `prop_col_1` AS `prop_name_1`,
198
+ ...
199
+ FROM `source_table`
200
+ [WHERE filter_col_1 = filter_val_1 AND ...]
201
+ """
202
+ select_terms: List[str] = []
203
+
204
+ # ID columns first. Use 'id' as the alias when single-column;
205
+ # otherwise keep the original column names (composite key).
206
+ if len(mapping.id_columns) == 1:
207
+ select_terms.append(
208
+ f"{_quote(mapping.id_columns[0], dialect)} AS {_quote('id', dialect)}"
209
+ )
210
+ else:
211
+ for col in mapping.id_columns:
212
+ select_terms.append(_quote(col, dialect))
213
+
214
+ # Property projections, aliased to the property names from the mapping.
215
+ for prop_name, source_col in mapping.property_columns.items():
216
+ if prop_name == source_col:
217
+ select_terms.append(_quote(source_col, dialect))
218
+ else:
219
+ select_terms.append(
220
+ f"{_quote(source_col, dialect)} AS {_quote(prop_name, dialect)}"
221
+ )
222
+
223
+ sql = "SELECT " + ", ".join(select_terms)
224
+ sql += f"\nFROM {_quote(mapping.source_table, dialect)}"
225
+
226
+ # filter_predicate (shared-table schemas).
227
+ if mapping.filter_predicate:
228
+ sql += "\nWHERE " + " AND ".join(_owned_clauses(mapping, dialect))
229
+
230
+ # Track projected columns in order for the ViewDefinition.
231
+ projected_cols: List[str] = []
232
+ if len(mapping.id_columns) == 1:
233
+ projected_cols.append("id")
234
+ else:
235
+ projected_cols.extend(mapping.id_columns)
236
+ projected_cols.extend(mapping.property_columns.keys())
237
+
238
+ return ViewDefinition(
239
+ name=_label_to_view_name(mapping.label),
240
+ sql=sql,
241
+ source=ViewSource.SCHEMA_LABEL,
242
+ source_label=mapping.label,
243
+ description=f"Projection of {mapping.label} entity rows.",
244
+ columns=projected_cols,
245
+ )
246
+
247
+
248
+ def _find_subclass_closures(
249
+ mappings: List["NodeMapping"],
250
+ ontology: "OntologyLayer",
251
+ ) -> Dict[str, List["NodeMapping"]]:
252
+ """Find parent classes whose subclasses are mapped in the schema.
253
+
254
+ For each NodeMapping in ``mappings``, ask the ontology for that
255
+ label's superclasses; group mappings by parent. A closure view is
256
+ emitted for each parent that has **two or more** mapped subclasses
257
+ (single-subclass closures are redundant with the label view).
258
+
259
+ Returns a dict ``{parent_label -> [child_mappings...]}`` where each
260
+ parent has >= 2 child mappings. Excludes the parent itself from
261
+ the children list when the parent is also directly mapped.
262
+ """
263
+ mapped_labels = {m.label for m in mappings if m.label is not None}
264
+ mapping_by_label = {m.label: m for m in mappings}
265
+ parent_to_children: Dict[str, List["NodeMapping"]] = {}
266
+
267
+ for mapping in mappings:
268
+ try:
269
+ supers = ontology.get_superclasses(mapping.label, include_self=False)
270
+ except Exception:
271
+ # Ontology doesn't recognize this label, no closure to build.
272
+ continue
273
+ for parent in supers:
274
+ if parent == mapping.label:
275
+ continue
276
+ parent_to_children.setdefault(parent, []).append(mapping)
277
+
278
+ # Filter to parents with 2+ mapped subclasses; keep input order stable.
279
+ return {
280
+ parent: children
281
+ for parent, children in parent_to_children.items()
282
+ if len(children) >= 2 and parent not in mapped_labels
283
+ # If the parent is itself directly mapped, its label view already
284
+ # exists. We still emit a closure view in W2 when the parent has
285
+ # children that contribute additional rows; for W1 we keep things
286
+ # simple and only emit closures for purely-abstract parents.
287
+ }
288
+
289
+
290
+ def _build_closure_view(
291
+ parent_label: str,
292
+ child_mappings: List["NodeMapping"],
293
+ dialect: "DialectConfig",
294
+ ) -> ViewDefinition:
295
+ """Build a SUBCLASS_CLOSURE view that unions child subclass rows.
296
+
297
+ Output shape:
298
+
299
+ SELECT `id_col` AS `id`, 'ChildLabel1' AS `__subclass_label` FROM `t1`
300
+ [WHERE ...]
301
+ UNION ALL
302
+ SELECT `id_col` AS `id`, 'ChildLabel2' AS `__subclass_label` FROM `t2`
303
+ [WHERE ...]
304
+ ...
305
+
306
+ W1 keeps the closure minimal: just `id` + `__subclass_label`. Joining
307
+ back to a child's label view recovers full properties. W2 may extend
308
+ to include the intersection of property columns across children.
309
+ """
310
+ branches: List[str] = []
311
+ for child in sorted(child_mappings, key=lambda m: m.label):
312
+ # Composite-key children are skipped for closure inclusion in W1:
313
+ # the id_alias trick relies on a single-column id. Compose-key
314
+ # support lands in W2 or W3.
315
+ if len(child.id_columns) != 1:
316
+ continue
317
+ select_clause = (
318
+ f"SELECT {_quote(child.id_columns[0], dialect)} AS {_quote('id', dialect)}, "
319
+ f"{_format_literal(child.label, dialect)} AS {_quote('__subclass_label', dialect)}\n"
320
+ f"FROM {_quote(child.source_table, dialect)}"
321
+ )
322
+ if child.filter_predicate:
323
+ select_clause += "\nWHERE " + " AND ".join(_owned_clauses(child, dialect))
324
+ branches.append(select_clause)
325
+
326
+ sql = "\nUNION ALL\n".join(branches)
327
+
328
+ return ViewDefinition(
329
+ name=_label_to_view_name(parent_label) + "_closure",
330
+ sql=sql,
331
+ source=ViewSource.SUBCLASS_CLOSURE,
332
+ source_label=parent_label,
333
+ description=(
334
+ f"Union of all {parent_label} subclasses "
335
+ f"({', '.join(sorted(m.label for m in child_mappings if m.label is not None))})."
336
+ ),
337
+ columns=["id", "__subclass_label"],
338
+ )
339
+
340
+
341
+ # ─── W2: OWL-defined class views (RL+ restrictions) ─────────────────
342
+
343
+
344
+ def _camel_to_upper_snake(camel: str) -> str:
345
+ """Convert a camelCase OWL property name to UPPER_SNAKE_CASE rel type.
346
+
347
+ ``propagatesTo`` → ``PROPAGATES_TO``. The ontology speaks camelCase; ProGraph schema
348
+ relationship types are conventionally UPPER_SNAKE_CASE.
349
+ """
350
+ out = re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", camel)
351
+ out = re.sub(r"(?<=[A-Z])([A-Z][a-z])", r"_\1", out)
352
+ return out.upper()
353
+
354
+
355
+ def _find_node_mapping(
356
+ mappings: List["NodeMapping"], label: str
357
+ ) -> Optional["NodeMapping"]:
358
+ """First (and conventionally only) NodeMapping for a label."""
359
+ for m in mappings:
360
+ if m.label == label:
361
+ return m
362
+ return None
363
+
364
+
365
+ def _build_defined_class_views(
366
+ schema: "GraphSchema",
367
+ ontology: "OntologyLayer",
368
+ mappings: List["NodeMapping"],
369
+ dialect: "DialectConfig",
370
+ ) -> List[ViewDefinition]:
371
+ """Build views for every supported RL+ defined class in the ontology.
372
+
373
+ Walks ``parse_defined_classes(ontology)`` and emits one view per
374
+ defined class whose base class is mapped in the schema. Classes
375
+ whose base class isn't mapped, or whose constraint references a
376
+ property/relationship/class we can't resolve, get skipped.
377
+ """
378
+ from prograph.owl.defined_classes import (
379
+ DataRangeConstraint,
380
+ InversePropertyConstraint,
381
+ MinCardinalityConstraint,
382
+ parse_defined_classes,
383
+ )
384
+
385
+ views: List[ViewDefinition] = []
386
+ defined = parse_defined_classes(ontology)
387
+
388
+ for dc in defined:
389
+ base_mapping = _find_node_mapping(mappings, dc.base_class)
390
+ if base_mapping is None:
391
+ # Base class isn't in the (filtered) schema, skip.
392
+ continue
393
+
394
+ view: Optional[ViewDefinition] = None
395
+ if isinstance(dc.constraint, DataRangeConstraint):
396
+ view = _build_data_range_view(dc, base_mapping, dialect)
397
+ elif isinstance(dc.constraint, MinCardinalityConstraint):
398
+ view = _build_min_cardinality_view(
399
+ dc, base_mapping, schema, dialect
400
+ )
401
+ elif isinstance(dc.constraint, InversePropertyConstraint):
402
+ view = _build_inverse_property_view(
403
+ dc, base_mapping, schema, mappings, dialect
404
+ )
405
+ # else: unknown constraint shape, silently skip.
406
+
407
+ if view is not None:
408
+ views.append(view)
409
+
410
+ return views
411
+
412
+
413
+ def _build_data_range_view(
414
+ dc: Any,
415
+ base_mapping: "NodeMapping",
416
+ dialect: "DialectConfig",
417
+ ) -> Optional[ViewDefinition]:
418
+ """Translate a DataRangeConstraint into a SELECT … WHERE view.
419
+
420
+ Example:
421
+ ``HighWearComponent ≡ Component ⊓ (wearIndex ≥ 0.7)``
422
+ → ``SELECT id, wear_index AS wearIndex FROM components
423
+ WHERE wear_index >= 0.7``
424
+ """
425
+ c = dc.constraint
426
+ prop = c.property_name
427
+
428
+ # Resolve the property to a source column via the base mapping. Try
429
+ # exact match first; fall back to the snake_case form so schemas that
430
+ # use ``{wear_index: wear_index}`` (the convention you'd reach for
431
+ # when the column name matches the RDF property local name) resolve
432
+ # against ``wearIndex`` from the ontology.
433
+ source_col = base_mapping.property_columns.get(prop)
434
+ if source_col is None:
435
+ source_col = base_mapping.property_columns.get(_snake_case(prop))
436
+ if source_col is None:
437
+ return None # Property isn't materialized on the base table, skip.
438
+
439
+ select_terms: List[str] = []
440
+ if len(base_mapping.id_columns) == 1:
441
+ select_terms.append(
442
+ f"{_quote(base_mapping.id_columns[0], dialect)} AS {_quote('id', dialect)}"
443
+ )
444
+ else:
445
+ select_terms.extend(_quote(c, dialect) for c in base_mapping.id_columns)
446
+ if prop == source_col:
447
+ select_terms.append(_quote(source_col, dialect))
448
+ else:
449
+ select_terms.append(
450
+ f"{_quote(source_col, dialect)} AS {_quote(prop, dialect)}"
451
+ )
452
+
453
+ sql = "SELECT " + ", ".join(select_terms)
454
+ sql += f"\nFROM {_quote(base_mapping.source_table, dialect)}"
455
+
456
+ where_clauses: List[str] = []
457
+ # Honor filter_predicate on the base mapping (shared-table schemas).
458
+ if base_mapping.filter_predicate:
459
+ where_clauses.extend(_owned_clauses(base_mapping, dialect))
460
+ if c.min_inclusive is not None:
461
+ where_clauses.append(f"{_quote(source_col, dialect)} >= {_format_literal(c.min_inclusive, dialect)}")
462
+ if c.max_inclusive is not None:
463
+ where_clauses.append(f"{_quote(source_col, dialect)} <= {_format_literal(c.max_inclusive, dialect)}")
464
+ if c.min_exclusive is not None:
465
+ where_clauses.append(f"{_quote(source_col, dialect)} > {_format_literal(c.min_exclusive, dialect)}")
466
+ if c.max_exclusive is not None:
467
+ where_clauses.append(f"{_quote(source_col, dialect)} < {_format_literal(c.max_exclusive, dialect)}")
468
+
469
+ if not where_clauses:
470
+ return None # No usable bound on the constraint, skip.
471
+
472
+ sql += "\nWHERE " + " AND ".join(where_clauses)
473
+
474
+ cols = (
475
+ ["id"] if len(base_mapping.id_columns) == 1 else list(base_mapping.id_columns)
476
+ )
477
+ cols.append(prop)
478
+
479
+ return ViewDefinition(
480
+ name=_label_to_view_name(dc.name),
481
+ sql=sql,
482
+ source=ViewSource.OWL_DEFINED_CLASS,
483
+ source_label=dc.name,
484
+ description=(
485
+ f"OWL-entailed {dc.name}: a {dc.base_class} with "
486
+ f"{prop} in the constraint's data range."
487
+ ),
488
+ columns=cols,
489
+ )
490
+
491
+
492
+ def _build_min_cardinality_view(
493
+ dc: Any,
494
+ base_mapping: "NodeMapping",
495
+ schema: "GraphSchema",
496
+ dialect: "DialectConfig",
497
+ ) -> Optional[ViewDefinition]:
498
+ """Translate a MinCardinalityConstraint into a GROUP BY … HAVING view.
499
+
500
+ Example:
501
+ ``CriticalPathComponent ≡ Component ⊓ (≥ 2 propagatesTo)``
502
+ → ``SELECT src AS id FROM propagates_to
503
+ GROUP BY src HAVING COUNT(*) >= 2``
504
+ """
505
+ c = dc.constraint
506
+ rel_type = _camel_to_upper_snake(c.property_name)
507
+
508
+ # Find the rel mapping; pick one matching the base class as start.
509
+ rel_mappings = schema.get_relationship_mappings(rel_type)
510
+ if not rel_mappings:
511
+ return None
512
+ rel = _pick_rel_for_base(rel_mappings, dc.base_class)
513
+ if rel is None:
514
+ return None
515
+
516
+ start_col = (
517
+ rel.start_id_columns[0] if len(rel.start_id_columns) == 1 else None
518
+ )
519
+ if start_col is None:
520
+ return None # Composite-key rel start, skip in W2.
521
+
522
+ sql = (
523
+ f"SELECT {_quote(start_col, dialect)} AS {_quote('id', dialect)}\n"
524
+ f"FROM {_quote(rel.source_table, dialect)}\n"
525
+ f"GROUP BY {_quote(start_col, dialect)}\n"
526
+ f"HAVING COUNT(*) >= {c.min_count}"
527
+ )
528
+
529
+ return ViewDefinition(
530
+ name=_label_to_view_name(dc.name),
531
+ sql=sql,
532
+ source=ViewSource.OWL_DEFINED_CLASS,
533
+ source_label=dc.name,
534
+ description=(
535
+ f"OWL-entailed {dc.name}: a {dc.base_class} with "
536
+ f"at least {c.min_count} outgoing {c.property_name} edges."
537
+ ),
538
+ columns=["id"],
539
+ )
540
+
541
+
542
+ def _build_inverse_property_view(
543
+ dc: Any,
544
+ base_mapping: "NodeMapping",
545
+ schema: "GraphSchema",
546
+ mappings: List["NodeMapping"],
547
+ dialect: "DialectConfig",
548
+ ) -> Optional[ViewDefinition]:
549
+ """Translate an InversePropertyConstraint into a SELECT … WHERE EXISTS view.
550
+
551
+ Example:
552
+ ``MonitoredComponent ≡ Component ⊓ ∃ inverse(monitors) . Sensor``
553
+ → ``SELECT DISTINCT dst AS id FROM monitors
554
+ WHERE src IN (SELECT id FROM sensors)``
555
+ """
556
+ c = dc.constraint
557
+ rel_type = _camel_to_upper_snake(c.property_name)
558
+ rel_mappings = schema.get_relationship_mappings(rel_type)
559
+ if not rel_mappings:
560
+ return None
561
+
562
+ # The constraint is "inverse of :p with someValuesFrom :TargetClass",
563
+ # so the relationship goes Sensor -[:MONITORS]-> Component. Pick the
564
+ # rel mapping whose end label is dc.base_class.
565
+ rel = next(
566
+ (r for r in rel_mappings if r.end_node_label == dc.base_class), None
567
+ )
568
+ if rel is None:
569
+ return None
570
+
571
+ target_mapping = _find_node_mapping(mappings, c.target_class)
572
+ if target_mapping is None:
573
+ return None
574
+ if len(target_mapping.id_columns) != 1:
575
+ return None # Composite-key target, skip in W2.
576
+
577
+ end_col = rel.end_id_columns[0] if len(rel.end_id_columns) == 1 else None
578
+ start_col = (
579
+ rel.start_id_columns[0] if len(rel.start_id_columns) == 1 else None
580
+ )
581
+ if not (end_col and start_col):
582
+ return None
583
+
584
+ target_table = target_mapping.source_table
585
+ target_id_col = target_mapping.id_columns[0]
586
+
587
+ inner_select = (
588
+ f"SELECT {_quote(target_id_col, dialect)} "
589
+ f"FROM {_quote(target_table, dialect)}"
590
+ )
591
+ if target_mapping.filter_predicate:
592
+ inner_select += " WHERE " + " AND ".join(_owned_clauses(target_mapping, dialect))
593
+
594
+ sql = (
595
+ f"SELECT DISTINCT {_quote(end_col, dialect)} AS {_quote('id', dialect)}\n"
596
+ f"FROM {_quote(rel.source_table, dialect)}\n"
597
+ f"WHERE {_quote(start_col, dialect)} IN (\n {inner_select}\n)"
598
+ )
599
+
600
+ return ViewDefinition(
601
+ name=_label_to_view_name(dc.name),
602
+ sql=sql,
603
+ source=ViewSource.OWL_DEFINED_CLASS,
604
+ source_label=dc.name,
605
+ description=(
606
+ f"OWL-entailed {dc.name}: a {dc.base_class} with at least one "
607
+ f"incoming {c.property_name} edge from a {c.target_class}."
608
+ ),
609
+ columns=["id"],
610
+ )
611
+
612
+
613
+ def _pick_rel_for_base(
614
+ rel_mappings: List[Any], base_class: str
615
+ ) -> Optional[Any]:
616
+ """Choose the rel mapping that starts from the given base class.
617
+
618
+ For min-cardinality: the relationship goes base → other. If
619
+ several mappings exist (rare), pick the first whose start label
620
+ matches. Returns ``None`` if no match.
621
+ """
622
+ for r in rel_mappings:
623
+ if r.start_node_label == base_class:
624
+ return r
625
+ return None
626
+
627
+
628
+ __all__ = ["generate_views"]