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,198 @@
1
+ """Which string columns compare byte for byte (rule `string-compares-bytes`).
2
+
3
+ A string column's SQL equality is the equality of its bytes only under its engine's and its
4
+ collation's say: DuckDB, PostgreSQL (a deterministic collation), Spark and Databricks (UTF8_BINARY)
5
+ compare so; a collation that folds case or accents, or trims trailing spaces (Databricks *_RTRIM),
6
+ does not, and neither do MySQL, SQL Server and Oracle (PAD SPACE: 'a' = 'a '). The engine records
7
+ the fact on each column's type (`types.CypherType.bytewise`) from the catalog; an IRI over such a
8
+ column may then be held as its value (`plan.ir.slot.held_as_values`). Catalog metadata only: no
9
+ query's result passes through here.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import replace
16
+ from typing import Any, Callable, Dict, List, Optional
17
+
18
+ from prograph.rules import home
19
+ from prograph.schema import types as T
20
+
21
+ # Engines whose string equality is byte equality under the binary (or a deterministic) collation.
22
+ BYTE_EQUAL_ENGINES = frozenset({'duckdb', 'postgresql', 'spark', 'databricks_sql'})
23
+
24
+ Collations = Callable[[str], Optional[str]]
25
+
26
+
27
+ def unknown(column: str) -> Optional[str]:
28
+ """No column's collation is known."""
29
+ return None
30
+
31
+
32
+ def binary(column: str) -> Optional[str]:
33
+ """Every column's collation is the binary one."""
34
+ return ""
35
+
36
+
37
+ @home("string-compares-bytes", "Whether a string column's SQL equality is the equality of its bytes",
38
+ terms=("collation", "COLLATE", "PAD SPACE", "bytewise", "binary collation", "UTF8_LCASE", "RTRIM",
39
+ "deterministic collation"))
40
+ def compares_bytes(backend: Optional[str], kind: T.CypherType, collation: Optional[str]) -> bool:
41
+ """Whether `=` on the column (and DISTINCT, GROUP BY, a join) holds exactly where the bytes are
42
+ equal: a STRING column, not CHAR(n), on DuckDB, PostgreSQL, Spark or Databricks, under a collation
43
+ that compares bytes. `collation` is what the catalog says, as the engine read it: "" for one that
44
+ compares bytes (none written, DuckDB with no `default_collation`, Databricks' UTF8_BINARY, a
45
+ PostgreSQL deterministic collation, the database's default included); a name for another (DuckDB
46
+ NOCASE, Databricks UTF8_LCASE or any *_RTRIM, a PostgreSQL nondeterministic one); None where
47
+ unknown, which is not exact. A type that compares otherwise whatever its collation (PostgreSQL's
48
+ CITEXT, `types.of_sql_type` marks it `collated`) never does. Frames (pandas, Arrow) are read as `duckdb`, Spark frames as `spark`.
49
+ Never on MySQL, SQL Server or Oracle (PAD SPACE)."""
50
+ return (backend in BYTE_EQUAL_ENGINES and kind == T.STRING and not kind.padded and not kind.collated
51
+ and collation is not None and collation == "")
52
+
53
+
54
+ def collation_in_type(sql_type: Any) -> str:
55
+ """The collation a Spark or Databricks type text names (`string collate UTF8_LCASE`), "" for the
56
+ binary one (none written, or UTF8_BINARY)."""
57
+ found = re.search(r'\bCOLLATE\s+([A-Za-z0-9_.]+)', str(sql_type), re.IGNORECASE)
58
+ if found is None or found.group(1).upper() == 'UTF8_BINARY':
59
+ return ""
60
+ return found.group(1)
61
+
62
+
63
+ def mark_bytewise(types: Dict[str, T.CypherType], backend: Optional[str],
64
+ collation_of: Collations) -> Dict[str, T.CypherType]:
65
+ """`types` with each STRING column that compares bytes (`compares_bytes`) marked `bytewise`, and each
66
+ one a DuckDB or PostgreSQL collation is known to compare otherwise (DuckDB NOCASE, a PostgreSQL
67
+ nondeterministic collation) marked `collated`: a plan reads it under the binary collation (reader
68
+ BINARY_TEXT), as SPARQL and Cypher compare code points, and PostgreSQL refuses a regular expression
69
+ (the IRI's escaping) on a nondeterministic one. Spark's and Databricks' are marked by their type text
70
+ (`types.of_sql_type`)."""
71
+ out = dict(types)
72
+ for column, kind in types.items():
73
+ if kind != T.STRING or kind.uuid:
74
+ continue
75
+ collation = collation_of(column)
76
+ if compares_bytes(backend, kind, collation):
77
+ out[column] = replace(kind, bytewise=True)
78
+ elif backend in ("duckdb", "postgresql") and collation != "" and not kind.padded:
79
+ # Known to compare otherwise, or unknown (a view or query over a collated table): read under the
80
+ # binary collation, which changes nothing for a column that compares bytes already.
81
+ out[column] = replace(kind, collated=True)
82
+ return out
83
+
84
+
85
+ def string_collations(conn: Any, backend: Optional[str], table: str, query: Optional[str] = None,
86
+ written: Optional[str] = None, described=()) -> Collations:
87
+ """Each column's collation of a source on a SQL connection, as `compares_bytes` reads it;
88
+ `described` the (column, type text) pairs the engine read. Unknown (None) where the catalog
89
+ cannot say; a read that fails says nothing."""
90
+ try:
91
+ if backend == 'databricks_sql':
92
+ kinds = {str(c).lower(): k for c, k in described}
93
+ return lambda column: collation_in_type(kinds.get(column.lower(), ""))
94
+ if backend == 'duckdb':
95
+ return _duckdb(conn, written or table, query)
96
+ if backend == 'postgresql' and query is None:
97
+ return _postgresql(conn, table, written)
98
+ except Exception: # noqa: BLE001 - no collation read: not exact
99
+ pass
100
+ return unknown
101
+
102
+
103
+ def _duckdb(conn: Any, table: str, query: Optional[str]) -> Collations:
104
+ """DuckDB keeps a column's collation in its type, which DESCRIBE and information_schema leave out:
105
+ it is in the table's CREATE text (`duckdb_tables().sql`), and `default_collation` gives one to every
106
+ string. A view or a query is known only where no table, view or query in the catalog writes COLLATE."""
107
+ default = conn.execute("SELECT current_setting('default_collation')").fetchall()[0][0]
108
+ if default:
109
+ return lambda column: str(default)
110
+ tables = conn.execute("SELECT database_name, schema_name, table_name, sql FROM duckdb_tables()").fetchall()
111
+ views = conn.execute("SELECT sql FROM duckdb_views() WHERE NOT internal").fetchall()
112
+ anywhere = any("COLLATE" in str(r[-1] or "").upper() for r in list(tables) + list(views))
113
+ if query is not None:
114
+ return binary if not anywhere and "COLLATE" not in query.upper() else unknown
115
+ if not anywhere:
116
+ return binary
117
+ parts = [p.lower() for p in _name_parts(table)]
118
+ found = [r for r in tables
119
+ if [str(x).lower() for x in r[:3]][-len(parts):] == parts]
120
+ if len(found) != 1:
121
+ return unknown
122
+ columns = _create_columns(str(found[0][3] or ""))
123
+ if columns is None:
124
+ return unknown
125
+ return lambda column: columns.get(column.lower())
126
+
127
+
128
+ def _name_parts(name: str) -> List[str]:
129
+ """A dotted name's parts, a double-quoted part kept whole."""
130
+ return [p[1:-1].replace('""', '"') if p[:1] == '"' else p
131
+ for p in re.findall(r'"(?:[^"]|"")*"|[^.]+', name)]
132
+
133
+
134
+ def _create_columns(sql: str) -> Optional[Dict[str, str]]:
135
+ """Each column of a DuckDB CREATE TABLE text, by lower-case name: "" where its definition writes
136
+ no COLLATE, else "COLLATE"; None where the text is not read."""
137
+ start = sql.find("(")
138
+ if start < 0:
139
+ return None
140
+ defs, depth, quote, current = [], 0, None, ""
141
+ for ch in sql[start + 1:]:
142
+ if quote:
143
+ current += ch
144
+ if ch == quote:
145
+ quote = None
146
+ continue
147
+ if ch in "\"'":
148
+ quote = ch
149
+ elif ch == "(":
150
+ depth += 1
151
+ elif ch == ")":
152
+ if depth == 0:
153
+ defs.append(current)
154
+ break
155
+ depth -= 1
156
+ elif ch == "," and depth == 0:
157
+ defs.append(current)
158
+ current = ""
159
+ continue
160
+ current += ch
161
+ out: Dict[str, str] = {}
162
+ for d in defs:
163
+ d = d.strip()
164
+ named = re.match(r'"((?:[^"]|"")*)"|([A-Za-z_][A-Za-z0-9_$]*)', d)
165
+ if named is None:
166
+ return None
167
+ name = named.group(1).replace('""', '"') if named.group(1) is not None else named.group(2)
168
+ if name.upper() in ("PRIMARY", "UNIQUE", "CHECK", "FOREIGN", "CONSTRAINT") and named.group(1) is None:
169
+ continue
170
+ out[name.lower()] = "COLLATE" if "COLLATE" in d.upper() else ""
171
+ return out
172
+
173
+
174
+ def _postgresql(conn: Any, table: str, written: Optional[str]) -> Collations:
175
+ """PostgreSQL's columns' collations (information_schema.columns.collation_name, NULL for the
176
+ database's default, which is deterministic) and whether a named one is deterministic
177
+ (pg_collation.collisdeterministic, PostgreSQL 12+)."""
178
+ from prograph.graph.drivers import fetch_rows
179
+ from prograph.plan.sql.dialect import get_dialect_instance
180
+ dialect = get_dialect_instance('postgresql')
181
+ marker, fold = dialect.param_placeholder, dialect.fold_identifier
182
+ schema_name, _, name = table.rpartition('.')
183
+ delimited = [p[:1] == '"' for p in str(written or table).split('.')]
184
+ sql = ("SELECT c.column_name, c.collation_name, (SELECT co.collisdeterministic FROM pg_catalog.pg_collation co "
185
+ "JOIN pg_catalog.pg_namespace n ON n.oid = co.collnamespace WHERE co.collname = c.collation_name "
186
+ "AND n.nspname = c.collation_schema) FROM information_schema.columns c "
187
+ f"WHERE c.table_name = {marker(1)}")
188
+ params = [name if delimited[-1] else fold(name)]
189
+ if schema_name:
190
+ sql += f" AND c.table_schema = {marker(2)}"
191
+ part = schema_name.split('.')[-1]
192
+ params.append(part if len(delimited) > 1 and delimited[-2] else fold(part))
193
+ rows = fetch_rows(conn, sql, tuple(params))[1]
194
+ out: Dict[str, Optional[str]] = {}
195
+ for column, collation, deterministic in rows:
196
+ out[str(column)] = "" if collation is None or deterministic is True else (
197
+ str(collation) if deterministic is False else None)
198
+ return lambda column: out.get(column)
@@ -0,0 +1,388 @@
1
+ """A YAML or Python schema as source maps, and back.
2
+
3
+ `compile_schema(schema)` gives the `SourceMaps` of a `GraphSchema`, built
4
+ from a YAML file, Python, or (for now) the R2RML
5
+ bridge's output. `project(maps)` gives the property-graph schema back,
6
+ exactly: the round trip
7
+ (`tests/schema/test_source_maps_round_trip.py`).
8
+
9
+ The terms are the ones `prograph.schema.iri` decides today: a subject is
10
+ `node_iri_template`, a class `class_iri`, a predicate `property_iri` and
11
+ `relationship_iri`. Compiling decides nothing of its own.
12
+
13
+ Every node mapping is kept, a second mapping of one label too, which
14
+ `GraphSchema.get_node_mapping` hides: its id is
15
+ `Label#2`. An edge's end names its label's first map, the one every reader
16
+ of the label reads today.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from functools import lru_cache
22
+ from dataclasses import replace
23
+ from typing import Any, Dict, List, Optional, Tuple
24
+
25
+ from prograph.rules import home
26
+
27
+ from prograph.schema.iri import is_column_valued, node_iri_template, template_parts
28
+ from prograph.schema.source_map import (
29
+ IRI,
30
+ LITERAL,
31
+ EdgeMap,
32
+ EndRef,
33
+ Key,
34
+ NodeMap,
35
+ PredicateDeclaration,
36
+ PredicateObject,
37
+ Settings,
38
+ Source,
39
+ SourceMaps,
40
+ TermMap,
41
+ names_one_key,
42
+ subject_identity_of,
43
+ )
44
+
45
+
46
+ def _pairs(value: Optional[Dict[Any, Any]]) -> Optional[Tuple[Tuple[Any, Any], ...]]:
47
+ return None if value is None else tuple(value.items())
48
+
49
+
50
+ def _source(mapping: Any) -> Source:
51
+ return Source(table=mapping.source_table, qualified=mapping.qualified_source_table,
52
+ query=getattr(mapping, "source_query", None),
53
+ filter=_pairs(getattr(mapping, "filter_predicate", None)))
54
+
55
+
56
+ @lru_cache(maxsize=4096)
57
+ def _iri_term(template: str, synthesized: bool = False) -> TermMap:
58
+ """An IRI term map from a template's text: a column-valued template
59
+ (`{uri}`) is its column. Frozen, so one per text is kept."""
60
+ parts = tuple(template_parts(template))
61
+ if is_column_valued(template):
62
+ return TermMap(IRI, column=parts[0][0], synthesized=synthesized)
63
+ return TermMap(IRI, template=parts, synthesized=synthesized)
64
+
65
+
66
+ def _subject(mapping: Any) -> TermMap:
67
+ return _iri_term(node_iri_template(mapping), synthesized=not mapping.iri_template)
68
+
69
+
70
+ def _parts(mapping: Any, alone: bool = False) -> Tuple[Source, Key, TermMap]:
71
+ """A node mapping's source, key and subject: its compiled map's, read
72
+ from its schema's cached source maps (`GraphSchema.node_map`). A
73
+ mapping no schema holds, or any with `alone` (a schema being built,
74
+ whose every change would compile it again), is compiled alone, to the
75
+ same parts."""
76
+ schema = None if alone else getattr(mapping, "_schema", None)
77
+ node = schema.node_map(mapping) if schema is not None else None
78
+ if node is not None:
79
+ return node.source, node.key, node.subject
80
+ return _source(mapping), Key(columns=tuple(mapping.id_columns)), _subject(mapping)
81
+
82
+
83
+ def mapping_subject_identity(mapping: Any, alone: bool = False) -> Tuple[Any, ...]:
84
+ """The subject identity (`prograph.schema.source_map.subject_identity_of`)
85
+ of a node mapping, for a caller holding a `NodeMapping` where one
86
+ holding a `NodeMap` asks `SourceMaps.subject_identity`."""
87
+ if alone:
88
+ return _identity_alone(mapping.qualified_source_table,
89
+ getattr(mapping, "source_query", None),
90
+ node_iri_template(mapping), not mapping.iri_template,
91
+ tuple(mapping.id_columns))
92
+ source, key, subject = _parts(mapping)
93
+ return subject_identity_of(source, key, subject)
94
+
95
+
96
+ @lru_cache(maxsize=65536)
97
+ def _identity_alone(qualified: str, query: Optional[str], template: str,
98
+ synthesized: bool, key: Tuple[str, ...]) -> Tuple[Any, ...]:
99
+ """A subject identity from what it is made of, kept per text: the R2RML
100
+ bridge asks it for every pair of relationship mappings it adds (NPD's
101
+ 1,068 ask 1.1 million times)."""
102
+ return subject_identity_of(Source(table="", qualified=qualified, query=query),
103
+ Key(columns=key), _iri_term(template, synthesized))
104
+
105
+
106
+ def subject_names_one_key(mapping: Any) -> bool:
107
+ """`SourceMaps.subject_names_one_key` of a node mapping: whether its
108
+ subject is written from its whole key."""
109
+ _, key, subject = _parts(mapping)
110
+ return names_one_key(key, subject)
111
+
112
+
113
+ def _declaration(schema: Any, iri: str, label: str, prop: str) -> Optional[Any]:
114
+ """The PredicateMapping that publishes `prop` of `label` under `iri`:
115
+ the label's own declaration, else one for no label, else another
116
+ label's whose rows hold this label's (`find_predicate_iri_for_property`
117
+ resolves the IRI so). Not the IRI's representative, which may be
118
+ another label's declaration with another datatype."""
119
+ from prograph.schema.mapping import PredicateKind
120
+ declared = [pm for pm in schema.predicate_declarations(iri)
121
+ if pm.kind == PredicateKind.DATATYPE and pm.property_name == prop]
122
+ for wanted in (label, None):
123
+ for pm in declared:
124
+ if pm.node_label == wanted:
125
+ return pm
126
+ return declared[0] if declared else None
127
+
128
+
129
+ def _predicate_objects(schema: Any, mapping: Any) -> Tuple[PredicateObject, ...]:
130
+ from prograph.schema.iri import property_iri
131
+ found = []
132
+ from prograph.schema.mapping import PredicateKind
133
+ for prop, column in (mapping.property_columns or {}).items():
134
+ # A property its label publishes under several predicates (e:m and
135
+ # e:j for one column) gives a triple under each; else the one IRI
136
+ # `property_iri` resolves.
137
+ iris = list(dict.fromkeys(
138
+ pm.predicate_iri
139
+ for declared in getattr(schema, "_predicate_mappings_by_iri", {}).values()
140
+ for pm in declared
141
+ if pm.kind == PredicateKind.DATATYPE and pm.property_name == prop
142
+ and pm.node_label == mapping.label))
143
+ for iri in iris or [property_iri(schema, mapping.label, prop)]:
144
+ pm = _declaration(schema, iri, mapping.label, prop)
145
+ found.append(PredicateObject(
146
+ predicate=iri,
147
+ object=TermMap(LITERAL, column=column,
148
+ datatype=getattr(pm, "datatype", None),
149
+ language=getattr(pm, "language", None),
150
+ language_column=getattr(pm, "language_column", None)),
151
+ property_name=prop, graph=mapping.graph_iri))
152
+ return tuple(found)
153
+
154
+
155
+ def _unique_id(name: str, used: set) -> str:
156
+ """`name` for its first map, `name#2` for the second, and on, stepping
157
+ over an id already taken."""
158
+ candidate, count = name, 1
159
+ while candidate in used:
160
+ count += 1
161
+ candidate = f"{name}#{count}"
162
+ used.add(candidate)
163
+ return candidate
164
+
165
+
166
+ def _end(columns: List[str], listed: bool, label: str,
167
+ node: Optional[NodeMap]) -> EndRef:
168
+ """An edge's end: its label's first map, and that map's subject over
169
+ the edge's columns in place of its key."""
170
+ if node is None:
171
+ return EndRef(map_id=None, label=label, columns=tuple(columns), listed=listed,
172
+ term=None, exists=True)
173
+ term = None
174
+ renamed = dict(zip(node.key.columns, columns))
175
+ subject = node.subject
176
+ if len(columns) == len(node.key.columns) and set(subject.columns()) <= set(renamed):
177
+ if subject.template is not None:
178
+ term = TermMap(IRI, template=tuple((renamed[t] if is_col else t, is_col)
179
+ for t, is_col in subject.template),
180
+ synthesized=subject.synthesized)
181
+ elif subject.column is not None:
182
+ term = TermMap(IRI, column=renamed[subject.column],
183
+ synthesized=subject.synthesized)
184
+ return EndRef(map_id=node.id, label=label, columns=tuple(columns), listed=listed,
185
+ term=term, exists=True)
186
+
187
+
188
+ @home("edge-ends", "A relationship's ends over its labels' node mappings",
189
+ terms=("relationship end", "edge end", "two maps of one label", "end label", "first map of a label", "peers"))
190
+ def _end_choices(columns: List[str], listed: bool, label: str, maps: List[NodeMap]) -> List[EndRef]:
191
+ """An edge's possible ends: one per distinct subject among its label's node maps (the first map giving
192
+ it, the others its `peers`); the label's first map's alone where they give one subject, or no map's
193
+ where the label has none."""
194
+ if not maps:
195
+ return [_end(columns, listed, label, None)]
196
+ # A map whose key is not as wide as the edge's columns names no node of them (unless none is).
197
+ maps = [n for n in maps if len(n.key.columns) == len(columns)] or maps[:1]
198
+ out: List[EndRef] = []
199
+ for node in maps:
200
+ ref = _end(columns, listed, label, node)
201
+ same = next((i for i, o in enumerate(out) if o.term is not None and o.term == ref.term), None)
202
+ if same is None:
203
+ out.append(ref)
204
+ else:
205
+ out[same] = replace(out[same], peers=out[same].peers + (node.id,))
206
+ return out
207
+
208
+
209
+ def _end_maps(r: Any, side: str, nodes: List[NodeMap], maps_of_label: Dict[str, List[NodeMap]]) -> List[NodeMap]:
210
+ """The node maps a relationship mapping's end may name: its label's, or, for an end given by an identity
211
+ (`end_node_identity`), the maps declaring that identity, whatever their labels (refused where none
212
+ does)."""
213
+ named = getattr(r, f"{side}_node_identity", None)
214
+ if named is None:
215
+ return maps_of_label.get(getattr(r, f"{side}_node_label"), [])
216
+ found = [n for n in nodes if n.identity == named]
217
+ if not found:
218
+ raise ValueError(f"the relationship mapping {r.rel_type!r} gives its {side} the identity {named!r}, which "
219
+ f"no node mapping declares: add identity: {named} to the node mappings it names")
220
+ return found
221
+
222
+
223
+ def compile_schema(schema: Any) -> SourceMaps:
224
+ """The source maps of a `GraphSchema`: a node map per node mapping and
225
+ an edge map per relationship mapping, in declaration order, and the
226
+ schema's settings and predicate declarations."""
227
+ from prograph.schema.iri import class_iri, is_rdf_class, relationship_iri
228
+
229
+ used: set = set()
230
+ nodes: List[NodeMap] = []
231
+ first_of_label: Dict[str, NodeMap] = {}
232
+ maps_of_label: Dict[str, List[NodeMap]] = {}
233
+ for order, m in enumerate(schema.node_mappings):
234
+ node = NodeMap(
235
+ id=_unique_id(m.label if m.label is not None else m.source_table, used), order=order, source=_source(m),
236
+ key=Key(columns=tuple(m.id_columns), stated=m.key_stated,
237
+ listed=isinstance(m._id_column, list), on_duplicate=m.on_duplicate,
238
+ trust=getattr(m, "keys", None)),
239
+ subject=_subject(m),
240
+ # A mapping with no label gives no class unless it declares one (`iri.is_rdf_class`).
241
+ classes=(class_iri(m),) if is_rdf_class(m) else (),
242
+ predicate_objects=_predicate_objects(schema, m),
243
+ graph=m.graph_iri, label=m.label, rdf_class=m.rdf_class,
244
+ declared_class=m.class_iri,
245
+ property_columns=tuple((m.property_columns or {}).items()),
246
+ mutable=m.mutable, identity=getattr(m, "identity", None),
247
+ iri_segment=getattr(m, "iri_segment", None), key_properties=True)
248
+ nodes.append(node)
249
+ if m.label is not None:
250
+ first_of_label.setdefault(m.label, node)
251
+ maps_of_label.setdefault(m.label, []).append(node)
252
+
253
+ used = set()
254
+ edges: List[EdgeMap] = []
255
+ for r in schema.relationship_mappings:
256
+ # An end names the node of its key in any of its label's maps: one edge map per pair of the ends'
257
+ # subjects, each end checked in the maps giving that subject (it was the first map's alone).
258
+ starts = _end_choices(r.start_id_columns, isinstance(r._start_id_column, list), r.start_node_label,
259
+ _end_maps(r, "start", nodes, maps_of_label))
260
+ ends = _end_choices(r.end_id_columns, isinstance(r._end_id_column, list), r.end_node_label,
261
+ _end_maps(r, "end", nodes, maps_of_label))
262
+ if getattr(r, "start_node_identity", None):
263
+ starts = [replace(x, identity=r.start_node_identity) for x in starts]
264
+ if getattr(r, "end_node_identity", None):
265
+ ends = [replace(x, identity=r.end_node_identity) for x in ends]
266
+ first = None
267
+ split = len(starts) * len(ends) > 1
268
+ for start in starts:
269
+ for end in ends:
270
+ # A branch's id is its first's and its number: the other mappings' ids are as they were.
271
+ edge = EdgeMap(
272
+ id=_unique_id(r.rel_type, used) if first is None else f"{first}@{len(edges) - first_at + 1}",
273
+ order=len(edges), source=_source(r),
274
+ predicate=relationship_iri(schema, r.rel_type), rel_type=r.rel_type,
275
+ start=start, end=end,
276
+ property_columns=tuple((r.property_columns or {}).items()),
277
+ reify=r.reify, relation_class_iri=r.relation_class_iri,
278
+ referential_integrity=r.referential_integrity,
279
+ graph=r.graph_iri, mutable=r.mutable, trust=getattr(r, "keys", None),
280
+ branch_of=first, split=split, row_key=getattr(r, "id_columns", None),
281
+ iri_segment=getattr(r, "iri_segment", None))
282
+ if first is None:
283
+ first, first_at = edge.id, len(edges)
284
+ edges.append(edge)
285
+
286
+ declarations = tuple(
287
+ (iri, tuple(PredicateDeclaration(
288
+ predicate_iri=pm.predicate_iri, kind=pm.kind.value, node_label=pm.node_label,
289
+ property_name=pm.property_name, relationship_type=pm.relationship_type,
290
+ datatype=pm.datatype, language=pm.language, language_column=pm.language_column)
291
+ for pm in declared))
292
+ for iri, declared in schema._predicate_mappings_by_iri.items())
293
+ representatives = []
294
+ for iri, pm in schema.predicate_mappings.items():
295
+ declared = schema._predicate_mappings_by_iri.get(iri, [])
296
+ position = next((i for i, d in enumerate(declared) if d is pm), None)
297
+ if position is None:
298
+ raise ValueError(f"predicate <{iri}>'s representative is none of its declarations")
299
+ representatives.append((iri, position))
300
+
301
+ return SourceMaps(
302
+ settings=Settings(name=schema.name, base_iri=schema.base_iri,
303
+ default_catalog=schema.default_catalog,
304
+ default_schema=schema.default_schema,
305
+ table_qualifications=tuple(schema.table_qualifications.items()),
306
+ prefixes=tuple(schema._prefix_map.items())),
307
+ nodes=tuple(nodes), edges=tuple(edges),
308
+ predicate_declarations=declarations,
309
+ representatives=tuple(representatives),
310
+ property_predicates=tuple(schema._property_predicate_iris.items()),
311
+ relationship_predicates=tuple(schema._relationship_predicate_iris.items()))
312
+
313
+
314
+ def _columns(columns: Tuple[str, ...], listed: bool) -> Any:
315
+ return list(columns) if listed else columns[0]
316
+
317
+
318
+ def project(maps: SourceMaps) -> Any:
319
+ """The property-graph schema of `maps`: the
320
+ `GraphSchema` they were compiled from, mapping for mapping and in
321
+ order, with the authored spellings (a key as a name or a list, no
322
+ iri_template where the IRI is synthesized, a class IRI only where one
323
+ was declared). Statistics and column types are the schema's, not the
324
+ maps', and are not carried."""
325
+ from prograph.schema.mapping import (
326
+ GraphSchema, NodeMapping, PredicateKind, PredicateMapping, RelationshipMapping)
327
+
328
+ s = maps.settings
329
+ schema = GraphSchema(default_catalog=s.default_catalog, default_schema=s.default_schema,
330
+ table_qualifications=dict(s.table_qualifications), name=s.name,
331
+ base_iri=s.base_iri)
332
+ for node in maps.nodes:
333
+ from prograph.schema.source_map import LEXICAL_R2RML
334
+ if node.label is None and (node.classes or node.subject.lexical == LEXICAL_R2RML):
335
+ # An R2RML map's classes are no label; a mapping authored with none is an unlabelled node mapping.
336
+ raise ValueError(f"source map {node.id!r} has no label to project")
337
+ projected = NodeMapping(
338
+ source_table=node.source.table, label=node.label,
339
+ id_column=_columns(node.key.columns, node.key.listed),
340
+ property_columns=dict(node.property_columns), graph_iri=node.graph,
341
+ filter_predicate=None if node.source.filter is None else dict(node.source.filter),
342
+ iri_template=None if node.subject.synthesized else node.subject.text(),
343
+ class_iri=node.declared_class, rdf_class=node.rdf_class,
344
+ source_query=node.source.query, key_stated=node.key.stated,
345
+ mutable=node.mutable, on_duplicate=node.key.on_duplicate, keys=node.key.trust,
346
+ identity=node.identity)
347
+ if node.iri_segment is not None:
348
+ projected.iri_segment = node.iri_segment
349
+ schema.add_node_mapping(projected)
350
+ for edge in maps.edges:
351
+ if edge.branch_of is not None:
352
+ continue # one relationship mapping's other ends (`compile_schema`): its first branch stands for it
353
+ if edge.rel_type is None:
354
+ raise ValueError(f"source map {edge.id!r} has no relationship type to project")
355
+ projected_edge = RelationshipMapping(
356
+ source_table=edge.source.table, rel_type=edge.rel_type,
357
+ start_node_label=edge.start.label,
358
+ start_id_column=_columns(edge.start.columns, edge.start.listed),
359
+ end_node_label=edge.end.label,
360
+ end_id_column=_columns(edge.end.columns, edge.end.listed),
361
+ start_node_identity=edge.start.identity, end_node_identity=edge.end.identity,
362
+ property_columns=dict(edge.property_columns), graph_iri=edge.graph,
363
+ filter_predicate=None if edge.source.filter is None else dict(edge.source.filter),
364
+ reify=edge.reify, relation_class_iri=edge.relation_class_iri,
365
+ referential_integrity=edge.referential_integrity, source_query=edge.source.query,
366
+ mutable=edge.mutable, keys=edge.trust,
367
+ id_column=None if edge.row_key is None else list(edge.row_key))
368
+ if edge.iri_segment is not None:
369
+ projected_edge.iri_segment = edge.iri_segment
370
+ schema.add_relationship_mapping(projected_edge)
371
+
372
+ # The predicate declarations as the schema holds them, set whole: replayed
373
+ # through add_predicate_mapping, the first-wins resolutions would follow
374
+ # the IRIs' order, not the order the declarations were made in.
375
+ by_iri: Dict[str, List[PredicateMapping]] = {}
376
+ for iri, declared in maps.predicate_declarations:
377
+ by_iri[iri] = [PredicateMapping(
378
+ predicate_iri=d.predicate_iri, kind=PredicateKind(d.kind), node_label=d.node_label,
379
+ property_name=d.property_name, relationship_type=d.relationship_type,
380
+ datatype=d.datatype, language=d.language, language_column=d.language_column)
381
+ for d in declared]
382
+ schema._predicate_mappings_by_iri = by_iri
383
+ schema.predicate_mappings = {iri: by_iri[iri][position]
384
+ for iri, position in maps.representatives}
385
+ schema._property_predicate_iris = dict(maps.property_predicates)
386
+ schema._relationship_predicate_iris = dict(maps.relationship_predicates)
387
+ schema._prefix_map = dict(s.prefixes)
388
+ return schema