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,338 @@
1
+ """Casts (SPARQL 1.1 17.5): xsd:string, xsd:integer, xsd:decimal, xsd:float, xsd:double,
2
+ xsd:boolean and xsd:dateTime, XPath's constructor functions over 17.5's table, and xsd:date (XPath's
3
+ too: Jena and Oxigraph read it) from a string, a dateTime or a date (m2-functions.md 28).
4
+
5
+ - From a string (a simple literal or xsd:string; a language-tagged literal only to xsd:string,
6
+ 17.5 lists no other): its text must be in the target's lexical space, as written (Jena and
7
+ Oxigraph trim nothing); a boolean's `true`, `false`, `1`, `0`.
8
+ - To xsd:string (F&O 3.1 19.1.2.2): an IRI's text, a literal's canonical text; an integral decimal
9
+ with no point (`7`); a double in [1e-6, 1e6) as a decimal (`1.5`, `-2.7`), zero `0` or `-0`, else
10
+ its canonical text (`1.0E20`, `INF`, `NaN`); a boolean `true` or `false`.
11
+ - To xsd:integer: a number truncated toward zero, NaN and INF an error, past 64 bits an error (D7);
12
+ a boolean 1 or 0.
13
+ - To xsd:decimal: a double its shortest digits' decimal, past 20 whole digits an error (D7, the
14
+ DECIMAL(38, 18) SQL holds), NaN and INF an error; an integer as DECIMAL(38, 0).
15
+ - To xsd:float or xsd:double: a double (a float is held as a double, the `xsd-casts-sql` rule; its text
16
+ is a double's shortest digits, a float's canonical text for 7 or fewer significant digits).
17
+ - To xsd:boolean: a number's `!= 0`, NaN false (F&O 19.1.1).
18
+ - To xsd:dateTime: a dateTime as it is, a text with no zone read; to xsd:date a dateTime's date.
19
+ A column's text with a zone is not built: the row raises, never a short answer; a constant's
20
+ zone is kept.
21
+ Every result is in D3's canonical form; a cast the table forbids, or of an ill-typed value, is an
22
+ error (unbound). A constant is cast at planning (`fold`).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+
29
+ import datetime as _dt
30
+ import math
31
+ from decimal import Decimal
32
+ from typing import Mapping, Optional
33
+
34
+ from prograph.plan.ir import expr as E
35
+ from prograph.plan.ir.facts import NotBuilt, const_slot, expr_slot
36
+ from prograph.plan.ir.slot import LOCAL, NOTHING, UNKNOWN, Bound, Slot, literal_slot
37
+ from prograph.plan.ir.terms import BlankTerm, IRITerm, LiteralTerm
38
+ from prograph.rules import module_home
39
+ from prograph.schema import xsd
40
+ from prograph.schema.source_map import BLANK, IRI, LITERAL
41
+
42
+ module_home("xsd-casts-sql", "SPARQL's casts (17.5) over the plan's cells, in SQL",
43
+ terms=("xsd:integer(", "xsd:string(", "cast", "17.5", "constructor function"))
44
+
45
+ DATE = xsd.XSD + "date"
46
+ TARGETS = frozenset({xsd.STRING, xsd.INTEGER, xsd.DECIMAL, xsd.FLOAT, xsd.DOUBLE, xsd.BOOLEAN,
47
+ xsd.DATETIME, DATE})
48
+ _INTEGERS = frozenset(xsd.INTEGER_DATATYPES)
49
+ _NUMBERS = _INTEGERS | {xsd.DECIMAL, xsd.FLOAT, xsd.DOUBLE}
50
+ # 17.5's table (rows: the source; xsd:date as XPath's constructor has it).
51
+ _ALLOWED = {
52
+ "string": TARGETS,
53
+ "number": {xsd.STRING, xsd.INTEGER, xsd.DECIMAL, xsd.FLOAT, xsd.DOUBLE, xsd.BOOLEAN},
54
+ "boolean": {xsd.STRING, xsd.INTEGER, xsd.DECIMAL, xsd.FLOAT, xsd.DOUBLE, xsd.BOOLEAN},
55
+ "dateTime": {xsd.STRING, xsd.DATETIME, DATE},
56
+ "date": {xsd.STRING, DATE, xsd.DATETIME}, # a date's midnight (F&O 3.1 19.1.4)
57
+ }
58
+ _DATETIME_FORM = r"^-?[0-9]{4,}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?$"
59
+ _DATE_FORM = r"^-?[0-9]{4,}-[0-9]{2}-[0-9]{2}$"
60
+ _ZONE = r"(Z|[+-][0-9]{2}:[0-9]{2})$"
61
+
62
+
63
+ def target_of(e: E.Call) -> str:
64
+ return e.args[1].value.text
65
+
66
+
67
+ def _source(slot: Slot) -> Optional[str]:
68
+ """The table row of a literal slot of one datatype; None for one 17.5 has no row for."""
69
+ dt = slot.datatype
70
+ if dt == xsd.STRING:
71
+ return "string"
72
+ if dt in _NUMBERS:
73
+ return "number"
74
+ return {xsd.BOOLEAN: "boolean", xsd.DATETIME: "dateTime", DATE: "date"}.get(dt)
75
+
76
+
77
+ def _constant(slot: Slot):
78
+ """The term of a constant written in the query, None otherwise."""
79
+ if not slot.provenance or len(slot.provenance) != 1:
80
+ return None
81
+ m = next(iter(slot.provenance))
82
+ if m.constant is None:
83
+ return None
84
+ if IRI in slot.kinds:
85
+ return IRITerm(m.constant)
86
+ if BLANK in slot.kinds:
87
+ return BlankTerm(m.constant)
88
+ return LiteralTerm(m.constant, slot.datatype if slot.language is None else None, slot.language)
89
+
90
+
91
+ def cast_slot(e: E.Call, slots: Mapping[str, Slot]) -> Slot:
92
+ target = target_of(e)
93
+ arg = expr_slot(e.args[0], slots)
94
+ if arg.present is Bound.NEVER:
95
+ return NOTHING
96
+ if not arg.terms:
97
+ raise NotBuilt("a cast of a database value")
98
+ term = _constant(arg)
99
+ if term is not None:
100
+ result = fold(term, target)
101
+ return const_slot(result) if result is not None else NOTHING
102
+ if arg.kinds == {IRI}:
103
+ return literal_slot(xsd.STRING, arg.present, native=True) if target == xsd.STRING else NOTHING
104
+ if arg.kind_varies or arg.datatype_varies or arg.held_as is not None or UNKNOWN in arg.datatypes:
105
+ raise NotBuilt("a cast of a column whose rows differ in kind or datatype, or of no recorded type")
106
+ kind = next(iter(arg.kinds))
107
+ if kind == BLANK:
108
+ return NOTHING
109
+ if kind == IRI or arg.datatype == xsd.RDF_LANGSTRING:
110
+ return literal_slot(xsd.STRING, arg.present, native=True) if target == xsd.STRING else NOTHING
111
+ source = _source(arg)
112
+ if source is None:
113
+ if target == xsd.STRING:
114
+ return literal_slot(xsd.STRING, arg.present, native=True)
115
+ return NOTHING
116
+ if target not in _ALLOWED[source]:
117
+ return NOTHING
118
+ if arg.datatype in (xsd.DATETIME, DATE) and arg.native is None:
119
+ raise NotBuilt("a cast of a date or dateTime held as text")
120
+ if arg.datatype == xsd.DATETIME and arg.zone != LOCAL and target != xsd.STRING:
121
+ raise NotBuilt("a cast of a zoned dateTime column")
122
+ sure = (target == xsd.STRING and arg.native is not None) or (target == arg.datatype and arg.native is not None)
123
+ bound = arg.present if sure else Bound.MAYBE
124
+ slot = literal_slot(target, bound, native=True)
125
+ if target == xsd.DECIMAL:
126
+ from dataclasses import replace
127
+ digits = arg.digits if arg.datatype == xsd.DECIMAL and arg.digits else \
128
+ ((38, 0) if source == "boolean" or arg.datatype in _INTEGERS else (38, 18))
129
+ slot = replace(slot, digits=digits)
130
+ if target == xsd.DATETIME:
131
+ from dataclasses import replace
132
+ slot = replace(slot, zone=LOCAL)
133
+ return slot
134
+
135
+
136
+ def cast_cell(e: E.Call, cells):
137
+ """The SQL of a cast (see the module's text)."""
138
+ from prograph.plan.ir import lower as L
139
+ R = L.R
140
+ target = target_of(e)
141
+ slot = cast_slot(e, {k: c.slot for k, c in cells.items()})
142
+ if slot.present is Bound.NEVER:
143
+ return L.Cell(slot, L.NULL)
144
+ arg = L.expr_cell(e.args[0], cells)
145
+ if _constant(arg.slot) is not None:
146
+ return L.Cell(slot, L.const_cell(fold(_constant(arg.slot), target)).value)
147
+ s = arg.slot
148
+ lex = L.lexical(arg)
149
+
150
+ def matches(form: str) -> R.Expr:
151
+ return R.CompareExpr(left=lex, op="RLIKE", right=L.text(form))
152
+
153
+ def zone_raises(value: R.Expr) -> R.Expr:
154
+ # A text with a zone is not built: the row raises (never a short answer), the raise cast
155
+ # to the value's type (PostgreSQL types a CASE's branches alike).
156
+ typed = "CAST_TIMESTAMP" if target == xsd.DATETIME else "CAST_DATE"
157
+ # The row's text is read in the raise: PostgreSQL's planner folds a constant one.
158
+ raised = L.fn(typed, L.fn("DATA_ERROR", L.text(
159
+ "ProGraph: a cast of a dateTime or date text with a zone is not built: "), lex))
160
+ return L.case(R.CompareExpr(left=lex, op="RLIKE", right=L.text(_ZONE)), raised, value)
161
+ kind = next(iter(s.kinds))
162
+ if kind == IRI or s.datatype == xsd.RDF_LANGSTRING or _source(s) is None:
163
+ return L.Cell(slot, lex) # to xsd:string only (cast_slot)
164
+ source = _source(s)
165
+ if source == "string":
166
+ if target == xsd.STRING:
167
+ return L.Cell(slot, lex)
168
+ if target in (xsd.INTEGER, xsd.DECIMAL, xsd.FLOAT, xsd.DOUBLE):
169
+ ok = L.valid_lexical(lex, L.text(target), {target})
170
+ convert = {xsd.INTEGER: "TRY_INTEGER_TEXT", xsd.DECIMAL: "TRY_DECIMAL_TEXT"}.get(target, "CAST_DOUBLE_TRY")
171
+ return L.Cell(slot, L.case(ok, L.fn(convert, lex)))
172
+ if target == xsd.BOOLEAN:
173
+ return L.Cell(slot, _boolean_of_text(lex, L))
174
+ if target == xsd.DATETIME:
175
+ return L.Cell(slot, zone_raises(L.case(matches(_DATETIME_FORM), L.fn("CAST_TIMESTAMP_TRY", lex))))
176
+ return L.Cell(slot, zone_raises(L.case(matches(_DATE_FORM), L.fn("CAST_DATE_TRY", lex))))
177
+ if source == "boolean":
178
+ b = arg.value if s.native == xsd.BOOLEAN else _boolean_of_text(lex, L)
179
+ if target == xsd.STRING:
180
+ return L.Cell(slot, L.case(b, L.text("true"), R.NotExpr(child=b), L.text("false")))
181
+ if target == xsd.BOOLEAN:
182
+ return L.Cell(slot, b)
183
+ one, zero = {xsd.INTEGER: (L.integer(1), L.integer(0)),
184
+ xsd.DECIMAL: (L.fn("INTEGER_AS_DECIMAL", L.integer(1)), L.fn("INTEGER_AS_DECIMAL", L.integer(0)))}.get(
185
+ target, (R.LitExpr(value=1.0, sql="CAST(1.0 AS DOUBLE)"), R.LitExpr(value=0.0, sql="CAST(0.0 AS DOUBLE)")))
186
+ if target in (xsd.FLOAT, xsd.DOUBLE):
187
+ one, zero = L.fn("CAST_DOUBLE", L.integer(1)), L.fn("CAST_DOUBLE", L.integer(0))
188
+ return L.Cell(slot, L.case(b, one, R.NotExpr(child=b), zero))
189
+ if source == "number":
190
+ v = L._number(arg)
191
+ dbl = s.datatype in (xsd.DOUBLE, xsd.FLOAT)
192
+ if target == xsd.STRING:
193
+ return L.Cell(slot, _string_of_number(v, s.datatype, L))
194
+ if target == xsd.INTEGER:
195
+ if s.datatype in _INTEGERS and not L.wide_integer(s):
196
+ return L.Cell(slot, v)
197
+ whole = L.case(R.CompareExpr(left=v, op=">=", right=L.integer(0)), L.fn("FLOOR", v), L.fn("CEIL", v))
198
+ value = L.fn("TRY_CAST_LONG", whole)
199
+ if dbl:
200
+ # Spark's try_cast of a double saturates at the long's bounds (1e20, INF): the range
201
+ # is tested first, |v| < 2^63, which NaN and INF fail.
202
+ fits = R.CompareExpr(left=L.fn("ABS", v), op="<",
203
+ right=R.LitExpr(value=2.0 ** 63, sql="9.223372036854775808E18"))
204
+ value = L.case(fits, value)
205
+ return L.Cell(slot, value)
206
+ if target == xsd.DECIMAL:
207
+ if s.datatype == xsd.DECIMAL:
208
+ return L.Cell(slot, v)
209
+ if not dbl:
210
+ return L.Cell(slot, L.fn("INTEGER_AS_DECIMAL", v))
211
+ fits = R.CompareExpr(left=L.fn("ABS", v), op="<", right=R.LitExpr(value=1e20, sql="1e20"))
212
+ text_ = L.fn("XSD_DOUBLE_TEXT", v)
213
+ return L.Cell(slot, L.case(fits, L.fn("DECIMAL_SIZED", text_, L.integer(38), L.integer(18))))
214
+ if target in (xsd.FLOAT, xsd.DOUBLE):
215
+ return L.Cell(slot, v if dbl else L.fn("CAST_DOUBLE", v))
216
+ # xsd:boolean: 0 false, NaN false, else true.
217
+ zero = L.eq(v, L.integer(0))
218
+ if dbl:
219
+ nan = L.eq(L.fn("XSD_DOUBLE_TEXT", v), L.text("NaN"))
220
+ return L.Cell(slot, L.case(L.any_of([zero, nan]), L.FALSE, L.TRUE))
221
+ return L.Cell(slot, L.case(zero, L.FALSE, L.TRUE))
222
+ # dateTime or date
223
+ if target == xsd.STRING:
224
+ return L.Cell(slot, lex)
225
+ if target == s.datatype:
226
+ return L.Cell(slot, arg.value)
227
+ if target == xsd.DATETIME:
228
+ return L.Cell(slot, L.fn("DATE_AT_MIDNIGHT", arg.value)) # a date's midnight
229
+ return L.Cell(slot, L.fn("CAST_DATE", arg.value)) # a dateTime's date
230
+
231
+
232
+ def _boolean_of_text(lex, L):
233
+ return L.case(L.any_of([L.eq(lex, L.text("true")), L.eq(lex, L.text("1"))]), L.TRUE,
234
+ L.any_of([L.eq(lex, L.text("false")), L.eq(lex, L.text("0"))]), L.FALSE)
235
+
236
+
237
+ def _string_of_number(v, datatype: str, L):
238
+ """F&O 3.1 19.1.2.2: an integer's digits; an integral decimal with no point; a double in
239
+ [1e-6, 1e6) as a decimal, zero `0` or `-0`, else its canonical text."""
240
+ R = L.R
241
+ if datatype in _INTEGERS:
242
+ return L.fn("CAST_STRING", v)
243
+
244
+ def of_decimal(d):
245
+ return L.decimal_text(d) # canonical: an integral one with no point (D3)
246
+ if datatype == xsd.DECIMAL:
247
+ return of_decimal(v)
248
+ t = L.fn("XSD_DOUBLE_TEXT", v)
249
+ a = L.fn("ABS", v)
250
+ plain = L.all_of([R.CompareExpr(left=a, op=">=", right=R.LitExpr(value=1e-6, sql="1e-6")),
251
+ R.CompareExpr(left=a, op="<", right=R.LitExpr(value=1e6, sql="1e6"))])
252
+ return L.case(L.eq(t, L.text("0.0E0")), L.text("0"), L.eq(t, L.text("-0.0E0")), L.text("-0"),
253
+ plain, of_decimal(L.fn("DECIMAL_SIZED", t, L.integer(38), L.integer(30))), t)
254
+
255
+
256
+ # -- constants, at planning ----------------------------------------------------------------
257
+
258
+ def fold(term, target: str) -> Optional[LiteralTerm]:
259
+ """A cast of a constant (see the module's text), None for an error."""
260
+ if isinstance(term, BlankTerm):
261
+ return None
262
+ if isinstance(term, IRITerm):
263
+ return LiteralTerm(term.text) if target == xsd.STRING else None
264
+ dt = term.datatype or xsd.STRING
265
+ if term.language is not None or dt == xsd.RDF_LANGSTRING:
266
+ return LiteralTerm(term.lexical) if target == xsd.STRING else None
267
+ source = {xsd.STRING: "string", xsd.BOOLEAN: "boolean", xsd.DATETIME: "dateTime", DATE: "date"}.get(
268
+ dt, "number" if dt in _NUMBERS else None)
269
+ if source is None:
270
+ return LiteralTerm(term.lexical) if target == xsd.STRING else None
271
+ if target not in _ALLOWED[source]:
272
+ return None
273
+ try:
274
+ value = xsd.parse(term.lexical, dt) if source != "string" else term.lexical
275
+ except (ValueError, TypeError, ArithmeticError):
276
+ return None # an ill-typed literal: an error
277
+ if source == "string":
278
+ if target == xsd.STRING:
279
+ return LiteralTerm(value)
280
+ try:
281
+ value = xsd.parse(value, target)
282
+ except (ValueError, TypeError, ArithmeticError):
283
+ return None
284
+ return _canonical(value, target)
285
+ if source in ("dateTime", "date"):
286
+ if target == xsd.STRING:
287
+ return LiteralTerm(xsd.canonical_lexical(value, dt))
288
+ if target == DATE and isinstance(value, _dt.datetime):
289
+ value = value.date()
290
+ elif target == xsd.DATETIME and not isinstance(value, _dt.datetime):
291
+ # A date's midnight, its zone kept (F&O 3.1 19.1.4): the zone is in the lexical form.
292
+ midnight = _dt.datetime(value.year, value.month, value.day).isoformat()
293
+ zone = re.search(_ZONE, term.lexical)
294
+ return LiteralTerm(midnight + (zone.group(1) if zone else ""), xsd.DATETIME)
295
+ return _canonical(value, target)
296
+ number = int(value) if isinstance(value, bool) else value
297
+ if target == xsd.STRING:
298
+ if isinstance(value, bool):
299
+ return LiteralTerm("true" if value else "false")
300
+ return LiteralTerm(_string_of(number, dt))
301
+ if target == xsd.BOOLEAN:
302
+ nan = isinstance(number, float) and not math.isfinite(number) and not math.isinf(number)
303
+ return _canonical(not (number == 0 or nan), target)
304
+ if target == xsd.INTEGER:
305
+ if isinstance(number, float) and not math.isfinite(number):
306
+ return None
307
+ whole = int(number)
308
+ return _canonical(whole, target) if -2 ** 63 <= whole < 2 ** 63 else None
309
+ if target == xsd.DECIMAL:
310
+ if isinstance(number, float):
311
+ if not math.isfinite(number):
312
+ return None
313
+ number = Decimal(repr(number))
314
+ d = Decimal(number)
315
+ if d.adjusted() >= 20:
316
+ return None
317
+ return _canonical(d.quantize(Decimal(1).scaleb(-18)) if d.as_tuple().exponent < -18 else d, target)
318
+ return _canonical(float(number), target)
319
+
320
+
321
+ def _canonical(value, datatype: str) -> LiteralTerm:
322
+ if datatype == xsd.FLOAT:
323
+ return LiteralTerm(xsd.canonical_lexical(float(value), xsd.FLOAT), xsd.FLOAT)
324
+ return LiteralTerm(xsd.canonical_lexical(value, datatype), datatype)
325
+
326
+
327
+ def _string_of(number, dt: str) -> str:
328
+ if isinstance(number, int):
329
+ return str(number)
330
+ if isinstance(number, Decimal):
331
+ return xsd.canonical_decimal(number)
332
+ x = float(number)
333
+ if x == 0:
334
+ return "-0" if math.copysign(1.0, x) < 0 else "0"
335
+ if not math.isfinite(x) or not 1e-6 <= abs(x) < 1e6:
336
+ return xsd.canonical_lexical(x, xsd.DOUBLE)
337
+ d = Decimal(repr(x))
338
+ return xsd.canonical_decimal(d)