sqlleaf 0.0.4__tar.gz → 0.0.5__tar.gz

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 (137) hide show
  1. {sqlleaf-0.0.4/sqlleaf.egg-info → sqlleaf-0.0.5}/PKG-INFO +1 -1
  2. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/pyproject.toml +1 -1
  3. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/mappings.py +100 -43
  4. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/base.py +1 -1
  5. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/copy.py +2 -2
  6. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/open.py +1 -1
  7. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/collector/collector.py +11 -4
  8. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/base.py +3 -3
  9. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/substitutor/substitute.py +39 -13
  10. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/base.py +32 -44
  11. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/copy.py +4 -4
  12. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/ctas.py +2 -3
  13. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/delete.py +2 -1
  14. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/expressions/functional_notation.py +1 -2
  15. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/expressions/row.py +1 -2
  16. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/insert.py +3 -4
  17. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/merge.py +2 -1
  18. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/open.py +2 -2
  19. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/transformer.py +9 -9
  20. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/unload.py +1 -1
  21. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/update.py +4 -5
  22. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/typing.py +2 -13
  23. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/util/expression.py +3 -3
  24. {sqlleaf-0.0.4 → sqlleaf-0.0.5/sqlleaf.egg-info}/PKG-INFO +1 -1
  25. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/LICENSE +0 -0
  26. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/README.md +0 -0
  27. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/setup.cfg +0 -0
  28. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/__init__.py +0 -0
  29. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/__init__.py +0 -0
  30. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/__init__.py +0 -0
  31. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/p_classes.py +0 -0
  32. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/p_dialect.py +0 -0
  33. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/p_generator.py +0 -0
  34. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/p_parser.py +0 -0
  35. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/dialects/plpgsql/p_tokenizer.py +0 -0
  36. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/exception.py +0 -0
  37. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/lineage.py +0 -0
  38. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/__init__.py +0 -0
  39. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/context.py +0 -0
  40. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/hook.py +0 -0
  41. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/__init__.py +0 -0
  42. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/base.py +0 -0
  43. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/column.py +0 -0
  44. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/dynamodb.py +0 -0
  45. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/function.py +0 -0
  46. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/interval.py +0 -0
  47. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/json.py +0 -0
  48. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/literal.py +0 -0
  49. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/null.py +0 -0
  50. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/pivot.py +0 -0
  51. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/program.py +0 -0
  52. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/sequence.py +0 -0
  53. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/star.py +0 -0
  54. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/stream.py +0 -0
  55. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/user_defined_function.py +0 -0
  56. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/var.py +0 -0
  57. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/variable.py +0 -0
  58. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/node/window.py +0 -0
  59. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/__init__.py +0 -0
  60. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/block.py +0 -0
  61. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/call.py +0 -0
  62. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/case.py +0 -0
  63. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/ctas.py +0 -0
  64. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/database.py +0 -0
  65. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/declare_item.py +0 -0
  66. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/delete.py +0 -0
  67. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/do.py +0 -0
  68. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/exception_.py +0 -0
  69. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/execute.py +0 -0
  70. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/execute_dynamic.py +0 -0
  71. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/fetch.py +0 -0
  72. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/for_in.py +0 -0
  73. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/holder.py +0 -0
  74. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/if_.py +0 -0
  75. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/insert.py +0 -0
  76. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/loop.py +0 -0
  77. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/merge.py +0 -0
  78. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/multitable_insert.py +0 -0
  79. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/perform.py +0 -0
  80. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/prepare.py +0 -0
  81. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/procedure.py +0 -0
  82. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/put.py +0 -0
  83. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/replace.py +0 -0
  84. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/schema.py +0 -0
  85. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/select.py +0 -0
  86. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/sequence.py +0 -0
  87. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/set.py +0 -0
  88. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/stage.py +0 -0
  89. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/table.py +0 -0
  90. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/trigger.py +0 -0
  91. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/type.py +0 -0
  92. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/unload.py +0 -0
  93. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/update.py +0 -0
  94. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/user_defined_function.py +0 -0
  95. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/values.py +0 -0
  96. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/view.py +0 -0
  97. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/models/query/while_.py +0 -0
  98. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/path.py +0 -0
  99. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/__init__.py +0 -0
  100. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/collector/__init__.py +0 -0
  101. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/collector/classify.py +0 -0
  102. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/__init__.py +0 -0
  103. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/__init__.py +0 -0
  104. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/athena.py +0 -0
  105. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/mysql.py +0 -0
  106. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/postgres.py +0 -0
  107. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/redshift.py +0 -0
  108. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/dialects/snowflake.py +0 -0
  109. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/generator/generator.py +0 -0
  110. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/substitutor/__init__.py +0 -0
  111. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/__init__.py +0 -0
  112. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/assignment.py +0 -0
  113. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/call.py +0 -0
  114. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/case.py +0 -0
  115. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/execute.py +0 -0
  116. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/execute_dynamic.py +0 -0
  117. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/expressions/__init__.py +0 -0
  118. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/expressions/format.py +0 -0
  119. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/expressions/values.py +0 -0
  120. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/for_in.py +1 -1
  121. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/multitable_insert.py +0 -0
  122. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/prepare.py +0 -0
  123. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/replace.py +0 -0
  124. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/processors/transformer/values.py +0 -0
  125. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/settings/__init__.py +0 -0
  126. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/settings/athena.py +0 -0
  127. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/settings/base.py +0 -0
  128. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/settings/postgres.py +0 -0
  129. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/util/__init__.py +0 -0
  130. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/util/graph.py +0 -0
  131. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/util/helpers.py +0 -0
  132. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf/util/iterators.py +0 -0
  133. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf.egg-info/SOURCES.txt +0 -0
  134. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf.egg-info/dependency_links.txt +0 -0
  135. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf.egg-info/requires.txt +0 -0
  136. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/sqlleaf.egg-info/top_level.txt +0 -0
  137. {sqlleaf-0.0.4 → sqlleaf-0.0.5}/tests/test_hooks.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlleaf
3
- Version: 0.0.4
3
+ Version: 0.0.5
4
4
  Summary: Trace your data
5
5
  Author-email: zac <zac@sqlleaf.io>
6
6
  Project-URL: Homepage, https://github.com/sqlleaf-io/sqlleaf
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlleaf"
3
- version = "0.0.4"
3
+ version = "0.0.5"
4
4
  authors = [
5
5
  {name = "zac", email = "zac@sqlleaf.io"}
6
6
  ]
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import logging
4
4
  import typing as t
5
+ from dataclasses import dataclass, field
5
6
 
6
7
  from sqlglot import MappingSchema, exp
7
8
  from sqlglot.dialects.dialect import DialectType
@@ -34,57 +35,89 @@ FunctionCallable = ProcedureQuery | UserDefinedFunctionQuery
34
35
  logger = logging.getLogger("sqlleaf")
35
36
 
36
37
 
37
- class ObjectMapping(MappingSchema):
38
- """
39
- Contains all the objects that get created, such as tables, procedures, functions, and sequences.
38
+ @dataclass
39
+ class ParamBinding:
40
+ """One parameter's binding for the lifetime of a single CALL."""
40
41
 
41
- We extends sqlglot.MappingSchema to provide additional functionality related to tracking these objects,
42
- while still allowing optimizer inside sqlglot to work (as it needs a mapping of objects to perform functions
43
- like qualification and simplification).
44
- """
42
+ value: exp.Expr
43
+ arg_name: str | None = None
45
44
 
46
- def __init__(self, dialect: str):
47
- super().__init__(
48
- dialect=dialect, normalize=False
49
- ) # Set `normalize=False` to prevent an unnecessary second parse.
50
- self.kind_mapping = {}
51
- self.kind_mapping_trie = {}
52
- # Session/global variables (e.g., SET var = ...)
53
- self.session_variables: dict[str, exp.Expr] = {}
54
- # Block-scoped variables: one dict per active block, innermost scope at the end
55
- self.variable_scopes: list[dict[str, exp.Expr]] = []
56
45
 
57
- # ---- Variable scope API ----
58
- def push_variable_scope(self) -> None:
59
- """Enter a new block scope."""
60
- self.variable_scopes.append({})
46
+ @dataclass
47
+ class VariableScope:
48
+ """One CALL boundary: its block stack and parameter bindings."""
49
+
50
+ blocks: list[dict[str, exp.Expr]] = field(default_factory=list)
51
+ bindings: dict[str, ParamBinding] = field(default_factory=dict)
61
52
 
62
- def pop_variable_scope(self) -> None:
63
- """Leave the current block scope."""
64
- if self.variable_scopes:
65
- self.variable_scopes.pop()
53
+
54
+ class Variables:
55
+ def __init__(self):
56
+ # The base scope runs DO / top-level code and is never popped
57
+ self.scopes: list[VariableScope] = [VariableScope()]
58
+
59
+ @property
60
+ def _active_blocks(self) -> list[dict[str, exp.Expr]]:
61
+ return self.scopes[-1].blocks
62
+
63
+ @property
64
+ def _active_bindings(self) -> dict[str, ParamBinding]:
65
+ return self.scopes[-1].bindings
66
+
67
+ # ---- Block API ----
68
+ def push_block(self) -> None:
69
+ """Enter a new DECLARE/BEGIN block."""
70
+ self._active_blocks.append({})
71
+
72
+ def pop_block(self) -> None:
73
+ """Leave the current DECLARE/BEGIN block."""
74
+ if self._active_blocks:
75
+ self._active_blocks.pop()
76
+
77
+ # ---- Scope API ----
78
+ def push_scope(self, bindings: dict[str, ParamBinding]) -> None:
79
+ """Enter a CALL boundary."""
80
+ self.scopes.append(VariableScope(bindings=bindings))
81
+
82
+ def pop_scope(self, write_back: bool = True) -> None:
83
+ """Leave the current CALL boundary, optionally writing OUT/INOUT values back to the caller."""
84
+ if len(self.scopes) == 1:
85
+ raise exception.MappingError("Cannot pop the base variable scope")
86
+ scope = self.scopes.pop()
87
+ if write_back:
88
+ for binding in scope.bindings.values():
89
+ if binding.arg_name is not None:
90
+ self.set_variable(binding.arg_name, binding.value)
66
91
 
67
92
  def declare_variable(self, name: str, value: exp.Expr | None = None) -> None:
68
- """Declare a variable in the current (innermost) scope."""
93
+ """Declare a variable in the current (innermost) block."""
69
94
  val = value if value is not None else exp.Null()
70
- self.variable_scopes[-1][name] = val
71
- logger.debug(f"Declared variable: {name} := {val.sql(dialect=self.dialect)}")
95
+ self._active_blocks[-1][name] = val
96
+ logger.debug(f"Declared variable: {name} := {val}")
72
97
 
73
98
  def set_variable(self, name: str, value: exp.Expr) -> None:
74
- """Assign a variable in the nearest scope where it was declared."""
75
- for scope in reversed(self.variable_scopes):
76
- if name in scope:
77
- scope[name] = value
78
- logger.debug(f"Set variable value: {name} := {value.sql(dialect=self.dialect)}")
99
+ """Assign a variable in the nearest block where it was declared."""
100
+ for block in reversed(self._active_blocks):
101
+ if name in block:
102
+ block[name] = value
103
+ logger.debug(f"Set variable value: {name} := {value}")
79
104
  return
80
105
 
106
+ binding = self._active_bindings.get(name)
107
+ if binding is not None:
108
+ binding.value = value
109
+ return
110
+
81
111
  raise exception.MappingError(f'"{name}" is not a known variable')
82
112
 
83
113
  def get_variable(self, name: str, raise_on_missing: bool = True) -> exp.Expr | None:
84
- """Resolve a variable by searching from innermost to outermost scopes."""
85
- for scope in reversed(self.variable_scopes):
86
- if name in scope:
87
- return scope[name]
114
+ """Resolve a variable by searching from innermost block outward, then the call's bindings."""
115
+ for block in reversed(self._active_blocks):
116
+ if name in block:
117
+ return block[name]
118
+ binding = self._active_bindings.get(name)
119
+ if binding is not None:
120
+ return binding.value
88
121
  if raise_on_missing:
89
122
  raise exception.MappingError(f"Could not find value for variable: {name}")
90
123
  return None
@@ -110,8 +143,28 @@ class ObjectMapping(MappingSchema):
110
143
  return resolved
111
144
 
112
145
  def get_scope(self) -> dict[str, exp.Expr]:
113
- """Return the current scope dict (innermost)."""
114
- return self.variable_scopes[-1]
146
+ """Return the current block dict (innermost)."""
147
+ return self._active_blocks[-1]
148
+
149
+
150
+ class ObjectMapping(MappingSchema):
151
+ """
152
+ Contains all the objects that get created, such as tables, procedures, functions, and sequences.
153
+
154
+ We extends sqlglot.MappingSchema to provide additional functionality related to tracking these objects,
155
+ while still allowing optimizer inside sqlglot to work (as it needs a mapping of objects to perform functions
156
+ like qualification and simplification).
157
+ """
158
+
159
+ def __init__(self, dialect: str):
160
+ super().__init__(
161
+ dialect=dialect, normalize=False
162
+ ) # Set `normalize=False` to prevent an unnecessary second parse.
163
+ self.kind_mapping = {}
164
+ self.kind_mapping_trie = {}
165
+ # Session/global variables (e.g., SET var = ...)
166
+ self.session_variables: dict[str, exp.Expr] = {}
167
+ self.variables = Variables()
115
168
 
116
169
  def add_database_query(self, query: DatabaseQuery) -> None:
117
170
  self._add_query(query=query, dialect=query.dialect)
@@ -356,7 +409,9 @@ class ObjectMapping(MappingSchema):
356
409
 
357
410
  return resolve_overloaded_function(node, candidates)
358
411
 
359
- def lookup_procedure_call(self, node: CallQuery) -> ProcedureQuery | None:
412
+ def lookup_procedure_call(
413
+ self, node: CallQuery, args: list[exp.Expr] | None = None
414
+ ) -> ProcedureQuery | None:
360
415
  """
361
416
  Looks up the procedure definition for a CALL statement.
362
417
  Returns the matched procedure definition, or None if no procedure with that name exists.
@@ -367,11 +422,11 @@ class ObjectMapping(MappingSchema):
367
422
  return None
368
423
 
369
424
  # Annotate copies so the call's own expressions are left untouched
370
- args = [arg.copy() for arg in node.args]
371
- for arg in args:
425
+ call_args = [arg.copy() for arg in (args if args is not None else node.args)]
426
+ for arg in call_args:
372
427
  annotate_types(_get_call_arg_value(arg), dialect=self.dialect, schema=self)
373
428
 
374
- return resolve_overloaded_procedure(args, candidates)
429
+ return resolve_overloaded_procedure(call_args, candidates)
375
430
 
376
431
 
377
432
  def resolve_overloaded_function(
@@ -504,6 +559,8 @@ def match_callable_arguments(args: list[exp.Expr], params: list[FunctionParam])
504
559
  if param.default is None and not param.is_variadic:
505
560
  return False
506
561
  elif param.is_input and not isinstance(bound[i], exp.Null):
562
+ if param.is_output and isinstance(bound[i], exp.Column) and not bound[i].table:
563
+ continue
507
564
  if not _match_argument(bound[i], param.type):
508
565
  return False
509
566
 
@@ -11,7 +11,7 @@ from sqlglot import exp
11
11
  from sqlglot.optimizer.annotate_types import annotate_types
12
12
 
13
13
  from sqlleaf import exception, mappings, util
14
- from sqlleaf.typing import SourceExprType, SourceInfo, SqlObjectType, TargetExprType, TargetInfo
14
+ from sqlleaf.typing import SourceInfo, SqlObjectType, TargetInfo
15
15
 
16
16
  logger = logging.getLogger("sqlleaf")
17
17
 
@@ -8,7 +8,7 @@ from sqlglot import exp
8
8
 
9
9
  from sqlleaf import exception, mappings, util
10
10
  from sqlleaf.models.query.base import Query
11
- from sqlleaf.typing import SourceExprType, SourceInfo, TargetExprType, TargetInfo
11
+ from sqlleaf.typing import SourceInfo, TargetInfo
12
12
 
13
13
  logger = logging.getLogger("sqlleaf")
14
14
 
@@ -114,7 +114,7 @@ class CopyQuery(Query):
114
114
 
115
115
  def get_source_and_target_expressions(
116
116
  self, expr: exp.Copy, dialect: str
117
- ) -> tuple[SourceExprType, TargetExprType]:
117
+ ) -> tuple[exp.Expr, exp.Expr]:
118
118
  """
119
119
  Determine the source and target expressions of the query.
120
120
  """
@@ -48,7 +48,7 @@ class OpenQuery(Query):
48
48
  [key]
49
49
  """
50
50
  cursor_name = self.target()
51
- cursor_expr = self.object_mapping.get_variable(name=cursor_name.name)
51
+ cursor_expr = self.object_mapping.variables.get_variable(name=cursor_name.name)
52
52
  if cursor_expr.parent:
53
53
  return cursor_expr.parent.args.get("cursor_args")
54
54
  return []
@@ -101,8 +101,11 @@ def _resolve_call_sites(
101
101
  Extract child statements and inline user-defined functions into downstream query holders.
102
102
  """
103
103
  subst_statements: list[exp.Expr] = []
104
+ call_scope_pushed = False
104
105
  if isinstance(query, CallQuery):
105
- subst_statements = substitute.substitute_call(query=query)
106
+ subst_statements, bindings = substitute.substitute_call(query=query)
107
+ object_mapping.variables.push_scope(bindings)
108
+ call_scope_pushed = True
106
109
  elif isinstance(query, DoQuery):
107
110
  subst_statements = query.inner_statements
108
111
  elif isinstance(query, ExecuteQuery):
@@ -120,9 +123,13 @@ def _resolve_call_sites(
120
123
  process_statement(subst_stmt, dialect, object_mapping, stmt_index, parent_holder=holder)
121
124
 
122
125
  parent_index = query.get_statement_index()
126
+
123
127
  for i, stmt in enumerate(subst_statements):
124
128
  process_statement(stmt, dialect, object_mapping, f"{parent_index}:{i}", parent_holder=holder)
125
129
 
130
+ if call_scope_pushed:
131
+ object_mapping.variables.pop_scope(write_back=True)
132
+
126
133
 
127
134
  def _collect_sequential_children(
128
135
  query: Q, holder: QueryHolder, dialect: str, object_mapping: mappings.ObjectMapping
@@ -133,7 +140,7 @@ def _collect_sequential_children(
133
140
  to use their results (e.g. variables/state).
134
141
  """
135
142
  if isinstance(query, (BlockQuery, ForInQuery, LoopQuery, WhileQuery)):
136
- object_mapping.push_variable_scope()
143
+ object_mapping.variables.push_block()
137
144
 
138
145
  if isinstance(query, BlockQuery):
139
146
  statement_idx = 0
@@ -163,7 +170,7 @@ def _collect_sequential_children(
163
170
  # Loop over the inner statements N times (where N = the loop count)
164
171
  for loop_val in query.range_values():
165
172
  val_expr = exp.Neg(this=exp.Literal.number(-loop_val)) if loop_val < 0 else exp.Literal.number(loop_val)
166
- object_mapping.declare_variable(target_name, val_expr)
173
+ object_mapping.variables.declare_variable(target_name, val_expr)
167
174
 
168
175
  for stmt in query.inner_statements:
169
176
  stmt_copy = util.copy_expression(stmt)
@@ -191,7 +198,7 @@ def _collect_sequential_children(
191
198
  process_statement(stmt, dialect, object_mapping, i + 1, parent_holder=holder)
192
199
 
193
200
  if isinstance(query, (BlockQuery, ForInQuery, LoopQuery, WhileQuery)):
194
- object_mapping.pop_variable_scope()
201
+ object_mapping.variables.pop_block()
195
202
 
196
203
 
197
204
  def _collect_structural_children(
@@ -31,8 +31,8 @@ from sqlleaf.models.node import (
31
31
  VarNode,
32
32
  WindowNode,
33
33
  )
34
- from sqlleaf.models.query import Query, TableQuery
35
- from sqlleaf.typing import SourceExprType, SqlObjectType, TargetExprType
34
+ from sqlleaf.models.query import TableQuery
35
+ from sqlleaf.typing import SqlObjectType
36
36
 
37
37
  logger = logging.getLogger("sqlleaf")
38
38
 
@@ -495,7 +495,7 @@ class BaseGenerator:
495
495
  def create_node_from_type(
496
496
  self,
497
497
  object_type: SqlObjectType,
498
- expression: TargetExprType | SourceExprType,
498
+ expression: exp.Expr | exp.Expr,
499
499
  column_name: str,
500
500
  gen_ctx: GeneratorContext,
501
501
  pos_ctx: PositionContext,
@@ -16,6 +16,7 @@ from sqlleaf.models.query import (
16
16
  Q,
17
17
  UserDefinedFunctionQuery,
18
18
  )
19
+ from sqlleaf.processors.transformer.base import BaseQueryTransformer
19
20
  from sqlleaf.processors.transformer.expressions import normalize_values, simplify_format
20
21
  from sqlleaf.processors.transformer.expressions.row import transform_row_function_to_subquery
21
22
 
@@ -192,7 +193,7 @@ def substitute_cursor_parameters(
192
193
  Result: `SELECT UPPER('abc') AS name`
193
194
  """
194
195
  params = [FunctionParam(name=arg.this.name, type=arg.args.get("kind")) for arg in cursor_args]
195
- params_from_variables = {param.name: object_mapping.get_variable(param.name, raise_on_missing=False) for param in params}
196
+ params_from_variables = {param.name: object_mapping.variables.get_variable(param.name, raise_on_missing=False) for param in params}
196
197
  param_map, positional_map = _build_param_maps(args=call_args or [], params=params, params_from_variables=params_from_variables)
197
198
  return substitute_parameters(cursor_query, None, param_map, positional_map)
198
199
 
@@ -321,7 +322,19 @@ def _replace_dot_reference(
321
322
  node.set("this", exp.Paren(this=sub.copy()))
322
323
 
323
324
 
324
- def substitute_call(query: CallQuery) -> list[exp.Expr]:
325
+ def _resolve_call_args(query: CallQuery) -> list[exp.Expr]:
326
+ """Resolve CALL argument expressions while the caller's variables are visible."""
327
+ query_transformer = BaseQueryTransformer(query)
328
+ resolved_args = []
329
+ for arg in query.args:
330
+ arg_copy = arg.copy()
331
+ wrapper = exp.select(arg_copy)
332
+ query_transformer.replace_variables_in_expression(wrapper)
333
+ resolved_args.append(wrapper.expressions[0])
334
+ return resolved_args
335
+
336
+
337
+ def substitute_call(query: CallQuery) -> tuple[list[exp.Expr], dict[str, mappings.ParamBinding]]:
325
338
  """
326
339
  Substitutes a CALL statement's arguments into the statmenets inside its body and returns them.
327
340
  Circular references in procedure-to-procedure calls could cause infinite recursion.
@@ -332,35 +345,48 @@ def substitute_call(query: CallQuery) -> list[exp.Expr]:
332
345
  ->
333
346
  SELECT 3;
334
347
  """
335
- matched_proc = query.object_mapping.lookup_procedure_call(query)
348
+ resolved_args = _resolve_call_args(query)
349
+ matched_proc = query.object_mapping.lookup_procedure_call(query, args=resolved_args)
336
350
  if not matched_proc:
337
- return []
351
+ return [], {}
338
352
 
339
353
  logger.debug(f"Substituting CALL query '{query.name}' with procedure body")
340
354
 
341
355
  # Re-use find_arg logic. We don't have an Anonymous node,
342
356
  # just a list of args from the CallQuery.
343
- param_map = {}
357
+ bindings = {}
344
358
  positional_map = {}
345
- args = query.args
359
+ args = resolved_args
346
360
 
347
361
  for i, param in enumerate(matched_proc.parameters):
348
- arg_expr = _find_arg(args, param, i) or param.default
362
+ arg_expr = _find_arg(args, param, i)
363
+ raw_arg_expr = _find_arg(query.args, param, i)
364
+
365
+ if param.is_output:
366
+ initial_value = exp.Null()
367
+ if param.is_input and arg_expr is not None:
368
+ initial_value = arg_expr.copy()
369
+ arg_name = raw_arg_expr.name if isinstance(raw_arg_expr, exp.Column) and not raw_arg_expr.table else None
370
+ bindings[param.name.lower()] = mappings.ParamBinding(value=initial_value, arg_name=arg_name)
371
+ else:
372
+ value = arg_expr or param.default or exp.Null()
373
+ bindings[param.name.lower()] = mappings.ParamBinding(value=value.copy())
349
374
 
350
375
  if arg_expr:
351
- param_map[param.name.lower()] = arg_expr
352
376
  positional_map[str(i + 1)] = arg_expr
377
+ elif param.default:
378
+ positional_map[str(i + 1)] = param.default
353
379
 
354
380
  replacement_exprs = []
355
381
  for stmt in matched_proc.inner_statements:
356
382
  # Procedures can contain multiple statements
357
- new_stmt = substitute_parameters(stmt.copy(), None, param_map, positional_map)
383
+ new_stmt = substitute_parameters(stmt.copy(), None, {}, positional_map)
358
384
  replacement_exprs.append(new_stmt)
359
385
 
360
386
  logger.debug(f"Substituted to {len(replacement_exprs)} statements:")
361
387
  for r in replacement_exprs:
362
388
  logger.debug(f" {r.sql(dialect=query.dialect)}")
363
- return replacement_exprs
389
+ return replacement_exprs, bindings
364
390
 
365
391
 
366
392
  def substitute_execute_with_plan(
@@ -425,7 +451,7 @@ def resolve_dynamic_sql_command(
425
451
  if isinstance(command, exp.Literal):
426
452
  resolved_command = command
427
453
  elif isinstance(command, exp.Column):
428
- resolved_command = object_mapping.get_variable(name=command.name)
454
+ resolved_command = object_mapping.variables.get_variable(name=command.name)
429
455
  if not isinstance(resolved_command, exp.Literal):
430
456
  exception.raise_error(
431
457
  exception.UnsupportedFeatureError,
@@ -438,7 +464,7 @@ def resolve_dynamic_sql_command(
438
464
  for column in list(command_with_variables.find_all(exp.Column)):
439
465
  if column.table:
440
466
  continue
441
- variable = object_mapping.get_variable(name=column.name, raise_on_missing=False)
467
+ variable = object_mapping.variables.get_variable(name=column.name, raise_on_missing=False)
442
468
  if variable is not None:
443
469
  column.replace(variable.copy())
444
470
  formatted_command = simplify_format(command_with_variables, dialect=dialect)
@@ -453,7 +479,7 @@ def resolve_dynamic_sql_command(
453
479
 
454
480
  resolved_stmt = sqlglot.parse_one(resolved_command.this, dialect=dialect)
455
481
  if using:
456
- resolved_using = object_mapping.get_variables_for(expressions=using)
482
+ resolved_using = object_mapping.variables.get_variables_for(expressions=using)
457
483
  if resolved_using:
458
484
  positional_map = {str(i + 1): value for i, value in enumerate(resolved_using)}
459
485
  resolved_stmt = substitute_parameters(resolved_stmt, None, {}, positional_map)