prograph 1.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prograph/__init__.py +36 -0
- prograph/__main__.py +5 -0
- prograph/_version.py +375 -0
- prograph/cli/__init__.py +1 -0
- prograph/cli/_iri_utils.py +124 -0
- prograph/cli/emit_genie_space.py +107 -0
- prograph/cli/generate_views.py +140 -0
- prograph/cli/main.py +420 -0
- prograph/cli/schema_inferrer.py +746 -0
- prograph/cli/ttl_loader.py +289 -0
- prograph/cli/upload_genie_space.py +84 -0
- prograph/config/__init__.py +27 -0
- prograph/config/yaml_config.py +848 -0
- prograph/demos/__init__.py +14 -0
- prograph/demos/turbofan/README.md +74 -0
- prograph/demos/turbofan/SCENARIO.md +209 -0
- prograph/demos/turbofan/__init__.py +75 -0
- prograph/demos/turbofan/create_tables.sql +206 -0
- prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
- prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
- prograph/demos/turbofan/demo.py +162 -0
- prograph/demos/turbofan/genie_qa_notebook.py +434 -0
- prograph/demos/turbofan/graph.yaml +1098 -0
- prograph/demos/turbofan/instance_graph_demo.py +32 -0
- prograph/demos/turbofan/load.py +223 -0
- prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
- prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
- prograph/demos/turbofan/payload-shapes.ttl +33 -0
- prograph/demos/turbofan/queries/example-queries.sparql +215 -0
- prograph/demos/turbofan/shapes.ttl +75 -0
- prograph/demos/turbofan/tables.py +106 -0
- prograph/demos/turbofan/turbofan_schema.py +393 -0
- prograph/demos/turbofan/validation_demo.py +153 -0
- prograph/describe.py +231 -0
- prograph/endpoint/__init__.py +12 -0
- prograph/endpoint/app.py +722 -0
- prograph/endpoint/cli.py +280 -0
- prograph/endpoint/credentials.py +240 -0
- prograph/endpoint/engines.py +418 -0
- prograph/endpoint/negotiate.py +101 -0
- prograph/endpoint/results.py +181 -0
- prograph/endpoint/service.py +31 -0
- prograph/engine.py +2718 -0
- prograph/execution.py +455 -0
- prograph/executors/__init__.py +6 -0
- prograph/executors/base.py +11 -0
- prograph/executors/databricks_sql_executor.py +51 -0
- prograph/executors/duckdb_executor.py +24 -0
- prograph/executors/mysql_executor.py +20 -0
- prograph/executors/oracle_executor.py +24 -0
- prograph/executors/pandas_executor.py +72 -0
- prograph/executors/postgresql_executor.py +35 -0
- prograph/executors/spark_executor.py +88 -0
- prograph/executors/sqlserver_executor.py +35 -0
- prograph/extras/__init__.py +1 -0
- prograph/extras/graphql/__init__.py +33 -0
- prograph/extras/graphql/execute.py +25 -0
- prograph/extras/graphql/schema.py +314 -0
- prograph/extras/instance_graph.py +559 -0
- prograph/genie/__init__.py +83 -0
- prograph/genie/databricks_uploader.py +306 -0
- prograph/genie/deploy.py +393 -0
- prograph/genie/formats.py +414 -0
- prograph/genie/instruction_generator.py +375 -0
- prograph/genie/sample_query_generator.py +256 -0
- prograph/genie/shacl_views.py +318 -0
- prograph/genie/space_emitter.py +329 -0
- prograph/genie/view_generator.py +628 -0
- prograph/genie/view_writer.py +172 -0
- prograph/graph/__init__.py +1 -0
- prograph/graph/ansi_session.py +348 -0
- prograph/graph/databricks_sql_graph.py +300 -0
- prograph/graph/drivers.py +143 -0
- prograph/graph/duckdb_graph.py +68 -0
- prograph/graph/mysql_graph.py +38 -0
- prograph/graph/oracle_graph.py +285 -0
- prograph/graph/pandas_graph.py +343 -0
- prograph/graph/postgresql_graph.py +644 -0
- prograph/graph/spark_graph.py +556 -0
- prograph/graph/sql_graph.py +83 -0
- prograph/graph/sqlserver_graph.py +72 -0
- prograph/hints.py +95 -0
- prograph/logging.py +550 -0
- prograph/mcp/__init__.py +29 -0
- prograph/mcp/__main__.py +180 -0
- prograph/mcp/bootstrap.py +98 -0
- prograph/mcp/server.py +601 -0
- prograph/mcp/sparql.py +397 -0
- prograph/mcp/tools.py +504 -0
- prograph/nlp/__init__.py +79 -0
- prograph/nlp/client.py +305 -0
- prograph/nlp/databricks_tools.py +369 -0
- prograph/nlp/graph_context.py +313 -0
- prograph/nlp/interface.py +652 -0
- prograph/nlp/prompts/__init__.py +19 -0
- prograph/nlp/prompts/examples.py +258 -0
- prograph/nlp/prompts/system.py +239 -0
- prograph/nlp/providers/__init__.py +14 -0
- prograph/nlp/providers/anthropic.py +274 -0
- prograph/nlp/providers/databricks.py +312 -0
- prograph/nlp/providers/openai.py +203 -0
- prograph/nlp/schema_context.py +78 -0
- prograph/ontology/__init__.py +53 -0
- prograph/ontology/alignment.py +542 -0
- prograph/ontology/hierarchy.py +310 -0
- prograph/ontology/imports.py +587 -0
- prograph/ontology/layer.py +991 -0
- prograph/ontology/skos.py +61 -0
- prograph/owl/__init__.py +27 -0
- prograph/owl/defined_classes.py +323 -0
- prograph/parameters.py +242 -0
- prograph/parser/__init__.py +1 -0
- prograph/parser/cypher/CypherLexer.py +836 -0
- prograph/parser/cypher/CypherListener.py +966 -0
- prograph/parser/cypher/CypherParser.py +10854 -0
- prograph/parser/cypher/CypherVisitor.py +543 -0
- prograph/parser/cypher/__init__.py +1 -0
- prograph/parser/sparql/SparqlLexer.py +801 -0
- prograph/parser/sparql/SparqlParser.py +10146 -0
- prograph/parser/sparql/SparqlParserListener.py +1056 -0
- prograph/parser/sparql/SparqlParserVisitor.py +593 -0
- prograph/parser/sparql/__init__.py +8 -0
- prograph/plan/__init__.py +3 -0
- prograph/plan/ir/__init__.py +1 -0
- prograph/plan/ir/casts.py +338 -0
- prograph/plan/ir/consistency.py +397 -0
- prograph/plan/ir/construct.py +90 -0
- prograph/plan/ir/cost.py +234 -0
- prograph/plan/ir/cypher_answer.py +1081 -0
- prograph/plan/ir/cypher_apoc.py +717 -0
- prograph/plan/ir/cypher_apoc_convert.py +505 -0
- prograph/plan/ir/cypher_apoc_date.py +845 -0
- prograph/plan/ir/cypher_apoc_map.py +496 -0
- prograph/plan/ir/cypher_apoc_meta.py +384 -0
- prograph/plan/ir/cypher_apoc_path.py +597 -0
- prograph/plan/ir/cypher_apoc_procedures.py +163 -0
- prograph/plan/ir/cypher_apoc_text.py +785 -0
- prograph/plan/ir/cypher_front.py +5474 -0
- prograph/plan/ir/cypher_functions.py +565 -0
- prograph/plan/ir/cypher_lists.py +935 -0
- prograph/plan/ir/cypher_maps.py +370 -0
- prograph/plan/ir/cypher_mixed.py +604 -0
- prograph/plan/ir/cypher_ontology.py +226 -0
- prograph/plan/ir/cypher_procedures.py +191 -0
- prograph/plan/ir/cypher_runtime_errors.py +107 -0
- prograph/plan/ir/cypher_temporal.py +1357 -0
- prograph/plan/ir/cypher_temporal_arith.py +339 -0
- prograph/plan/ir/cypher_values.py +546 -0
- prograph/plan/ir/cypher_write.py +612 -0
- prograph/plan/ir/dataset.py +643 -0
- prograph/plan/ir/dates.py +102 -0
- prograph/plan/ir/entry.py +992 -0
- prograph/plan/ir/expr.py +260 -0
- prograph/plan/ir/facts.py +1171 -0
- prograph/plan/ir/fresh.py +291 -0
- prograph/plan/ir/freshness.py +625 -0
- prograph/plan/ir/identity.py +797 -0
- prograph/plan/ir/java_datetime.py +265 -0
- prograph/plan/ir/java_regex.py +391 -0
- prograph/plan/ir/join_order.py +39 -0
- prograph/plan/ir/key_checks.py +433 -0
- prograph/plan/ir/keys.py +454 -0
- prograph/plan/ir/lower.py +5323 -0
- prograph/plan/ir/ops.py +619 -0
- prograph/plan/ir/owl_rl.py +1119 -0
- prograph/plan/ir/owl_rl_rules.py +725 -0
- prograph/plan/ir/profiles.py +694 -0
- prograph/plan/ir/ql.py +987 -0
- prograph/plan/ir/rdfs.py +342 -0
- prograph/plan/ir/rewrite.py +1782 -0
- prograph/plan/ir/saturate.py +339 -0
- prograph/plan/ir/semantics.py +103 -0
- prograph/plan/ir/slot.py +509 -0
- prograph/plan/ir/sparql_front.py +3418 -0
- prograph/plan/ir/strings.py +534 -0
- prograph/plan/ir/term_functions.py +274 -0
- prograph/plan/ir/terms.py +84 -0
- prograph/plan/ir/xpath_regex.py +264 -0
- prograph/plan/run_record.py +65 -0
- prograph/plan/sql/__init__.py +21 -0
- prograph/plan/sql/dialect.py +3726 -0
- prograph/plan/sql/mysql_serializer.py +103 -0
- prograph/plan/sql/names.py +65 -0
- prograph/plan/sql/oracle_serializer.py +306 -0
- prograph/plan/sql/pg_serializer.py +501 -0
- prograph/plan/sql/rel_algebra.py +781 -0
- prograph/plan/sql/sql_serializer.py +1419 -0
- prograph/plan/sql/sqlserver_serializer.py +603 -0
- prograph/provenance.py +222 -0
- prograph/r2rml/__init__.py +48 -0
- prograph/r2rml/catalog.py +259 -0
- prograph/r2rml/compile.py +372 -0
- prograph/r2rml/direct.py +140 -0
- prograph/r2rml/export.py +495 -0
- prograph/r2rml/model.py +180 -0
- prograph/r2rml/parser.py +546 -0
- prograph/r2rml/schema.py +120 -0
- prograph/read_only.py +122 -0
- prograph/results.py +157 -0
- prograph/rules/__init__.py +168 -0
- prograph/rules/__main__.py +32 -0
- prograph/schema/__init__.py +60 -0
- prograph/schema/change_set.py +50 -0
- prograph/schema/collations.py +198 -0
- prograph/schema/compile_schema.py +388 -0
- prograph/schema/context.py +845 -0
- prograph/schema/examples.py +234 -0
- prograph/schema/iri.py +817 -0
- prograph/schema/literals.py +94 -0
- prograph/schema/lpg_view.py +617 -0
- prograph/schema/mapping.py +1803 -0
- prograph/schema/maps_schema.py +40 -0
- prograph/schema/naming.py +77 -0
- prograph/schema/query_sources.py +59 -0
- prograph/schema/rows.py +215 -0
- prograph/schema/source_map.py +1103 -0
- prograph/schema/store_view.py +459 -0
- prograph/schema/types.py +569 -0
- prograph/schema/xsd.py +569 -0
- prograph/shacl/__init__.py +30 -0
- prograph/shacl/dqv.py +58 -0
- prograph/shacl/generate.py +255 -0
- prograph/shacl/report.py +138 -0
- prograph/shacl/validator.py +164 -0
- prograph/store.py +1737 -0
- prograph/utils/__init__.py +6 -0
- prograph/utils/exceptions.py +308 -0
- prograph/utils/helpers.py +126 -0
- prograph/warnings.py +46 -0
- prograph/writes.py +369 -0
- prograph-1.3.3.dist-info/METADATA +281 -0
- prograph-1.3.3.dist-info/RECORD +237 -0
- prograph-1.3.3.dist-info/WHEEL +5 -0
- prograph-1.3.3.dist-info/entry_points.txt +3 -0
- prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
- prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
- prograph-1.3.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""Cypher's operators over values, in the one plan (`CYPHER` semantics): arithmetic and string
|
|
2
|
+
concatenation. A value's slot is a database value of one type (`slot.value_slot`); null in, null out.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from typing import TYPE_CHECKING, Dict, List, Mapping
|
|
9
|
+
|
|
10
|
+
from prograph.plan.ir import expr as E
|
|
11
|
+
from prograph.plan.ir.facts import NotBuilt, expr_slot
|
|
12
|
+
from prograph.plan.ir.slot import BOOLEAN, LIST, LITERAL, NOTHING, UNKNOWN, VALUE, Bound, Slot, value_slot
|
|
13
|
+
from prograph.plan.sql import rel_algebra as R
|
|
14
|
+
from prograph.rules import home
|
|
15
|
+
from prograph.schema import xsd
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from prograph.plan.ir import lower as L
|
|
19
|
+
|
|
20
|
+
ARITHMETIC = frozenset({"+", "-", "*", "/", "%", "^", "NEG"})
|
|
21
|
+
STRING_PREDICATES = {"STARTS WITH": "STR_STARTS", "ENDS WITH": "STR_ENDS", "CONTAINS": "STR_CONTAINS"}
|
|
22
|
+
_FLOATS = (xsd.DOUBLE, xsd.FLOAT)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _kind(slot: Slot) -> str:
|
|
26
|
+
""""integer", "float" or "string" for a value of that one type; NotBuilt otherwise."""
|
|
27
|
+
if slot.kinds != {VALUE} or len(slot.datatypes) != 1:
|
|
28
|
+
raise NotBuilt("a Cypher operator over a value of no one type")
|
|
29
|
+
dt = slot.datatype
|
|
30
|
+
if dt in _FLOATS:
|
|
31
|
+
return "float"
|
|
32
|
+
if dt == xsd.INTEGER or dt in xsd.INTEGER_DATATYPES:
|
|
33
|
+
return "integer"
|
|
34
|
+
if dt == xsd.DECIMAL:
|
|
35
|
+
return "decimal"
|
|
36
|
+
if dt == xsd.STRING:
|
|
37
|
+
return "string"
|
|
38
|
+
raise NotBuilt(f"a Cypher operator over a {dt} value")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _result_kind(op: str, kinds: List[str]) -> str:
|
|
42
|
+
"""The kind of an operator's result, by SPARQL's numeric promotion (integer, then decimal, then
|
|
43
|
+
float): a decimal with an integer or a decimal a decimal, with a float a float; `^` a float."""
|
|
44
|
+
if "string" in kinds:
|
|
45
|
+
if op == "+" and kinds == ["string", "string"]:
|
|
46
|
+
return "string"
|
|
47
|
+
raise NotBuilt(f"{op} over a string and another kind")
|
|
48
|
+
if op == "^" or "float" in kinds:
|
|
49
|
+
return "float"
|
|
50
|
+
if "decimal" in kinds:
|
|
51
|
+
return "decimal"
|
|
52
|
+
return "integer"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _decimal_slot(op: str, args: List[Slot], null: Bound) -> Slot:
|
|
56
|
+
"""A decimal result's slot, its SQL digits by the decimal home (`facts.decimal_digits`, rule
|
|
57
|
+
decimal-arithmetic-width): a sign changes none; a quotient is DECIMAL(38, 18), exact to 18 places; a
|
|
58
|
+
result of an operand of no known digits (an unconstrained NUMERIC) has none."""
|
|
59
|
+
from prograph.plan.ir.facts import AVERAGE_DIGITS, decimal_digits, operand_digits
|
|
60
|
+
digits = [operand_digits(a) for a in args]
|
|
61
|
+
if op == "NEG":
|
|
62
|
+
held = digits[0]
|
|
63
|
+
elif op == "/":
|
|
64
|
+
held = AVERAGE_DIGITS
|
|
65
|
+
elif any(d is None for d in digits):
|
|
66
|
+
held = None
|
|
67
|
+
else:
|
|
68
|
+
held = decimal_digits(op, digits, warn=False)
|
|
69
|
+
return value_slot(xsd.DECIMAL, null, digits=held)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _case_parts(slot: Slot, conds, branches, cells, L) -> tuple:
|
|
73
|
+
"""The parts of a CASE over nodes, relationships, paths or lists of them (PostgreSQL's answer): each part picked
|
|
74
|
+
as the value is, a branch with no row (null) null in every part, `[]` the empty parts of the CASE's lists;
|
|
75
|
+
none where a branch holds no parts."""
|
|
76
|
+
from prograph.plan.ir.cypher_answer import element_shape, empty_parts
|
|
77
|
+
shape = element_shape(slot, L)
|
|
78
|
+
if shape is None:
|
|
79
|
+
return ()
|
|
80
|
+
width = len(shape.parts(True))
|
|
81
|
+
picked = []
|
|
82
|
+
for x in branches:
|
|
83
|
+
cell = L.expr_cell(x, cells)
|
|
84
|
+
if cell.slot.present is Bound.NEVER:
|
|
85
|
+
picked.append((L.NULL,) * width)
|
|
86
|
+
elif cell.parts and element_shape(cell.slot, L) == shape:
|
|
87
|
+
picked.append(cell.parts)
|
|
88
|
+
elif cell.slot.kinds == {LIST} and not cell.slot.datatypes and shape.many and isinstance(x, E.Call) \
|
|
89
|
+
and x.name == "LIST" and not x.args:
|
|
90
|
+
picked.append(empty_parts(shape, L))
|
|
91
|
+
else:
|
|
92
|
+
return ()
|
|
93
|
+
out = []
|
|
94
|
+
for i in range(width):
|
|
95
|
+
args: List["R.Expr"] = []
|
|
96
|
+
for c, parts in zip(conds, picked):
|
|
97
|
+
args += [c, parts[i]]
|
|
98
|
+
args.append(picked[-1][i])
|
|
99
|
+
out.append(L.case(*args) if len(args) > 1 else args[0])
|
|
100
|
+
return tuple(out)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _case_value(x: E.Expr, cells, slot: Slot, L) -> "R.Expr":
|
|
104
|
+
"""A CASE branch's value in the CASE's type: a list of no element type yet (`[]`) as the empty list
|
|
105
|
+
of the other branches' elements (PostgreSQL's untyped `[]` is text[])."""
|
|
106
|
+
cell = L.expr_cell(x, cells)
|
|
107
|
+
if cell.slot.present is Bound.NEVER:
|
|
108
|
+
return L.NULL
|
|
109
|
+
if cell.slot.kinds == {LIST} and not cell.slot.datatypes and slot.datatypes:
|
|
110
|
+
from prograph.plan.ir.cypher_lists import element_slot, empty_of
|
|
111
|
+
if isinstance(x, E.Call) and x.name == "LIST" and not x.args:
|
|
112
|
+
return empty_of(element_slot(slot), L)
|
|
113
|
+
raise NotBuilt("a CASE of a list of no element type beside a typed one")
|
|
114
|
+
return cell.value
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cypher_slot(e: E.Call, slots: Mapping[str, Slot]) -> Slot:
|
|
118
|
+
"""The slot of a Cypher operator's value (rule cypher-arithmetic); a call whose argument's kind is known
|
|
119
|
+
wrong raises on a row (`cypher_runtime_errors`), a slot that says so."""
|
|
120
|
+
from prograph.plan.ir.cypher_runtime_errors import RuntimeTypeError, raising_slot
|
|
121
|
+
if e.name == "RUNTIME_ERROR": # the front end's literal known wrong
|
|
122
|
+
return raising_slot(1, e.args[0].value)
|
|
123
|
+
try:
|
|
124
|
+
return _cypher_slot(e, slots)
|
|
125
|
+
except RuntimeTypeError as err:
|
|
126
|
+
return raising_slot(err.arg, err.error)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _wrong_operand(op: str, args: List[Slot]) -> None:
|
|
130
|
+
"""A string beside `-`, `*`, `/`, `%`, `^` or a negation, or a boolean beside any operator, is an error
|
|
131
|
+
where a row holds it (openCypher 9: InvalidArgumentType); `+` of a string and a number is a string."""
|
|
132
|
+
from prograph.plan.ir.cypher_runtime_errors import RuntimeTypeError
|
|
133
|
+
if any(a.present is Bound.NEVER for a in args):
|
|
134
|
+
return # a null operand: null
|
|
135
|
+
for i, a in enumerate(args):
|
|
136
|
+
if a.kinds != {VALUE} or len(a.datatypes) != 1:
|
|
137
|
+
continue
|
|
138
|
+
if a.datatype == xsd.BOOLEAN or (a.datatype == xsd.STRING and op != "+"):
|
|
139
|
+
raise RuntimeTypeError(i, "InvalidArgumentType", f"{'-' if op == 'NEG' else op} over a {'boolean' if a.datatype == xsd.BOOLEAN else 'string'}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _cypher_slot(e: E.Call, slots: Mapping[str, Slot]) -> Slot:
|
|
143
|
+
if e.name in STRING_PREDICATES:
|
|
144
|
+
return BOOLEAN
|
|
145
|
+
if e.name in ("NODE", "REL"): # its datatype records how its properties are held (`element_type`)
|
|
146
|
+
from prograph.plan.ir.cypher_answer import NODE_TYPE, REL_TYPE, element_type, node_slot, rel_slot
|
|
147
|
+
rest = e.args[1:] if e.name == "NODE" else e.args[4:]
|
|
148
|
+
named = [(k.value, expr_slot(v, slots)) for k, v in zip(rest[0::2], rest[1::2])
|
|
149
|
+
if not k.value.startswith("label:")]
|
|
150
|
+
if e.name == "NODE":
|
|
151
|
+
return node_slot(element_type(NODE_TYPE, named))
|
|
152
|
+
return rel_slot(element_type(REL_TYPE, named))
|
|
153
|
+
if e.name == "PATH":
|
|
154
|
+
from prograph.plan.ir.cypher_answer import path_slot, path_type
|
|
155
|
+
return path_slot(path_type(*(expr_slot(a, slots) for a in e.args)))
|
|
156
|
+
if e.name == "PATH_PART": # nodes(p), relationships(p) of a path held as a value
|
|
157
|
+
from prograph.plan.ir.cypher_answer import path_part_slot
|
|
158
|
+
return path_part_slot(e, slots)
|
|
159
|
+
if e.name == "PATH_LIST": # nodes(p), relationships(p): the path's list, null for a null path
|
|
160
|
+
from prograph.plan.ir.slot import list_slot
|
|
161
|
+
part = e.args[0].args[0 if e.args[1].value == "nodes" else 1]
|
|
162
|
+
return replace(expr_slot(part, slots), null=Bound.MAYBE) if expr_slot(part, slots).datatypes else \
|
|
163
|
+
list_slot(None, Bound.MAYBE)
|
|
164
|
+
if e.name in ("HAS_LABEL", "TRAIL_HAS"):
|
|
165
|
+
return BOOLEAN
|
|
166
|
+
if e.name == "EMPTY_ELEMENTS": # a zero-length trail's lists of nodes or relationships (cypher-trails)
|
|
167
|
+
# Of no element type: [] joins any list of nodes or relationships (their element types record
|
|
168
|
+
# how each holds its properties, `cypher_answer.element_type`).
|
|
169
|
+
from prograph.plan.ir.slot import list_slot
|
|
170
|
+
return list_slot(None, Bound.NEVER)
|
|
171
|
+
if e.name in ("DELETED_READ", "DELETED_NULL"): # a deleted element's property or label, read after its DELETE (cypher-writes)
|
|
172
|
+
return expr_slot(e.args[1], slots)
|
|
173
|
+
if e.name == "STORE_TEXT": # a statement's text, for the owned store (rule cypher-writes)
|
|
174
|
+
return value_slot(xsd.STRING, Bound.MAYBE)
|
|
175
|
+
if e.name == "ELEMENT_ID": # a node's identity text (rule cypher-node-of-value)
|
|
176
|
+
return value_slot(xsd.STRING, Bound.MAYBE)
|
|
177
|
+
if e.name == "KEY_IRI": # a MERGE key's IRI (rule store-mint)
|
|
178
|
+
from prograph.schema.source_map import IRI
|
|
179
|
+
return Slot(kinds=frozenset({IRI}), bound=Bound.ALWAYS)
|
|
180
|
+
if e.name == "RAND": # rule fresh-values
|
|
181
|
+
from prograph.plan.ir.fresh import cypher_rand_slot
|
|
182
|
+
return cypher_rand_slot()
|
|
183
|
+
from prograph.plan.ir.cypher_functions import FUNCTIONS, function_slot
|
|
184
|
+
if e.name in FUNCTIONS:
|
|
185
|
+
return function_slot(e, slots)
|
|
186
|
+
from prograph.plan.ir.cypher_apoc import apoc_slot, is_apoc
|
|
187
|
+
if is_apoc(e):
|
|
188
|
+
return apoc_slot(e, slots)
|
|
189
|
+
if e.name == "CASE":
|
|
190
|
+
from prograph.plan.ir.cypher_lists import element_type, typed_slot
|
|
191
|
+
values = [expr_slot(v, slots) for v in e.args[1:-1:2]] + [expr_slot(e.args[-1], slots)]
|
|
192
|
+
# Values of one type (lists and maps of one type among them; a node, a term or several types
|
|
193
|
+
# not built).
|
|
194
|
+
dt = element_type(values, "a CASE")
|
|
195
|
+
if dt is None:
|
|
196
|
+
return NOTHING
|
|
197
|
+
return typed_slot(dt, Bound.MAYBE)
|
|
198
|
+
if e.name in ("PATTERN_COUNT", "PATTERN_LIST", "PER_ELEMENT"): # not joined here (`cypher_front.attach_counts`)
|
|
199
|
+
what = "size() of a pattern comprehension" if e.name == "PATTERN_COUNT" else "a pattern comprehension"
|
|
200
|
+
raise NotBuilt(f"{what} outside a RETURN or WITH item or a WHERE (inside an aggregate, ORDER BY, UNWIND "
|
|
201
|
+
"or a subquery)")
|
|
202
|
+
if e.name == "MIXED_OF": # a node map's property as a mixed value (rule cypher-mixed-values)
|
|
203
|
+
from prograph.plan.ir.cypher_mixed import mixed_of_slot
|
|
204
|
+
return mixed_of_slot(expr_slot(e.args[0], slots))
|
|
205
|
+
if e.name == "SOURCE_TEMPORAL": # a source DATE/TIME/TIMESTAMP column (rule cypher-source-temporal)
|
|
206
|
+
from prograph.plan.ir.cypher_lists import LIST_OF
|
|
207
|
+
from prograph.plan.ir.slot import list_slot
|
|
208
|
+
inner = expr_slot(e.args[0], slots)
|
|
209
|
+
target = e.args[1].value
|
|
210
|
+
if inner.present is Bound.NEVER:
|
|
211
|
+
return NOTHING
|
|
212
|
+
return list_slot(target[len(LIST_OF):], inner.null) if target.startswith(LIST_OF) \
|
|
213
|
+
else value_slot(target, inner.null)
|
|
214
|
+
if e.name == "TEMPORAL_KEY": # a time's or date-time's order key, one of several (rule cypher-temporal)
|
|
215
|
+
inner = expr_slot(e.args[0], slots)
|
|
216
|
+
part = e.args[1].value if len(e.args) > 1 else 0
|
|
217
|
+
return NOTHING if inner.present is Bound.NEVER else value_slot(xsd.STRING if part == 2 else xsd.INTEGER,
|
|
218
|
+
Bound.MAYBE)
|
|
219
|
+
if e.name == "LABELS":
|
|
220
|
+
from prograph.plan.ir.slot import list_slot
|
|
221
|
+
return list_slot(xsd.STRING, Bound.MAYBE)
|
|
222
|
+
from prograph.plan.ir.cypher_lists import LIST_CALLS, list_call_slot
|
|
223
|
+
if e.name in LIST_CALLS:
|
|
224
|
+
return list_call_slot(e, slots)
|
|
225
|
+
from prograph.plan.ir.cypher_maps import MAP_CALLS, map_call_slot
|
|
226
|
+
if e.name in MAP_CALLS:
|
|
227
|
+
return map_call_slot(e, slots)
|
|
228
|
+
if e.name not in ARITHMETIC:
|
|
229
|
+
raise NotBuilt(f"the Cypher function {e.name}")
|
|
230
|
+
args = [expr_slot(a, slots) for a in e.args]
|
|
231
|
+
if not any(a.kinds == {LIST} for a in args):
|
|
232
|
+
_wrong_operand(e.name, args)
|
|
233
|
+
if e.name == "+" and any(a.kinds == {LIST} for a in args):
|
|
234
|
+
from prograph.plan.ir.cypher_lists import concat_slot
|
|
235
|
+
return concat_slot(*args)
|
|
236
|
+
if any(a.present is Bound.NEVER for a in args):
|
|
237
|
+
return NOTHING
|
|
238
|
+
from prograph.plan.ir.cypher_temporal_arith import is_temporal, result_type
|
|
239
|
+
if any(is_temporal(a) for a in args): # rule cypher-temporal-arithmetic
|
|
240
|
+
if e.name not in ("+", "-", "*", "/") or len(args) != 2:
|
|
241
|
+
raise NotBuilt(f"{e.name} of a temporal value (no such operator in openCypher, or not built)")
|
|
242
|
+
typed = [a.datatype if is_temporal(a) else None for a in args]
|
|
243
|
+
if None in typed and _kind(args[typed.index(None)]) == "string":
|
|
244
|
+
raise NotBuilt(f"{e.name} of a temporal value and a string")
|
|
245
|
+
null = Bound.NEVER if all(a.present is Bound.ALWAYS for a in args) else Bound.MAYBE
|
|
246
|
+
return value_slot(result_type(e.name, *typed), null)
|
|
247
|
+
kind = _result_kind(e.name, [_kind(a) for a in args])
|
|
248
|
+
null = Bound.NEVER if all(a.present is Bound.ALWAYS for a in args) else Bound.MAYBE
|
|
249
|
+
if kind == "decimal":
|
|
250
|
+
return _decimal_slot(e.name, args, null)
|
|
251
|
+
return value_slot({"integer": xsd.INTEGER, "float": xsd.DOUBLE, "string": xsd.STRING}[kind], null)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@home("cypher-arithmetic", "Cypher's arithmetic and string concatenation, in SQL",
|
|
255
|
+
terms=("+", "-", "*", "/", "%", "^", "arithmetic", "overflow", "division by zero", "Cypher arithmetic"))
|
|
256
|
+
def cypher_cell(e: E.Call, cells: Dict[str, "L.Cell"]) -> "L.Cell":
|
|
257
|
+
"""openCypher 9's mathematical operators: null where an operand is null; two integers give an
|
|
258
|
+
integer, the database's error past 64 bits; `/` and `%` of integers truncate toward zero, a zero
|
|
259
|
+
divisor an error; a float operand makes the
|
|
260
|
+
result a float, IEEE's (x / 0.0 is Infinity, -Infinity or NaN; x % 0.0 NaN); a mapped DECIMAL
|
|
261
|
+
with decimals or integers an exact decimal (`_decimal`); `^` a float; a string `+` a string their
|
|
262
|
+
concatenation."""
|
|
263
|
+
from prograph.plan.ir import lower as L
|
|
264
|
+
from prograph.plan.ir.cypher_runtime_errors import runtime_cell
|
|
265
|
+
raising = runtime_cell(e, cells)
|
|
266
|
+
if raising is not None:
|
|
267
|
+
return raising
|
|
268
|
+
if e.name in STRING_PREDICATES:
|
|
269
|
+
return string_predicate(e, cells)
|
|
270
|
+
if e.name == "NODE":
|
|
271
|
+
from prograph.plan.ir.cypher_answer import node_cell
|
|
272
|
+
return node_cell(e, cells)
|
|
273
|
+
if e.name == "REL":
|
|
274
|
+
from prograph.plan.ir.cypher_answer import rel_cell
|
|
275
|
+
return rel_cell(e, cells)
|
|
276
|
+
if e.name == "PATH":
|
|
277
|
+
from prograph.plan.ir.cypher_answer import path_cell
|
|
278
|
+
return path_cell(e, cells)
|
|
279
|
+
if e.name == "PATH_PART":
|
|
280
|
+
from prograph.plan.ir.cypher_answer import path_part_cell
|
|
281
|
+
return path_part_cell(e, cells)
|
|
282
|
+
if e.name == "PATH_LIST":
|
|
283
|
+
from prograph.plan.ir.cypher_answer import path_cell
|
|
284
|
+
path = path_cell(e.args[0], cells)
|
|
285
|
+
part = L.expr_cell(e.args[0].args[0 if e.args[1].value == "nodes" else 1], cells)
|
|
286
|
+
# PostgreSQL's parts (rule cypher-result-values): the list's, null with the path (its `ids` part says so).
|
|
287
|
+
parts = tuple(L.case(L.is_null(path.value), L.NULL, x) for x in part.parts)
|
|
288
|
+
return L.Cell(cypher_slot(e, {n: c.slot for n, c in cells.items()}),
|
|
289
|
+
L.case(L.is_null(path.value), L.NULL, part.value), parts=parts)
|
|
290
|
+
if e.name in ("HAS_LABEL", "LABELS"):
|
|
291
|
+
return _labels(e, cells)
|
|
292
|
+
if e.name == "ELEMENT_ID":
|
|
293
|
+
return element_id(e, cells)
|
|
294
|
+
if e.name == "STORE_TEXT":
|
|
295
|
+
from prograph.plan.ir.cypher_write import text_cell
|
|
296
|
+
return text_cell(e, cells)
|
|
297
|
+
if e.name in ("DELETED_READ", "DELETED_NULL"):
|
|
298
|
+
from prograph.plan.ir.cypher_write import deleted_read_cell
|
|
299
|
+
return deleted_read_cell(e, cells)
|
|
300
|
+
if e.name == "KEY_IRI":
|
|
301
|
+
from prograph.plan.ir.fresh import key_iri_cell
|
|
302
|
+
return key_iri_cell(e, cells)
|
|
303
|
+
if e.name == "RAND": # rule fresh-values
|
|
304
|
+
from prograph.plan.ir.fresh import cypher_rand_cell
|
|
305
|
+
return cypher_rand_cell(e, cells)
|
|
306
|
+
from prograph.plan.ir.cypher_functions import FUNCTIONS, function_cell
|
|
307
|
+
if e.name in FUNCTIONS:
|
|
308
|
+
return function_cell(e, cells)
|
|
309
|
+
from prograph.plan.ir.cypher_apoc import apoc_cell, is_apoc
|
|
310
|
+
if is_apoc(e):
|
|
311
|
+
return apoc_cell(e, cells)
|
|
312
|
+
if e.name == "EMPTY_ELEMENTS":
|
|
313
|
+
# [] beside the trails' lists of whole nodes or relationships: PostgreSQL holds those as jsonb
|
|
314
|
+
# arrays, and gives a bare [] the type text[], which a union with them refuses.
|
|
315
|
+
from prograph.plan.ir.lower import DIALECT
|
|
316
|
+
from prograph.plan.sql import rel_algebra as R
|
|
317
|
+
slot = cypher_slot(e, {})
|
|
318
|
+
if DIALECT.get() in ("postgresql", "postgres"):
|
|
319
|
+
return L.Cell(slot, R.LitExpr(value="[]", sql="CAST(ARRAY[] AS JSONB[])"))
|
|
320
|
+
return L.Cell(slot, L.fn("ARRAY"))
|
|
321
|
+
if e.name == "TRAIL_HAS": # a relationship's identity among a trail's (rule cypher-trails)
|
|
322
|
+
trail, rel = (L.expr_cell(a, cells) for a in e.args)
|
|
323
|
+
return L.Cell(BOOLEAN, L.fn("CYPHER_LIST_CONTAINS", trail.value, L.lexical(rel)))
|
|
324
|
+
if e.name == "CASE":
|
|
325
|
+
slot = cypher_slot(e, {n: c.slot for n, c in cells.items()})
|
|
326
|
+
if slot.present is Bound.NEVER:
|
|
327
|
+
return L.nothing()
|
|
328
|
+
args: List["R.Expr"] = []
|
|
329
|
+
branches = [] # each branch's cell, for the parts of a list of elements (PostgreSQL's answer)
|
|
330
|
+
conds: List["R.Expr"] = []
|
|
331
|
+
for when, then in zip(e.args[0:-1:2], e.args[1:-1:2]):
|
|
332
|
+
if isinstance(when, E.Const) and when.value is None:
|
|
333
|
+
continue # WHEN null: never taken
|
|
334
|
+
cond = L.boolean(when, cells)
|
|
335
|
+
value = _case_value(then, cells, slot, L)
|
|
336
|
+
args += [L.fn("COALESCE", cond, L.FALSE), value]
|
|
337
|
+
conds.append(args[-2])
|
|
338
|
+
branches.append(then)
|
|
339
|
+
args.append(_case_value(e.args[-1], cells, slot, L))
|
|
340
|
+
cell = L.Cell(slot, L.case(*args) if len(args) > 1 else args[0]) # every WHEN null: the ELSE
|
|
341
|
+
parts = _case_parts(slot, conds, branches + [e.args[-1]], cells, L)
|
|
342
|
+
return L.Cell(slot, cell.value, parts=parts) if parts else cell
|
|
343
|
+
if e.name == "MIXED_OF":
|
|
344
|
+
from prograph.plan.ir.cypher_mixed import mixed_of_slot, wrap
|
|
345
|
+
# A property the node maps give in two types (`cypher_front.scan`): each map's value the tagged struct,
|
|
346
|
+
# a jsonb object on PostgreSQL, so the union's column holds one type and each value keeps its own.
|
|
347
|
+
inner = L.expr_cell(e.args[0], cells)
|
|
348
|
+
return L.Cell(mixed_of_slot(inner.slot), wrap(inner, L, scalar=True))
|
|
349
|
+
if e.name == "SOURCE_TEMPORAL":
|
|
350
|
+
from prograph.plan.ir.cypher_lists import LIST_OF
|
|
351
|
+
from prograph.plan.ir.cypher_temporal import source_cell
|
|
352
|
+
from prograph.plan.ir.strings import _dialect_has
|
|
353
|
+
inner = L.expr_cell(e.args[0], cells)
|
|
354
|
+
if inner.slot.present is Bound.NEVER:
|
|
355
|
+
return L.nothing()
|
|
356
|
+
target = e.args[1].value
|
|
357
|
+
element = target[len(LIST_OF):] if target.startswith(LIST_OF) else None
|
|
358
|
+
need = {"urn:prograph:cypher:date": "CYPHER_SOURCE_DAYS", "urn:prograph:cypher:localtime": "CYPHER_SOURCE_TIME_NS",
|
|
359
|
+
"urn:prograph:cypher:localdatetime": "CYPHER_SOURCE_LOCAL_NS",
|
|
360
|
+
"urn:prograph:cypher:datetime": "CYPHER_SOURCE_INSTANT_NS",
|
|
361
|
+
"urn:prograph:cypher:time": "CYPHER_SOURCE_OFFSET",
|
|
362
|
+
"urn:prograph:cypher:duration": "CYPHER_FIELD_LONG"}[element or target]
|
|
363
|
+
struct = e.args[2].value if len(e.args) > 2 else None # a struct of the temporal's parts
|
|
364
|
+
if struct is not None:
|
|
365
|
+
need = "CYPHER_FIELD_LONG"
|
|
366
|
+
if not _dialect_has(need):
|
|
367
|
+
what = {"CYPHER_SOURCE_TIME_NS": "TIME", "CYPHER_SOURCE_OFFSET": "TIME WITH TIME ZONE",
|
|
368
|
+
"CYPHER_FIELD_LONG": "temporal struct"}.get(need, "DATE or TIMESTAMP")
|
|
369
|
+
raise NotBuilt(f"a {what} column read by Cypher on this engine")
|
|
370
|
+
if element is not None: # an array of them: a list of the temporals, each made as one is
|
|
371
|
+
from prograph.plan.ir.slot import list_slot
|
|
372
|
+
from prograph.plan.sql import rel_algebra as R
|
|
373
|
+
var = R.LitExpr(value="_st", sql="_st")
|
|
374
|
+
made = source_cell(element, L.Cell(value_slot(element, Bound.MAYBE), var), L, struct).value
|
|
375
|
+
return L.Cell(list_slot(element, inner.slot.null),
|
|
376
|
+
L.case(L.is_null(inner.value), L.NULL, L.fn("LIST_TRANSFORM", inner.value, var, made)))
|
|
377
|
+
return source_cell(target, inner, L, struct)
|
|
378
|
+
if e.name == "TEMPORAL_KEY":
|
|
379
|
+
from prograph.plan.ir.cypher_temporal import struct_keys
|
|
380
|
+
inner = L.expr_cell(e.args[0], cells)
|
|
381
|
+
if inner.slot.present is Bound.NEVER:
|
|
382
|
+
return L.nothing()
|
|
383
|
+
return L.Cell(cypher_slot(e, {n: c.slot for n, c in cells.items()}),
|
|
384
|
+
struct_keys(inner.slot.datatype, inner.value, L)[e.args[1].value if len(e.args) > 1 else 0])
|
|
385
|
+
from prograph.plan.ir.cypher_lists import LIST_CALLS, list_call_cell
|
|
386
|
+
if e.name in LIST_CALLS:
|
|
387
|
+
return list_call_cell(e, cells)
|
|
388
|
+
from prograph.plan.ir.cypher_maps import MAP_CALLS, map_call_cell
|
|
389
|
+
if e.name in MAP_CALLS:
|
|
390
|
+
return map_call_cell(e, cells)
|
|
391
|
+
slot = cypher_slot(e, {n: c.slot for n, c in cells.items()})
|
|
392
|
+
if e.name == "+" and slot.kinds == {LIST}:
|
|
393
|
+
from prograph.plan.ir.cypher_lists import concat_cell
|
|
394
|
+
return concat_cell(e, cells)
|
|
395
|
+
if slot.present is Bound.NEVER:
|
|
396
|
+
return L.nothing()
|
|
397
|
+
from prograph.plan.ir.cypher_temporal_arith import TEMPORAL
|
|
398
|
+
if slot.datatypes and slot.datatype in TEMPORAL: # rule cypher-temporal-arithmetic
|
|
399
|
+
from prograph.plan.ir.cypher_temporal_arith import cell as temporal_cell
|
|
400
|
+
return temporal_cell(e, cells)
|
|
401
|
+
args = [L.expr_cell(a, cells) for a in e.args]
|
|
402
|
+
kinds = [_kind(a.slot) for a in args]
|
|
403
|
+
kind = _result_kind(e.name, kinds)
|
|
404
|
+
values = [a.value for a in args]
|
|
405
|
+
if kind == "string":
|
|
406
|
+
return L.Cell(slot, L.fn("STR_CONCAT", *values))
|
|
407
|
+
if kind == "float":
|
|
408
|
+
x = [L.fn("CAST_DOUBLE", v) if k in ("integer", "decimal") else v for v, k in zip(values, kinds)]
|
|
409
|
+
return L.Cell(slot, _float(e.name, x, L))
|
|
410
|
+
if kind == "decimal":
|
|
411
|
+
return L.Cell(slot, _decimal(e.name, args, kinds, slot, L))
|
|
412
|
+
# 64-bit whatever the operands' SQL width (a literal or an INTEGER column is 32 bits on the engines).
|
|
413
|
+
return L.Cell(slot, _integer(e.name, [L.fn("CAST_LONG", v) for v in values], L))
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _float(op: str, x: List[R.Expr], L) -> R.Expr:
|
|
417
|
+
if op == "NEG":
|
|
418
|
+
return L.fn("*", x[0], L.fn("CAST_DOUBLE", L.text("-1"))) # -(0.0) is -0.0
|
|
419
|
+
a, b = x
|
|
420
|
+
if op in ("+", "-", "*"):
|
|
421
|
+
return L.fn(op, a, b)
|
|
422
|
+
if op == "^":
|
|
423
|
+
return L.fn("POWER", a, b)
|
|
424
|
+
zero = R.CompareExpr(left=b, op="=", right=L.fn("CAST_DOUBLE", L.text("0")))
|
|
425
|
+
if op == "/":
|
|
426
|
+
# x / 0.0: x times Infinity (0 * Infinity and NaN * Infinity are NaN); PostgreSQL raises on it.
|
|
427
|
+
return L.case(zero, L.fn("*", a, L.fn("CAST_DOUBLE", L.text("Infinity"))), L.fn("/", a, b))
|
|
428
|
+
# %: the sign of the dividend, as Java's (the dialects' CYPHER_FLOAT_MOD); x % 0.0 is NaN.
|
|
429
|
+
return L.case(zero, L.fn("*", a, L.fn("CAST_DOUBLE", L.text("NaN"))), L.fn("CYPHER_FLOAT_MOD", a, b))
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _decimal(op: str, args: List["L.Cell"], kinds: List[str], slot: Slot, L) -> R.Expr:
|
|
433
|
+
"""Decimals with decimals or integers, exact as SQL's DECIMAL, at the digits and by the SQL of the decimal
|
|
434
|
+
home SPARQL's arithmetic uses (`facts.decimal_digits`, `lower.exact_decimal`, `lower.exact_quotient`):
|
|
435
|
+
`+`, `-` and `*` exact to 18 places after the point (rounded half away from zero past them) and 38
|
|
436
|
+
digits in all; `/` the quotient rounded at 18 places; `%` the remainder, of the dividend's sign. Where
|
|
437
|
+
SPARQL's value would be unbound (past 38 digits, or a quotient past 20 whole digits) Cypher's is an
|
|
438
|
+
error, as an integer's past 64 bits is; a zero divisor of `/` or `%` raises the integers' error
|
|
439
|
+
(`dialect.ZERO_DIVISOR`). An integer operand is read as its 64 bits."""
|
|
440
|
+
from prograph.plan.ir.facts import RESULT_SCALE, decimal_width, operand_digits
|
|
441
|
+
from prograph.plan.sql.dialect import ZERO_DIVISOR
|
|
442
|
+
values = [a.value if k == "decimal" else L.fn("CAST_LONG", a.value) for a, k in zip(args, kinds)]
|
|
443
|
+
if op == "NEG":
|
|
444
|
+
return L.fn("-", L.integer(0), values[0])
|
|
445
|
+
a, b = values
|
|
446
|
+
both = L.all_of([L.is_null(a, negated=True), L.is_null(b, negated=True)])
|
|
447
|
+
digits = slot.digits or (38, RESULT_SCALE)
|
|
448
|
+
|
|
449
|
+
def raised(message: str) -> R.Expr:
|
|
450
|
+
return L.fn("DECIMAL_SIZED", L.fn("RAISE_ERROR", L.text(message)), L.integer(digits[0]), L.integer(digits[1]))
|
|
451
|
+
|
|
452
|
+
past = "ProGraph: a decimal result past 38 digits"
|
|
453
|
+
if op in ("/", "%"):
|
|
454
|
+
zero = L.all_of([R.CompareExpr(left=b, op="=", right=L.integer(0)), L.is_null(a, negated=True)])
|
|
455
|
+
if op == "/":
|
|
456
|
+
fits, quotient = L.exact_quotient(values, args)
|
|
457
|
+
return L.case(zero, raised(ZERO_DIVISOR), fits, quotient, both, raised(past))
|
|
458
|
+
remainder = L.fn("%", a, b)
|
|
459
|
+
if slot.digits is not None:
|
|
460
|
+
remainder = L.fn("DECIMAL_SIZED", remainder, L.integer(digits[0]), L.integer(digits[1]))
|
|
461
|
+
return L.case(zero, raised(ZERO_DIVISOR), remainder)
|
|
462
|
+
value = L.exact_decimal(op, args, values)
|
|
463
|
+
operands = [operand_digits(x.slot) for x in args]
|
|
464
|
+
if any(d is None for d in operands):
|
|
465
|
+
return value # the database's own exact arithmetic, its overflow its error
|
|
466
|
+
width, places = decimal_width(op, operands)
|
|
467
|
+
if width <= 38 and places <= RESULT_SCALE:
|
|
468
|
+
return value # every result fits: the database's arithmetic as declared
|
|
469
|
+
# Tried per row, NULL where no candidate fits 38 digits (`exact_decimal`): an error here.
|
|
470
|
+
return L.case(L.all_of([both, L.is_null(value)]), raised(past), value)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _integer(op: str, v: List[R.Expr], L) -> R.Expr:
|
|
474
|
+
# The database's 64-bit arithmetic, which raises past 64 bits: DuckDB and PostgreSQL always, Spark
|
|
475
|
+
# and Databricks in the ANSI mode the engine runs its statements in (`graph.ansi_session`).
|
|
476
|
+
if op == "NEG":
|
|
477
|
+
return L.fn("-", L.integer(0), v[0])
|
|
478
|
+
a, b = v
|
|
479
|
+
if op in ("+", "-", "*"):
|
|
480
|
+
return L.fn(op, a, b)
|
|
481
|
+
# Truncated toward zero, a zero divisor raising (the dialects' INT_DIV and INT_MOD).
|
|
482
|
+
return L.fn("INT_DIV" if op == "/" else "INT_MOD", a, b)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
@home("cypher-string-predicates", "Cypher's STARTS WITH, ENDS WITH and CONTAINS, in SQL",
|
|
486
|
+
terms=("STARTS WITH", "ENDS WITH", "CONTAINS", "string predicate"))
|
|
487
|
+
def string_predicate(e: E.Call, cells: Dict[str, "L.Cell"]) -> "L.Cell":
|
|
488
|
+
"""openCypher 9's string predicates: true or false for two strings, by code point (the dialects'
|
|
489
|
+
STR_STARTS, STR_ENDS, STR_CONTAINS), null where an operand is null or not a string."""
|
|
490
|
+
from prograph.plan.ir import lower as L
|
|
491
|
+
args = [L.expr_cell(a, cells) for a in e.args]
|
|
492
|
+
strings = all(a.slot.kinds == {VALUE} and a.slot.datatypes == {xsd.STRING} for a in args)
|
|
493
|
+
if not strings or any(a.slot.present is Bound.NEVER for a in args):
|
|
494
|
+
# A condition (a boolean, never a string) gives null as any other non-string operand does.
|
|
495
|
+
plain = [a for a in args if a.slot.kinds != {LITERAL} or a.slot.datatypes != {xsd.BOOLEAN}]
|
|
496
|
+
if any(a.slot.kinds - {VALUE} for a in plain) or \
|
|
497
|
+
any(UNKNOWN in a.slot.datatypes or len(a.slot.datatypes) > 1 for a in plain):
|
|
498
|
+
raise NotBuilt(f"{e.name} over a value of no one type")
|
|
499
|
+
return L.Cell(BOOLEAN, L.NULL_BOOLEAN)
|
|
500
|
+
return L.Cell(BOOLEAN, L.fn(STRING_PREDICATES[e.name], *(a.value for a in args)))
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _labels(e: E.Call, cells: Dict[str, "L.Cell"]) -> "L.Cell":
|
|
504
|
+
"""`n:A` (HAS_LABEL: true where the node's flag for A is set, false where not, null for a null node)
|
|
505
|
+
and labels(n) (the labels whose flags are set, in name order; null for a null node). The flags are
|
|
506
|
+
the node scan's (rule cypher-node-scan)."""
|
|
507
|
+
from prograph.plan.ir import lower as L
|
|
508
|
+
from prograph.plan.sql import rel_algebra as R
|
|
509
|
+
node = L.expr_cell(e.args[0], cells)
|
|
510
|
+
if e.name == "HAS_LABEL":
|
|
511
|
+
flag = L.expr_cell(e.args[1], cells)
|
|
512
|
+
has = L.FALSE if flag.slot.present is Bound.NEVER else L.is_null(flag.value, negated=True)
|
|
513
|
+
return L.Cell(BOOLEAN, L.case(L.is_null(node.value), L.NULL_BOOLEAN, has))
|
|
514
|
+
from prograph.plan.ir.slot import list_slot
|
|
515
|
+
rest = e.args[1:]
|
|
516
|
+
names = [L.case(L.is_null(L.expr_cell(f, cells).value, negated=True), L.text(k.value))
|
|
517
|
+
for k, f in zip(rest[0::2], rest[1::2])]
|
|
518
|
+
var = R.LitExpr(value="_lb", sql="_lb")
|
|
519
|
+
listed = L.fn("LIST_FILTER", L.fn("ARRAY", *names), var, L.is_null(var, negated=True)) if names else \
|
|
520
|
+
L.fn("LIST_FILTER", L.fn("ARRAY", L.fn("CAST_STRING", L.NULL)), var, L.FALSE)
|
|
521
|
+
return L.Cell(list_slot(xsd.STRING, Bound.MAYBE), L.case(L.is_null(node.value), L.NULL, listed))
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def element_id(e: E.Call, cells: Dict[str, "L.Cell"]) -> "L.Cell":
|
|
525
|
+
"""`ELEMENT_ID(x)` (`cypher_front.node_of_value`): a node's identity as the text a node value holds as its
|
|
526
|
+
`id` (`cypher_answer.node_cell`): of a node of the pattern its identity's text, of a node held as a value
|
|
527
|
+
its `id` field; null for a null node. `ELEMENT_ID(r, field)` of a relationship held as a value: its `id`,
|
|
528
|
+
`type`, `start` or `end` text (`cypher_answer.rel_cell`; `cypher_front.rel_list_conditions`). Part of
|
|
529
|
+
rule cypher-node-of-value. `ELEMENT_ID(x, 'node')`, `id(x)` and `elementId(x)` (rule lpg-view): a node's identity
|
|
530
|
+
text, as `ELEMENT_ID(x)`; of a relationship refused."""
|
|
531
|
+
from prograph.plan.ir import lower as L
|
|
532
|
+
from prograph.plan.ir.cypher_answer import REL_TYPE, element_base, identity_text
|
|
533
|
+
x = L.expr_cell(e.args[0], cells)
|
|
534
|
+
field = e.args[1].value if len(e.args) > 1 else "id"
|
|
535
|
+
slot = value_slot(xsd.STRING, Bound.MAYBE)
|
|
536
|
+
if x.slot.present is Bound.NEVER:
|
|
537
|
+
return L.nothing()
|
|
538
|
+
base = element_base(x.slot.datatype) if x.slot.kinds == {VALUE} and len(x.slot.datatypes) == 1 else None
|
|
539
|
+
if base == REL_TYPE and field in ("type", "start", "end"):
|
|
540
|
+
return L.Cell(slot, L.fn("CYPHER_FIELD_STRING", x.value, L.text(field)))
|
|
541
|
+
if field == "node" and base == REL_TYPE:
|
|
542
|
+
raise NotBuilt("id() or elementId() of a relationship (map the relationship's key column as a property to read it)")
|
|
543
|
+
text = identity_text(x, L) if field in ("id", "node") else None
|
|
544
|
+
if text is not None:
|
|
545
|
+
return L.Cell(slot, text)
|
|
546
|
+
raise NotBuilt("the identity of a value that is not a node or relationship")
|