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,40 @@
1
+ """A schema over source maps compiled elsewhere: provisional and internal.
2
+
3
+ The Cypher TCK harness builds source maps for each scenario's typed tables, and the owned store will
4
+ generate a mapping the same way. Neither is authored in YAML or R2RML, so neither has an authoring
5
+ object. `SourceMapsSchema` carries the maps and the engine-side state a `GraphSchema` holds (column
6
+ types, constraints, prefixes, the base IRI), as `R2RMLSchema` does for an R2RML document: its node and
7
+ relationship mappings stay empty, so nothing reads an authoring object on this path, and the maps are
8
+ what the plan reads (`entry.source_maps`). The public form of this entry is undecided; until then it is reached only through `ProGraph._from_source_maps`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from prograph.schema.mapping import GraphSchema
16
+
17
+
18
+ class SourceMapsSchema(GraphSchema):
19
+ """A schema whose source maps are given, compiled (provisional, internal)."""
20
+
21
+ def __init__(self, maps: Any) -> None:
22
+ settings = maps.settings
23
+ super().__init__(default_catalog=settings.default_catalog, default_schema=settings.default_schema,
24
+ table_qualifications=dict(settings.table_qualifications or ()),
25
+ name=settings.name, base_iri=settings.base_iri)
26
+ self.__dict__["given_source_maps"] = maps
27
+ for prefix, ns in settings.prefixes or ():
28
+ self.add_prefix(prefix, ns)
29
+
30
+ def source_maps(self):
31
+ given = self.__dict__["given_source_maps"]
32
+ if self.__dict__.get("owned_store") is None:
33
+ return given
34
+ # An owned store's maps join the given ones (`r2rml.schema.with_included`), once per store version.
35
+ from prograph.r2rml.schema import store_version, with_included
36
+ cached = self.__dict__.get("_with_store")
37
+ if cached is None or cached[0] != store_version(self):
38
+ cached = (store_version(self), with_included(self, given))
39
+ self.__dict__["_with_store"] = cached
40
+ return cached[1]
@@ -0,0 +1,77 @@
1
+ """One naming rule from an RDF predicate to a relationship type.
2
+
3
+ An RDF predicate's local name is camelCase (`isPartOf`); a relationship type
4
+ is UPPER_SNAKE (`IS_PART_OF`). Each layer used to convert on its own:
5
+ infer-schema, load-ttl and the R2RML bridge upper-cased (`ISPARTOF`), the
6
+ OWL reasoner split on case (`IS_PART_OF`), SPARQL matched the local name as
7
+ written in one place and upper-cased it in another. A schema built by one
8
+ layer then silently matched nothing in the next.
9
+
10
+ Two functions, used by every layer:
11
+
12
+ - ``rel_type_from_local_name`` names a new relationship type, for the
13
+ layers that generate a schema.
14
+ - ``resolve_rel_type`` finds the declared type a name refers to, for the
15
+ layers that read one. It matches ignoring case and underscores, so
16
+ `knows`, `isPartOf`, `ISPARTOF` and `IS_PART_OF` all find a declared
17
+ `IS_PART_OF`, whichever convention the schema used.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from typing import Iterable, Optional
24
+ from prograph.rules import module_home
25
+
26
+ module_home("local-names", "Predicate names",
27
+ terms=("local name", "predicate name", "relationship type", "IRI local name"))
28
+
29
+
30
+ def local_name(iri: str) -> str:
31
+ """An IRI's local name: the text after its last `#`, else after its last `/` (`http://ex/a#b` is
32
+ `b`, `http://ex/a/b` is `b`); the whole IRI where it has neither."""
33
+ text = str(iri)
34
+ if text.endswith(("#", "/")):
35
+ return text # no local name
36
+ for sep in ("#", "/"):
37
+ if sep in text:
38
+ return text.rsplit(sep, 1)[1]
39
+ return text
40
+
41
+
42
+ def rel_type_from_local_name(local: str) -> str:
43
+ """The UPPER_SNAKE relationship type for a predicate's local name:
44
+ `isPartOf` to `IS_PART_OF`, `hasHPCModule` to `HAS_HPC_MODULE`,
45
+ `knows` to `KNOWS`. A name with no lower-case letter is kept as it is."""
46
+ if not any(ch.islower() for ch in local):
47
+ return local
48
+ out = []
49
+ for i, ch in enumerate(local):
50
+ if ch.isupper() and i > 0:
51
+ prev, nxt = local[i - 1], local[i + 1] if i + 1 < len(local) else ""
52
+ if prev.islower() or prev.isdigit() or (prev.isupper() and nxt.islower()):
53
+ out.append("_")
54
+ out.append("_" if ch in "-. " else ch.upper())
55
+ return re.sub(r"_+", "_", "".join(out)).strip("_")
56
+
57
+
58
+ def column_from_local_name(local: str) -> str:
59
+ """The snake_case column or property name for a predicate's local name,
60
+ by the same split as relationship types: `wearIndex` to `wear_index`,
61
+ `hasHPCModule` to `has_hpc_module`, `HPC` to `hpc`."""
62
+ return rel_type_from_local_name(local).lower()
63
+
64
+
65
+ def _key(name: str) -> str:
66
+ return re.sub(r"[^0-9a-z]", "", name.lower())
67
+
68
+
69
+ def resolve_rel_type(name: str, rel_types: Iterable[str]) -> Optional[str]:
70
+ """The declared relationship type `name` refers to: an exact match, or
71
+ else the one type equal to it ignoring case and underscores. None when
72
+ there is no such type, or more than one."""
73
+ types = list(dict.fromkeys(rel_types))
74
+ if name in types:
75
+ return name
76
+ matches = [t for t in types if _key(t) == _key(name)]
77
+ return matches[0] if len(matches) == 1 else None
@@ -0,0 +1,59 @@
1
+ """The column types of an rr:sqlQuery source (R2RML 5.2) over frames: the query described where the
2
+ frames are read, DuckDB's DESCRIBE over the embedded connection, or the Spark DataFrame's schema.
3
+ Metadata, not a query's result rows (the result path is elsewhere). The types are keyed by
4
+ the source map's name for the query (`Source.table`), the name the planner asks by, and by the
5
+ schema's (`source_queries`)."""
6
+
7
+ from typing import Any
8
+
9
+
10
+ def describe(engine: Any, schema: Any) -> None:
11
+ """Record each query source's column types on `schema.column_types`; a query not described
12
+ keeps none (its literals are not built), and is logged."""
13
+ from prograph.schema import collations as C
14
+ from prograph.schema import types as T
15
+ graph = getattr(getattr(engine, "executor", None), "graph", None)
16
+ queries = dict(schema.source_queries or {})
17
+ try:
18
+ from prograph.plan.ir.entry import source_maps
19
+ maps = source_maps(schema)
20
+ for m in list(maps.nodes) + list(maps.edges):
21
+ source = getattr(m, "source", None)
22
+ if source is not None and source.query is not None:
23
+ queries.setdefault(source.table, source.query)
24
+ except Exception: # noqa: BLE001 - a mapping the one plan does not read has no source maps
25
+ pass
26
+ for table, query in queries.items():
27
+ if table in schema.column_types:
28
+ continue
29
+ try:
30
+ if getattr(graph, "_local_sql", None) is not None:
31
+ described = graph._run_local_sql(f"DESCRIBE {query}").fetchall()
32
+ # The frames are read through DuckDB: its strings compare bytes, unless the query collates.
33
+ schema.column_types[table] = C.mark_bytewise(
34
+ {str(r[0]): T.of_sql_type(str(r[1])) for r in described}, 'duckdb',
35
+ C.binary if "COLLATE" not in str(query).upper() else C.unknown)
36
+ elif getattr(engine, "backend", None) == "spark" and getattr(graph, "dataframes", None):
37
+ spark = next(iter(graph.dataframes.values())).sparkSession
38
+ if hasattr(graph, "_ensure_temp_views"):
39
+ graph._ensure_temp_views()
40
+ kinds = dict(spark.sql(query).dtypes)
41
+ schema.column_types[table] = C.mark_bytewise(
42
+ {name: T.of_sql_type(kind, timestamp_is_an_instant=True) for name, kind in kinds.items()},
43
+ 'spark', lambda c, kinds=kinds: C.collation_in_type(kinds.get(c, "")))
44
+ except Exception as exc: # noqa: BLE001 - a query's types are read where they can be
45
+ from prograph.logging import get_plan_logger
46
+ get_plan_logger().warning("column_types_skip", reason="query_not_described",
47
+ table=table, error=str(exc)[:200])
48
+ # The database refused the query: R2RML 5.2 makes an rr:sqlQuery the database's own SQL, so
49
+ # one written for another (PostgreSQL's double-quoted names, read by Spark as strings)
50
+ # cannot be read here at all. Say so now, not later as a value of no type.
51
+ from prograph.r2rml.compile import R2RMLMappingError
52
+ backend = getattr(engine, "backend", None) or "this backend"
53
+ said = next((line.strip() for line in str(exc).splitlines() if line.strip()), type(exc).__name__)
54
+ shown = " ".join(str(query).split())
55
+ raise R2RMLMappingError(
56
+ f"the rr:sqlQuery {shown[:160]!r}{'...' if len(shown) > 160 else ''} does not run on "
57
+ f"{backend}: {said[:300]}. An rr:sqlQuery is the database's own SQL "
58
+ f"(R2RML 5.2): write it in {backend}'s dialect, or export the mapping for it "
59
+ f"(to_r2rml(..., dialect=...))") from exc
@@ -0,0 +1,215 @@
1
+ """Reading a mapped backend's rows, one way, for everything that projects them.
2
+
3
+ The RDF-facing parts of ProGraph all do the same thing: walk a mapping's rows,
4
+ derive an IRI from the id column, emit statements. IRIs already have one
5
+ resolver (:mod:`prograph.schema.iri`); this is the other half, the values that
6
+ resolver is given.
7
+
8
+ It matters because reading rows is not neutral. Pandas' ``iterrows()`` builds a
9
+ Series per row, which forces a single dtype across the row: a table whose
10
+ columns are all numeric, an ``_inferred`` flag stored as 1/0 is enough to make
11
+ one, has its integer ids upcast, so an id of ``1`` arrives as ``1.0``. Two
12
+ projections reading rows two different ways then disagree about the same entity:
13
+ the old SHACL reader emitted ``…/m/1`` while provenance keyed ``…/m/1.0``, nothing
14
+ raised, and the join between a violation and its lineage silently never matched.
15
+ An action layer reads that miss as "the fact was asserted".
16
+
17
+ Column-wise reading also preserves the declared datatype (an id column stays
18
+ ``xsd:integer``, so an ``sh:datatype xsd:integer`` constraint is satisfiable at
19
+ all) and is ~100x faster; ``iterrows`` was a quarter of the bridge's runtime.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Dict, Iterator, List, Optional
25
+ from prograph.rules import module_home
26
+
27
+ module_home("mapping-rows", "Rows a mapping owns",
28
+ terms=("filter_predicate", "rows a mapping owns", "IS NULL", "discriminator"))
29
+
30
+
31
+ def _is_pandas_df(df: Any) -> bool:
32
+ try:
33
+ import pandas as pd
34
+ return isinstance(df, pd.DataFrame)
35
+ except ImportError: # pragma: no cover
36
+ return False
37
+
38
+
39
+ def _is_spark_df(df: Any) -> bool:
40
+ return (
41
+ df is not None
42
+ and not _is_pandas_df(df)
43
+ and hasattr(df, "schema")
44
+ and hasattr(df, "rdd")
45
+ )
46
+
47
+
48
+ def _column_values(column: Any) -> list:
49
+ """A pandas column as Python values. A nullable extension column
50
+ (`Int64`, `boolean`) marks a missing value pd.NA, which raises when
51
+ compared; it is None here, as on the SQL path. Done per column."""
52
+ import pandas as pd
53
+ if pd.api.types.is_extension_array_dtype(column.dtype):
54
+ return column.astype(object).where(column.notna(), None).tolist()
55
+ return column.tolist()
56
+
57
+
58
+ def iter_rows(df: Any) -> Iterator[Dict[str, Any]]:
59
+ """Rows of a Pandas or Spark DataFrame as dicts.
60
+
61
+ Anything else, including ``None``, which is what a schema mapping whose
62
+ table isn't loaded resolves to, yields nothing.
63
+ """
64
+ if _is_pandas_df(df):
65
+ columns = list(df.columns)
66
+ if not columns:
67
+ return
68
+ for values in zip(*(_column_values(df[column]) for column in columns)):
69
+ yield dict(zip(columns, values))
70
+ elif _is_spark_df(df):
71
+ for r in df.collect():
72
+ yield r.asDict()
73
+ else:
74
+ return
75
+
76
+
77
+ def iter_inferred_rows(df: Any) -> Iterator[Dict[str, Any]]:
78
+ """Rows a reasoner materialized. Those whose ``_inferred`` flag is truthy.
79
+
80
+ The flag is tested on the fetched value rather than by dtype or in a SQL
81
+ predicate, because backends store it as BOOLEAN, NUMBER(1) or BIT, and
82
+ because tables no reasoner has written to carry no such column at all.
83
+ """
84
+ for row in iter_rows(df):
85
+ flag = row.get("_inferred")
86
+ # A frame where only entailed rows carry the flag holds NaN on the
87
+ # asserted ones, and NaN != 0: they read as entailed.
88
+ if flag is not None and flag == flag and flag is not False and flag != 0:
89
+ yield row
90
+
91
+
92
+ __all__ = ["iter_rows", "iter_inferred_rows", "owned_column_mask", "owned_condition",
93
+ "owned_rows", "row_owned_by"]
94
+
95
+
96
+ def owned_column_mask(column: Any, value: Any) -> Any:
97
+ """Which rows of a pandas column hold `value` of a ``filter_predicate``.
98
+
99
+ The pandas form of the rule "this row is the mapping's own", and the
100
+ one place that knows a None value means the column IS NULL:
101
+ the rows where it is missing (None, NaN, NaT, pd.NA). Any other value
102
+ is equality, so a missing value never matches it. The SQL forms are
103
+ ``prograph.writes.column_condition`` (text) and
104
+ ``prograph.plan.interpreter.expr_translator.owned_column_test``
105
+ (structured); the Spark form is :func:`owned_condition` (a whole
106
+ mapping at once); the form for
107
+ a row held as a dict is :func:`row_owned_by`.
108
+ """
109
+ from prograph.schema.types import missing_mask
110
+
111
+ return missing_mask(column) if value is None else column == value
112
+
113
+
114
+ def row_owned_by(row: Any, predicate: Any) -> bool:
115
+ """The per-row form of :func:`owned_column_mask`: whether a row (a dict
116
+ or a Series) holds every value of `predicate`, a None being a missing
117
+ one. No predicate is every row."""
118
+ from prograph.schema.types import is_missing
119
+
120
+ return all(is_missing(row.get(column)) if value is None else row.get(column) == value
121
+ for column, value in (predicate or {}).items())
122
+
123
+
124
+ def owned_condition(mapping: Any, column_of: Any, present: Any = None) -> Any:
125
+ """Whether a row is one `mapping` owns, as a Spark Column: true or false,
126
+ never null. None when the mapping has no ``filter_predicate``.
127
+
128
+ The Spark form of :func:`owned_column_mask`, and so the Spark home of
129
+ the rule that a None value means the column IS NULL. Any other
130
+ value is equality, which a null column does not satisfy (false, not
131
+ null).
132
+
133
+ `column_of(name)` is the Spark Column holding the table column `name`
134
+ in the DataFrame being read; `present`, when given, is the column names
135
+ that DataFrame has, and a discriminator it lacks is skipped (as
136
+ `owned_rows` does). A row filter and a per-row test are one rule: both
137
+ come from here."""
138
+ from pyspark.sql import functions as F
139
+ tests = []
140
+ for column, value in (getattr(mapping, "filter_predicate", None) or {}).items():
141
+ if present is not None and column not in present:
142
+ continue
143
+ if value is None:
144
+ tests.append(column_of(column).isNull())
145
+ else:
146
+ tests.append(F.coalesce(column_of(column) == F.lit(value), F.lit(False)))
147
+ if not tests:
148
+ return None
149
+ condition = tests[0]
150
+ for test in tests[1:]:
151
+ condition = condition & test
152
+ return condition
153
+
154
+
155
+ def owned_rows(frame: Any, mapping: Any) -> Any:
156
+ """The rows of `frame` that `mapping` owns.
157
+
158
+ `frame` is the mapping's source table as a pandas or a Spark DataFrame.
159
+ A mapping with a ``filter_predicate`` owns the rows whose discriminator
160
+ columns hold its values (a None value: the column has none): labels that share a table (Person and Robot
161
+ in one `entity` table) each see their own rows, and a relationship
162
+ mapping its own edges. With no ``filter_predicate`` the mapping owns
163
+ the table. A discriminator column the frame does not have is skipped,
164
+ as a frame that is one label's rows already may not carry it.
165
+
166
+ The one place the rule is applied to a DataFrame; the graphs call it
167
+ wherever they read a mapping's table. In SQL the same rule is the
168
+ interpreter's `_apply_filter_predicate`.
169
+ """
170
+ predicate = getattr(mapping, "filter_predicate", None)
171
+ if frame is None or not predicate:
172
+ return frame
173
+ if _is_spark_df(frame):
174
+ # The dialect quotes the name: a column called `a.b` is one column,
175
+ # not field b of a.
176
+ from pyspark.sql import functions as F
177
+ from prograph.plan.sql.dialect import get_dialect_instance
178
+ quote = get_dialect_instance("spark").quote
179
+ condition = owned_condition(mapping, lambda c: F.col(quote(c)), set(frame.columns))
180
+ return frame if condition is None else frame.filter(condition)
181
+ for column, value in predicate.items():
182
+ if column not in frame.columns:
183
+ continue
184
+ frame = frame[owned_column_mask(frame[column], value)]
185
+ return frame
186
+
187
+
188
+ # The SQL text form of "a row this mapping owns" (moved from prograph.writes).
189
+
190
+ def owned_values(mapping: Any) -> Dict[str, Any]:
191
+ """The column values that make a row one this mapping owns: its
192
+ `filter_predicate`, which tells apart the labels, or the relationship
193
+ types, that share a table. A write reads them as conditions; a CREATE
194
+ writes them, or the row it made belongs to no label and no type."""
195
+ return dict(mapping.filter_predicate or {}) # a None value: the column is NULL
196
+
197
+
198
+ def column_condition(column_sql: str, value: Any, literal: Any) -> str:
199
+ """One SQL test of the rule "this row is the mapping's own": `column_sql`
200
+ (already quoted, and qualified if need be) equals the value, or IS NULL
201
+ when the value is None. A ``filter_predicate`` value of None means the
202
+ column has none; ``= NULL`` is never true. `literal` writes a
203
+ value as SQL text in the target dialect. The one home of the SQL text
204
+ form: every statement and view that renders a ``filter_predicate``
205
+ calls it (the pandas, Spark and structured forms are in
206
+ ``prograph.schema.rows`` and ``expr_translator.owned_column_test``)."""
207
+ return f"{column_sql} IS NULL" if value is None else f"{column_sql} = {literal(value)}"
208
+
209
+
210
+ def owned_conditions(mapping: Any, dialect: Any, alias: Optional[str] = None) -> List[str]:
211
+ """The SQL conditions for "a row this mapping owns"
212
+ (:func:`owned_values`), the columns qualified by `alias` if given."""
213
+ prefix = f"{alias}." if alias else ""
214
+ return [column_condition(f"{prefix}{dialect.quote(column)}", value, dialect.literal)
215
+ for column, value in owned_values(mapping).items()]