sqlspec 0.25.0__py3-none-any.whl → 0.27.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (199) hide show
  1. sqlspec/__init__.py +7 -15
  2. sqlspec/_serialization.py +256 -24
  3. sqlspec/_typing.py +71 -52
  4. sqlspec/adapters/adbc/_types.py +1 -1
  5. sqlspec/adapters/adbc/adk/__init__.py +5 -0
  6. sqlspec/adapters/adbc/adk/store.py +870 -0
  7. sqlspec/adapters/adbc/config.py +69 -12
  8. sqlspec/adapters/adbc/data_dictionary.py +340 -0
  9. sqlspec/adapters/adbc/driver.py +266 -58
  10. sqlspec/adapters/adbc/litestar/__init__.py +5 -0
  11. sqlspec/adapters/adbc/litestar/store.py +504 -0
  12. sqlspec/adapters/adbc/type_converter.py +153 -0
  13. sqlspec/adapters/aiosqlite/_types.py +1 -1
  14. sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
  15. sqlspec/adapters/aiosqlite/adk/store.py +527 -0
  16. sqlspec/adapters/aiosqlite/config.py +88 -15
  17. sqlspec/adapters/aiosqlite/data_dictionary.py +149 -0
  18. sqlspec/adapters/aiosqlite/driver.py +143 -40
  19. sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
  20. sqlspec/adapters/aiosqlite/litestar/store.py +281 -0
  21. sqlspec/adapters/aiosqlite/pool.py +7 -7
  22. sqlspec/adapters/asyncmy/__init__.py +7 -1
  23. sqlspec/adapters/asyncmy/_types.py +2 -2
  24. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  25. sqlspec/adapters/asyncmy/adk/store.py +493 -0
  26. sqlspec/adapters/asyncmy/config.py +68 -23
  27. sqlspec/adapters/asyncmy/data_dictionary.py +161 -0
  28. sqlspec/adapters/asyncmy/driver.py +313 -58
  29. sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
  30. sqlspec/adapters/asyncmy/litestar/store.py +296 -0
  31. sqlspec/adapters/asyncpg/__init__.py +2 -1
  32. sqlspec/adapters/asyncpg/_type_handlers.py +71 -0
  33. sqlspec/adapters/asyncpg/_types.py +11 -7
  34. sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
  35. sqlspec/adapters/asyncpg/adk/store.py +450 -0
  36. sqlspec/adapters/asyncpg/config.py +59 -35
  37. sqlspec/adapters/asyncpg/data_dictionary.py +173 -0
  38. sqlspec/adapters/asyncpg/driver.py +170 -25
  39. sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
  40. sqlspec/adapters/asyncpg/litestar/store.py +253 -0
  41. sqlspec/adapters/bigquery/_types.py +1 -1
  42. sqlspec/adapters/bigquery/adk/__init__.py +5 -0
  43. sqlspec/adapters/bigquery/adk/store.py +576 -0
  44. sqlspec/adapters/bigquery/config.py +27 -10
  45. sqlspec/adapters/bigquery/data_dictionary.py +149 -0
  46. sqlspec/adapters/bigquery/driver.py +368 -142
  47. sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
  48. sqlspec/adapters/bigquery/litestar/store.py +327 -0
  49. sqlspec/adapters/bigquery/type_converter.py +125 -0
  50. sqlspec/adapters/duckdb/_types.py +1 -1
  51. sqlspec/adapters/duckdb/adk/__init__.py +14 -0
  52. sqlspec/adapters/duckdb/adk/store.py +553 -0
  53. sqlspec/adapters/duckdb/config.py +80 -20
  54. sqlspec/adapters/duckdb/data_dictionary.py +163 -0
  55. sqlspec/adapters/duckdb/driver.py +167 -45
  56. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  57. sqlspec/adapters/duckdb/litestar/store.py +332 -0
  58. sqlspec/adapters/duckdb/pool.py +4 -4
  59. sqlspec/adapters/duckdb/type_converter.py +133 -0
  60. sqlspec/adapters/oracledb/_numpy_handlers.py +133 -0
  61. sqlspec/adapters/oracledb/_types.py +20 -2
  62. sqlspec/adapters/oracledb/adk/__init__.py +5 -0
  63. sqlspec/adapters/oracledb/adk/store.py +1745 -0
  64. sqlspec/adapters/oracledb/config.py +122 -32
  65. sqlspec/adapters/oracledb/data_dictionary.py +509 -0
  66. sqlspec/adapters/oracledb/driver.py +353 -91
  67. sqlspec/adapters/oracledb/litestar/__init__.py +5 -0
  68. sqlspec/adapters/oracledb/litestar/store.py +767 -0
  69. sqlspec/adapters/oracledb/migrations.py +348 -73
  70. sqlspec/adapters/oracledb/type_converter.py +207 -0
  71. sqlspec/adapters/psqlpy/_type_handlers.py +44 -0
  72. sqlspec/adapters/psqlpy/_types.py +2 -1
  73. sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
  74. sqlspec/adapters/psqlpy/adk/store.py +482 -0
  75. sqlspec/adapters/psqlpy/config.py +46 -17
  76. sqlspec/adapters/psqlpy/data_dictionary.py +172 -0
  77. sqlspec/adapters/psqlpy/driver.py +123 -209
  78. sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
  79. sqlspec/adapters/psqlpy/litestar/store.py +272 -0
  80. sqlspec/adapters/psqlpy/type_converter.py +102 -0
  81. sqlspec/adapters/psycopg/_type_handlers.py +80 -0
  82. sqlspec/adapters/psycopg/_types.py +2 -1
  83. sqlspec/adapters/psycopg/adk/__init__.py +5 -0
  84. sqlspec/adapters/psycopg/adk/store.py +944 -0
  85. sqlspec/adapters/psycopg/config.py +69 -35
  86. sqlspec/adapters/psycopg/data_dictionary.py +331 -0
  87. sqlspec/adapters/psycopg/driver.py +238 -81
  88. sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
  89. sqlspec/adapters/psycopg/litestar/store.py +554 -0
  90. sqlspec/adapters/sqlite/__init__.py +2 -1
  91. sqlspec/adapters/sqlite/_type_handlers.py +86 -0
  92. sqlspec/adapters/sqlite/_types.py +1 -1
  93. sqlspec/adapters/sqlite/adk/__init__.py +5 -0
  94. sqlspec/adapters/sqlite/adk/store.py +572 -0
  95. sqlspec/adapters/sqlite/config.py +87 -15
  96. sqlspec/adapters/sqlite/data_dictionary.py +149 -0
  97. sqlspec/adapters/sqlite/driver.py +137 -54
  98. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  99. sqlspec/adapters/sqlite/litestar/store.py +318 -0
  100. sqlspec/adapters/sqlite/pool.py +18 -9
  101. sqlspec/base.py +45 -26
  102. sqlspec/builder/__init__.py +73 -4
  103. sqlspec/builder/_base.py +162 -89
  104. sqlspec/builder/_column.py +62 -29
  105. sqlspec/builder/_ddl.py +180 -121
  106. sqlspec/builder/_delete.py +5 -4
  107. sqlspec/builder/_dml.py +388 -0
  108. sqlspec/{_sql.py → builder/_factory.py} +53 -94
  109. sqlspec/builder/_insert.py +32 -131
  110. sqlspec/builder/_join.py +375 -0
  111. sqlspec/builder/_merge.py +446 -11
  112. sqlspec/builder/_parsing_utils.py +111 -17
  113. sqlspec/builder/_select.py +1457 -24
  114. sqlspec/builder/_update.py +11 -42
  115. sqlspec/cli.py +307 -194
  116. sqlspec/config.py +252 -67
  117. sqlspec/core/__init__.py +5 -4
  118. sqlspec/core/cache.py +17 -17
  119. sqlspec/core/compiler.py +62 -9
  120. sqlspec/core/filters.py +37 -37
  121. sqlspec/core/hashing.py +9 -9
  122. sqlspec/core/parameters.py +83 -48
  123. sqlspec/core/result.py +102 -46
  124. sqlspec/core/splitter.py +16 -17
  125. sqlspec/core/statement.py +36 -30
  126. sqlspec/core/type_conversion.py +235 -0
  127. sqlspec/driver/__init__.py +7 -6
  128. sqlspec/driver/_async.py +188 -151
  129. sqlspec/driver/_common.py +285 -80
  130. sqlspec/driver/_sync.py +188 -152
  131. sqlspec/driver/mixins/_result_tools.py +20 -236
  132. sqlspec/driver/mixins/_sql_translator.py +4 -4
  133. sqlspec/exceptions.py +75 -7
  134. sqlspec/extensions/adk/__init__.py +53 -0
  135. sqlspec/extensions/adk/_types.py +51 -0
  136. sqlspec/extensions/adk/converters.py +172 -0
  137. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +144 -0
  138. sqlspec/extensions/adk/migrations/__init__.py +0 -0
  139. sqlspec/extensions/adk/service.py +181 -0
  140. sqlspec/extensions/adk/store.py +536 -0
  141. sqlspec/extensions/aiosql/adapter.py +73 -53
  142. sqlspec/extensions/litestar/__init__.py +21 -4
  143. sqlspec/extensions/litestar/cli.py +54 -10
  144. sqlspec/extensions/litestar/config.py +59 -266
  145. sqlspec/extensions/litestar/handlers.py +46 -17
  146. sqlspec/extensions/litestar/migrations/0001_create_session_table.py +137 -0
  147. sqlspec/extensions/litestar/migrations/__init__.py +3 -0
  148. sqlspec/extensions/litestar/plugin.py +324 -223
  149. sqlspec/extensions/litestar/providers.py +25 -25
  150. sqlspec/extensions/litestar/store.py +265 -0
  151. sqlspec/loader.py +30 -49
  152. sqlspec/migrations/__init__.py +4 -3
  153. sqlspec/migrations/base.py +302 -39
  154. sqlspec/migrations/commands.py +611 -144
  155. sqlspec/migrations/context.py +142 -0
  156. sqlspec/migrations/fix.py +199 -0
  157. sqlspec/migrations/loaders.py +68 -23
  158. sqlspec/migrations/runner.py +543 -107
  159. sqlspec/migrations/tracker.py +237 -21
  160. sqlspec/migrations/utils.py +51 -3
  161. sqlspec/migrations/validation.py +177 -0
  162. sqlspec/protocols.py +66 -36
  163. sqlspec/storage/_utils.py +98 -0
  164. sqlspec/storage/backends/fsspec.py +134 -106
  165. sqlspec/storage/backends/local.py +78 -51
  166. sqlspec/storage/backends/obstore.py +278 -162
  167. sqlspec/storage/registry.py +75 -39
  168. sqlspec/typing.py +16 -84
  169. sqlspec/utils/config_resolver.py +153 -0
  170. sqlspec/utils/correlation.py +4 -5
  171. sqlspec/utils/data_transformation.py +3 -2
  172. sqlspec/utils/deprecation.py +9 -8
  173. sqlspec/utils/fixtures.py +4 -4
  174. sqlspec/utils/logging.py +46 -6
  175. sqlspec/utils/module_loader.py +2 -2
  176. sqlspec/utils/schema.py +288 -0
  177. sqlspec/utils/serializers.py +50 -2
  178. sqlspec/utils/sync_tools.py +21 -17
  179. sqlspec/utils/text.py +1 -2
  180. sqlspec/utils/type_guards.py +111 -20
  181. sqlspec/utils/version.py +433 -0
  182. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/METADATA +40 -21
  183. sqlspec-0.27.0.dist-info/RECORD +207 -0
  184. sqlspec/builder/mixins/__init__.py +0 -55
  185. sqlspec/builder/mixins/_cte_and_set_ops.py +0 -254
  186. sqlspec/builder/mixins/_delete_operations.py +0 -50
  187. sqlspec/builder/mixins/_insert_operations.py +0 -282
  188. sqlspec/builder/mixins/_join_operations.py +0 -389
  189. sqlspec/builder/mixins/_merge_operations.py +0 -592
  190. sqlspec/builder/mixins/_order_limit_operations.py +0 -152
  191. sqlspec/builder/mixins/_pivot_operations.py +0 -157
  192. sqlspec/builder/mixins/_select_operations.py +0 -936
  193. sqlspec/builder/mixins/_update_operations.py +0 -218
  194. sqlspec/builder/mixins/_where_clause.py +0 -1304
  195. sqlspec-0.25.0.dist-info/RECORD +0 -139
  196. sqlspec-0.25.0.dist-info/licenses/NOTICE +0 -29
  197. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/WHEEL +0 -0
  198. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/entry_points.txt +0 -0
  199. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,936 +0,0 @@
1
- # pyright: reportPrivateUsage=false
2
- """SELECT clause mixins.
3
-
4
- Provides mixins for SELECT statement functionality including column selection,
5
- CASE expressions, subqueries, and window functions.
6
- """
7
-
8
- from typing import TYPE_CHECKING, Any, Optional, Union, cast
9
-
10
- from mypy_extensions import trait
11
- from sqlglot import exp
12
- from typing_extensions import Self
13
-
14
- from sqlspec.builder._parsing_utils import parse_column_expression, parse_table_expression
15
- from sqlspec.exceptions import SQLBuilderError
16
- from sqlspec.utils.type_guards import has_query_builder_parameters, is_expression
17
-
18
- if TYPE_CHECKING:
19
- from sqlspec.builder._column import Column, ColumnExpression, FunctionColumn
20
- from sqlspec.core.statement import SQL
21
- from sqlspec.protocols import SelectBuilderProtocol, SQLBuilderProtocol
22
-
23
- __all__ = ("Case", "CaseBuilder", "SelectClauseMixin", "SubqueryBuilder", "WindowFunctionBuilder")
24
-
25
-
26
- @trait
27
- class SelectClauseMixin:
28
- """Consolidated mixin providing all SELECT-related clauses and functionality."""
29
-
30
- __slots__ = ()
31
-
32
- # Type annotations for PyRight - these will be provided by the base class
33
- def get_expression(self) -> Optional[exp.Expression]: ...
34
- def set_expression(self, expression: exp.Expression) -> None: ...
35
-
36
- def select(self, *columns: Union[str, exp.Expression, "Column", "FunctionColumn", "SQL", "Case"]) -> Self:
37
- """Add columns to SELECT clause.
38
-
39
- Raises:
40
- SQLBuilderError: If the current expression is not a SELECT statement.
41
-
42
- Returns:
43
- The current builder instance for method chaining.
44
- """
45
- builder = cast("SQLBuilderProtocol", self)
46
- current_expr = self.get_expression()
47
- if current_expr is None:
48
- self.set_expression(exp.Select())
49
- current_expr = self.get_expression()
50
-
51
- if not isinstance(current_expr, exp.Select):
52
- msg = "Cannot add select columns to a non-SELECT expression."
53
- raise SQLBuilderError(msg)
54
- for column in columns:
55
- current_expr = current_expr.select(parse_column_expression(column, builder), copy=False)
56
- self.set_expression(current_expr)
57
- return cast("Self", builder)
58
-
59
- def distinct(self, *columns: Union[str, exp.Expression, "Column", "FunctionColumn", "SQL"]) -> Self:
60
- """Add DISTINCT clause to SELECT.
61
-
62
- Args:
63
- *columns: Optional columns to make distinct. If none provided, applies DISTINCT to all selected columns.
64
-
65
- Raises:
66
- SQLBuilderError: If the current expression is not a SELECT statement.
67
-
68
- Returns:
69
- The current builder instance for method chaining.
70
- """
71
- builder = cast("SQLBuilderProtocol", self)
72
- if builder._expression is None:
73
- builder._expression = exp.Select()
74
- if not isinstance(builder._expression, exp.Select):
75
- msg = "Cannot add DISTINCT to a non-SELECT expression."
76
- raise SQLBuilderError(msg)
77
- if not columns:
78
- builder._expression.set("distinct", exp.Distinct())
79
- else:
80
- distinct_columns = [parse_column_expression(column, builder) for column in columns]
81
- builder._expression.set("distinct", exp.Distinct(expressions=distinct_columns))
82
- return cast("Self", builder)
83
-
84
- def from_(self, table: Union[str, exp.Expression, Any], alias: Optional[str] = None) -> Self:
85
- """Add FROM clause.
86
-
87
- Args:
88
- table: The table name, expression, or subquery to select from.
89
- alias: Optional alias for the table.
90
-
91
- Raises:
92
- SQLBuilderError: If the current expression is not a SELECT statement or if the table type is unsupported.
93
-
94
- Returns:
95
- The current builder instance for method chaining.
96
- """
97
- builder = cast("SQLBuilderProtocol", self)
98
- if builder._expression is None:
99
- builder._expression = exp.Select()
100
- if not isinstance(builder._expression, exp.Select):
101
- msg = "FROM clause is only supported for SELECT statements."
102
- raise SQLBuilderError(msg)
103
- from_expr: exp.Expression
104
- if isinstance(table, str):
105
- from_expr = parse_table_expression(table, alias)
106
- elif is_expression(table):
107
- from_expr = exp.alias_(table, alias) if alias else table
108
- elif has_query_builder_parameters(table):
109
- subquery = table.build()
110
- sql_str = subquery.sql if hasattr(subquery, "sql") and not callable(subquery.sql) else str(subquery)
111
- subquery_exp = exp.paren(exp.maybe_parse(sql_str, dialect=getattr(builder, "dialect", None)))
112
- from_expr = exp.alias_(subquery_exp, alias) if alias else subquery_exp
113
- current_parameters = getattr(builder, "_parameters", None)
114
- merged_parameters = getattr(type(builder), "ParameterConverter", None)
115
- if merged_parameters and hasattr(subquery, "parameters"):
116
- subquery_parameters = getattr(subquery, "parameters", {})
117
- merged_parameters = merged_parameters.merge_parameters(
118
- parameters=subquery_parameters,
119
- args=current_parameters if isinstance(current_parameters, list) else None,
120
- kwargs=current_parameters if isinstance(current_parameters, dict) else {},
121
- )
122
- setattr(builder, "_parameters", merged_parameters)
123
- else:
124
- from_expr = table
125
- builder._expression = builder._expression.from_(from_expr, copy=False)
126
- return cast("Self", builder)
127
-
128
- def group_by(self, *columns: Union[str, exp.Expression]) -> Self:
129
- """Add GROUP BY clause.
130
-
131
- Args:
132
- *columns: Columns to group by. Can be column names, expressions,
133
- or special grouping expressions like ROLLUP, CUBE, etc.
134
-
135
- Returns:
136
- The current builder instance for method chaining.
137
- """
138
- current_expr = self.get_expression()
139
- if current_expr is None or not isinstance(current_expr, exp.Select):
140
- return self
141
-
142
- for column in columns:
143
- current_expr = current_expr.group_by(exp.column(column) if isinstance(column, str) else column, copy=False)
144
- self.set_expression(current_expr)
145
- return self
146
-
147
- def group_by_rollup(self, *columns: Union[str, exp.Expression]) -> Self:
148
- """Add GROUP BY ROLLUP clause.
149
-
150
- ROLLUP generates subtotals and grand totals for a hierarchical set of columns.
151
-
152
- Args:
153
- *columns: Columns to include in the rollup hierarchy.
154
-
155
- Returns:
156
- The current builder instance for method chaining.
157
-
158
- Example:
159
- ```python
160
- query = (
161
- sql.select("product", "region", sql.sum("sales"))
162
- .from_("sales_data")
163
- .group_by_rollup("product", "region")
164
- )
165
- ```
166
- """
167
- column_exprs = [exp.column(col) if isinstance(col, str) else col for col in columns]
168
- rollup_expr = exp.Rollup(expressions=column_exprs)
169
- return self.group_by(rollup_expr)
170
-
171
- def group_by_cube(self, *columns: Union[str, exp.Expression]) -> Self:
172
- """Add GROUP BY CUBE clause.
173
-
174
- CUBE generates subtotals for all possible combinations of the specified columns.
175
-
176
- Args:
177
- *columns: Columns to include in the cube.
178
-
179
- Returns:
180
- The current builder instance for method chaining.
181
-
182
- Example:
183
- ```python
184
- query = (
185
- sql.select("product", "region", sql.sum("sales"))
186
- .from_("sales_data")
187
- .group_by_cube("product", "region")
188
- )
189
- ```
190
- """
191
- column_exprs = [exp.column(col) if isinstance(col, str) else col for col in columns]
192
- cube_expr = exp.Cube(expressions=column_exprs)
193
- return self.group_by(cube_expr)
194
-
195
- def group_by_grouping_sets(self, *column_sets: Union[tuple[str, ...], list[str]]) -> Self:
196
- """Add GROUP BY GROUPING SETS clause.
197
-
198
- GROUPING SETS allows you to specify multiple grouping sets in a single query.
199
-
200
- Args:
201
- *column_sets: Sets of columns to group by. Each set can be a tuple or list.
202
- Empty tuple/list creates a grand total grouping.
203
-
204
- Returns:
205
- The current builder instance for method chaining.
206
-
207
- Example:
208
- ```python
209
- query = (
210
- sql.select("product", "region", sql.sum("sales"))
211
- .from_("sales_data")
212
- .group_by_grouping_sets(("product",), ("region",), ())
213
- )
214
- ```
215
- """
216
- set_expressions = []
217
- for column_set in column_sets:
218
- if isinstance(column_set, (tuple, list)):
219
- if len(column_set) == 0:
220
- set_expressions.append(exp.Tuple(expressions=[]))
221
- else:
222
- columns = [exp.column(col) for col in column_set]
223
- set_expressions.append(exp.Tuple(expressions=columns))
224
- else:
225
- set_expressions.append(exp.column(column_set))
226
-
227
- grouping_sets_expr = exp.GroupingSets(expressions=set_expressions)
228
- return self.group_by(grouping_sets_expr)
229
-
230
- def count_(self, column: "Union[str, exp.Expression]" = "*", alias: Optional[str] = None) -> Self:
231
- """Add COUNT function to SELECT clause.
232
-
233
- Args:
234
- column: The column to count (default is "*").
235
- alias: Optional alias for the count.
236
-
237
- Returns:
238
- The current builder instance for method chaining.
239
- """
240
- builder = cast("SelectBuilderProtocol", self)
241
- if column == "*":
242
- count_expr = exp.Count(this=exp.Star())
243
- else:
244
- col_expr = exp.column(column) if isinstance(column, str) else column
245
- count_expr = exp.Count(this=col_expr)
246
-
247
- select_expr = exp.alias_(count_expr, alias) if alias else count_expr
248
- return cast("Self", builder.select(select_expr))
249
-
250
- def sum_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
251
- """Add SUM function to SELECT clause.
252
-
253
- Args:
254
- column: The column to sum.
255
- alias: Optional alias for the sum.
256
-
257
- Returns:
258
- The current builder instance for method chaining.
259
- """
260
- builder = cast("SelectBuilderProtocol", self)
261
- col_expr = exp.column(column) if isinstance(column, str) else column
262
- sum_expr = exp.Sum(this=col_expr)
263
- select_expr = exp.alias_(sum_expr, alias) if alias else sum_expr
264
- return cast("Self", builder.select(select_expr))
265
-
266
- def avg_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
267
- """Add AVG function to SELECT clause.
268
-
269
- Args:
270
- column: The column to average.
271
- alias: Optional alias for the average.
272
-
273
- Returns:
274
- The current builder instance for method chaining.
275
- """
276
- builder = cast("SelectBuilderProtocol", self)
277
- col_expr = exp.column(column) if isinstance(column, str) else column
278
- avg_expr = exp.Avg(this=col_expr)
279
- select_expr = exp.alias_(avg_expr, alias) if alias else avg_expr
280
- return cast("Self", builder.select(select_expr))
281
-
282
- def max_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
283
- """Add MAX function to SELECT clause.
284
-
285
- Args:
286
- column: The column to find the maximum of.
287
- alias: Optional alias for the maximum.
288
-
289
- Returns:
290
- The current builder instance for method chaining.
291
- """
292
- builder = cast("SelectBuilderProtocol", self)
293
- col_expr = exp.column(column) if isinstance(column, str) else column
294
- max_expr = exp.Max(this=col_expr)
295
- select_expr = exp.alias_(max_expr, alias) if alias else max_expr
296
- return cast("Self", builder.select(select_expr))
297
-
298
- def min_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
299
- """Add MIN function to SELECT clause.
300
-
301
- Args:
302
- column: The column to find the minimum of.
303
- alias: Optional alias for the minimum.
304
-
305
- Returns:
306
- The current builder instance for method chaining.
307
- """
308
- builder = cast("SelectBuilderProtocol", self)
309
- col_expr = exp.column(column) if isinstance(column, str) else column
310
- min_expr = exp.Min(this=col_expr)
311
- select_expr = exp.alias_(min_expr, alias) if alias else min_expr
312
- return cast("Self", builder.select(select_expr))
313
-
314
- def array_agg(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
315
- """Add ARRAY_AGG aggregate function to SELECT clause.
316
-
317
- Args:
318
- column: The column to aggregate into an array.
319
- alias: Optional alias for the result.
320
-
321
- Returns:
322
- The current builder instance for method chaining.
323
- """
324
- builder = cast("SelectBuilderProtocol", self)
325
- col_expr = exp.column(column) if isinstance(column, str) else column
326
- array_agg_expr = exp.ArrayAgg(this=col_expr)
327
- select_expr = exp.alias_(array_agg_expr, alias) if alias else array_agg_expr
328
- return cast("Self", builder.select(select_expr))
329
-
330
- def count_distinct(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
331
- """Add COUNT(DISTINCT column) to SELECT clause.
332
-
333
- Args:
334
- column: The column to count distinct values of.
335
- alias: Optional alias for the count.
336
-
337
- Returns:
338
- The current builder instance for method chaining.
339
- """
340
- builder = cast("SelectBuilderProtocol", self)
341
- col_expr = exp.column(column) if isinstance(column, str) else column
342
- count_expr = exp.Count(this=exp.Distinct(expressions=[col_expr]))
343
- select_expr = exp.alias_(count_expr, alias) if alias else count_expr
344
- return cast("Self", builder.select(select_expr))
345
-
346
- def stddev(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
347
- """Add STDDEV aggregate function to SELECT clause.
348
-
349
- Args:
350
- column: The column to calculate standard deviation of.
351
- alias: Optional alias for the result.
352
-
353
- Returns:
354
- The current builder instance for method chaining.
355
- """
356
- builder = cast("SelectBuilderProtocol", self)
357
- col_expr = exp.column(column) if isinstance(column, str) else column
358
- stddev_expr = exp.Stddev(this=col_expr)
359
- select_expr = exp.alias_(stddev_expr, alias) if alias else stddev_expr
360
- return cast("Self", builder.select(select_expr))
361
-
362
- def stddev_pop(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
363
- """Add STDDEV_POP aggregate function to SELECT clause.
364
-
365
- Args:
366
- column: The column to calculate population standard deviation of.
367
- alias: Optional alias for the result.
368
-
369
- Returns:
370
- The current builder instance for method chaining.
371
- """
372
- builder = cast("SelectBuilderProtocol", self)
373
- col_expr = exp.column(column) if isinstance(column, str) else column
374
- stddev_pop_expr = exp.StddevPop(this=col_expr)
375
- select_expr = exp.alias_(stddev_pop_expr, alias) if alias else stddev_pop_expr
376
- return cast("Self", builder.select(select_expr))
377
-
378
- def stddev_samp(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
379
- """Add STDDEV_SAMP aggregate function to SELECT clause.
380
-
381
- Args:
382
- column: The column to calculate sample standard deviation of.
383
- alias: Optional alias for the result.
384
-
385
- Returns:
386
- The current builder instance for method chaining.
387
- """
388
- builder = cast("SelectBuilderProtocol", self)
389
- col_expr = exp.column(column) if isinstance(column, str) else column
390
- stddev_samp_expr = exp.StddevSamp(this=col_expr)
391
- select_expr = exp.alias_(stddev_samp_expr, alias) if alias else stddev_samp_expr
392
- return cast("Self", builder.select(select_expr))
393
-
394
- def variance(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
395
- """Add VARIANCE aggregate function to SELECT clause.
396
-
397
- Args:
398
- column: The column to calculate variance of.
399
- alias: Optional alias for the result.
400
-
401
- Returns:
402
- The current builder instance for method chaining.
403
- """
404
- builder = cast("SelectBuilderProtocol", self)
405
- col_expr = exp.column(column) if isinstance(column, str) else column
406
- variance_expr = exp.Variance(this=col_expr)
407
- select_expr = exp.alias_(variance_expr, alias) if alias else variance_expr
408
- return cast("Self", builder.select(select_expr))
409
-
410
- def var_pop(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
411
- """Add VAR_POP aggregate function to SELECT clause.
412
-
413
- Args:
414
- column: The column to calculate population variance of.
415
- alias: Optional alias for the result.
416
-
417
- Returns:
418
- The current builder instance for method chaining.
419
- """
420
- builder = cast("SelectBuilderProtocol", self)
421
- col_expr = exp.column(column) if isinstance(column, str) else column
422
- var_pop_expr = exp.VariancePop(this=col_expr)
423
- select_expr = exp.alias_(var_pop_expr, alias) if alias else var_pop_expr
424
- return cast("Self", builder.select(select_expr))
425
-
426
- def string_agg(self, column: Union[str, exp.Expression], separator: str = ",", alias: Optional[str] = None) -> Self:
427
- """Add STRING_AGG aggregate function to SELECT clause.
428
-
429
- Args:
430
- column: The column to aggregate into a string.
431
- separator: The separator between values (default is comma).
432
- alias: Optional alias for the result.
433
-
434
- Returns:
435
- The current builder instance for method chaining.
436
-
437
- Note:
438
- Different databases have different names for this function:
439
- - PostgreSQL: STRING_AGG
440
- - MySQL: GROUP_CONCAT
441
- - SQLite: GROUP_CONCAT
442
- SQLGlot will handle the translation.
443
- """
444
- builder = cast("SelectBuilderProtocol", self)
445
- col_expr = exp.column(column) if isinstance(column, str) else column
446
- string_agg_expr = exp.GroupConcat(this=col_expr, separator=exp.convert(separator))
447
- select_expr = exp.alias_(string_agg_expr, alias) if alias else string_agg_expr
448
- return cast("Self", builder.select(select_expr))
449
-
450
- def json_agg(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
451
- """Add JSON_AGG aggregate function to SELECT clause.
452
-
453
- Args:
454
- column: The column to aggregate into a JSON array.
455
- alias: Optional alias for the result.
456
-
457
- Returns:
458
- The current builder instance for method chaining.
459
- """
460
- builder = cast("SelectBuilderProtocol", self)
461
- col_expr = exp.column(column) if isinstance(column, str) else column
462
- json_agg_expr = exp.JSONArrayAgg(this=col_expr)
463
- select_expr = exp.alias_(json_agg_expr, alias) if alias else json_agg_expr
464
- return cast("Self", builder.select(select_expr))
465
-
466
- def window(
467
- self,
468
- function_expr: Union[str, exp.Expression],
469
- partition_by: Optional[Union[str, list[str], exp.Expression, list[exp.Expression]]] = None,
470
- order_by: Optional[Union[str, list[str], exp.Expression, list[exp.Expression]]] = None,
471
- frame: Optional[str] = None,
472
- alias: Optional[str] = None,
473
- ) -> Self:
474
- """Add a window function to the SELECT clause.
475
-
476
- Args:
477
- function_expr: The window function expression (e.g., "COUNT(*)", "ROW_NUMBER()").
478
- partition_by: Column(s) to partition by.
479
- order_by: Column(s) to order by within the window.
480
- frame: Window frame specification (e.g., "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW").
481
- alias: Optional alias for the window function.
482
-
483
- Raises:
484
- SQLBuilderError: If the current expression is not a SELECT statement or function parsing fails.
485
-
486
- Returns:
487
- The current builder instance for method chaining.
488
- """
489
- current_expr = self.get_expression()
490
- if current_expr is None:
491
- self.set_expression(exp.Select())
492
- current_expr = self.get_expression()
493
-
494
- if not isinstance(current_expr, exp.Select):
495
- msg = "Cannot add window function to a non-SELECT expression."
496
- raise SQLBuilderError(msg)
497
-
498
- func_expr_parsed: exp.Expression
499
- if isinstance(function_expr, str):
500
- parsed: Optional[exp.Expression] = exp.maybe_parse(function_expr, dialect=getattr(self, "dialect", None))
501
- if not parsed:
502
- msg = f"Could not parse function expression: {function_expr}"
503
- raise SQLBuilderError(msg)
504
- func_expr_parsed = parsed
505
- else:
506
- func_expr_parsed = function_expr
507
-
508
- over_args: dict[str, Any] = {}
509
- if partition_by:
510
- if isinstance(partition_by, str):
511
- over_args["partition_by"] = [exp.column(partition_by)]
512
- elif isinstance(partition_by, list):
513
- over_args["partition_by"] = [exp.column(col) if isinstance(col, str) else col for col in partition_by]
514
- elif isinstance(partition_by, exp.Expression):
515
- over_args["partition_by"] = [partition_by]
516
-
517
- if order_by:
518
- if isinstance(order_by, str):
519
- over_args["order"] = exp.column(order_by).asc()
520
- elif isinstance(order_by, list):
521
- order_expressions: list[Union[exp.Expression, exp.Column]] = []
522
- for col in order_by:
523
- if isinstance(col, str):
524
- order_expressions.append(exp.column(col).asc())
525
- else:
526
- order_expressions.append(col)
527
- over_args["order"] = exp.Order(expressions=order_expressions)
528
- elif isinstance(order_by, exp.Expression):
529
- over_args["order"] = order_by
530
-
531
- if frame:
532
- frame_expr: Optional[exp.Expression] = exp.maybe_parse(frame, dialect=getattr(self, "dialect", None))
533
- if frame_expr:
534
- over_args["frame"] = frame_expr
535
-
536
- window_expr = exp.Window(this=func_expr_parsed, **over_args)
537
- current_expr = current_expr.select(exp.alias_(window_expr, alias) if alias else window_expr, copy=False)
538
- self.set_expression(current_expr)
539
- return self
540
-
541
- def case_(self, alias: "Optional[str]" = None) -> "CaseBuilder":
542
- """Create a CASE expression for the SELECT clause.
543
-
544
- Args:
545
- alias: Optional alias for the CASE expression.
546
-
547
- Returns:
548
- CaseBuilder: A CaseBuilder instance for building the CASE expression.
549
- """
550
- builder = cast("SelectBuilderProtocol", self)
551
- return CaseBuilder(builder, alias)
552
-
553
-
554
- class CaseBuilder:
555
- """Builder for CASE expressions."""
556
-
557
- __slots__ = ("_alias", "_case_expr", "_parent")
558
-
559
- def __init__(self, parent: "SelectBuilderProtocol", alias: "Optional[str]" = None) -> None:
560
- """Initialize CaseBuilder.
561
-
562
- Args:
563
- parent: The parent builder with select capabilities.
564
- alias: Optional alias for the CASE expression.
565
- """
566
- self._parent = parent
567
- self._alias = alias
568
- self._case_expr = exp.Case()
569
-
570
- def when(self, condition: "Union[str, exp.Expression]", value: "Any") -> "CaseBuilder":
571
- """Add WHEN clause to CASE expression.
572
-
573
- Args:
574
- condition: The condition to test.
575
- value: The value to return if condition is true.
576
-
577
- Returns:
578
- CaseBuilder: The current builder instance for method chaining.
579
- """
580
- cond_expr = exp.condition(condition) if isinstance(condition, str) else condition
581
- param_name = self._parent._generate_unique_parameter_name("case_when_value")
582
- param_name = self._parent.add_parameter(value, name=param_name)[1]
583
- value_expr = exp.Placeholder(this=param_name)
584
-
585
- when_clause = exp.When(this=cond_expr, then=value_expr)
586
-
587
- if not self._case_expr.args.get("ifs"):
588
- self._case_expr.set("ifs", [])
589
- self._case_expr.args["ifs"].append(when_clause)
590
- return self
591
-
592
- def else_(self, value: "Any") -> "CaseBuilder":
593
- """Add ELSE clause to CASE expression.
594
-
595
- Args:
596
- value: The value to return if no conditions match.
597
-
598
- Returns:
599
- CaseBuilder: The current builder instance for method chaining.
600
- """
601
- param_name = self._parent._generate_unique_parameter_name("case_else_value")
602
- param_name = self._parent.add_parameter(value, name=param_name)[1]
603
- value_expr = exp.Placeholder(this=param_name)
604
- self._case_expr.set("default", value_expr)
605
- return self
606
-
607
- def end(self) -> "SelectBuilderProtocol":
608
- """Finalize the CASE expression and add it to the SELECT clause.
609
-
610
- Returns:
611
- The parent builder instance.
612
- """
613
- select_expr = exp.alias_(self._case_expr, self._alias) if self._alias else self._case_expr
614
- return self._parent.select(select_expr)
615
-
616
-
617
- @trait
618
- class WindowFunctionBuilder:
619
- """Builder for window functions with fluent syntax.
620
-
621
- Example:
622
- ```python
623
- from sqlspec import sql
624
-
625
- # sql.row_number_.partition_by("department").order_by("salary")
626
- window_func = (
627
- sql.row_number_.partition_by("department")
628
- .order_by("salary")
629
- .as_("row_num")
630
- )
631
- ```
632
- """
633
-
634
- def __init__(self, function_name: str) -> None:
635
- """Initialize the window function builder.
636
-
637
- Args:
638
- function_name: Name of the window function (row_number, rank, etc.)
639
- """
640
- self._function_name = function_name
641
- self._partition_by_cols: list[exp.Expression] = []
642
- self._order_by_cols: list[exp.Expression] = []
643
- self._alias: Optional[str] = None
644
-
645
- def __eq__(self, other: object) -> "ColumnExpression": # type: ignore[override]
646
- """Equal to (==) - convert to expression then compare."""
647
- from sqlspec.builder._column import ColumnExpression
648
-
649
- window_expr = self._build_expression()
650
- if other is None:
651
- return ColumnExpression(exp.Is(this=window_expr, expression=exp.Null()))
652
- return ColumnExpression(exp.EQ(this=window_expr, expression=exp.convert(other)))
653
-
654
- def __hash__(self) -> int:
655
- """Make WindowFunctionBuilder hashable."""
656
- return hash(id(self))
657
-
658
- def partition_by(self, *columns: Union[str, exp.Expression]) -> "WindowFunctionBuilder":
659
- """Add PARTITION BY clause.
660
-
661
- Args:
662
- *columns: Columns to partition by.
663
-
664
- Returns:
665
- Self for method chaining.
666
- """
667
- for col in columns:
668
- col_expr = exp.column(col) if isinstance(col, str) else col
669
- self._partition_by_cols.append(col_expr)
670
- return self
671
-
672
- def order_by(self, *columns: Union[str, exp.Expression]) -> "WindowFunctionBuilder":
673
- """Add ORDER BY clause.
674
-
675
- Args:
676
- *columns: Columns to order by.
677
-
678
- Returns:
679
- Self for method chaining.
680
- """
681
- for col in columns:
682
- if isinstance(col, str):
683
- col_expr = exp.column(col).asc()
684
- self._order_by_cols.append(col_expr)
685
- else:
686
- # Convert to ordered expression
687
- self._order_by_cols.append(exp.Ordered(this=col, desc=False))
688
- return self
689
-
690
- def as_(self, alias: str) -> exp.Alias:
691
- """Complete the window function with an alias.
692
-
693
- Args:
694
- alias: Alias name for the window function.
695
-
696
- Returns:
697
- Aliased window function expression.
698
- """
699
- window_expr = self._build_expression()
700
- return cast("exp.Alias", exp.alias_(window_expr, alias))
701
-
702
- def build(self) -> exp.Expression:
703
- """Complete the window function without an alias.
704
-
705
- Returns:
706
- Window function expression.
707
- """
708
- return self._build_expression()
709
-
710
- def _build_expression(self) -> exp.Expression:
711
- """Build the complete window function expression."""
712
- # Create the function expression
713
- func_expr = exp.Anonymous(this=self._function_name.upper(), expressions=[])
714
-
715
- # Build the OVER clause arguments
716
- over_args: dict[str, Any] = {}
717
-
718
- if self._partition_by_cols:
719
- over_args["partition_by"] = self._partition_by_cols
720
-
721
- if self._order_by_cols:
722
- over_args["order"] = exp.Order(expressions=self._order_by_cols)
723
-
724
- return exp.Window(this=func_expr, **over_args)
725
-
726
-
727
- @trait
728
- class SubqueryBuilder:
729
- """Builder for subquery operations with fluent syntax.
730
-
731
- Example:
732
- ```python
733
- from sqlspec import sql
734
-
735
- # sql.exists_(subquery)
736
- exists_check = sql.exists_(
737
- sql.select("1")
738
- .from_("orders")
739
- .where_eq("user_id", sql.users.id)
740
- )
741
-
742
- # sql.in_(subquery)
743
- in_check = sql.in_(
744
- sql.select("category_id")
745
- .from_("categories")
746
- .where_eq("active", True)
747
- )
748
- ```
749
- """
750
-
751
- def __init__(self, operation: str) -> None:
752
- """Initialize the subquery builder.
753
-
754
- Args:
755
- operation: Type of subquery operation (exists, in, any, all)
756
- """
757
- self._operation = operation
758
-
759
- def __eq__(self, other: object) -> "ColumnExpression": # type: ignore[override]
760
- """Equal to (==) - not typically used but needed for type consistency."""
761
- from sqlspec.builder._column import ColumnExpression
762
-
763
- # SubqueryBuilder doesn't have a direct expression, so this is a placeholder
764
- # In practice, this shouldn't be called as subqueries are used differently
765
- placeholder_expr = exp.Literal.string(f"subquery_{self._operation}")
766
- if other is None:
767
- return ColumnExpression(exp.Is(this=placeholder_expr, expression=exp.Null()))
768
- return ColumnExpression(exp.EQ(this=placeholder_expr, expression=exp.convert(other)))
769
-
770
- def __hash__(self) -> int:
771
- """Make SubqueryBuilder hashable."""
772
- return hash(id(self))
773
-
774
- def __call__(self, subquery: Union[str, exp.Expression, Any]) -> exp.Expression:
775
- """Build the subquery expression.
776
-
777
- Args:
778
- subquery: The subquery - can be a SQL string, SelectBuilder, or expression
779
-
780
- Returns:
781
- The subquery expression (EXISTS, IN, ANY, ALL, etc.)
782
- """
783
- subquery_expr: exp.Expression
784
- if isinstance(subquery, str):
785
- # Parse as SQL
786
- parsed: Optional[exp.Expression] = exp.maybe_parse(subquery)
787
- if not parsed:
788
- msg = f"Could not parse subquery SQL: {subquery}"
789
- raise SQLBuilderError(msg)
790
- subquery_expr = parsed
791
- elif hasattr(subquery, "build") and callable(getattr(subquery, "build", None)):
792
- # It's a query builder - build it to get the SQL and parse
793
- built_query = subquery.build() # pyright: ignore[reportAttributeAccessIssue]
794
- subquery_expr = exp.maybe_parse(built_query.sql)
795
- if not subquery_expr:
796
- msg = f"Could not parse built query: {built_query.sql}"
797
- raise SQLBuilderError(msg)
798
- elif isinstance(subquery, exp.Expression):
799
- subquery_expr = subquery
800
- else:
801
- # Try to convert to expression
802
- parsed = exp.maybe_parse(str(subquery))
803
- if not parsed:
804
- msg = f"Could not convert subquery to expression: {subquery}"
805
- raise SQLBuilderError(msg)
806
- subquery_expr = parsed
807
-
808
- # Build the appropriate expression based on operation
809
- if self._operation == "exists":
810
- return exp.Exists(this=subquery_expr)
811
- if self._operation == "in":
812
- # For IN, we create a subquery that can be used with WHERE column IN (subquery)
813
- return exp.In(expressions=[subquery_expr])
814
- if self._operation == "any":
815
- return exp.Any(this=subquery_expr)
816
- if self._operation == "all":
817
- return exp.All(this=subquery_expr)
818
- msg = f"Unknown subquery operation: {self._operation}"
819
- raise SQLBuilderError(msg)
820
-
821
-
822
- @trait
823
- class Case:
824
- """Builder for CASE expressions using the SQL factory.
825
-
826
- Example:
827
- ```python
828
- from sqlspec import sql
829
-
830
- case_expr = (
831
- sql.case()
832
- .when(sql.age < 18, "Minor")
833
- .when(sql.age < 65, "Adult")
834
- .else_("Senior")
835
- .end()
836
- )
837
- ```
838
- """
839
-
840
- def __init__(self) -> None:
841
- """Initialize the CASE expression builder."""
842
- self._conditions: list[exp.If] = []
843
- self._default: Optional[exp.Expression] = None
844
-
845
- def __eq__(self, other: object) -> "ColumnExpression": # type: ignore[override]
846
- """Equal to (==) - convert to expression then compare."""
847
- from sqlspec.builder._column import ColumnExpression
848
-
849
- case_expr = exp.Case(ifs=self._conditions, default=self._default)
850
- if other is None:
851
- return ColumnExpression(exp.Is(this=case_expr, expression=exp.Null()))
852
- return ColumnExpression(exp.EQ(this=case_expr, expression=exp.convert(other)))
853
-
854
- def __hash__(self) -> int:
855
- """Make Case hashable."""
856
- return hash(id(self))
857
-
858
- def when(self, condition: Union[str, exp.Expression], value: Union[str, exp.Expression, Any]) -> Self:
859
- """Add a WHEN clause.
860
-
861
- Args:
862
- condition: Condition to test.
863
- value: Value to return if condition is true.
864
-
865
- Returns:
866
- Self for method chaining.
867
- """
868
- from sqlspec._sql import SQLFactory
869
-
870
- cond_expr = exp.maybe_parse(condition) or exp.column(condition) if isinstance(condition, str) else condition
871
- val_expr = SQLFactory._to_expression(value)
872
-
873
- # SQLGlot uses exp.If for CASE WHEN clauses, not exp.When
874
- when_clause = exp.If(this=cond_expr, true=val_expr)
875
- self._conditions.append(when_clause)
876
- return self
877
-
878
- def else_(self, value: Union[str, exp.Expression, Any]) -> Self:
879
- """Add an ELSE clause.
880
-
881
- Args:
882
- value: Default value to return.
883
-
884
- Returns:
885
- Self for method chaining.
886
- """
887
- from sqlspec._sql import SQLFactory
888
-
889
- self._default = SQLFactory._to_expression(value)
890
- return self
891
-
892
- def end(self) -> Self:
893
- """Complete the CASE expression.
894
-
895
- Returns:
896
- Complete CASE expression.
897
- """
898
- return self
899
-
900
- @property
901
- def _expression(self) -> exp.Case:
902
- """Get the sqlglot expression for this case builder.
903
-
904
- This allows the CaseBuilder to be used wherever expressions are expected.
905
- """
906
- return exp.Case(ifs=self._conditions, default=self._default)
907
-
908
- def as_(self, alias: str) -> exp.Alias:
909
- """Complete the CASE expression with an alias.
910
-
911
- Args:
912
- alias: Alias name for the CASE expression.
913
-
914
- Returns:
915
- Aliased CASE expression.
916
- """
917
- case_expr = exp.Case(ifs=self._conditions, default=self._default)
918
- return cast("exp.Alias", exp.alias_(case_expr, alias))
919
-
920
- @property
921
- def conditions(self) -> "list[exp.If]":
922
- """Get CASE conditions (public API).
923
-
924
- Returns:
925
- List of If expressions representing WHEN clauses
926
- """
927
- return self._conditions
928
-
929
- @property
930
- def default(self) -> Optional[exp.Expression]:
931
- """Get CASE default value (public API).
932
-
933
- Returns:
934
- Default expression for the ELSE clause, or None
935
- """
936
- return self._default