sqlleaf 0.0.2__tar.gz → 0.0.3__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 (134) hide show
  1. {sqlleaf-0.0.2/sqlleaf.egg-info → sqlleaf-0.0.3}/PKG-INFO +7 -1
  2. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/README.md +6 -0
  3. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/pyproject.toml +1 -1
  4. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/mappings.py +16 -5
  5. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/__init__.py +6 -0
  6. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/block.py +4 -0
  7. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/declare_item.py +4 -0
  8. sqlleaf-0.0.3/sqlleaf/models/query/do.py +108 -0
  9. sqlleaf-0.0.2/sqlleaf/models/query/for_in.py → sqlleaf-0.0.3/sqlleaf/models/query/exception_.py +6 -6
  10. sqlleaf-0.0.3/sqlleaf/models/query/for_in.py +94 -0
  11. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/collector/classify.py +2 -0
  12. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/collector/collector.py +52 -5
  13. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/__init__.py +2 -0
  14. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/base.py +15 -2
  15. sqlleaf-0.0.3/sqlleaf/processors/transformer/for_in.py +30 -0
  16. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/transformer.py +4 -1
  17. {sqlleaf-0.0.2 → sqlleaf-0.0.3/sqlleaf.egg-info}/PKG-INFO +7 -1
  18. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf.egg-info/SOURCES.txt +5 -1
  19. sqlleaf-0.0.3/tests/test_hooks.py +64 -0
  20. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/LICENSE +0 -0
  21. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/setup.cfg +0 -0
  22. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/__init__.py +0 -0
  23. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/__init__.py +0 -0
  24. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/__init__.py +0 -0
  25. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/p_classes.py +0 -0
  26. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/p_dialect.py +0 -0
  27. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/p_generator.py +0 -0
  28. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/p_parser.py +0 -0
  29. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/dialects/plpgsql/p_tokenizer.py +0 -0
  30. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/exception.py +0 -0
  31. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/lineage.py +0 -0
  32. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/__init__.py +0 -0
  33. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/context.py +0 -0
  34. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/hook.py +0 -0
  35. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/__init__.py +0 -0
  36. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/base.py +0 -0
  37. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/column.py +0 -0
  38. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/dynamodb.py +0 -0
  39. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/function.py +0 -0
  40. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/interval.py +0 -0
  41. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/json.py +0 -0
  42. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/literal.py +0 -0
  43. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/null.py +0 -0
  44. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/pivot.py +0 -0
  45. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/program.py +0 -0
  46. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/sequence.py +0 -0
  47. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/star.py +0 -0
  48. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/stream.py +0 -0
  49. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/user_defined_function.py +0 -0
  50. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/var.py +0 -0
  51. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/variable.py +0 -0
  52. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/node/window.py +0 -0
  53. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/base.py +0 -0
  54. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/call.py +0 -0
  55. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/copy.py +0 -0
  56. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/ctas.py +0 -0
  57. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/database.py +0 -0
  58. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/delete.py +0 -0
  59. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/execute.py +0 -0
  60. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/execute_dynamic.py +0 -0
  61. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/fetch.py +0 -0
  62. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/holder.py +0 -0
  63. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/if_.py +0 -0
  64. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/insert.py +0 -0
  65. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/loop.py +0 -0
  66. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/merge.py +0 -0
  67. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/multitable_insert.py +0 -0
  68. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/open.py +0 -0
  69. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/perform.py +0 -0
  70. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/prepare.py +0 -0
  71. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/procedure.py +0 -0
  72. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/put.py +0 -0
  73. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/replace.py +0 -0
  74. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/schema.py +0 -0
  75. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/select.py +0 -0
  76. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/sequence.py +0 -0
  77. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/set.py +0 -0
  78. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/stage.py +0 -0
  79. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/table.py +0 -0
  80. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/trigger.py +0 -0
  81. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/type.py +0 -0
  82. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/unload.py +0 -0
  83. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/update.py +0 -0
  84. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/user_defined_function.py +0 -0
  85. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/values.py +0 -0
  86. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/view.py +0 -0
  87. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/models/query/while_.py +0 -0
  88. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/path.py +0 -0
  89. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/__init__.py +0 -0
  90. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/collector/__init__.py +0 -0
  91. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/__init__.py +0 -0
  92. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/__init__.py +0 -0
  93. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/athena.py +0 -0
  94. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/base.py +0 -0
  95. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/mysql.py +0 -0
  96. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/postgres.py +0 -0
  97. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/redshift.py +0 -0
  98. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/dialects/snowflake.py +0 -0
  99. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/generator/generator.py +0 -0
  100. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/substitutor/__init__.py +0 -0
  101. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/substitutor/substitute.py +0 -0
  102. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/assignment.py +0 -0
  103. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/call.py +0 -0
  104. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/copy.py +0 -0
  105. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/ctas.py +0 -0
  106. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/delete.py +0 -0
  107. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/execute.py +0 -0
  108. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/execute_dynamic.py +0 -0
  109. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/expressions/__init__.py +0 -0
  110. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/expressions/format.py +0 -0
  111. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/expressions/functional_notation.py +0 -0
  112. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/expressions/row.py +0 -0
  113. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/expressions/values.py +0 -0
  114. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/insert.py +0 -0
  115. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/merge.py +0 -0
  116. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/multitable_insert.py +0 -0
  117. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/open.py +0 -0
  118. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/replace.py +0 -0
  119. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/unload.py +0 -0
  120. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/update.py +0 -0
  121. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/processors/transformer/values.py +0 -0
  122. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/settings/__init__.py +0 -0
  123. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/settings/athena.py +0 -0
  124. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/settings/base.py +0 -0
  125. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/settings/postgres.py +0 -0
  126. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/typing.py +0 -0
  127. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/util/__init__.py +0 -0
  128. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/util/expression.py +0 -0
  129. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/util/graph.py +0 -0
  130. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/util/helpers.py +0 -0
  131. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf/util/iterators.py +0 -0
  132. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf.egg-info/dependency_links.txt +0 -0
  133. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf.egg-info/requires.txt +0 -0
  134. {sqlleaf-0.0.2 → sqlleaf-0.0.3}/sqlleaf.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlleaf
3
- Version: 0.0.2
3
+ Version: 0.0.3
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
@@ -43,6 +43,12 @@ column[logins.name] -> function[LOWER] -> column[users.name]
43
43
  function[CURRENT_TIMESTAMP] -> column[users.birthday]
44
44
  ```
45
45
 
46
+ ## Installation
47
+ Available on PyPI:
48
+ ```
49
+ pip3 install sqlleaf
50
+ ```
51
+
46
52
  ## Applications
47
53
  sqlleaf allows you to build a wide range of new applications on top of SQL databases, such as:
48
54
  - data tracing and tagging systems, such as personally identifiable information tracking
@@ -30,6 +30,12 @@ column[logins.name] -> function[LOWER] -> column[users.name]
30
30
  function[CURRENT_TIMESTAMP] -> column[users.birthday]
31
31
  ```
32
32
 
33
+ ## Installation
34
+ Available on PyPI:
35
+ ```
36
+ pip3 install sqlleaf
37
+ ```
38
+
33
39
  ## Applications
34
40
  sqlleaf allows you to build a wide range of new applications on top of SQL databases, such as:
35
41
  - data tracing and tagging systems, such as personally identifiable information tracking
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlleaf"
3
- version = "0.0.2"
3
+ version = "0.0.3"
4
4
  authors = [
5
5
  {name = "zac", email = "zac@sqlleaf.io"}
6
6
  ]
@@ -60,13 +60,24 @@ class ObjectMapping(MappingSchema):
60
60
  if self.variable_scopes:
61
61
  self.variable_scopes.pop()
62
62
 
63
+ def declare_variable(self, name: str, value: exp.Expr | None = None) -> None:
64
+ """Declare a variable in the current (innermost) scope."""
65
+ val = value if value is not None else exp.Null()
66
+ self.variable_scopes[-1][name] = val
67
+ logger.debug(f"Declared variable: {name} := {val.sql(dialect=self.dialect)}")
68
+
63
69
  def set_variable(self, name: str, value: exp.Expr) -> None:
64
- """Assign or declare a variable in the current scope."""
65
- self.variable_scopes[-1][name] = value
66
- logger.debug(f"Set variable value: {name} := {value.sql()}")
70
+ """Assign a variable in the nearest scope where it was declared."""
71
+ for scope in reversed(self.variable_scopes):
72
+ if name in scope:
73
+ scope[name] = value
74
+ logger.debug(f"Set variable value: {name} := {value.sql(dialect=self.dialect)}")
75
+ return
76
+
77
+ raise exception.MappingError(f'"{name}" is not a known variable')
67
78
 
68
79
  def get_variable(self, name: str, raise_on_missing: bool = True) -> exp.Expr | None:
69
- """Resolve a variable by searching from innermost to outermost scopes, then session vars."""
80
+ """Resolve a variable by searching from innermost to outermost scopes."""
70
81
  for scope in reversed(self.variable_scopes):
71
82
  if name in scope:
72
83
  return scope[name]
@@ -87,7 +98,7 @@ class ObjectMapping(MappingSchema):
87
98
  resolved = []
88
99
  for expr in expressions:
89
100
  if isinstance(expr, exp.Column) and not expr.table:
90
- variable = self.get_variable(expr.name)
101
+ variable = self.get_variable(expr.name, raise_on_missing=False)
91
102
  if variable is not None:
92
103
  resolved.append(variable.copy())
93
104
  continue
@@ -8,11 +8,14 @@ from sqlleaf.models.query.ctas import CTASQuery as CTASQuery
8
8
  from sqlleaf.models.query.database import DatabaseQuery as DatabaseQuery
9
9
  from sqlleaf.models.query.declare_item import AssignmentQuery as AssignmentQuery
10
10
  from sqlleaf.models.query.delete import DeleteQuery as DeleteQuery
11
+ from sqlleaf.models.query.do import DoQuery as DoQuery
12
+ from sqlleaf.models.query.exception_ import ExceptionQuery as ExceptionQuery
11
13
  from sqlleaf.models.query.execute import ExecuteQuery as ExecuteQuery
12
14
  from sqlleaf.models.query.execute_dynamic import ExecuteDynamicQuery as ExecuteDynamicQuery
13
15
  from sqlleaf.models.query.fetch import FetchQuery as FetchQuery
14
16
  from sqlleaf.models.query.for_in import ForInQuery as ForInQuery
15
17
  from sqlleaf.models.query.holder import QueryHolder as QueryHolder
18
+ from sqlleaf.models.query.if_ import IfQuery as IfQuery
16
19
  from sqlleaf.models.query.insert import InsertQuery as InsertQuery
17
20
  from sqlleaf.models.query.loop import LoopQuery as LoopQuery
18
21
  from sqlleaf.models.query.merge import MergeQuery as MergeQuery
@@ -49,11 +52,14 @@ __all__ = [
49
52
  "CTASQuery",
50
53
  "DatabaseQuery",
51
54
  "DeleteQuery",
55
+ "DoQuery",
56
+ "ExceptionQuery",
52
57
  "ExecuteDynamicQuery",
53
58
  "ExecuteQuery",
54
59
  "FetchQuery",
55
60
  "ForInQuery",
56
61
  "FunctionParam",
62
+ "IfQuery",
57
63
  "InsertQuery",
58
64
  "LoopQuery",
59
65
  "MergeQuery",
@@ -33,3 +33,7 @@ class BlockQuery(Query):
33
33
  @property
34
34
  def inner_statements(self) -> list[exp.Expr]:
35
35
  return self.statement.expressions
36
+
37
+ @property
38
+ def exception_statement(self) -> pgexp.PGException | None:
39
+ return self.statement.args.get("exception")
@@ -26,6 +26,10 @@ class AssignmentQuery(Query):
26
26
  target_info=None,
27
27
  )
28
28
 
29
+ @property
30
+ def is_declaration(self) -> bool:
31
+ return isinstance(self.statement, pgexp.PGDeclareItem)
32
+
29
33
  def get_key(self) -> exp.Expr:
30
34
  return self.statement.this.name
31
35
 
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+ import sqlglot
7
+ from sqlglot import exp
8
+
9
+ from sqlleaf import exception, mappings
10
+ from sqlleaf.models.query.base import Query
11
+ from sqlleaf.util import iterators
12
+
13
+
14
+ def _extract_do_body_and_language(raw_text: str) -> tuple[str, str]:
15
+ text = raw_text.strip()
16
+ language = "PLPGSQL"
17
+
18
+ lang_match = re.search(r"LANGUAGE\s+([a-zA-Z0-9_'\"]+)", text, re.IGNORECASE)
19
+ if lang_match:
20
+ language = lang_match.group(1).strip("'\"").upper()
21
+ text = text[: lang_match.start()] + text[lang_match.end() :]
22
+ text = text.strip()
23
+
24
+ dollar_match = re.match(r"^\$([a-zA-Z0-9_]*)\$(.*)\$\1\$$", text, re.DOTALL)
25
+ if dollar_match:
26
+ body = dollar_match.group(2)
27
+ elif text.startswith("'") and text.endswith("'"):
28
+ body = text[1:-1].replace("''", "'")
29
+ else:
30
+ body = text
31
+
32
+ return language, body.strip()
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class DoQueryProperties:
37
+ language: str
38
+ body: str
39
+ inner_statements: list[exp.Expr]
40
+
41
+ @classmethod
42
+ def from_expression(
43
+ cls, statement: exp.Command, dialect: str, object_mapping: mappings.ObjectMapping
44
+ ) -> DoQueryProperties:
45
+ expr = statement.args.get("expression")
46
+ if isinstance(expr, (exp.Literal, exp.Heredoc)):
47
+ raw_text = expr.this
48
+ elif hasattr(expr, "name") and expr.name:
49
+ raw_text = expr.name
50
+ elif expr is not None:
51
+ raw_text = str(expr)
52
+ else:
53
+ raw_text = ""
54
+
55
+ language, body = _extract_do_body_and_language(raw_text)
56
+
57
+ if language.upper() not in iterators.SUPPORTED_LANGUAGES:
58
+ exception.raise_error(
59
+ exception.UnsupportedFeatureError,
60
+ message=f"Unsupported language for DO block: {language}",
61
+ )
62
+
63
+ parse_dialect = language.lower() if dialect == "postgres" and language.upper() == "PLPGSQL" else dialect
64
+ inner_statements = sqlglot.parse(body, dialect=parse_dialect)
65
+ inner_statements = [
66
+ stmt
67
+ for stmt in inner_statements
68
+ if not isinstance(stmt, (exp.EndStatement, exp.Column, exp.Identifier))
69
+ ]
70
+
71
+ return cls(
72
+ language=language,
73
+ body=body,
74
+ inner_statements=inner_statements,
75
+ )
76
+
77
+
78
+ class DoQuery(Query):
79
+ KIND = "do"
80
+
81
+ def __init__(
82
+ self,
83
+ expr: exp.Command,
84
+ dialect: str,
85
+ object_mapping: mappings.ObjectMapping,
86
+ statement_index: int,
87
+ ):
88
+ super().__init__(
89
+ dialect=dialect,
90
+ statement=expr,
91
+ statement_index=statement_index,
92
+ object_mapping=object_mapping,
93
+ source_info=None,
94
+ target_info=None,
95
+ )
96
+ self.properties = DoQueryProperties.from_expression(expr, dialect, object_mapping)
97
+
98
+ @property
99
+ def language(self) -> str:
100
+ return self.properties.language
101
+
102
+ @property
103
+ def body(self) -> str:
104
+ return self.properties.body
105
+
106
+ @property
107
+ def inner_statements(self) -> list[exp.Expr]:
108
+ return self.properties.inner_statements
@@ -3,16 +3,16 @@ from __future__ import annotations
3
3
  from sqlglot import exp
4
4
 
5
5
  from sqlleaf import mappings
6
- from sqlleaf.models.query.base import Query
7
6
  from sqlleaf.dialects.plpgsql import pgexp
7
+ from sqlleaf.models.query.base import Query
8
8
 
9
9
 
10
- class ForInQuery(Query):
11
- KIND = "for_in"
10
+ class ExceptionQuery(Query):
11
+ KIND = "exception"
12
12
 
13
13
  def __init__(
14
14
  self,
15
- expr: pgexp.PGForIn,
15
+ expr: pgexp.PGException,
16
16
  dialect: str,
17
17
  object_mapping: mappings.ObjectMapping,
18
18
  statement_index: int,
@@ -27,5 +27,5 @@ class ForInQuery(Query):
27
27
  )
28
28
 
29
29
  @property
30
- def inner_statements(self) -> list[exp.Expr]:
31
- return self.statement.expressions
30
+ def whens(self) -> list[pgexp.PGWhen]:
31
+ return self.statement.args.get("whens") or []
@@ -0,0 +1,94 @@
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import exp
4
+
5
+ from sqlleaf import mappings
6
+ from sqlleaf.dialects.plpgsql import pgexp
7
+ from sqlleaf.models.query.base import Query
8
+
9
+
10
+ class ForInQuery(Query):
11
+ KIND = "for_in"
12
+
13
+ def __init__(
14
+ self,
15
+ expr: pgexp.PGForIn,
16
+ dialect: str,
17
+ object_mapping: mappings.ObjectMapping,
18
+ statement_index: int,
19
+ ):
20
+ super().__init__(
21
+ dialect=dialect,
22
+ statement=expr,
23
+ statement_index=statement_index,
24
+ object_mapping=object_mapping,
25
+ source_info=None,
26
+ target_info=None,
27
+ )
28
+
29
+ @property
30
+ def inner_statements(self) -> list[exp.Expr]:
31
+ return self.statement.expressions or []
32
+
33
+ @property
34
+ def target(self) -> exp.Identifier | exp.Column | None:
35
+ return self.statement.this
36
+
37
+ @property
38
+ def query(self) -> exp.Expr | None:
39
+ return self.statement.args.get("query")
40
+
41
+ @property
42
+ def is_range(self) -> bool:
43
+ return self.statement.args.get("start") is not None
44
+
45
+ @property
46
+ def start(self) -> exp.Expr | None:
47
+ return self.statement.args.get("start")
48
+
49
+ @property
50
+ def end(self) -> exp.Expr | None:
51
+ return self.statement.args.get("end")
52
+
53
+ @property
54
+ def step(self) -> exp.Expr | exp.Literal:
55
+ return self.statement.args.get("step") or exp.Literal.number(1)
56
+
57
+ @property
58
+ def is_reverse(self) -> bool:
59
+ return bool(self.statement.args.get("reverse"))
60
+
61
+ def range_values(self) -> list[int]:
62
+ """
63
+ Return the list of integer values produced by the range iterator.
64
+
65
+ For example, given expression "FOR x IN 1..3", we return [1,2,3]
66
+
67
+ # TODO: this can return expressions, not just integers
68
+ """
69
+ if self.start is None or self.end is None:
70
+ return []
71
+
72
+ start_val = self.start.to_py()
73
+ end_val = self.end.to_py()
74
+ step_val = self.step.to_py()
75
+
76
+ # TODO: validate relations between start/end/steps/
77
+
78
+ """
79
+ FOR i IN 1..3 LOOP
80
+ -- i will take on the values 1,2,3 within the loop
81
+ END LOOP;
82
+
83
+ FOR i IN 1..3 BY 2 LOOP
84
+ -- i will take on the values 1,3 within the loop
85
+ END LOOP;
86
+
87
+ FOR i IN REVERSE 3..1 LOOP
88
+ -- i will take on the values 3,2,1 within the loop
89
+ END LOOP;
90
+ """
91
+ if self.is_reverse:
92
+ return list(range(start_val, end_val - 1, -step_val)) if start_val >= end_val else []
93
+ else:
94
+ return list(range(start_val, end_val + 1, step_val)) if start_val <= end_val else []
@@ -52,6 +52,8 @@ def _classify_command(stmt: exp.Command, dialect: str) -> tuple[str, bool]:
52
52
  return "replace", _is_replace_supported(stmt, dialect)
53
53
  if stmt.this.upper() == "CALL":
54
54
  return "call", True
55
+ if stmt.this.upper() == "DO" or stmt.name.upper() == "DO":
56
+ return "do", True
55
57
  return "", False
56
58
 
57
59
 
@@ -17,7 +17,7 @@ from sqlleaf.processors.transformer.expressions import simplify_row_in_values
17
17
 
18
18
  logger = logging.getLogger("sqlleaf")
19
19
 
20
- IMMEDIATE_TRANSFORM = (BlockQuery, ForInQuery, LoopQuery, OpenQuery, WhileQuery)
20
+ IMMEDIATE_TRANSFORM = (BlockQuery, ExceptionQuery, ForInQuery, IfQuery, LoopQuery, OpenQuery, WhileQuery)
21
21
 
22
22
  """
23
23
  Parses text for SQL statements and collects them into Query models.
@@ -72,7 +72,7 @@ def process_statement(
72
72
  if isinstance(query, IMMEDIATE_TRANSFORM):
73
73
  # Immediately transform queries inside a dynamic SQL block so that subsequent statements can used their values
74
74
  transformer.transform_query(holder)
75
- _collect_sequential_children(query, holder, dialect, object_mapping)
75
+ _collect_sequential_children(holder.transformed, holder, dialect, object_mapping)
76
76
  else:
77
77
  _resolve_call_sites(query, holder, dialect, object_mapping)
78
78
  _collect_structural_children(query, holder, dialect, object_mapping)
@@ -96,6 +96,8 @@ def _resolve_call_sites(
96
96
  subst_statements: list[exp.Expr] = []
97
97
  if isinstance(query, CallQuery):
98
98
  subst_statements = substitute.substitute_call(query=query)
99
+ elif isinstance(query, DoQuery):
100
+ subst_statements = query.inner_statements
99
101
  elif isinstance(query, ExecuteQuery):
100
102
  subst_statements = substitute.substitute_execute(query=query)
101
103
  elif isinstance(query, ExecuteDynamicQuery):
@@ -136,11 +138,46 @@ def _collect_sequential_children(
136
138
  process_statement(block_expr, dialect, object_mapping, statement_idx, parent_holder=holder)
137
139
  statement_idx += 1
138
140
 
141
+ if query.exception_statement:
142
+ process_statement(query.exception_statement, dialect, object_mapping, statement_idx, parent_holder=holder)
143
+ statement_idx += 1
144
+
145
+ elif isinstance(query, ExceptionQuery):
146
+ statement_idx = 0
147
+ for when in query.whens:
148
+ for stmt in when.args.get("then") or []:
149
+ process_statement(stmt, dialect, object_mapping, statement_idx, parent_holder=holder)
150
+ statement_idx += 1
151
+
139
152
  elif isinstance(query, ForInQuery):
140
- process_statement(query.statement.args["query"], dialect, object_mapping, 0, parent_holder=holder)
153
+ if query.is_range:
154
+ target_name = query.target.name
155
+ statement_idx = 0
156
+ # Loop over the inner statements N times (where N = the loop count)
157
+ for loop_val in query.range_values():
158
+ val_expr = exp.Neg(this=exp.Literal.number(-loop_val)) if loop_val < 0 else exp.Literal.number(loop_val)
159
+ object_mapping.declare_variable(target_name, val_expr)
160
+
161
+ for stmt in query.inner_statements:
162
+ stmt_copy = util.copy_expression(stmt)
163
+ process_statement(stmt_copy, dialect, object_mapping, statement_idx, parent_holder=holder)
164
+ statement_idx += 1
165
+ else:
166
+ if query.query is not None:
167
+ process_statement(query.query, dialect, object_mapping, 0, parent_holder=holder)
141
168
 
142
- for i, stmt in enumerate(query.inner_statements):
143
- process_statement(stmt, dialect, object_mapping, i + 1, parent_holder=holder)
169
+ for i, stmt in enumerate(query.inner_statements):
170
+ process_statement(stmt, dialect, object_mapping, i + 1, parent_holder=holder)
171
+
172
+ elif isinstance(query, IfQuery):
173
+ statement_idx = 0
174
+ for branch in query.branches:
175
+ for stmt in branch.args.get("then") or []:
176
+ process_statement(stmt, dialect, object_mapping, statement_idx, parent_holder=holder)
177
+ statement_idx += 1
178
+ for stmt in query.default_statements:
179
+ process_statement(stmt, dialect, object_mapping, statement_idx, parent_holder=holder)
180
+ statement_idx += 1
144
181
 
145
182
  elif isinstance(query, (LoopQuery, WhileQuery)):
146
183
  for i, stmt in enumerate(query.inner_statements):
@@ -378,8 +415,10 @@ _UNNAMED_TYPE_MAP: dict[type, type] = {
378
415
  # PL/pgSQL
379
416
  pgexp.PGBlock: BlockQuery,
380
417
  pgexp.PGDeclareItem: AssignmentQuery,
418
+ pgexp.PGException: ExceptionQuery,
381
419
  pgexp.PGFetch: FetchQuery,
382
420
  pgexp.PGForIn: ForInQuery,
421
+ pgexp.PGIf: IfQuery,
383
422
  pgexp.PGOpen: OpenQuery,
384
423
  pgexp.PGPerform: PerformQuery,
385
424
  pgexp.PGExecute: ExecuteDynamicQuery,
@@ -411,6 +450,10 @@ def _process_unnamed(
411
450
  return CallQuery(
412
451
  expr=statement, dialect=dialect, object_mapping=object_mapping, statement_index=statement_index
413
452
  )
453
+ if isinstance(statement, exp.Command) and (statement.this.upper() == "DO" or statement.name.upper() == "DO"):
454
+ return DoQuery(
455
+ expr=statement, dialect=dialect, object_mapping=object_mapping, statement_index=statement_index
456
+ )
414
457
  if isinstance(statement, exp.Command) and statement.this.upper() == "EXECUTE":
415
458
  return ExecuteQuery(
416
459
  expr=statement, dialect=dialect, object_mapping=object_mapping, statement_index=statement_index
@@ -676,6 +719,7 @@ _QUERY_PROCESSORS: dict[str, t.Callable] = {
676
719
  "execute": _process_execute,
677
720
  "stage": _process_stage,
678
721
  "call": _process_unnamed,
722
+ "do": _process_unnamed,
679
723
  "copy": _process_unnamed,
680
724
  "put": _process_unnamed,
681
725
  "set": _process_unnamed,
@@ -683,13 +727,16 @@ _QUERY_PROCESSORS: dict[str, t.Callable] = {
683
727
  "type": _process_type,
684
728
  "pgblock": _process_unnamed,
685
729
  "pgdeclareitem": _process_unnamed,
730
+ "pgexception": _process_unnamed,
686
731
  "pgfetch": _process_unnamed,
687
732
  "pgforin": _process_unnamed,
733
+ "pgif": _process_unnamed,
688
734
  "pgloop": _process_unnamed,
689
735
  "pgopen": _process_unnamed,
690
736
  "pgperform": _process_unnamed,
691
737
  "pgexecute": _process_unnamed,
692
738
  "propertyeq": _process_unnamed,
739
+ "whileblock": _process_unnamed,
693
740
  }
694
741
 
695
742
 
@@ -6,6 +6,7 @@ from sqlleaf.processors.transformer.ctas import CTASTransformer
6
6
  from sqlleaf.processors.transformer.delete import DeleteTransformer
7
7
  from sqlleaf.processors.transformer.execute import ExecuteTransformer
8
8
  from sqlleaf.processors.transformer.execute_dynamic import ExecuteDynamicTransformer
9
+ from sqlleaf.processors.transformer.for_in import ForInTransformer
9
10
  from sqlleaf.processors.transformer.insert import InsertTransformer
10
11
  from sqlleaf.processors.transformer.merge import MergeTransformer
11
12
  from sqlleaf.processors.transformer.multitable_insert import MultitableInsertTransformer
@@ -24,6 +25,7 @@ __all__ = [
24
25
  "DeleteTransformer",
25
26
  "ExecuteTransformer",
26
27
  "ExecuteDynamicTransformer",
28
+ "ForInTransformer",
27
29
  "InsertTransformer",
28
30
  "MergeTransformer",
29
31
  "MultitableInsertTransformer",
@@ -1,6 +1,5 @@
1
1
  import functools
2
2
  import logging
3
- import typing as t
4
3
 
5
4
  import sqlglot
6
5
  from sqlglot import exp
@@ -151,7 +150,14 @@ class BaseQueryTransformer:
151
150
  return expression.subquery(copy=False)
152
151
 
153
152
  # Skip replacement of variables *inside* inner block statements; these are done for each individual statement later.
154
- if isinstance(statement, (pgexp.PGBlock, pgexp.PGForIn, pgexp.PGLoop, exp.WhileBlock)):
153
+ if isinstance(statement, (pgexp.PGBlock, pgexp.PGException, pgexp.PGIf, pgexp.PGLoop, exp.WhileBlock)):
154
+ return
155
+
156
+ if isinstance(statement, pgexp.PGForIn):
157
+ for key in ("start", "end", "step", "query"):
158
+ child = statement.args.get(key)
159
+ if isinstance(child, exp.Expr):
160
+ self.replace_variables_in_expression(child)
155
161
  return
156
162
 
157
163
  # Skip replacement of variables inside cursor declarations; cursors are instantiated when OPEN is executed.
@@ -163,6 +169,13 @@ class BaseQueryTransformer:
163
169
  if column.parent is None:
164
170
  continue
165
171
 
172
+ # If the column is on the LHS of an assignment or declaration, skip it.
173
+ if isinstance(statement, (exp.PropertyEQ, pgexp.PGDeclareItem)):
174
+ if column is statement.this or (
175
+ isinstance(statement.this, exp.Expr) and column in statement.this.find_all(exp.Column)
176
+ ):
177
+ continue
178
+
166
179
  # If the column is after 'INTO', skip it.
167
180
  if isinstance(statement, pgexp.PGFetch):
168
181
  if column in statement.args.get("expressions", []):
@@ -0,0 +1,30 @@
1
+ import logging
2
+
3
+ from sqlglot import exp
4
+ from sqlglot.optimizer.simplify import simplify
5
+
6
+ from sqlleaf.dialects.plpgsql import pgexp
7
+ from sqlleaf.models.query import ForInQuery
8
+ from sqlleaf.processors.transformer import base
9
+ from sqlleaf.typing import E
10
+
11
+ logger = logging.getLogger("sqlleaf")
12
+
13
+
14
+ class ForInTransformer(base.BaseQueryTransformer):
15
+ QUERY = ForInQuery
16
+
17
+ def transform(self, statement: E) -> E:
18
+ """
19
+ Simplify range bounds (start, end, and step expressions) in a FOR ... IN loop statement.
20
+
21
+ Example:
22
+ FOR i IN (1 + 1)..(2 * 3) BY (1 + 1) -> FOR i IN 2..6 BY 2
23
+ """
24
+ if isinstance(statement, pgexp.PGForIn):
25
+ for key in ("start", "end", "step"):
26
+ child = statement.args.get(key)
27
+ if isinstance(child, exp.Expr):
28
+ statement.set(key, simplify(child))
29
+
30
+ return statement
@@ -48,7 +48,10 @@ def set_variables_in_scope(query: Q) -> None:
48
48
  # `my_var := 42`
49
49
  name = query.get_key()
50
50
  value = query.get_value()
51
- query.object_mapping.set_variable(name=name, value=value)
51
+ if query.is_declaration:
52
+ query.object_mapping.declare_variable(name=name, value=value)
53
+ else:
54
+ query.object_mapping.set_variable(name=name, value=value)
52
55
 
53
56
  elif isinstance(query, SelectQuery):
54
57
  original_stmt = query.holder.original.statement
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlleaf
3
- Version: 0.0.2
3
+ Version: 0.0.3
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
@@ -43,6 +43,12 @@ column[logins.name] -> function[LOWER] -> column[users.name]
43
43
  function[CURRENT_TIMESTAMP] -> column[users.birthday]
44
44
  ```
45
45
 
46
+ ## Installation
47
+ Available on PyPI:
48
+ ```
49
+ pip3 install sqlleaf
50
+ ```
51
+
46
52
  ## Applications
47
53
  sqlleaf allows you to build a wide range of new applications on top of SQL databases, such as:
48
54
  - data tracing and tagging systems, such as personally identifiable information tracking
@@ -49,6 +49,8 @@ sqlleaf/models/query/ctas.py
49
49
  sqlleaf/models/query/database.py
50
50
  sqlleaf/models/query/declare_item.py
51
51
  sqlleaf/models/query/delete.py
52
+ sqlleaf/models/query/do.py
53
+ sqlleaf/models/query/exception_.py
52
54
  sqlleaf/models/query/execute.py
53
55
  sqlleaf/models/query/execute_dynamic.py
54
56
  sqlleaf/models/query/fetch.py
@@ -103,6 +105,7 @@ sqlleaf/processors/transformer/ctas.py
103
105
  sqlleaf/processors/transformer/delete.py
104
106
  sqlleaf/processors/transformer/execute.py
105
107
  sqlleaf/processors/transformer/execute_dynamic.py
108
+ sqlleaf/processors/transformer/for_in.py
106
109
  sqlleaf/processors/transformer/insert.py
107
110
  sqlleaf/processors/transformer/merge.py
108
111
  sqlleaf/processors/transformer/multitable_insert.py
@@ -125,4 +128,5 @@ sqlleaf/util/__init__.py
125
128
  sqlleaf/util/expression.py
126
129
  sqlleaf/util/graph.py
127
130
  sqlleaf/util/helpers.py
128
- sqlleaf/util/iterators.py
131
+ sqlleaf/util/iterators.py
132
+ tests/test_hooks.py
@@ -0,0 +1,64 @@
1
+ import os
2
+ import sys
3
+
4
+ from sqlglot import exp
5
+
6
+ from sqlleaf.models.node import FunctionNode, N
7
+ from sqlleaf.lineage import Hook
8
+ from tests.new_fixtures import holder as holder
9
+
10
+ sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
11
+
12
+ DIALECT = "postgres"
13
+
14
+
15
+ sql = """
16
+ INSERT INTO fruit.processed (name)
17
+ SELECT LOWER('hello') AS name;
18
+ """
19
+
20
+
21
+ def test__hooks_no_functions_created(holder):
22
+ hooks = [Hook(name="no_functions", kind=FunctionNode, func=lambda n: None)]
23
+ h = holder(sql=sql, dialect=DIALECT, with_tables=True, hooks=hooks)
24
+
25
+ assert h.paths == [['literal["hello"]', "column[fruit.processed.name]"]]
26
+ assert len(h.nodes) == 2
27
+ assert len(h.edges) == 1
28
+ h.lineage.deregister_hooks(hooks)
29
+ assert h.lineage.user_defined_hooks == []
30
+
31
+
32
+ def test__hooks_functions_created(holder):
33
+ hooks = [Hook(name="allow_functions", kind=FunctionNode, func=lambda n: n)]
34
+ h = holder(sql=sql, dialect=DIALECT, with_tables=True, hooks=hooks)
35
+
36
+ assert h.paths == [['literal["hello"]', "function[LOWER]", "column[fruit.processed.name]"]]
37
+ assert len(h.nodes) == 3
38
+ assert len(h.edges) == 2
39
+ h.lineage.deregister_hooks(hooks)
40
+ assert h.lineage.user_defined_hooks == []
41
+
42
+
43
+ def test__hooks_functions_created_if_integer_arg(holder):
44
+ sql = """
45
+ INSERT INTO fruit.processed (name, age)
46
+ SELECT LOWER('hello') AS name, MAX(3) FROM fruit.raw;
47
+ """
48
+
49
+ def only_integer_arg(node: N):
50
+ func_args = list[exp.Expr](node.expr.iter_expressions())
51
+
52
+ if len(func_args) > 0 and isinstance(func_args[0], exp.Literal) and func_args[0].is_number:
53
+ return node
54
+ return None
55
+
56
+ hooks = [Hook(name="only_integer_arg", kind=FunctionNode, func=only_integer_arg)]
57
+ h = holder(sql=sql, dialect=DIALECT, with_tables=True, hooks=hooks)
58
+
59
+ assert h.paths == [
60
+ ['literal["hello"]', "column[fruit.processed.name]"],
61
+ ["literal[3]", "function[MAX]", "column[fruit.processed.age]"],
62
+ ]
63
+ assert len(h.nodes) == 5
64
+ assert len(h.edges) == 3
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes