sqlspec 0.16.0__cp312-cp312-win_amd64.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.

Potentially problematic release.


This version of sqlspec might be problematic. Click here for more details.

Files changed (148) hide show
  1. 51ff5a9eadfdefd49f98__mypyc.cp312-win_amd64.pyd +0 -0
  2. sqlspec/__init__.py +92 -0
  3. sqlspec/__main__.py +12 -0
  4. sqlspec/__metadata__.py +14 -0
  5. sqlspec/_serialization.py +77 -0
  6. sqlspec/_sql.py +1347 -0
  7. sqlspec/_typing.py +680 -0
  8. sqlspec/adapters/__init__.py +0 -0
  9. sqlspec/adapters/adbc/__init__.py +5 -0
  10. sqlspec/adapters/adbc/_types.py +12 -0
  11. sqlspec/adapters/adbc/config.py +361 -0
  12. sqlspec/adapters/adbc/driver.py +512 -0
  13. sqlspec/adapters/aiosqlite/__init__.py +19 -0
  14. sqlspec/adapters/aiosqlite/_types.py +13 -0
  15. sqlspec/adapters/aiosqlite/config.py +253 -0
  16. sqlspec/adapters/aiosqlite/driver.py +248 -0
  17. sqlspec/adapters/asyncmy/__init__.py +19 -0
  18. sqlspec/adapters/asyncmy/_types.py +12 -0
  19. sqlspec/adapters/asyncmy/config.py +180 -0
  20. sqlspec/adapters/asyncmy/driver.py +274 -0
  21. sqlspec/adapters/asyncpg/__init__.py +21 -0
  22. sqlspec/adapters/asyncpg/_types.py +17 -0
  23. sqlspec/adapters/asyncpg/config.py +229 -0
  24. sqlspec/adapters/asyncpg/driver.py +344 -0
  25. sqlspec/adapters/bigquery/__init__.py +18 -0
  26. sqlspec/adapters/bigquery/_types.py +12 -0
  27. sqlspec/adapters/bigquery/config.py +298 -0
  28. sqlspec/adapters/bigquery/driver.py +558 -0
  29. sqlspec/adapters/duckdb/__init__.py +22 -0
  30. sqlspec/adapters/duckdb/_types.py +12 -0
  31. sqlspec/adapters/duckdb/config.py +504 -0
  32. sqlspec/adapters/duckdb/driver.py +368 -0
  33. sqlspec/adapters/oracledb/__init__.py +32 -0
  34. sqlspec/adapters/oracledb/_types.py +14 -0
  35. sqlspec/adapters/oracledb/config.py +317 -0
  36. sqlspec/adapters/oracledb/driver.py +538 -0
  37. sqlspec/adapters/psqlpy/__init__.py +16 -0
  38. sqlspec/adapters/psqlpy/_types.py +11 -0
  39. sqlspec/adapters/psqlpy/config.py +214 -0
  40. sqlspec/adapters/psqlpy/driver.py +530 -0
  41. sqlspec/adapters/psycopg/__init__.py +32 -0
  42. sqlspec/adapters/psycopg/_types.py +17 -0
  43. sqlspec/adapters/psycopg/config.py +426 -0
  44. sqlspec/adapters/psycopg/driver.py +796 -0
  45. sqlspec/adapters/sqlite/__init__.py +15 -0
  46. sqlspec/adapters/sqlite/_types.py +11 -0
  47. sqlspec/adapters/sqlite/config.py +240 -0
  48. sqlspec/adapters/sqlite/driver.py +294 -0
  49. sqlspec/base.py +571 -0
  50. sqlspec/builder/__init__.py +62 -0
  51. sqlspec/builder/_base.py +440 -0
  52. sqlspec/builder/_column.py +324 -0
  53. sqlspec/builder/_ddl.py +1383 -0
  54. sqlspec/builder/_ddl_utils.py +104 -0
  55. sqlspec/builder/_delete.py +77 -0
  56. sqlspec/builder/_insert.py +241 -0
  57. sqlspec/builder/_merge.py +56 -0
  58. sqlspec/builder/_parsing_utils.py +140 -0
  59. sqlspec/builder/_select.py +174 -0
  60. sqlspec/builder/_update.py +186 -0
  61. sqlspec/builder/mixins/__init__.py +55 -0
  62. sqlspec/builder/mixins/_cte_and_set_ops.py +195 -0
  63. sqlspec/builder/mixins/_delete_operations.py +36 -0
  64. sqlspec/builder/mixins/_insert_operations.py +152 -0
  65. sqlspec/builder/mixins/_join_operations.py +115 -0
  66. sqlspec/builder/mixins/_merge_operations.py +416 -0
  67. sqlspec/builder/mixins/_order_limit_operations.py +123 -0
  68. sqlspec/builder/mixins/_pivot_operations.py +144 -0
  69. sqlspec/builder/mixins/_select_operations.py +599 -0
  70. sqlspec/builder/mixins/_update_operations.py +164 -0
  71. sqlspec/builder/mixins/_where_clause.py +609 -0
  72. sqlspec/cli.py +247 -0
  73. sqlspec/config.py +395 -0
  74. sqlspec/core/__init__.py +63 -0
  75. sqlspec/core/cache.cp312-win_amd64.pyd +0 -0
  76. sqlspec/core/cache.py +873 -0
  77. sqlspec/core/compiler.cp312-win_amd64.pyd +0 -0
  78. sqlspec/core/compiler.py +396 -0
  79. sqlspec/core/filters.cp312-win_amd64.pyd +0 -0
  80. sqlspec/core/filters.py +830 -0
  81. sqlspec/core/hashing.cp312-win_amd64.pyd +0 -0
  82. sqlspec/core/hashing.py +310 -0
  83. sqlspec/core/parameters.cp312-win_amd64.pyd +0 -0
  84. sqlspec/core/parameters.py +1209 -0
  85. sqlspec/core/result.cp312-win_amd64.pyd +0 -0
  86. sqlspec/core/result.py +664 -0
  87. sqlspec/core/splitter.cp312-win_amd64.pyd +0 -0
  88. sqlspec/core/splitter.py +819 -0
  89. sqlspec/core/statement.cp312-win_amd64.pyd +0 -0
  90. sqlspec/core/statement.py +666 -0
  91. sqlspec/driver/__init__.py +19 -0
  92. sqlspec/driver/_async.py +472 -0
  93. sqlspec/driver/_common.py +612 -0
  94. sqlspec/driver/_sync.py +473 -0
  95. sqlspec/driver/mixins/__init__.py +6 -0
  96. sqlspec/driver/mixins/_result_tools.py +164 -0
  97. sqlspec/driver/mixins/_sql_translator.py +36 -0
  98. sqlspec/exceptions.py +193 -0
  99. sqlspec/extensions/__init__.py +0 -0
  100. sqlspec/extensions/aiosql/__init__.py +10 -0
  101. sqlspec/extensions/aiosql/adapter.py +461 -0
  102. sqlspec/extensions/litestar/__init__.py +6 -0
  103. sqlspec/extensions/litestar/_utils.py +52 -0
  104. sqlspec/extensions/litestar/cli.py +48 -0
  105. sqlspec/extensions/litestar/config.py +92 -0
  106. sqlspec/extensions/litestar/handlers.py +260 -0
  107. sqlspec/extensions/litestar/plugin.py +145 -0
  108. sqlspec/extensions/litestar/providers.py +454 -0
  109. sqlspec/loader.cp312-win_amd64.pyd +0 -0
  110. sqlspec/loader.py +760 -0
  111. sqlspec/migrations/__init__.py +35 -0
  112. sqlspec/migrations/base.py +414 -0
  113. sqlspec/migrations/commands.py +443 -0
  114. sqlspec/migrations/loaders.py +402 -0
  115. sqlspec/migrations/runner.py +213 -0
  116. sqlspec/migrations/tracker.py +140 -0
  117. sqlspec/migrations/utils.py +129 -0
  118. sqlspec/protocols.py +400 -0
  119. sqlspec/py.typed +0 -0
  120. sqlspec/storage/__init__.py +23 -0
  121. sqlspec/storage/backends/__init__.py +0 -0
  122. sqlspec/storage/backends/base.py +163 -0
  123. sqlspec/storage/backends/fsspec.py +386 -0
  124. sqlspec/storage/backends/obstore.py +459 -0
  125. sqlspec/storage/capabilities.py +102 -0
  126. sqlspec/storage/registry.py +239 -0
  127. sqlspec/typing.py +299 -0
  128. sqlspec/utils/__init__.py +3 -0
  129. sqlspec/utils/correlation.py +150 -0
  130. sqlspec/utils/deprecation.py +106 -0
  131. sqlspec/utils/fixtures.cp312-win_amd64.pyd +0 -0
  132. sqlspec/utils/fixtures.py +58 -0
  133. sqlspec/utils/logging.py +127 -0
  134. sqlspec/utils/module_loader.py +89 -0
  135. sqlspec/utils/serializers.py +4 -0
  136. sqlspec/utils/singleton.py +32 -0
  137. sqlspec/utils/sync_tools.cp312-win_amd64.pyd +0 -0
  138. sqlspec/utils/sync_tools.py +237 -0
  139. sqlspec/utils/text.cp312-win_amd64.pyd +0 -0
  140. sqlspec/utils/text.py +96 -0
  141. sqlspec/utils/type_guards.cp312-win_amd64.pyd +0 -0
  142. sqlspec/utils/type_guards.py +1135 -0
  143. sqlspec-0.16.0.dist-info/METADATA +365 -0
  144. sqlspec-0.16.0.dist-info/RECORD +148 -0
  145. sqlspec-0.16.0.dist-info/WHEEL +4 -0
  146. sqlspec-0.16.0.dist-info/entry_points.txt +2 -0
  147. sqlspec-0.16.0.dist-info/licenses/LICENSE +21 -0
  148. sqlspec-0.16.0.dist-info/licenses/NOTICE +29 -0
@@ -0,0 +1,174 @@
1
+ """Safe SQL query builder with validation and parameter binding.
2
+
3
+ This module provides a fluent interface for building SQL queries safely,
4
+ with automatic parameter binding and validation.
5
+ """
6
+
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Optional, Union
10
+
11
+ from sqlglot import exp
12
+ from typing_extensions import Self
13
+
14
+ from sqlspec.builder._base import QueryBuilder, SafeQuery
15
+ from sqlspec.builder.mixins import (
16
+ CommonTableExpressionMixin,
17
+ HavingClauseMixin,
18
+ JoinClauseMixin,
19
+ LimitOffsetClauseMixin,
20
+ OrderByClauseMixin,
21
+ PivotClauseMixin,
22
+ SelectClauseMixin,
23
+ SetOperationMixin,
24
+ UnpivotClauseMixin,
25
+ WhereClauseMixin,
26
+ )
27
+ from sqlspec.core.result import SQLResult
28
+
29
+ __all__ = ("Select",)
30
+
31
+
32
+ TABLE_HINT_PATTERN = r"\b{}\b(\s+AS\s+\w+)?"
33
+
34
+
35
+ @dataclass
36
+ class Select(
37
+ QueryBuilder,
38
+ WhereClauseMixin,
39
+ OrderByClauseMixin,
40
+ LimitOffsetClauseMixin,
41
+ SelectClauseMixin,
42
+ JoinClauseMixin,
43
+ HavingClauseMixin,
44
+ SetOperationMixin,
45
+ CommonTableExpressionMixin,
46
+ PivotClauseMixin,
47
+ UnpivotClauseMixin,
48
+ ):
49
+ """Type-safe builder for SELECT queries with schema/model integration.
50
+
51
+ This builder provides a fluent, safe interface for constructing SQL SELECT statements.
52
+
53
+ Example:
54
+ >>> class User(BaseModel):
55
+ ... id: int
56
+ ... name: str
57
+ >>> builder = Select("id", "name").from_("users")
58
+ >>> result = driver.execute(builder)
59
+ """
60
+
61
+ _with_parts: "dict[str, Union[exp.CTE, Select]]" = field(default_factory=dict, init=False)
62
+ _expression: Optional[exp.Expression] = field(default=None, init=False, repr=False, compare=False, hash=False)
63
+ _hints: "list[dict[str, object]]" = field(default_factory=list, init=False, repr=False)
64
+
65
+ def __init__(self, *columns: str, **kwargs: Any) -> None:
66
+ """Initialize SELECT with optional columns.
67
+
68
+ Args:
69
+ *columns: Column names to select (e.g., "id", "name", "u.email")
70
+ **kwargs: Additional QueryBuilder arguments (dialect, schema, etc.)
71
+
72
+ Examples:
73
+ Select("id", "name") # Shorthand for Select().select("id", "name")
74
+ Select() # Same as Select() - start empty
75
+ """
76
+ super().__init__(**kwargs)
77
+
78
+ self._with_parts = {}
79
+ self._expression = None
80
+ self._hints = []
81
+
82
+ self._create_base_expression()
83
+
84
+ if columns:
85
+ self.select(*columns)
86
+
87
+ @property
88
+ def _expected_result_type(self) -> "type[SQLResult]":
89
+ """Get the expected result type for SELECT operations.
90
+
91
+ Returns:
92
+ type: The SelectResult type.
93
+ """
94
+ return SQLResult
95
+
96
+ def _create_base_expression(self) -> "exp.Select":
97
+ if self._expression is None or not isinstance(self._expression, exp.Select):
98
+ self._expression = exp.Select()
99
+ return self._expression
100
+
101
+ def with_hint(
102
+ self,
103
+ hint: "str",
104
+ *,
105
+ location: "str" = "statement",
106
+ table: "Optional[str]" = None,
107
+ dialect: "Optional[str]" = None,
108
+ ) -> "Self":
109
+ """Attach an optimizer or dialect-specific hint to the query.
110
+
111
+ Args:
112
+ hint: The raw hint string (e.g., 'INDEX(users idx_users_name)').
113
+ location: Where to apply the hint ('statement', 'table').
114
+ table: Table name if the hint is for a specific table.
115
+ dialect: Restrict the hint to a specific dialect (optional).
116
+
117
+ Returns:
118
+ The current builder instance for method chaining.
119
+ """
120
+ self._hints.append({"hint": hint, "location": location, "table": table, "dialect": dialect})
121
+ return self
122
+
123
+ def build(self) -> "SafeQuery":
124
+ """Builds the SQL query string and parameters with hint injection.
125
+
126
+ Returns:
127
+ SafeQuery: A dataclass containing the SQL string and parameters.
128
+ """
129
+ safe_query = super().build()
130
+
131
+ if not self._hints:
132
+ return safe_query
133
+
134
+ modified_expr = self._expression.copy() if self._expression else self._create_base_expression()
135
+
136
+ if isinstance(modified_expr, exp.Select):
137
+ statement_hints = [h["hint"] for h in self._hints if h.get("location") == "statement"]
138
+ if statement_hints:
139
+ hint_expressions = []
140
+
141
+ def parse_hint(hint: Any) -> exp.Expression:
142
+ """Parse a single hint."""
143
+ try:
144
+ hint_str = str(hint) # Ensure hint is a string
145
+ hint_expr: Optional[exp.Expression] = exp.maybe_parse(hint_str, dialect=self.dialect_name)
146
+ if hint_expr:
147
+ return hint_expr
148
+ return exp.Anonymous(this=hint_str)
149
+ except Exception:
150
+ return exp.Anonymous(this=str(hint))
151
+
152
+ hint_expressions = [parse_hint(hint) for hint in statement_hints]
153
+
154
+ if hint_expressions:
155
+ hint_node = exp.Hint(expressions=hint_expressions)
156
+ modified_expr.set("hint", hint_node)
157
+
158
+ modified_sql = modified_expr.sql(dialect=self.dialect_name, pretty=True)
159
+
160
+ table_hints = [h for h in self._hints if h.get("location") == "table" and h.get("table")]
161
+ if table_hints:
162
+ for th in table_hints:
163
+ table = str(th["table"])
164
+ hint = th["hint"]
165
+ pattern = TABLE_HINT_PATTERN.format(re.escape(table))
166
+ compiled_pattern = re.compile(pattern, re.IGNORECASE)
167
+
168
+ def replacement_func(match: re.Match[str]) -> str:
169
+ alias_part = match.group(1) or ""
170
+ return f"/*+ {hint} */ {table}{alias_part}" # noqa: B023
171
+
172
+ modified_sql = compiled_pattern.sub(replacement_func, modified_sql, count=1)
173
+
174
+ return SafeQuery(sql=modified_sql, parameters=safe_query.parameters, dialect=safe_query.dialect)
@@ -0,0 +1,186 @@
1
+ """Safe SQL query builder with validation and parameter binding.
2
+
3
+ This module provides a fluent interface for building SQL queries safely,
4
+ with automatic parameter binding and validation.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Any, Optional, Union
9
+
10
+ from sqlglot import exp
11
+ from typing_extensions import Self
12
+
13
+ from sqlspec.builder._base import QueryBuilder, SafeQuery
14
+ from sqlspec.builder.mixins import (
15
+ ReturningClauseMixin,
16
+ UpdateFromClauseMixin,
17
+ UpdateSetClauseMixin,
18
+ UpdateTableClauseMixin,
19
+ WhereClauseMixin,
20
+ )
21
+ from sqlspec.core.result import SQLResult
22
+ from sqlspec.exceptions import SQLBuilderError
23
+
24
+ if TYPE_CHECKING:
25
+ from sqlspec.builder._select import Select
26
+
27
+ __all__ = ("Update",)
28
+
29
+
30
+ @dataclass(unsafe_hash=True)
31
+ class Update(
32
+ QueryBuilder,
33
+ WhereClauseMixin,
34
+ ReturningClauseMixin,
35
+ UpdateSetClauseMixin,
36
+ UpdateFromClauseMixin,
37
+ UpdateTableClauseMixin,
38
+ ):
39
+ """Builder for UPDATE statements.
40
+
41
+ This builder provides a fluent interface for constructing SQL UPDATE statements
42
+ with automatic parameter binding and validation.
43
+
44
+ Example:
45
+ ```python
46
+ update_query = (
47
+ Update()
48
+ .table("users")
49
+ .set(name="John Doe")
50
+ .set(email="john@example.com")
51
+ .where("id = 1")
52
+ )
53
+
54
+ update_query = (
55
+ Update("users").set(name="John Doe").where("id = 1")
56
+ )
57
+
58
+ update_query = (
59
+ Update()
60
+ .table("users")
61
+ .set(status="active")
62
+ .where_eq("id", 123)
63
+ )
64
+
65
+ update_query = (
66
+ Update()
67
+ .table("users", "u")
68
+ .set(name="Updated Name")
69
+ .from_("profiles", "p")
70
+ .where("u.id = p.user_id AND p.is_verified = true")
71
+ )
72
+ ```
73
+ """
74
+
75
+ def __init__(self, table: Optional[str] = None, **kwargs: Any) -> None:
76
+ """Initialize UPDATE with optional table.
77
+
78
+ Args:
79
+ table: Target table name
80
+ **kwargs: Additional QueryBuilder arguments
81
+ """
82
+ super().__init__(**kwargs)
83
+
84
+ if table:
85
+ self.table(table)
86
+
87
+ @property
88
+ def _expected_result_type(self) -> "type[SQLResult]":
89
+ """Return the expected result type for this builder."""
90
+ return SQLResult
91
+
92
+ def _create_base_expression(self) -> exp.Update:
93
+ """Create a base UPDATE expression.
94
+
95
+ Returns:
96
+ A new sqlglot Update expression with empty clauses.
97
+ """
98
+ return exp.Update(this=None, expressions=[], joins=[])
99
+
100
+ def join(
101
+ self,
102
+ table: "Union[str, exp.Expression, Select]",
103
+ on: "Union[str, exp.Expression]",
104
+ alias: "Optional[str]" = None,
105
+ join_type: str = "INNER",
106
+ ) -> "Self":
107
+ """Add JOIN clause to the UPDATE statement.
108
+
109
+ Args:
110
+ table: The table name, expression, or subquery to join.
111
+ on: The JOIN condition.
112
+ alias: Optional alias for the joined table.
113
+ join_type: Type of join (INNER, LEFT, RIGHT, FULL).
114
+
115
+ Returns:
116
+ The current builder instance for method chaining.
117
+
118
+ Raises:
119
+ SQLBuilderError: If the current expression is not an UPDATE statement.
120
+ """
121
+ if self._expression is None or not isinstance(self._expression, exp.Update):
122
+ msg = "Cannot add JOIN clause to non-UPDATE expression."
123
+ raise SQLBuilderError(msg)
124
+
125
+ table_expr: exp.Expression
126
+ if isinstance(table, str):
127
+ table_expr = exp.table_(table, alias=alias)
128
+ elif isinstance(table, QueryBuilder):
129
+ subquery = table.build()
130
+ subquery_exp = exp.paren(exp.maybe_parse(subquery.sql, dialect=self.dialect))
131
+ table_expr = exp.alias_(subquery_exp, alias) if alias else subquery_exp
132
+
133
+ subquery_parameters = table._parameters
134
+ if subquery_parameters:
135
+ for p_name, p_value in subquery_parameters.items():
136
+ self.add_parameter(p_value, name=p_name)
137
+ else:
138
+ table_expr = table
139
+
140
+ on_expr: exp.Expression = exp.condition(on) if isinstance(on, str) else on
141
+
142
+ join_type_upper = join_type.upper()
143
+ if join_type_upper == "INNER":
144
+ join_expr = exp.Join(this=table_expr, on=on_expr)
145
+ elif join_type_upper == "LEFT":
146
+ join_expr = exp.Join(this=table_expr, on=on_expr, side="LEFT")
147
+ elif join_type_upper == "RIGHT":
148
+ join_expr = exp.Join(this=table_expr, on=on_expr, side="RIGHT")
149
+ elif join_type_upper == "FULL":
150
+ join_expr = exp.Join(this=table_expr, on=on_expr, side="FULL", kind="OUTER")
151
+ else:
152
+ msg = f"Unsupported join type: {join_type}"
153
+ raise SQLBuilderError(msg)
154
+
155
+ if not self._expression.args.get("joins"):
156
+ self._expression.set("joins", [])
157
+ self._expression.args["joins"].append(join_expr)
158
+
159
+ return self
160
+
161
+ def build(self) -> "SafeQuery":
162
+ """Build the UPDATE query with validation.
163
+
164
+ Returns:
165
+ SafeQuery: The built query with SQL and parameters.
166
+
167
+ Raises:
168
+ SQLBuilderError: If no table is set or expression is not an UPDATE.
169
+ """
170
+ if self._expression is None:
171
+ msg = "UPDATE expression not initialized."
172
+ raise SQLBuilderError(msg)
173
+
174
+ if not isinstance(self._expression, exp.Update):
175
+ msg = "No UPDATE expression to build or expression is of the wrong type."
176
+ raise SQLBuilderError(msg)
177
+
178
+ if getattr(self._expression, "this", None) is None:
179
+ msg = "No table specified for UPDATE statement."
180
+ raise SQLBuilderError(msg)
181
+
182
+ if not self._expression.args.get("expressions"):
183
+ msg = "At least one SET clause must be specified for UPDATE statement."
184
+ raise SQLBuilderError(msg)
185
+
186
+ return super().build()
@@ -0,0 +1,55 @@
1
+ """SQL statement builder mixins."""
2
+
3
+ from sqlspec.builder.mixins._cte_and_set_ops import CommonTableExpressionMixin, SetOperationMixin
4
+ from sqlspec.builder.mixins._delete_operations import DeleteFromClauseMixin
5
+ from sqlspec.builder.mixins._insert_operations import InsertFromSelectMixin, InsertIntoClauseMixin, InsertValuesMixin
6
+ from sqlspec.builder.mixins._join_operations import JoinClauseMixin
7
+ from sqlspec.builder.mixins._merge_operations import (
8
+ MergeIntoClauseMixin,
9
+ MergeMatchedClauseMixin,
10
+ MergeNotMatchedBySourceClauseMixin,
11
+ MergeNotMatchedClauseMixin,
12
+ MergeOnClauseMixin,
13
+ MergeUsingClauseMixin,
14
+ )
15
+ from sqlspec.builder.mixins._order_limit_operations import (
16
+ LimitOffsetClauseMixin,
17
+ OrderByClauseMixin,
18
+ ReturningClauseMixin,
19
+ )
20
+ from sqlspec.builder.mixins._pivot_operations import PivotClauseMixin, UnpivotClauseMixin
21
+ from sqlspec.builder.mixins._select_operations import CaseBuilder, SelectClauseMixin
22
+ from sqlspec.builder.mixins._update_operations import (
23
+ UpdateFromClauseMixin,
24
+ UpdateSetClauseMixin,
25
+ UpdateTableClauseMixin,
26
+ )
27
+ from sqlspec.builder.mixins._where_clause import HavingClauseMixin, WhereClauseMixin
28
+
29
+ __all__ = (
30
+ "CaseBuilder",
31
+ "CommonTableExpressionMixin",
32
+ "DeleteFromClauseMixin",
33
+ "HavingClauseMixin",
34
+ "InsertFromSelectMixin",
35
+ "InsertIntoClauseMixin",
36
+ "InsertValuesMixin",
37
+ "JoinClauseMixin",
38
+ "LimitOffsetClauseMixin",
39
+ "MergeIntoClauseMixin",
40
+ "MergeMatchedClauseMixin",
41
+ "MergeNotMatchedBySourceClauseMixin",
42
+ "MergeNotMatchedClauseMixin",
43
+ "MergeOnClauseMixin",
44
+ "MergeUsingClauseMixin",
45
+ "OrderByClauseMixin",
46
+ "PivotClauseMixin",
47
+ "ReturningClauseMixin",
48
+ "SelectClauseMixin",
49
+ "SetOperationMixin",
50
+ "UnpivotClauseMixin",
51
+ "UpdateFromClauseMixin",
52
+ "UpdateSetClauseMixin",
53
+ "UpdateTableClauseMixin",
54
+ "WhereClauseMixin",
55
+ )
@@ -0,0 +1,195 @@
1
+ """CTE (Common Table Expression) and Set Operations mixins for SQL builders."""
2
+
3
+ from typing import Any, Optional, Union
4
+
5
+ from sqlglot import exp
6
+ from typing_extensions import Self
7
+
8
+ from sqlspec.exceptions import SQLBuilderError
9
+
10
+ __all__ = ("CommonTableExpressionMixin", "SetOperationMixin")
11
+
12
+
13
+ class CommonTableExpressionMixin:
14
+ """Mixin providing WITH clause (Common Table Expressions) support for SQL builders."""
15
+
16
+ _expression: Optional[exp.Expression] = None
17
+
18
+ def with_(
19
+ self, name: str, query: Union[Any, str], recursive: bool = False, columns: Optional[list[str]] = None
20
+ ) -> Self:
21
+ """Add WITH clause (Common Table Expression).
22
+
23
+ Args:
24
+ name: The name of the CTE.
25
+ query: The query for the CTE (builder instance or SQL string).
26
+ recursive: Whether this is a recursive CTE.
27
+ columns: Optional column names for the CTE.
28
+
29
+ Raises:
30
+ SQLBuilderError: If the query type is unsupported.
31
+
32
+ Returns:
33
+ The current builder instance for method chaining.
34
+ """
35
+ if self._expression is None:
36
+ msg = "Cannot add WITH clause: expression not initialized."
37
+ raise SQLBuilderError(msg)
38
+
39
+ if not isinstance(self._expression, (exp.Select, exp.Insert, exp.Update, exp.Delete)):
40
+ msg = f"Cannot add WITH clause to {type(self._expression).__name__} expression."
41
+ raise SQLBuilderError(msg)
42
+
43
+ cte_expr: Optional[exp.Expression] = None
44
+ if isinstance(query, str):
45
+ cte_expr = exp.maybe_parse(query, dialect=self.dialect) # type: ignore[attr-defined]
46
+ elif isinstance(query, exp.Expression):
47
+ cte_expr = query
48
+ else:
49
+ built_query = query.to_statement() # pyright: ignore
50
+ cte_sql = built_query.sql
51
+ cte_expr = exp.maybe_parse(cte_sql, dialect=self.dialect) # type: ignore[attr-defined]
52
+
53
+ parameters = built_query.parameters
54
+ if parameters:
55
+ if isinstance(parameters, dict):
56
+ for param_name, param_value in parameters.items():
57
+ self.add_parameter(param_value, name=param_name) # type: ignore[attr-defined]
58
+ elif isinstance(parameters, (list, tuple)):
59
+ for param_value in parameters:
60
+ self.add_parameter(param_value) # type: ignore[attr-defined]
61
+
62
+ if not cte_expr:
63
+ msg = f"Could not parse CTE query: {query}"
64
+ raise SQLBuilderError(msg)
65
+
66
+ if columns:
67
+ cte_alias_expr = exp.alias_(cte_expr, name, table=[exp.to_identifier(col) for col in columns])
68
+ else:
69
+ cte_alias_expr = exp.alias_(cte_expr, name)
70
+
71
+ existing_with = self._expression.args.get("with") # pyright: ignore
72
+ if existing_with:
73
+ existing_with.expressions.append(cte_alias_expr)
74
+ if recursive:
75
+ existing_with.set("recursive", recursive)
76
+ else:
77
+ self._expression = self._expression.with_(cte_alias_expr, as_=name, copy=False) # type: ignore[union-attr]
78
+ if recursive:
79
+ with_clause = self._expression.find(exp.With)
80
+ if with_clause:
81
+ with_clause.set("recursive", recursive)
82
+ self._with_ctes[name] = exp.CTE(this=cte_expr, alias=exp.to_table(name)) # type: ignore[attr-defined]
83
+
84
+ return self
85
+
86
+
87
+ class SetOperationMixin:
88
+ """Mixin providing set operations (UNION, INTERSECT, EXCEPT) for SELECT builders."""
89
+
90
+ _expression: Any = None
91
+ _parameters: dict[str, Any]
92
+ dialect: Any = None
93
+
94
+ def union(self, other: Any, all_: bool = False) -> Self:
95
+ """Combine this query with another using UNION.
96
+
97
+ Args:
98
+ other: Another SelectBuilder or compatible builder to union with.
99
+ all_: If True, use UNION ALL instead of UNION.
100
+
101
+ Raises:
102
+ SQLBuilderError: If the current expression is not a SELECT statement.
103
+
104
+ Returns:
105
+ The new builder instance for the union query.
106
+ """
107
+ left_query = self.build() # type: ignore[attr-defined]
108
+ right_query = other.build()
109
+ left_expr: Optional[exp.Expression] = exp.maybe_parse(left_query.sql, dialect=self.dialect)
110
+ right_expr: Optional[exp.Expression] = exp.maybe_parse(right_query.sql, dialect=self.dialect)
111
+ if not left_expr or not right_expr:
112
+ msg = "Could not parse queries for UNION operation"
113
+ raise SQLBuilderError(msg)
114
+ union_expr = exp.union(left_expr, right_expr, distinct=not all_)
115
+ new_builder = type(self)()
116
+ new_builder.dialect = self.dialect
117
+ new_builder._expression = union_expr
118
+ merged_parameters = dict(left_query.parameters)
119
+ for param_name, param_value in right_query.parameters.items():
120
+ if param_name in merged_parameters:
121
+ counter = 1
122
+ new_param_name = f"{param_name}_right_{counter}"
123
+ while new_param_name in merged_parameters:
124
+ counter += 1
125
+ new_param_name = f"{param_name}_right_{counter}"
126
+
127
+ def rename_parameter(node: exp.Expression) -> exp.Expression:
128
+ if isinstance(node, exp.Placeholder) and node.name == param_name: # noqa: B023
129
+ return exp.Placeholder(this=new_param_name) # noqa: B023
130
+ return node
131
+
132
+ right_expr = right_expr.transform(rename_parameter)
133
+ union_expr = exp.union(left_expr, right_expr, distinct=not all_)
134
+ new_builder._expression = union_expr
135
+ merged_parameters[new_param_name] = param_value
136
+ else:
137
+ merged_parameters[param_name] = param_value
138
+ new_builder._parameters = merged_parameters
139
+ return new_builder
140
+
141
+ def intersect(self, other: Any) -> Self:
142
+ """Add INTERSECT clause.
143
+
144
+ Args:
145
+ other: Another SelectBuilder or compatible builder to intersect with.
146
+
147
+ Raises:
148
+ SQLBuilderError: If the current expression is not a SELECT statement.
149
+
150
+ Returns:
151
+ The new builder instance for the intersect query.
152
+ """
153
+ left_query = self.build() # type: ignore[attr-defined]
154
+ right_query = other.build()
155
+ left_expr: Optional[exp.Expression] = exp.maybe_parse(left_query.sql, dialect=self.dialect)
156
+ right_expr: Optional[exp.Expression] = exp.maybe_parse(right_query.sql, dialect=self.dialect)
157
+ if not left_expr or not right_expr:
158
+ msg = "Could not parse queries for INTERSECT operation"
159
+ raise SQLBuilderError(msg)
160
+ intersect_expr = exp.intersect(left_expr, right_expr, distinct=True)
161
+ new_builder = type(self)()
162
+ new_builder.dialect = self.dialect
163
+ new_builder._expression = intersect_expr
164
+ merged_parameters = dict(left_query.parameters)
165
+ merged_parameters.update(right_query.parameters)
166
+ new_builder._parameters = merged_parameters
167
+ return new_builder
168
+
169
+ def except_(self, other: Any) -> Self:
170
+ """Combine this query with another using EXCEPT.
171
+
172
+ Args:
173
+ other: Another SelectBuilder or compatible builder to except with.
174
+
175
+ Raises:
176
+ SQLBuilderError: If the current expression is not a SELECT statement.
177
+
178
+ Returns:
179
+ The new builder instance for the except query.
180
+ """
181
+ left_query = self.build() # type: ignore[attr-defined]
182
+ right_query = other.build()
183
+ left_expr: Optional[exp.Expression] = exp.maybe_parse(left_query.sql, dialect=self.dialect)
184
+ right_expr: Optional[exp.Expression] = exp.maybe_parse(right_query.sql, dialect=self.dialect)
185
+ if not left_expr or not right_expr:
186
+ msg = "Could not parse queries for EXCEPT operation"
187
+ raise SQLBuilderError(msg)
188
+ except_expr = exp.except_(left_expr, right_expr)
189
+ new_builder = type(self)()
190
+ new_builder.dialect = self.dialect
191
+ new_builder._expression = except_expr
192
+ merged_parameters = dict(left_query.parameters)
193
+ merged_parameters.update(right_query.parameters)
194
+ new_builder._parameters = merged_parameters
195
+ return new_builder
@@ -0,0 +1,36 @@
1
+ """Delete operation mixins for SQL builders."""
2
+
3
+ from typing import Optional
4
+
5
+ from sqlglot import exp
6
+ from typing_extensions import Self
7
+
8
+ from sqlspec.exceptions import SQLBuilderError
9
+
10
+ __all__ = ("DeleteFromClauseMixin",)
11
+
12
+
13
+ class DeleteFromClauseMixin:
14
+ """Mixin providing FROM clause for DELETE builders."""
15
+
16
+ _expression: Optional[exp.Expression] = None
17
+
18
+ def from_(self, table: str) -> Self:
19
+ """Set the target table for the DELETE statement.
20
+
21
+ Args:
22
+ table: The table name to delete from.
23
+
24
+ Returns:
25
+ The current builder instance for method chaining.
26
+ """
27
+ if self._expression is None:
28
+ self._expression = exp.Delete()
29
+ if not isinstance(self._expression, exp.Delete):
30
+ current_expr_type = type(self._expression).__name__
31
+ msg = f"Base expression for Delete is {current_expr_type}, expected Delete."
32
+ raise SQLBuilderError(msg)
33
+
34
+ setattr(self, "_table", table)
35
+ self._expression.set("this", exp.to_table(table))
36
+ return self