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,6 @@
1
+ """Utilities module for shared helper functions."""
2
+
3
+ from prograph.utils.helpers import clean_string
4
+ from prograph.utils.exceptions import CypherSyntaxError, CypherExecutionError
5
+
6
+ __all__ = ["clean_string", "CypherSyntaxError", "CypherExecutionError"]
@@ -0,0 +1,308 @@
1
+ """Custom exceptions for ProGraph."""
2
+
3
+
4
+ class CypherError(Exception):
5
+ """Base exception for all ProGraph Cypher errors."""
6
+ pass
7
+
8
+
9
+ class CypherSyntaxError(CypherError):
10
+ """Raised when there is a syntax error in the Cypher query."""
11
+
12
+ def __init__(self, message: str, line: int = None, column: int = None):
13
+ self.line = line
14
+ self.column = column
15
+ location = ""
16
+ if line is not None:
17
+ location = f" at line {line}"
18
+ if column is not None:
19
+ location += f", column {column}"
20
+ super().__init__(f"Syntax error{location}: {message}")
21
+
22
+
23
+ class CypherExecutionError(CypherError):
24
+ """Raised when there is an error during query execution."""
25
+ pass
26
+
27
+
28
+ class ReadOnlyGraphError(CypherExecutionError):
29
+ """A write ProGraph does not make. ProGraph is read-only
30
+ over the tables it maps: every write through a query or an API to a
31
+ user's data raises this, with `prograph.read_only`'s message, before
32
+ anything is read or written. The one class: the pandas, Spark and
33
+ indexed graphs raise it too."""
34
+
35
+ def __init__(self, message: str = "Cannot modify a read-only virtual graph"):
36
+ super().__init__(message)
37
+
38
+
39
+ class StoreReadOnlyError(ReadOnlyGraphError):
40
+ """A write step into the owned store on a connection the database keeps read-only (a read-only
41
+ transaction or session, `default_transaction_read_only`): refused before the step writes anything, by name, never the
42
+ database's raw error."""
43
+
44
+
45
+ class StoreWriteConflictError(CypherExecutionError):
46
+ """A write step into the owned store on Delta (Spark, Databricks) lost its race to other writers more
47
+ often than the redo bound allows (each lost race reads the store again and redoes the whole step). Nothing
48
+ of the step is visible; call the query again (the same step key writes it once)."""
49
+
50
+
51
+ class StoreStepCommittedError(CypherExecutionError):
52
+ """A write step into the owned store on Delta committed (its marker landed), and a statement after the
53
+ commit failed (reading the store again, so the answer could not be read). The write is done and visible:
54
+ this is not "nothing happened". `step` is its key; calling the query again with that key writes nothing and
55
+ answers with the answer the step kept (`Store.kept_answer`), the very one the first run gave. The original error is the `__cause__`."""
56
+
57
+ def __init__(self, message: str, step: str):
58
+ super().__init__(message)
59
+ self.step = step
60
+
61
+
62
+ class StoreAnswerNotKeptError(CypherExecutionError):
63
+ """A write step into the owned store was applied before (its step key is in the store) and the answer it gave
64
+ was not kept: it is bigger than the store keeps (`Store.ANSWER_CAP`), or the step was applied before the
65
+ store kept answers. Nothing is written again and no answer is read again from the store as it is now (a SET
66
+ that reads its own property would answer a state no run had). `step` is the key."""
67
+
68
+ def __init__(self, message: str, step: str):
69
+ super().__init__(message)
70
+ self.step = step
71
+
72
+
73
+ class StoreStepKeyReusedError(CypherExecutionError):
74
+ """A write step key the owned store applied before came with another query (or the same query with other
75
+ parameters), or the step recorded no query digest (applied before the store did, so the query cannot be
76
+ checked). Nothing is written and no kept answer is returned under the new query. `step` is the key."""
77
+
78
+ def __init__(self, message: str, step: str):
79
+ super().__init__(message)
80
+ self.step = step
81
+
82
+
83
+ class UnknownNameError(CypherExecutionError, ValueError):
84
+ """A label, relationship type or property the schema does not declare. Raised by `GraphSchema.require_name`, the one home of the
85
+ check; a ValueError too, which callers of require_name have always
86
+ caught. Carries: the name, its kind ('label',
87
+ 'relationship_type' or 'property'), the labels or relationship types it
88
+ was looked up on (empty where it was every one), the nearest declared
89
+ names, and the labels or types that do declare a property the lookup did
90
+ not reach (a write through one label of a property another label on the
91
+ same rows declares)."""
92
+
93
+ def __init__(self, name: str, kind: str, nearest=(), labels=(), declared_by=()):
94
+ self.name = name
95
+ self.kind = kind
96
+ self.labels = list(labels)
97
+ self.nearest = list(nearest)
98
+ self.declared_by = list(declared_by)
99
+ where = f"on {', '.join(self.labels)}" if self.labels else "by the schema"
100
+ text = f"{kind.replace('_', ' ').capitalize()} {name!r} is not declared {where}"
101
+ if self.declared_by:
102
+ text += f"; {', '.join(self.declared_by)} declare{'s' if len(self.declared_by) == 1 else ''} it"
103
+ if self.nearest:
104
+ text += f"; did you mean {', '.join(repr(n) for n in self.nearest)}?"
105
+ super().__init__(text)
106
+
107
+
108
+ class DuplicateNodeKeyError(CypherExecutionError):
109
+ """A node mapping's stated key that the data breaks: two rows hold one
110
+ key value, so the key names no single node (Cypher's on_duplicate refuse).
111
+ Raised for a Cypher statement that reads the mapping, before anything is
112
+ read, unless the key is trusted. Carries the mapping's label, its table,
113
+ its key columns and one key value two rows share."""
114
+
115
+ def __init__(self, label: str, table: str, key, example):
116
+ self.label = label
117
+ self.table = table
118
+ self.key = list(key)
119
+ self.example = tuple(example)
120
+ key_text = ", ".join(self.key)
121
+ if len(self.key) == 1:
122
+ value_text = f"{self.key[0]} = {self.example[0]!r}"
123
+ else:
124
+ value_text = "(" + key_text + ") = (" + ", ".join(repr(v) for v in self.example) + ")"
125
+ super().__init__(
126
+ f"The node mapping {label!r} (table {table!r}) states the key ({key_text}), and the "
127
+ f"data breaks it: more than one row has {value_text}. A node's key is its identity "
128
+ f"in Cypher, so these rows name no single node. Map one row per key (filter a "
129
+ f"history table on its current rows, or state a composite key), or trust the key "
130
+ f"with on_duplicate: trust on the mapping or trust_keys=True on the engine; over a "
131
+ f"broken key a trusted answer is undefined.")
132
+
133
+
134
+ class SQLGenerationError(Exception):
135
+ """Raised when a query cannot be converted to SQL.
136
+
137
+ The tree serializer returned None: the query pattern is not supported
138
+ by the SQL generation pipeline. In 'auto' mode this triggers Python
139
+ fallback; in 'sql' mode it raises.
140
+ """
141
+
142
+ def __init__(self, message: str, reason: str = None, query: str = None):
143
+ self.reason = reason
144
+ self.query = query
145
+ super().__init__(message)
146
+
147
+
148
+ class NulCharacterError(SQLGenerationError, ValueError):
149
+ """A string holding a NUL character (U+0000) in a query or a value written: no database ProGraph targets
150
+ holds one in text (PostgreSQL's text cannot), so it has no SQL literal. A ValueError as well, as before."""
151
+
152
+ def __init__(self, message: str = "a string with a NUL character (U+0000) has no SQL literal: no database "
153
+ "text holds one; remove the character or write it another way"):
154
+ super().__init__(message, reason="nul_character")
155
+
156
+
157
+ class SQLRuntimeError(Exception):
158
+ """Raised when generated SQL fails at execution time on the warehouse.
159
+
160
+ The SQL was generated successfully but the database rejected it
161
+ (e.g., UNRESOLVED_COLUMN, RECURSION_ROW_LIMIT_EXCEEDED, type errors).
162
+ This is distinct from SQLGenerationError, the tree serializer succeeded
163
+ but the SQL it produced is invalid or hits engine limits.
164
+ """
165
+
166
+ def __init__(self, message: str, reason: str = None, sql: str = None):
167
+ self.reason = reason
168
+ self.sql = sql
169
+ super().__init__(message)
170
+
171
+
172
+ class MissingDriverError(ImportError):
173
+ """Raised when a SQL backend's Arrow driver is not installed.
174
+
175
+ A SQL backend's result is the Arrow its driver returns, so
176
+ without the driver the backend refuses instead of reading rows another
177
+ way. ``package`` is what to install.
178
+ """
179
+
180
+ def __init__(self, message: str, package: str = None, backend: str = None):
181
+ self.package = package
182
+ self.backend = backend
183
+ super().__init__(message)
184
+
185
+
186
+ class BackendConnectionError(Exception):
187
+ """Raised when ProGraph could not open a SQL backend's connection from
188
+ the URL or connection string it was given. The message carries the
189
+ driver's reason with the credentials removed."""
190
+
191
+ def __init__(self, message: str, backend: str = None):
192
+ self.backend = backend
193
+ super().__init__(message)
194
+
195
+
196
+ class StoreConnectionError(ValueError):
197
+ """An owned store (``store=``) is on another connection than the one the engine reads its tables on: its
198
+ statements and the mapped tables would sit in two databases, and a query reads both. Raised when the
199
+ engine is built; the message says which connection to pass."""
200
+
201
+
202
+ class OWLProfileError(Exception):
203
+ """An engine's ontology has axioms the engine's OWL profile does not answer: outside the W3C
204
+ profile, or inside it and not answered yet (``on_unsupported="error"``, the default). Raised when
205
+ the engine is built; the message names each axiom, what it is and why, and ``report`` is the
206
+ ``OntologyReport`` (``engine.ontology_report()``'s)."""
207
+
208
+ def __init__(self, message: str, report=None):
209
+ self.report = report
210
+ super().__init__(message)
211
+
212
+
213
+ class InconsistentOntologyError(Exception):
214
+ """The engine's ontology and the data it reads are inconsistent under its OWL profile (an individual of two
215
+ disjoint classes, an irreflexive property's loop, two values of a functional property that are not one
216
+ value ...), under ``inconsistency="error"`` (the default): raised where it is found, when the engine is built
217
+ or when a materialization runs. The message names each rule or check that matched, its axiom, how many facts
218
+ and a few of them; ``report`` is the ``ConsistencyReport`` (``engine.consistency_report()``'s under
219
+ ``inconsistency="report"``)."""
220
+
221
+ def __init__(self, message: str, report=None):
222
+ self.report = report
223
+ super().__init__(message)
224
+
225
+
226
+ class QueryTooExpensiveError(Exception):
227
+ """Raised before any SQL runs when a query has a costly shape the engine's ``refuse_costly`` or
228
+ the query's ``refuse`` hint names (`prograph.plan.ir.cost`). ``shape`` is the shape:
229
+ ``unpinned-join``, ``unseeded-closure`` or ``whole-graph``; the message says how to narrow it."""
230
+
231
+ def __init__(self, shape: str, message: str):
232
+ self.shape = shape
233
+ super().__init__(f"Query refused (refuse_costly): {message}")
234
+
235
+
236
+ class AskLanguageError(ValueError):
237
+ """Natural-language ``ask`` was given a language it does not write: it writes SPARQL (the default) and
238
+ Cypher."""
239
+
240
+ def __init__(self, language: str):
241
+ super().__init__(f"ask writes SPARQL or Cypher, not {language!r}: ask with language='sparql' or "
242
+ "language='cypher'.")
243
+
244
+
245
+ class CypherWriteRefusedError(CypherExecutionError, NotImplementedError):
246
+ """A Cypher write ProGraph does not make yet, or does not make here (one-plan 2.10): an updating clause
247
+ other than CREATE, a read after an updating clause, a write with no owned store or on an engine other
248
+ than DuckDB. Raised before anything is written; the message says what to do instead."""
249
+
250
+ def __init__(self, message: str):
251
+ super().__init__(f"one-plan: {message}")
252
+
253
+
254
+ class GraphQLNotInReleaseError(NotImplementedError):
255
+ """GraphQL queries (`prograph.extras.graphql.execute_graphql`) are not supported in ProGraph 1.x. Its
256
+ generated schema (`graphql_schema`) works."""
257
+
258
+ def __init__(self):
259
+ super().__init__("GraphQL queries are not supported in ProGraph 1.x. graphql_schema(engine) still gives "
260
+ "the schema; query the data in SPARQL or Cypher.")
261
+
262
+
263
+ class MaterializationBudgetExceeded(Exception):
264
+ """OWL RL materialization (``materialize_entailments(max_rounds=...)``) ran its rounds at most and the
265
+ last one still derived facts: nothing was written (the step is rolled back whole)."""
266
+
267
+ def __init__(self, max_rounds: int):
268
+ self.max_rounds = max_rounds
269
+ super().__init__(
270
+ f"OWL RL materialization did not reach its fixpoint in {max_rounds} rounds (each round runs every "
271
+ f"rule once; the last still derived facts): nothing was written. Call "
272
+ f"materialize_entailments(max_rounds=...) with more rounds")
273
+
274
+
275
+ class StoredFactsNotCurrentError(RuntimeError):
276
+ """Stored OWL RL facts (``profile="rl"``) that cannot be proven current for a query: a source that only a
277
+ whole-table checksum proves unchanged (no declared version column, not a Delta table), or a source changed
278
+ while the owned store cannot be written (read-only), so no refresh runs. The message names the ways out:
279
+ ``version_columns=``, ``materialize_entailments()``, ``freshness="last_run"``."""
280
+
281
+
282
+ class ConsistencyVerdictNotCurrentError(StoredFactsNotCurrentError):
283
+ """Under ``profile="ql"`` and ``freshness="strict"``: a table the consistency checks read that nothing proves
284
+ unchanged since they ran (no declared version column, not a Delta table, too big for a checksum per query).
285
+ The message names the table, its checks and the ways to make it provable: ``version_columns=``, a Delta
286
+ table, a smaller table; or the default freshness, which keeps the build's verdict and warns."""
287
+
288
+
289
+ # What a database says when it stops a statement at its statement timeout: Databricks SQL's
290
+ # STATEMENT_TIMEOUT ("Statement has timed out after 10 seconds."), PostgreSQL's statement_timeout
291
+ # ("canceling statement due to statement timeout").
292
+ _STATEMENT_TIMEOUT_TEXT = ("statement has timed out", "due to statement timeout")
293
+
294
+
295
+ def is_statement_timeout(error: BaseException) -> bool:
296
+ """Whether `error` is the database stopping a statement at its timeout (`prograph serve
297
+ --timeout` sets Databricks SQL's STATEMENT_TIMEOUT): a server answers it as a timeout (MCP
298
+ `reason` "timeout", HTTP 503 at /sparql), not as an execution error."""
299
+ text = str(error).lower()
300
+ return any(marker in text for marker in _STATEMENT_TIMEOUT_TEXT)
301
+
302
+
303
+ class SourceNotReadableError(ValueError):
304
+ """A mapped source the engine could not read: its table missing or not readable, a file source on a SQL
305
+ backend, or a column the mapping names that the table lacks. Raised at the first query that reads it (a
306
+ file source on a SQL backend, when the engine starts), naming the source, the table and the database's
307
+ own message, so the cause is not met later as a query that cannot be built."""
308
+
@@ -0,0 +1,126 @@
1
+ """Helper functions for cypher-engine."""
2
+
3
+ import re
4
+ from typing import Optional
5
+
6
+
7
+ def clean_string(s: Optional[str]) -> Optional[str]:
8
+ """Remove quotes from string literals and process escape sequences.
9
+
10
+ Args:
11
+ s: String that may have quotes
12
+
13
+ Returns:
14
+ String with outer quotes removed and escape sequences processed
15
+ """
16
+ if not s:
17
+ return s
18
+
19
+ s = s.strip()
20
+
21
+ # Remove matching double or single quotes
22
+ if (s.startswith('"') and s.endswith('"')) or \
23
+ (s.startswith("'") and s.endswith("'")):
24
+ s = s[1:-1]
25
+
26
+ # Process escape sequences
27
+ s = _process_escapes(s)
28
+
29
+ return s
30
+
31
+
32
+ def _process_escapes(s: str) -> str:
33
+ """Process Cypher escape sequences in a string.
34
+
35
+ Handles:
36
+ - \\uXXXX - Unicode escape (4 hex digits)
37
+ - \\UXXXXXXXX - Unicode escape (8 hex digits)
38
+ - \\n, \\t, \\r, \\b, \\f - standard escapes
39
+ - \\\\, \\', \\" - literal backslash, quote escapes
40
+ """
41
+ result = []
42
+ i = 0
43
+ while i < len(s):
44
+ if s[i] == '\\' and i + 1 < len(s):
45
+ next_char = s[i + 1]
46
+ if next_char == 'u' and i + 5 < len(s):
47
+ # \uXXXX - 4 hex digits
48
+ hex_part = s[i + 2:i + 6]
49
+ if all(c in '0123456789abcdefABCDEF' for c in hex_part):
50
+ result.append(chr(int(hex_part, 16)))
51
+ i += 6
52
+ continue
53
+ elif next_char == 'U' and i + 9 < len(s):
54
+ # \UXXXXXXXX - 8 hex digits
55
+ hex_part = s[i + 2:i + 10]
56
+ if all(c in '0123456789abcdefABCDEF' for c in hex_part):
57
+ result.append(chr(int(hex_part, 16)))
58
+ i += 10
59
+ continue
60
+ elif next_char == 'n':
61
+ result.append('\n')
62
+ i += 2
63
+ continue
64
+ elif next_char == 't':
65
+ result.append('\t')
66
+ i += 2
67
+ continue
68
+ elif next_char == 'r':
69
+ result.append('\r')
70
+ i += 2
71
+ continue
72
+ elif next_char == 'b':
73
+ result.append('\b')
74
+ i += 2
75
+ continue
76
+ elif next_char == 'f':
77
+ result.append('\f')
78
+ i += 2
79
+ continue
80
+ elif next_char == '\\':
81
+ result.append('\\')
82
+ i += 2
83
+ continue
84
+ elif next_char == "'":
85
+ result.append("'")
86
+ i += 2
87
+ continue
88
+ elif next_char == '"':
89
+ result.append('"')
90
+ i += 2
91
+ continue
92
+ result.append(s[i])
93
+ i += 1
94
+ return ''.join(result)
95
+
96
+
97
+ class ByIdentity:
98
+ """A memo keyed by the identity of an object (a subquery's plan, an
99
+ expression), which keeps each key it holds alive with its value.
100
+
101
+ ``id()`` is unique only among objects that exist at the same time: keyed
102
+ by ``id(plan)`` alone, a plan built and dropped during a statement's
103
+ build left its id free for a later plan, which then read the first
104
+ plan's entry, its CTE and columns.
105
+ Holding the key, an entry's id cannot be reused while the memo lives,
106
+ and a lookup is a hit only for that same object."""
107
+
108
+ __slots__ = ('_entries',)
109
+
110
+ def __init__(self):
111
+ self._entries = {}
112
+
113
+ def get(self, key, tag=None, default=None):
114
+ entry = self._entries.get((tag, id(key)))
115
+ if entry is None or entry[0] is not key:
116
+ return default
117
+ return entry[1]
118
+
119
+ def put(self, key, value, tag=None) -> None:
120
+ self._entries[(tag, id(key))] = (key, value)
121
+
122
+ def __len__(self) -> int:
123
+ return len(self._entries)
124
+
125
+ def clear(self) -> None:
126
+ self._entries.clear()
prograph/warnings.py ADDED
@@ -0,0 +1,46 @@
1
+ """The warnings ProGraph gives in documented use, importable from one place, to filter or catch:
2
+
3
+ import warnings
4
+ from prograph.warnings import AssertedKeyWarning
5
+ warnings.filterwarnings("ignore", category=AssertedKeyWarning)
6
+
7
+ Each name is the class itself (defined where it is raised), so a filter on either path is the same filter.
8
+ """
9
+
10
+ from prograph.rules import module_home
11
+
12
+ module_home("public-warnings", "The warnings a user can filter, under one public import path",
13
+ terms=("warning", "filterwarnings", "AssertedKeyWarning", "public import", "prograph.warnings"))
14
+
15
+ from prograph.engine import UnknownNumericDigitsWarning # noqa: E402
16
+ from prograph.graph.ansi_session import DecimalPrecisionLossWarning # noqa: E402
17
+ from prograph.plan.ir.cost import ProGraphCostWarning # noqa: E402
18
+ from prograph.plan.ir.consistency import ConsistencyVerdictWarning # noqa: E402
19
+ from prograph.plan.ir.cypher_ontology import CypherOntologyWarning # noqa: E402
20
+ from prograph.plan.ir.facts import DecimalRangeWarning # noqa: E402
21
+ from prograph.plan.ir.keys import AssertedKeyWarning, RepeatedKeyWarning, RepeatingKeyWarning # noqa: E402
22
+ from prograph.plan.ir.sparql_front import ( # noqa: E402
23
+ DatatypeOverrideWarning, OutsideGroupWarning, PatternNeverMatchesWarning)
24
+ from prograph.r2rml.export import ForeignKeyTypeWarning # noqa: E402
25
+ from prograph.r2rml.schema import PrefixClashWarning # noqa: E402
26
+ from prograph.schema.iri import IdentityMeetWarning # noqa: E402
27
+ from prograph.schema.mapping import OnDuplicateIgnoredWarning # noqa: E402
28
+
29
+ __all__ = [
30
+ "AssertedKeyWarning", # a `keys: trusted` key: a promise ProGraph does not check
31
+ "RepeatedKeyWarning", # an asserted key found repeated
32
+ "RepeatingKeyWarning", # an asserted key the statistics say may repeat
33
+ "CypherOntologyWarning", # an ontology axiom Cypher does not apply (it applies the class and property hierarchies only)
34
+ "ProGraphCostWarning", # a query shape expensive by nature
35
+ "DecimalRangeWarning", # a decimal operation declared wider than 38 digits
36
+ "DecimalPrecisionLossWarning", # a session setting that loses decimal precision
37
+ "UnknownNumericDigitsWarning", # PostgreSQL NUMERIC columns of no known precision and scale
38
+ "DatatypeOverrideWarning", # a mapping's datatype override
39
+ "OutsideGroupWarning", # a variable read outside its GROUP BY
40
+ "PatternNeverMatchesWarning", # a pattern no mapping can match
41
+ "IdentityMeetWarning", # two mappings' subjects that may give one IRI
42
+ "OnDuplicateIgnoredWarning", # an on_duplicate setting with no effect
43
+ "PrefixClashWarning", # an included R2RML document binding a prefix differently
44
+ "ForeignKeyTypeWarning", # an exported foreign key whose column and key differ in type
45
+ "ConsistencyVerdictWarning", # a ql consistency verdict kept from the build for a table nothing proves current
46
+ ]