sqlleaf 0.0.8__py3-none-any.whl → 0.0.9__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 (37) hide show
  1. sqlleaf/dialects/athena/config.py +3 -2
  2. sqlleaf/dialects/base.py +7 -11
  3. sqlleaf/dialects/postgres/config.py +3 -2
  4. sqlleaf/lineage.py +105 -65
  5. sqlleaf/mappings.py +30 -14
  6. sqlleaf/models/node/__init__.py +2 -2
  7. sqlleaf/models/node/column.py +3 -2
  8. sqlleaf/models/node/json.py +29 -2
  9. sqlleaf/models/node/{counter.py → series.py} +3 -3
  10. sqlleaf/models/node/window.py +3 -1
  11. sqlleaf/models/query/base.py +18 -3
  12. sqlleaf/models/query/ctas.py +18 -5
  13. sqlleaf/models/query/reset.py +3 -3
  14. sqlleaf/models/query/sequence.py +4 -0
  15. sqlleaf/models/query/set.py +4 -4
  16. sqlleaf/models/query/table.py +20 -6
  17. sqlleaf/models/query/type.py +4 -0
  18. sqlleaf/models/query/use.py +1 -1
  19. sqlleaf/models/query/view.py +3 -2
  20. sqlleaf/path.py +71 -13
  21. sqlleaf/processors/collector/collector.py +6 -4
  22. sqlleaf/processors/generator/dialects/base.py +118 -8
  23. sqlleaf/processors/generator/dialects/postgres.py +7 -10
  24. sqlleaf/processors/generator/generator.py +1 -1
  25. sqlleaf/processors/substitutor/substitute.py +3 -3
  26. sqlleaf/processors/transformer/base.py +107 -53
  27. sqlleaf/processors/transformer/copy.py +0 -1
  28. sqlleaf/processors/transformer/expressions/operator.py +4 -4
  29. sqlleaf/processors/transformer/insert.py +0 -2
  30. sqlleaf/util/__init__.py +0 -6
  31. sqlleaf/util/expression.py +3 -1
  32. {sqlleaf-0.0.8.dist-info → sqlleaf-0.0.9.dist-info}/METADATA +2 -2
  33. {sqlleaf-0.0.8.dist-info → sqlleaf-0.0.9.dist-info}/RECORD +36 -37
  34. sqlleaf/util/graph.py +0 -117
  35. {sqlleaf-0.0.8.dist-info → sqlleaf-0.0.9.dist-info}/WHEEL +0 -0
  36. {sqlleaf-0.0.8.dist-info → sqlleaf-0.0.9.dist-info}/licenses/LICENSE +0 -0
  37. {sqlleaf-0.0.8.dist-info → sqlleaf-0.0.9.dist-info}/top_level.txt +0 -0
@@ -6,8 +6,9 @@ from sqlleaf.dialects.base import DialectConfig
6
6
 
7
7
  class AthenaConfig(DialectConfig):
8
8
  DIALECT = "athena"
9
- DEFAULT_USER_CATALOG = "awsdatacatalog"
10
- DEFAULT_SYSTEM_CATALOG = ""
9
+ DEFAULT_CATALOG = "awsdatacatalog"
10
+ DEFAULT_USER_SCHEMA = "default"
11
+ DEFAULT_SYSTEM_SCHEMA = ""
11
12
  PSEUDOCOLUMNS = {
12
13
  "$bucket": "BIGINT",
13
14
  "$file_modified_time": "TIMESTAMP",
sqlleaf/dialects/base.py CHANGED
@@ -26,10 +26,14 @@ class DialectConfig:
26
26
  # A registry to store subclasses
27
27
  _dialects = {}
28
28
  DIALECT = ""
29
- DEFAULT_USER_CATALOG = ""
30
- DEFAULT_SYSTEM_CATALOG = ""
29
+ # The catalog that the dialect's objects belong to, if the dialect has a catalog level above schemas
30
+ DEFAULT_CATALOG = ""
31
+ DEFAULT_USER_SCHEMA = ""
32
+ DEFAULT_SYSTEM_SCHEMA = ""
33
+ # The schema that temporary objects are created in, if the dialect has one
34
+ DEFAULT_TEMPORARY_SCHEMA: str = ""
31
35
  # The language of procedures that do not declare one explicitly
32
- DEFAULT_PROCEDURE_LANGUAGE: str | None = None
36
+ DEFAULT_PROCEDURE_LANGUAGE: str = ""
33
37
  # Metadata fields, keyed by their suffix (e.g. '$files' in 'my_table$files'), mapped to their column names and types
34
38
  METADATA_FIELDS: dict[str, dict[str, str]] = {}
35
39
 
@@ -76,11 +80,3 @@ class DialectConfig:
76
80
  exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
77
81
  for name, kind in self.METADATA_FIELDS[suffix].items()
78
82
  ]
79
-
80
- class ParameterModeDialect(Dialect):
81
- """
82
- The generic dialect, which also accepts IN, OUT, and INOUT parameter modes in procedure parameters.
83
- """
84
-
85
- class Parser(sqlglot.Parser):
86
- _parse_function_parameter = with_parameter_modes(sqlglot.Parser._parse_function_parameter)
@@ -6,8 +6,9 @@ from sqlleaf.dialects.base import DialectConfig
6
6
 
7
7
  class PostgresConfig(DialectConfig):
8
8
  DIALECT = "postgres"
9
- DEFAULT_USER_CATALOG = "public"
10
- DEFAULT_SYSTEM_CATALOG = "pg_catalog"
9
+ DEFAULT_USER_SCHEMA = "public"
10
+ DEFAULT_SYSTEM_SCHEMA = "pg_catalog"
11
+ DEFAULT_TEMPORARY_SCHEMA = "pg_temp"
11
12
  PSEUDOCOLUMNS = {
12
13
  "cmax": "OID",
13
14
  "cmin": "OID",
sqlleaf/lineage.py CHANGED
@@ -2,15 +2,12 @@ import json
2
2
  import logging
3
3
  import typing as t
4
4
 
5
- from networkx import MultiDiGraph, descendants
5
+ from networkx import MultiDiGraph
6
6
 
7
- from sqlleaf import exception, mappings, path, util
7
+ from sqlleaf import exception, mappings, path
8
8
  from sqlleaf.models.hook import Hook
9
9
  from sqlleaf.models.node import EdgeAttributes, GraphAttributes, N, NodeAttributes
10
- from sqlleaf.models.query import (
11
- Q,
12
- )
13
- from sqlleaf.path import LineagePath
10
+ from sqlleaf.models.query import Q
14
11
  from sqlleaf.processors.collector import collector
15
12
  from sqlleaf.processors.generator import generator
16
13
 
@@ -26,8 +23,7 @@ class Lineage:
26
23
  def __init__(self):
27
24
  self.graph = new_graph() # The graph that contains all lineage
28
25
  self.subgraphs: list[MultiDiGraph] = [] # The subgraphs that make up the main graph
29
- self.paths: dict[str, list[LineagePath]] = {} # The paths throughout the graph
30
- self.collected_queries: collector.CollectQueryResult | None = None
26
+ self.collected_queries = collector.CollectQueryResult()
31
27
  self.user_defined_hooks: list[Hook] = []
32
28
  self.object_mapping: mappings.ObjectMapping | None = None
33
29
 
@@ -110,13 +106,13 @@ class Lineage:
110
106
 
111
107
  Examples:
112
108
  # Find all columns whose name is 'price'
113
- find_node(ColumnNode(column="price"))
109
+ find_nodes(ColumnNode(column="price"))
114
110
 
115
111
  # Find two columns: one unqualified, another fully qualified
116
- find_node(ColumnNode(column="age"), ColumnNode(schema="fruit", table="raw", column="name"))
112
+ find_nodes(ColumnNode(column="age"), ColumnNode(schema="fruit", table="raw", column="name"))
117
113
 
118
114
  # Find all functions
119
- find_node(FunctionNode())
115
+ find_nodes(FunctionNode())
120
116
  """
121
117
  if self.object_mapping is None:
122
118
  return []
@@ -137,6 +133,68 @@ class Lineage:
137
133
 
138
134
  return found
139
135
 
136
+ def paths_downstream_from(self, node: NodeAttributes) -> t.Generator[path.LineagePath]:
137
+ """
138
+ Find all the paths that begin with the given node.
139
+
140
+ The node is looked up with `find_nodes()`, so a partial node matches every node with the same name.
141
+
142
+ Examples:
143
+ # Find every path downward from a column
144
+ paths_downstream_from(ColumnNode(column="price"))
145
+ """
146
+ for start in self.find_nodes(node):
147
+ for hops in path.find_edges_from_root(self.graph, start.full_name):
148
+ if hops:
149
+ yield path.LineagePath(hops=hops)
150
+
151
+ def paths_upstream_from(self, node: NodeAttributes) -> t.Generator[path.LineagePath]:
152
+ """
153
+ Find all the paths that end with the given node as their leaf.
154
+
155
+ The reverse of `paths_downstream_from()`. The node is looked up with `find_nodes()`, so a partial node
156
+ matches every node with the same name.
157
+
158
+ Examples:
159
+ # Find every path upward from a column
160
+ paths_upstream_from(ColumnNode(column="total"))
161
+ """
162
+ reversed_graph = self.graph.reverse(copy=False)
163
+ for end in self.find_nodes(node):
164
+ for hops in path.find_edges_from_root(reversed_graph, end.full_name):
165
+ if hops:
166
+ yield path.LineagePath(hops=list(reversed(hops)))
167
+
168
+ def has_path(self, src: NodeAttributes, dst: NodeAttributes) -> bool:
169
+ """
170
+ Check whether there is a path from any node matching the first node to any node matching the second.
171
+
172
+ Examples:
173
+ # Check whether price flows into total
174
+ has_path(ColumnNode(column="price"), ColumnNode(column="total"))
175
+ """
176
+ from networkx import has_path as nx_has_path
177
+
178
+ return any(
179
+ nx_has_path(self.graph, s.full_name, d.full_name)
180
+ for s in self.find_nodes(src)
181
+ for d in self.find_nodes(dst)
182
+ if self.graph.has_node(s.full_name) and self.graph.has_node(d.full_name)
183
+ )
184
+
185
+ def paths_between_nodes(self, src: NodeAttributes, dst: NodeAttributes) -> t.Generator[path.LineagePath]:
186
+ """
187
+ Find all the paths that begin with a node matching the first node and end with a node matching the second.
188
+
189
+ Examples:
190
+ # Find every path from price to total
191
+ paths_between_nodes(ColumnNode(column="price"), ColumnNode(column="total"))
192
+ """
193
+ dst_names = {d.full_name for d in self.find_nodes(dst)}
194
+
195
+ for p in self.paths_downstream_from(src):
196
+ if p.hops[-1].child.full_name in dst_names:
197
+ yield p
140
198
 
141
199
  def get_original_queries(self) -> list[Q]:
142
200
  """
@@ -150,7 +208,7 @@ class Lineage:
150
208
  """
151
209
  return [q.transformed for q in self.graph.graph["attrs"].queries]
152
210
 
153
- def get_paths(self) -> t.Generator[LineagePath]:
211
+ def get_paths(self) -> t.Generator[path.LineagePath]:
154
212
  """
155
213
  paths: [
156
214
  {
@@ -166,7 +224,7 @@ class Lineage:
166
224
  for p in path.find_all_paths(graph=self.graph):
167
225
  yield p
168
226
 
169
- def print_json(self):
227
+ def print_json(self) -> None:
170
228
  """
171
229
  Print the graph as JSON.
172
230
  """
@@ -192,65 +250,45 @@ class Lineage:
192
250
  )
193
251
  )
194
252
 
195
- def print_tree(self, full_name=False):
253
+ def print_tree(self, full_name: bool = False) -> None:
196
254
  """
197
255
  Print from the leaves to the root (as left to right) so that the tree is displayed correctly.
198
- For example:
256
+ Mimics the `tree` utility on Linux.
199
257
 
200
- INSERT INTO fruit.processed
201
- SELECT SUBSTRING(name, 2, 4) AS name
202
- FROM fruit.raw
258
+ For example, given query:
259
+ INSERT INTO fruit.processed
260
+ SELECT SUBSTRING(name, 2, 4) AS name
261
+ FROM fruit.raw
203
262
 
204
263
  Output:
205
-
206
- column[fruit.processed.name]
207
- └── function[SUBSTRING]
208
- ├── column[fruit.raw.name]
209
- ├── literal[2]
210
- └── literal[4]
264
+ .
265
+ └── column[fruit.processed.name]
266
+ └── function[SUBSTRING]
267
+ ├── column[fruit.raw.name]
268
+ ├── literal[2]
269
+ └── literal[4]
211
270
  """
212
- g = self.graph.reverse() # We print from the leaves to the roots
213
- root_columns = util.get_root_nodes(g)
214
- seen = set()
215
- symbol = "└──"
216
-
271
+ g = self.graph.reverse(copy=False) # We print from the leaves to the roots
217
272
  attr = "full_name" if full_name else "friendly_name"
218
273
 
219
- # TODO: this may not be needed since the NodeAttributes are node
274
+ def print_entry(name: str, prefix: str, is_last: bool, ancestors: frozenset[str]) -> None:
275
+ connector = "└── " if is_last else "├── "
276
+ print(prefix + connector + getattr(g.nodes[name]["attrs"], attr))
277
+ # A last entry has no siblings below it, so its children are indented instead of guided
278
+ child_prefix = prefix + (" " if is_last else "│ ")
279
+ print_children(name, child_prefix, ancestors | {name})
280
+
281
+ def print_children(name: str, prefix: str, ancestors: frozenset[str]) -> None:
282
+ children = sorted(n for n in g.successors(name) if n != name and n not in ancestors)
283
+ for i, child in enumerate(children):
284
+ print_entry(child, prefix, i == len(children) - 1, ancestors)
285
+
286
+ root_columns = path.get_root_nodes(g)
287
+ print(".")
220
288
  for i, root in enumerate(root_columns):
221
- for depth, edge_attrs in util.find_edges_downward(
222
- g, root
223
- ): # TODO: fetch edges in order of function argument index
224
- # Swap the parent and child
225
- parent_name = edge_attrs.child.full_name
226
- child_name = edge_attrs.parent.full_name
227
- num_descendents_of_child = len(descendants(g, child_name))
228
-
229
- parent_node = g.nodes[parent_name]["attrs"]
230
- child_node = g.nodes[child_name]["attrs"]
231
-
232
- if parent_name not in seen:
233
- symbol = "└──"
234
-
235
- # Print arrows
236
- if depth > 0:
237
- prefix = ((depth - 1) * 4 * " ") + f"{symbol} "
238
- else:
239
- prefix = ""
240
- print("%s%s" % (prefix, getattr(parent_node, attr)))
241
- seen.add(parent_name)
242
-
243
- # Print the child if we're at the end of the path
244
- if num_descendents_of_child == 0:
245
- if depth == 0:
246
- # Direct load (source -> target)
247
- prefix = "└── "
248
- else:
249
- prefix = (depth * 4 * " ") + f"{symbol} "
250
- print("%s%s" % (prefix, getattr(child_node, attr)))
251
- seen.add(child_name)
252
-
253
- def print_paths(self):
289
+ print_entry(root, "", i == len(root_columns) - 1, frozenset())
290
+
291
+ def print_paths(self) -> None:
254
292
  """
255
293
  Iterate over all the paths in the graph and print each one.
256
294
 
@@ -302,9 +340,11 @@ class Lineage:
302
340
  """
303
341
  self.user_defined_hooks = [udh for udh in self.user_defined_hooks if udh not in hooks]
304
342
 
305
- def init_object_mapping(self, dialect: str):
343
+ def init_object_mapping(self, dialect: str) -> None:
306
344
  if not self.object_mapping:
307
- self.object_mapping = mappings.ObjectMapping(dialect=dialect, object_loader=collector.SystemObjectLoader(dialect))
345
+ self.object_mapping = mappings.ObjectMapping(
346
+ dialect=dialect, object_loader=collector.SystemObjectLoader(dialect)
347
+ )
308
348
 
309
349
 
310
350
  def new_graph() -> MultiDiGraph:
sqlleaf/mappings.py CHANGED
@@ -31,21 +31,18 @@ from sqlleaf.models.query import (
31
31
  )
32
32
  from sqlleaf.path import NodeIndex
33
33
 
34
- ColumnMapping = t.Union[dict, str, list]
34
+ ColumnMapping = dict | str | list
35
35
  FunctionCallable = ProcedureQuery | UserDefinedFunctionQuery
36
36
 
37
37
  logger = logging.getLogger("sqlleaf")
38
38
 
39
39
 
40
- ParamMode = t.Literal["IN", "OUT", "INOUT"]
41
-
42
-
43
40
  @dataclass
44
41
  class ParamBinding:
45
42
  """One parameter's binding for the lifetime of a single CALL."""
46
43
 
47
44
  value: exp.Expr
48
- mode: ParamMode
45
+ mode: t.Literal["IN", "OUT", "INOUT"]
49
46
  arg_name: str | None = None
50
47
 
51
48
  @property
@@ -76,6 +73,7 @@ class Variables:
76
73
  """
77
74
  Tracks the state of every variable currently available to SQL statements.
78
75
  """
76
+
79
77
  def __init__(self):
80
78
  # An initial scope exists for the top-level statements
81
79
  self.scopes: list[VariableScope] = [VariableScope()]
@@ -198,17 +196,26 @@ class ObjectMapping(MappingSchema):
198
196
  ) # Set `normalize=False` to prevent an unnecessary second parse.
199
197
  self.kind_mapping = {}
200
198
  self.kind_mapping_trie = {}
201
- config = DialectConfig(dialect)
202
- # The catalog that unqualified user objects are created in, and the one holding system objects
203
- self.current_user_catalog: str = config.DEFAULT_USER_CATALOG
204
- self.current_system_catalog: str = config.DEFAULT_SYSTEM_CATALOG
205
- self.current_database: str | None = None # For MySQL
199
+ self.dialect_config = DialectConfig(dialect)
200
+ # The catalog that user objects belong to, the schema that unqualified user objects are created in, and the schema holding system objects
201
+ self.current_catalog: str = self.dialect_config.DEFAULT_CATALOG
202
+ self.current_user_schema: str = self.dialect_config.DEFAULT_USER_SCHEMA
203
+ self.current_system_schema: str = self.dialect_config.DEFAULT_SYSTEM_SCHEMA
204
+ self.temporary_schema: str = self.dialect_config.DEFAULT_TEMPORARY_SCHEMA
206
205
  # Load system objects lazily from disk
207
206
  self.system_object_loader = object_loader
208
207
  self.variables = Variables()
209
208
  # Nodes that have been added to the graph, indexed by class
210
209
  self.node_index = NodeIndex()
211
210
 
211
+ def get_current_schema(self, statement: exp.Create) -> str:
212
+ """
213
+ Get the schema an unqualified object is created in. Temporary objects live in the temporary schema, if there is one.
214
+ """
215
+ if self.temporary_schema and statement.find(exp.TemporaryProperty):
216
+ return self.temporary_schema
217
+ return self.current_user_schema
218
+
212
219
  def add_database_query(self, query: DatabaseQuery) -> None:
213
220
  self._add_query(query=query, dialect=query.dialect)
214
221
 
@@ -292,8 +299,7 @@ class ObjectMapping(MappingSchema):
292
299
 
293
300
  # Normalize the table parts (catalog.db.table.column)
294
301
  table = query.get_target_as_table()
295
- normalized_table = self._normalize_table(table, dialect=dialect, normalize=normalize)
296
- parts = self.table_parts(normalized_table)
302
+ parts = list(self._normalize_table_parts(table, dialect=dialect, normalize=normalize))
297
303
 
298
304
  if kind == "udf":
299
305
  # Store the UDF with other UDFs of the same name
@@ -320,6 +326,10 @@ class ObjectMapping(MappingSchema):
320
326
  normalize=normalize,
321
327
  match_depth=match_depth,
322
328
  )
329
+ if kind == "table":
330
+ # Invisible columns are excluded from a bare star, but can still be referenced by name
331
+ visible_columns = {col.name for col in query.get_column_defs(include_system=True)}
332
+ nested_set(self.visible, tuple(reversed(parts)), visible_columns)
323
333
 
324
334
  def _add_columns_for_table(
325
335
  self,
@@ -341,9 +351,15 @@ class ObjectMapping(MappingSchema):
341
351
  if self.system_object_loader is not None:
342
352
  self.system_object_loader(self, object, kind)
343
353
 
344
- def find(self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False) -> t.Any | None:
354
+ def column_names(
355
+ self,
356
+ table: exp.Table | str,
357
+ only_visible: bool = False,
358
+ dialect: DialectType = None,
359
+ normalize: bool | None = None,
360
+ ) -> list[str]:
345
361
  self.handle_missing_object(table)
346
- return super().find(table, raise_on_missing=raise_on_missing, ensure_data_types=ensure_data_types)
362
+ return super().column_names(table, only_visible=only_visible, dialect=dialect, normalize=normalize)
347
363
 
348
364
  def find_columns_for_table(
349
365
  self,
@@ -4,7 +4,6 @@ from enum import StrEnum, auto
4
4
 
5
5
  class NodeKind(StrEnum):
6
6
  COLUMN = auto()
7
- COUNTER = auto()
8
7
  DYNAMODB = auto()
9
8
  FUNCTION = auto()
10
9
  INTERVAL = auto()
@@ -15,6 +14,7 @@ class NodeKind(StrEnum):
15
14
  UNPIVOT = auto()
16
15
  PROGRAM = auto()
17
16
  SEQUENCE = auto()
17
+ SERIES = auto()
18
18
  STAR = auto()
19
19
  STREAM = auto()
20
20
  UDF = auto()
@@ -30,7 +30,6 @@ from sqlleaf.models.node.base import NodeAttributes as NodeAttributes
30
30
  from sqlleaf.models.node.column import ColumnNode as ColumnNode
31
31
  from sqlleaf.models.node.column import FileColumnNode as FileColumnNode
32
32
  from sqlleaf.models.node.column import StageColumnNode as StageColumnNode
33
- from sqlleaf.models.node.counter import CounterNode as CounterNode
34
33
  from sqlleaf.models.node.dynamodb import DynamoDbNode as DynamoDbNode
35
34
  from sqlleaf.models.node.function import FunctionNode as FunctionNode
36
35
  from sqlleaf.models.node.interval import IntervalNode as IntervalNode
@@ -41,6 +40,7 @@ from sqlleaf.models.node.pivot import PivotNode as PivotNode
41
40
  from sqlleaf.models.node.pivot import UnpivotNode as UnpivotNode
42
41
  from sqlleaf.models.node.program import ProgramNode as ProgramNode
43
42
  from sqlleaf.models.node.sequence import SequenceNode as SequenceNode
43
+ from sqlleaf.models.node.series import SeriesNode as SeriesNode
44
44
  from sqlleaf.models.node.star import StarNode as StarNode
45
45
  from sqlleaf.models.node.stream import StreamNode as StreamNode
46
46
  from sqlleaf.models.node.user_defined_function import UserDefinedFunctionNode as UserDefinedFunctionNode
@@ -182,8 +182,8 @@ class ColumnNode(NodeAttributes):
182
182
  self.parent_kind = TableType.DERIVED_TABLE
183
183
  return True
184
184
 
185
- if isinstance(source, exp.Table) and isinstance(source.this, exp.Anonymous):
186
- # Table function, e.g. SELECT * FROM FUNCTION()
185
+ if isinstance(source, exp.Table) and isinstance(source.this, (exp.Anonymous, exp.JSONTable)):
186
+ # Table function, e.g. SELECT * FROM FUNCTION() or SELECT * FROM JSON_TABLE()
187
187
  self.parent_kind = TableType.UDTF
188
188
  return True
189
189
 
@@ -295,6 +295,7 @@ class ColumnNode(NodeAttributes):
295
295
  f |= {
296
296
  "table": table,
297
297
  "schema": self.schema,
298
+ "catalog": self.catalog,
298
299
  "type": self.data_type,
299
300
  }
300
301
 
@@ -1,9 +1,10 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import logging
4
+ import re
4
5
  import typing as t
5
6
 
6
- from sqlglot import exp
7
+ from sqlglot import exp, jsonpath
7
8
 
8
9
  from sqlleaf.models.context import GeneratorContext
9
10
  from sqlleaf.models.node import NodeAttributes, NodeKind
@@ -20,6 +21,19 @@ class JsonPathNode(NodeAttributes):
20
21
  self.selector_depth = selector_depth
21
22
 
22
23
  def with_context(self, gen_ctx: GeneratorContext) -> t.Self:
24
+ if isinstance(gen_ctx.expr, exp.JSONTable):
25
+ # The row path of a JSON_TABLE, e.g. '$[*]' in JSON_TABLE(data, '$[*]' COLUMNS (...))
26
+ self.name = self.selector = gen_ctx.expr.args["path"].name
27
+ self.selector_depth = len(self.json_selectors(gen_ctx.expr))
28
+ return super().with_context(gen_ctx)
29
+
30
+ if isinstance(gen_ctx.expr, exp.JSONColumnDef):
31
+ # A JSON_TABLE column, e.g. user_id INT PATH '$.id'. Without a PATH, Postgres defaults to the column name
32
+ path = gen_ctx.expr.args.get("path")
33
+ self.name = self.selector = path.name if path else f'$."{gen_ctx.expr.name}"'
34
+ self.selector_depth = len(self.json_selectors(gen_ctx.expr))
35
+ return super().with_context(gen_ctx)
36
+
23
37
  expr = t.cast(exp.JSONExtract, gen_ctx.expr)
24
38
 
25
39
  selectors = self.json_selectors(expr)
@@ -29,14 +43,27 @@ class JsonPathNode(NodeAttributes):
29
43
  return super().with_context(gen_ctx)
30
44
 
31
45
  @staticmethod
32
- def json_selectors(expr: exp.JSONExtract):
46
+ def json_selectors(expr: exp.JSONExtract | exp.JSONValue | exp.JSONColumnDef | exp.JSONTable) -> list[exp.Expr]:
33
47
  """
34
48
  Collect all the JSON path elements recursively.
35
49
  e.g.
36
50
  SELECT my_json -> 'a' -> 'b'
37
51
  produces
38
52
  ['a', 'b']
53
+
54
+ or if we have JSON_VALUE / JSON_QUERY, then the path is a string.
55
+ e.g.
56
+ 'lax $.user.age'
57
+ produces the elements of the parsed path:
58
+ ['.user', '.age']
39
59
  """
60
+ if isinstance(expr, (exp.JSONValue, exp.JSONColumnDef, exp.JSONTable)) or expr.args.get("json_query"):
61
+ path = expr.args["path"] if isinstance(expr, (exp.JSONValue, exp.JSONColumnDef, exp.JSONTable)) else expr.expression
62
+ path_name = path.name if path else f'$."{expr.name}"'
63
+ # sqlglot keeps the JSON path as a raw string with its mode prefix, so it is parsed here
64
+ parsed = jsonpath.parse(re.sub(r"^(lax|strict)\s+", "", path_name))
65
+ return list(parsed.find_all(exp.JSONPathKey, exp.JSONPathSubscript))
66
+
40
67
  methods = {
41
68
  # Mapping of expression -> attribute getter
42
69
  exp.JSONPathKey: None,
@@ -3,9 +3,9 @@ from __future__ import annotations
3
3
  from sqlleaf.models.node import NodeAttributes, NodeKind
4
4
 
5
5
 
6
- # Represents the source of a 'WITH ORDINALITY' column
7
- class CounterNode(NodeAttributes):
8
- KIND = NodeKind.COUNTER
6
+ # Represents an anonymous series, e.g. the source of a 'WITH ORDINALITY' column or Athena's SEQUENCE()
7
+ class SeriesNode(NodeAttributes):
8
+ KIND = NodeKind.SERIES
9
9
  WITH_POSITIONS = True
10
10
 
11
11
  def fields(self) -> dict[str, str]:
@@ -13,7 +13,9 @@ class WindowNode(NodeAttributes):
13
13
  KIND = NodeKind.WINDOW
14
14
 
15
15
  def with_context(self, gen_ctx: GeneratorContext) -> t.Self:
16
- expr = t.cast(exp.Window, gen_ctx.expr.this)
16
+ expr = gen_ctx.expr.this
17
+ if isinstance(expr, (exp.IgnoreNulls, exp.RespectNulls)):
18
+ expr = expr.this
17
19
  self.name = util.calculate_function_name(expr, gen_ctx.query.dialect)
18
20
 
19
21
  return super().with_context(gen_ctx)
@@ -56,6 +56,18 @@ class Query:
56
56
  def set_holder(self, holder: QueryHolder) -> None:
57
57
  self.holder = holder
58
58
 
59
+ @property
60
+ def temporary(self) -> bool:
61
+ """
62
+ Whether the query's target lives in the dialect's temporary schema (e.g. 'pg_temp').
63
+ """
64
+ target = self.target_info.expression if self.target_info else None
65
+ return (
66
+ bool(self.object_mapping.temporary_schema)
67
+ and isinstance(target, exp.Table)
68
+ and target.db == self.object_mapping.temporary_schema
69
+ )
70
+
59
71
  def _determine_expression_type(self, expr: exp.Expr | list[exp.Expr], dialect: str) -> SqlObjectType:
60
72
  """
61
73
  Determine the type of object that an expression represents.
@@ -187,7 +199,7 @@ class Query:
187
199
  table_query = self.object_mapping.get_table_or_stage(table, raise_on_missing=False)
188
200
  if not table_query:
189
201
  return []
190
- return [col.copy() for col in table_query.get_column_defs()]
202
+ return [col.copy() for col in table_query.get_column_defs(include_invisible=True)]
191
203
 
192
204
  def get_sources(self) -> list[exp.Expr]:
193
205
  """
@@ -226,14 +238,17 @@ class Query:
226
238
  def get_ctes(self) -> list:
227
239
  return []
228
240
 
229
- def get_column_defs(self, include_system: bool = False) -> list[exp.ColumnDef]:
241
+ def get_column_defs(self, include_system: bool = False, include_invisible: bool = False) -> list[exp.ColumnDef]:
230
242
  return self.column_defs
231
243
 
232
244
  def get_column_names_with_types(self, include_system: bool = False) -> dict[str, str]:
233
245
  """
234
246
  Used by sqlglot's MappingSchema
235
247
  """
236
- columns = {col.name: str(col.kind) for col in self.get_column_defs(include_system=include_system)}
248
+ columns = {
249
+ col.name: str(col.kind)
250
+ for col in self.get_column_defs(include_system=include_system, include_invisible=True)
251
+ }
237
252
  return columns
238
253
 
239
254
  @property
@@ -29,9 +29,12 @@ class CTASQuery(Query):
29
29
  source = exec_prop.this
30
30
 
31
31
  target = util.get_table(expr)
32
- if not target.db and object_mapping.current_user_catalog:
32
+ if not target.db and object_mapping.current_user_schema:
33
33
  # Set the schema as the currently selected one
34
- target.set("db", exp.to_identifier(object_mapping.current_user_catalog))
34
+ default_schema = object_mapping.get_current_schema(expr)
35
+ target.set("db", exp.to_identifier(default_schema))
36
+ if target.db and object_mapping.current_catalog and not target.catalog:
37
+ target.set("catalog", exp.to_identifier(object_mapping.current_catalog))
35
38
 
36
39
  source_type = self._determine_expression_type(source, dialect)
37
40
  target_type = self._determine_expression_type(target, dialect)
@@ -44,7 +47,8 @@ class CTASQuery(Query):
44
47
  source_info=SourceInfo(expression=source, type=source_type),
45
48
  target_info=TargetInfo(expression=target, type=target_type),
46
49
  )
47
- self.column_defs: list[exp.ColumnDef] = columns
50
+ self.column_defs: list[exp.ColumnDef] = [col_def for col_def in columns if not self._is_invisible(col_def)]
51
+ self.invisible_column_defs: list[exp.ColumnDef] = [col_def for col_def in columns if self._is_invisible(col_def)]
48
52
  self.system_column_defs: list[exp.ColumnDef] = system_columns
49
53
  self.inherited_by: list[TableQuery] = []
50
54
 
@@ -55,5 +59,14 @@ class CTASQuery(Query):
55
59
 
56
60
  self.property: str = util.find_property(expr, self.target_info.expression, dialect)
57
61
 
58
- def get_column_defs(self, include_system: bool = False) -> list[exp.ColumnDef]:
59
- return self.column_defs + self.system_column_defs if include_system else self.column_defs
62
+ @staticmethod
63
+ def _is_invisible(col_def: exp.ColumnDef) -> bool:
64
+ return col_def.find(exp.InvisibleColumnConstraint) is not None
65
+
66
+ def get_column_defs(self, include_system: bool = False, include_invisible: bool = False) -> list[exp.ColumnDef]:
67
+ column_defs = self.column_defs
68
+ if include_invisible:
69
+ column_defs = column_defs + self.invisible_column_defs
70
+ if include_system:
71
+ column_defs = column_defs + self.system_column_defs
72
+ return column_defs
@@ -24,7 +24,7 @@ class ResetQuery(Query):
24
24
  skip_type_annotation=True,
25
25
  )
26
26
 
27
- self.reset_catalog()
27
+ self.reset_schema()
28
28
 
29
- def reset_catalog(self) -> None:
30
- self.object_mapping.current_user_catalog = DialectConfig(self.dialect).DEFAULT_USER_CATALOG
29
+ def reset_schema(self) -> None:
30
+ self.object_mapping.current_user_schema = DialectConfig(self.dialect).DEFAULT_USER_SCHEMA
@@ -19,6 +19,10 @@ class SequenceQuery(Query):
19
19
  ):
20
20
  source = None
21
21
  target = expr.this
22
+ if not target.db and object_mapping.current_user_schema:
23
+ # Set the schema as the currently selected one
24
+ default_schema = object_mapping.get_current_schema(expr)
25
+ target.set("db", exp.to_identifier(default_schema))
22
26
 
23
27
  target_type = self._determine_expression_type(target, dialect)
24
28