sqlspec 0.16.1__cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.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.cpython-312-aarch64-linux-gnu.so +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 +1780 -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 +473 -0
  52. sqlspec/builder/_column.py +320 -0
  53. sqlspec/builder/_ddl.py +1346 -0
  54. sqlspec/builder/_ddl_utils.py +103 -0
  55. sqlspec/builder/_delete.py +76 -0
  56. sqlspec/builder/_insert.py +256 -0
  57. sqlspec/builder/_merge.py +71 -0
  58. sqlspec/builder/_parsing_utils.py +140 -0
  59. sqlspec/builder/_select.py +170 -0
  60. sqlspec/builder/_update.py +188 -0
  61. sqlspec/builder/mixins/__init__.py +55 -0
  62. sqlspec/builder/mixins/_cte_and_set_ops.py +222 -0
  63. sqlspec/builder/mixins/_delete_operations.py +41 -0
  64. sqlspec/builder/mixins/_insert_operations.py +244 -0
  65. sqlspec/builder/mixins/_join_operations.py +122 -0
  66. sqlspec/builder/mixins/_merge_operations.py +476 -0
  67. sqlspec/builder/mixins/_order_limit_operations.py +135 -0
  68. sqlspec/builder/mixins/_pivot_operations.py +153 -0
  69. sqlspec/builder/mixins/_select_operations.py +603 -0
  70. sqlspec/builder/mixins/_update_operations.py +187 -0
  71. sqlspec/builder/mixins/_where_clause.py +621 -0
  72. sqlspec/cli.py +247 -0
  73. sqlspec/config.py +395 -0
  74. sqlspec/core/__init__.py +63 -0
  75. sqlspec/core/cache.cpython-312-aarch64-linux-gnu.so +0 -0
  76. sqlspec/core/cache.py +871 -0
  77. sqlspec/core/compiler.cpython-312-aarch64-linux-gnu.so +0 -0
  78. sqlspec/core/compiler.py +417 -0
  79. sqlspec/core/filters.cpython-312-aarch64-linux-gnu.so +0 -0
  80. sqlspec/core/filters.py +830 -0
  81. sqlspec/core/hashing.cpython-312-aarch64-linux-gnu.so +0 -0
  82. sqlspec/core/hashing.py +310 -0
  83. sqlspec/core/parameters.cpython-312-aarch64-linux-gnu.so +0 -0
  84. sqlspec/core/parameters.py +1237 -0
  85. sqlspec/core/result.cpython-312-aarch64-linux-gnu.so +0 -0
  86. sqlspec/core/result.py +677 -0
  87. sqlspec/core/splitter.cpython-312-aarch64-linux-gnu.so +0 -0
  88. sqlspec/core/splitter.py +819 -0
  89. sqlspec/core/statement.cpython-312-aarch64-linux-gnu.so +0 -0
  90. sqlspec/core/statement.py +676 -0
  91. sqlspec/driver/__init__.py +19 -0
  92. sqlspec/driver/_async.py +502 -0
  93. sqlspec/driver/_common.py +631 -0
  94. sqlspec/driver/_sync.py +503 -0
  95. sqlspec/driver/mixins/__init__.py +6 -0
  96. sqlspec/driver/mixins/_result_tools.py +193 -0
  97. sqlspec/driver/mixins/_sql_translator.py +86 -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.cpython-312-aarch64-linux-gnu.so +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 +407 -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.cpython-312-aarch64-linux-gnu.so +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.cpython-312-aarch64-linux-gnu.so +0 -0
  138. sqlspec/utils/sync_tools.py +237 -0
  139. sqlspec/utils/text.cpython-312-aarch64-linux-gnu.so +0 -0
  140. sqlspec/utils/text.py +96 -0
  141. sqlspec/utils/type_guards.cpython-312-aarch64-linux-gnu.so +0 -0
  142. sqlspec/utils/type_guards.py +1139 -0
  143. sqlspec-0.16.1.dist-info/METADATA +365 -0
  144. sqlspec-0.16.1.dist-info/RECORD +148 -0
  145. sqlspec-0.16.1.dist-info/WHEEL +7 -0
  146. sqlspec-0.16.1.dist-info/entry_points.txt +2 -0
  147. sqlspec-0.16.1.dist-info/licenses/LICENSE +21 -0
  148. sqlspec-0.16.1.dist-info/licenses/NOTICE +29 -0
@@ -0,0 +1,603 @@
1
+ """SELECT clause mixins consolidated into a single module."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Any, Optional, Union, cast
5
+
6
+ from mypy_extensions import trait
7
+ from sqlglot import exp
8
+ from typing_extensions import Self
9
+
10
+ from sqlspec.builder._parsing_utils import parse_column_expression, parse_table_expression
11
+ from sqlspec.exceptions import SQLBuilderError
12
+ from sqlspec.utils.type_guards import has_query_builder_parameters, is_expression
13
+
14
+ if TYPE_CHECKING:
15
+ from sqlspec.builder._column import Column, FunctionColumn
16
+ from sqlspec.protocols import SelectBuilderProtocol, SQLBuilderProtocol
17
+
18
+ __all__ = ("CaseBuilder", "SelectClauseMixin")
19
+
20
+
21
+ @trait
22
+ class SelectClauseMixin:
23
+ """Consolidated mixin providing all SELECT-related clauses and functionality."""
24
+
25
+ __slots__ = ()
26
+
27
+ # Type annotation for PyRight - this will be provided by the base class
28
+ _expression: Optional[exp.Expression]
29
+
30
+ def select(self, *columns: Union[str, exp.Expression, "Column", "FunctionColumn"]) -> Self:
31
+ """Add columns to SELECT clause.
32
+
33
+ Raises:
34
+ SQLBuilderError: If the current expression is not a SELECT statement.
35
+
36
+ Returns:
37
+ The current builder instance for method chaining.
38
+ """
39
+ builder = cast("SQLBuilderProtocol", self)
40
+ if builder._expression is None:
41
+ builder._expression = exp.Select()
42
+ if not isinstance(builder._expression, exp.Select):
43
+ msg = "Cannot add select columns to a non-SELECT expression."
44
+ raise SQLBuilderError(msg)
45
+ for column in columns:
46
+ builder._expression = builder._expression.select(parse_column_expression(column), copy=False)
47
+ return cast("Self", builder)
48
+
49
+ def distinct(self, *columns: Union[str, exp.Expression, "Column", "FunctionColumn"]) -> Self:
50
+ """Add DISTINCT clause to SELECT.
51
+
52
+ Args:
53
+ *columns: Optional columns to make distinct. If none provided, applies DISTINCT to all selected columns.
54
+
55
+ Raises:
56
+ SQLBuilderError: If the current expression is not a SELECT statement.
57
+
58
+ Returns:
59
+ The current builder instance for method chaining.
60
+ """
61
+ builder = cast("SQLBuilderProtocol", self)
62
+ if builder._expression is None:
63
+ builder._expression = exp.Select()
64
+ if not isinstance(builder._expression, exp.Select):
65
+ msg = "Cannot add DISTINCT to a non-SELECT expression."
66
+ raise SQLBuilderError(msg)
67
+ if not columns:
68
+ builder._expression.set("distinct", exp.Distinct())
69
+ else:
70
+ distinct_columns = [parse_column_expression(column) for column in columns]
71
+ builder._expression.set("distinct", exp.Distinct(expressions=distinct_columns))
72
+ return cast("Self", builder)
73
+
74
+ def from_(self, table: Union[str, exp.Expression, Any], alias: Optional[str] = None) -> Self:
75
+ """Add FROM clause.
76
+
77
+ Args:
78
+ table: The table name, expression, or subquery to select from.
79
+ alias: Optional alias for the table.
80
+
81
+ Raises:
82
+ SQLBuilderError: If the current expression is not a SELECT statement or if the table type is unsupported.
83
+
84
+ Returns:
85
+ The current builder instance for method chaining.
86
+ """
87
+ builder = cast("SQLBuilderProtocol", self)
88
+ if builder._expression is None:
89
+ builder._expression = exp.Select()
90
+ if not isinstance(builder._expression, exp.Select):
91
+ msg = "FROM clause is only supported for SELECT statements."
92
+ raise SQLBuilderError(msg)
93
+ from_expr: exp.Expression
94
+ if isinstance(table, str):
95
+ from_expr = parse_table_expression(table, alias)
96
+ elif is_expression(table):
97
+ from_expr = exp.alias_(table, alias) if alias else table
98
+ elif has_query_builder_parameters(table):
99
+ subquery = table.build()
100
+ sql_str = subquery.sql if hasattr(subquery, "sql") and not callable(subquery.sql) else str(subquery)
101
+ subquery_exp = exp.paren(exp.maybe_parse(sql_str, dialect=getattr(builder, "dialect", None)))
102
+ from_expr = exp.alias_(subquery_exp, alias) if alias else subquery_exp
103
+ current_parameters = getattr(builder, "_parameters", None)
104
+ merged_parameters = getattr(type(builder), "ParameterConverter", None)
105
+ if merged_parameters and hasattr(subquery, "parameters"):
106
+ subquery_parameters = getattr(subquery, "parameters", {})
107
+ merged_parameters = merged_parameters.merge_parameters(
108
+ parameters=subquery_parameters,
109
+ args=current_parameters if isinstance(current_parameters, list) else None,
110
+ kwargs=current_parameters if isinstance(current_parameters, dict) else {},
111
+ )
112
+ setattr(builder, "_parameters", merged_parameters)
113
+ else:
114
+ from_expr = table
115
+ builder._expression = builder._expression.from_(from_expr, copy=False)
116
+ return cast("Self", builder)
117
+
118
+ def group_by(self, *columns: Union[str, exp.Expression]) -> Self:
119
+ """Add GROUP BY clause.
120
+
121
+ Args:
122
+ *columns: Columns to group by. Can be column names, expressions,
123
+ or special grouping expressions like ROLLUP, CUBE, etc.
124
+
125
+ Returns:
126
+ The current builder instance for method chaining.
127
+ """
128
+ if self._expression is None or not isinstance(self._expression, exp.Select):
129
+ return self
130
+
131
+ for column in columns:
132
+ self._expression = self._expression.group_by(
133
+ exp.column(column) if isinstance(column, str) else column, copy=False
134
+ )
135
+ return self
136
+
137
+ def group_by_rollup(self, *columns: Union[str, exp.Expression]) -> Self:
138
+ """Add GROUP BY ROLLUP clause.
139
+
140
+ ROLLUP generates subtotals and grand totals for a hierarchical set of columns.
141
+
142
+ Args:
143
+ *columns: Columns to include in the rollup hierarchy.
144
+
145
+ Returns:
146
+ The current builder instance for method chaining.
147
+
148
+ Example:
149
+ ```python
150
+ query = (
151
+ sql.select("product", "region", sql.sum("sales"))
152
+ .from_("sales_data")
153
+ .group_by_rollup("product", "region")
154
+ )
155
+ ```
156
+ """
157
+ column_exprs = [exp.column(col) if isinstance(col, str) else col for col in columns]
158
+ rollup_expr = exp.Rollup(expressions=column_exprs)
159
+ return self.group_by(rollup_expr)
160
+
161
+ def group_by_cube(self, *columns: Union[str, exp.Expression]) -> Self:
162
+ """Add GROUP BY CUBE clause.
163
+
164
+ CUBE generates subtotals for all possible combinations of the specified columns.
165
+
166
+ Args:
167
+ *columns: Columns to include in the cube.
168
+
169
+ Returns:
170
+ The current builder instance for method chaining.
171
+
172
+ Example:
173
+ ```python
174
+ query = (
175
+ sql.select("product", "region", sql.sum("sales"))
176
+ .from_("sales_data")
177
+ .group_by_cube("product", "region")
178
+ )
179
+ ```
180
+ """
181
+ column_exprs = [exp.column(col) if isinstance(col, str) else col for col in columns]
182
+ cube_expr = exp.Cube(expressions=column_exprs)
183
+ return self.group_by(cube_expr)
184
+
185
+ def group_by_grouping_sets(self, *column_sets: Union[tuple[str, ...], list[str]]) -> Self:
186
+ """Add GROUP BY GROUPING SETS clause.
187
+
188
+ GROUPING SETS allows you to specify multiple grouping sets in a single query.
189
+
190
+ Args:
191
+ *column_sets: Sets of columns to group by. Each set can be a tuple or list.
192
+ Empty tuple/list creates a grand total grouping.
193
+
194
+ Returns:
195
+ The current builder instance for method chaining.
196
+
197
+ Example:
198
+ ```python
199
+ query = (
200
+ sql.select("product", "region", sql.sum("sales"))
201
+ .from_("sales_data")
202
+ .group_by_grouping_sets(("product",), ("region",), ())
203
+ )
204
+ ```
205
+ """
206
+ set_expressions = []
207
+ for column_set in column_sets:
208
+ if isinstance(column_set, (tuple, list)):
209
+ if len(column_set) == 0:
210
+ set_expressions.append(exp.Tuple(expressions=[]))
211
+ else:
212
+ columns = [exp.column(col) for col in column_set]
213
+ set_expressions.append(exp.Tuple(expressions=columns))
214
+ else:
215
+ set_expressions.append(exp.column(column_set))
216
+
217
+ grouping_sets_expr = exp.GroupingSets(expressions=set_expressions)
218
+ return self.group_by(grouping_sets_expr)
219
+
220
+ def count_(self, column: "Union[str, exp.Expression]" = "*", alias: Optional[str] = None) -> Self:
221
+ """Add COUNT function to SELECT clause.
222
+
223
+ Args:
224
+ column: The column to count (default is "*").
225
+ alias: Optional alias for the count.
226
+
227
+ Returns:
228
+ The current builder instance for method chaining.
229
+ """
230
+ builder = cast("SelectBuilderProtocol", self)
231
+ if column == "*":
232
+ count_expr = exp.Count(this=exp.Star())
233
+ else:
234
+ col_expr = exp.column(column) if isinstance(column, str) else column
235
+ count_expr = exp.Count(this=col_expr)
236
+
237
+ select_expr = exp.alias_(count_expr, alias) if alias else count_expr
238
+ return cast("Self", builder.select(select_expr))
239
+
240
+ def sum_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
241
+ """Add SUM function to SELECT clause.
242
+
243
+ Args:
244
+ column: The column to sum.
245
+ alias: Optional alias for the sum.
246
+
247
+ Returns:
248
+ The current builder instance for method chaining.
249
+ """
250
+ builder = cast("SelectBuilderProtocol", self)
251
+ col_expr = exp.column(column) if isinstance(column, str) else column
252
+ sum_expr = exp.Sum(this=col_expr)
253
+ select_expr = exp.alias_(sum_expr, alias) if alias else sum_expr
254
+ return cast("Self", builder.select(select_expr))
255
+
256
+ def avg_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
257
+ """Add AVG function to SELECT clause.
258
+
259
+ Args:
260
+ column: The column to average.
261
+ alias: Optional alias for the average.
262
+
263
+ Returns:
264
+ The current builder instance for method chaining.
265
+ """
266
+ builder = cast("SelectBuilderProtocol", self)
267
+ col_expr = exp.column(column) if isinstance(column, str) else column
268
+ avg_expr = exp.Avg(this=col_expr)
269
+ select_expr = exp.alias_(avg_expr, alias) if alias else avg_expr
270
+ return cast("Self", builder.select(select_expr))
271
+
272
+ def max_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
273
+ """Add MAX function to SELECT clause.
274
+
275
+ Args:
276
+ column: The column to find the maximum of.
277
+ alias: Optional alias for the maximum.
278
+
279
+ Returns:
280
+ The current builder instance for method chaining.
281
+ """
282
+ builder = cast("SelectBuilderProtocol", self)
283
+ col_expr = exp.column(column) if isinstance(column, str) else column
284
+ max_expr = exp.Max(this=col_expr)
285
+ select_expr = exp.alias_(max_expr, alias) if alias else max_expr
286
+ return cast("Self", builder.select(select_expr))
287
+
288
+ def min_(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
289
+ """Add MIN function to SELECT clause.
290
+
291
+ Args:
292
+ column: The column to find the minimum of.
293
+ alias: Optional alias for the minimum.
294
+
295
+ Returns:
296
+ The current builder instance for method chaining.
297
+ """
298
+ builder = cast("SelectBuilderProtocol", self)
299
+ col_expr = exp.column(column) if isinstance(column, str) else column
300
+ min_expr = exp.Min(this=col_expr)
301
+ select_expr = exp.alias_(min_expr, alias) if alias else min_expr
302
+ return cast("Self", builder.select(select_expr))
303
+
304
+ def array_agg(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
305
+ """Add ARRAY_AGG aggregate function to SELECT clause.
306
+
307
+ Args:
308
+ column: The column to aggregate into an array.
309
+ alias: Optional alias for the result.
310
+
311
+ Returns:
312
+ The current builder instance for method chaining.
313
+ """
314
+ builder = cast("SelectBuilderProtocol", self)
315
+ col_expr = exp.column(column) if isinstance(column, str) else column
316
+ array_agg_expr = exp.ArrayAgg(this=col_expr)
317
+ select_expr = exp.alias_(array_agg_expr, alias) if alias else array_agg_expr
318
+ return cast("Self", builder.select(select_expr))
319
+
320
+ def count_distinct(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
321
+ """Add COUNT(DISTINCT column) to SELECT clause.
322
+
323
+ Args:
324
+ column: The column to count distinct values of.
325
+ alias: Optional alias for the count.
326
+
327
+ Returns:
328
+ The current builder instance for method chaining.
329
+ """
330
+ builder = cast("SelectBuilderProtocol", self)
331
+ col_expr = exp.column(column) if isinstance(column, str) else column
332
+ count_expr = exp.Count(this=exp.Distinct(expressions=[col_expr]))
333
+ select_expr = exp.alias_(count_expr, alias) if alias else count_expr
334
+ return cast("Self", builder.select(select_expr))
335
+
336
+ def stddev(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
337
+ """Add STDDEV aggregate function to SELECT clause.
338
+
339
+ Args:
340
+ column: The column to calculate standard deviation of.
341
+ alias: Optional alias for the result.
342
+
343
+ Returns:
344
+ The current builder instance for method chaining.
345
+ """
346
+ builder = cast("SelectBuilderProtocol", self)
347
+ col_expr = exp.column(column) if isinstance(column, str) else column
348
+ stddev_expr = exp.Stddev(this=col_expr)
349
+ select_expr = exp.alias_(stddev_expr, alias) if alias else stddev_expr
350
+ return cast("Self", builder.select(select_expr))
351
+
352
+ def stddev_pop(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
353
+ """Add STDDEV_POP aggregate function to SELECT clause.
354
+
355
+ Args:
356
+ column: The column to calculate population standard deviation of.
357
+ alias: Optional alias for the result.
358
+
359
+ Returns:
360
+ The current builder instance for method chaining.
361
+ """
362
+ builder = cast("SelectBuilderProtocol", self)
363
+ col_expr = exp.column(column) if isinstance(column, str) else column
364
+ stddev_pop_expr = exp.StddevPop(this=col_expr)
365
+ select_expr = exp.alias_(stddev_pop_expr, alias) if alias else stddev_pop_expr
366
+ return cast("Self", builder.select(select_expr))
367
+
368
+ def stddev_samp(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
369
+ """Add STDDEV_SAMP aggregate function to SELECT clause.
370
+
371
+ Args:
372
+ column: The column to calculate sample standard deviation of.
373
+ alias: Optional alias for the result.
374
+
375
+ Returns:
376
+ The current builder instance for method chaining.
377
+ """
378
+ builder = cast("SelectBuilderProtocol", self)
379
+ col_expr = exp.column(column) if isinstance(column, str) else column
380
+ stddev_samp_expr = exp.StddevSamp(this=col_expr)
381
+ select_expr = exp.alias_(stddev_samp_expr, alias) if alias else stddev_samp_expr
382
+ return cast("Self", builder.select(select_expr))
383
+
384
+ def variance(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
385
+ """Add VARIANCE aggregate function to SELECT clause.
386
+
387
+ Args:
388
+ column: The column to calculate variance of.
389
+ alias: Optional alias for the result.
390
+
391
+ Returns:
392
+ The current builder instance for method chaining.
393
+ """
394
+ builder = cast("SelectBuilderProtocol", self)
395
+ col_expr = exp.column(column) if isinstance(column, str) else column
396
+ variance_expr = exp.Variance(this=col_expr)
397
+ select_expr = exp.alias_(variance_expr, alias) if alias else variance_expr
398
+ return cast("Self", builder.select(select_expr))
399
+
400
+ def var_pop(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
401
+ """Add VAR_POP aggregate function to SELECT clause.
402
+
403
+ Args:
404
+ column: The column to calculate population variance of.
405
+ alias: Optional alias for the result.
406
+
407
+ Returns:
408
+ The current builder instance for method chaining.
409
+ """
410
+ builder = cast("SelectBuilderProtocol", self)
411
+ col_expr = exp.column(column) if isinstance(column, str) else column
412
+ var_pop_expr = exp.VariancePop(this=col_expr)
413
+ select_expr = exp.alias_(var_pop_expr, alias) if alias else var_pop_expr
414
+ return cast("Self", builder.select(select_expr))
415
+
416
+ def string_agg(self, column: Union[str, exp.Expression], separator: str = ",", alias: Optional[str] = None) -> Self:
417
+ """Add STRING_AGG aggregate function to SELECT clause.
418
+
419
+ Args:
420
+ column: The column to aggregate into a string.
421
+ separator: The separator between values (default is comma).
422
+ alias: Optional alias for the result.
423
+
424
+ Returns:
425
+ The current builder instance for method chaining.
426
+
427
+ Note:
428
+ Different databases have different names for this function:
429
+ - PostgreSQL: STRING_AGG
430
+ - MySQL: GROUP_CONCAT
431
+ - SQLite: GROUP_CONCAT
432
+ SQLGlot will handle the translation.
433
+ """
434
+ builder = cast("SelectBuilderProtocol", self)
435
+ col_expr = exp.column(column) if isinstance(column, str) else column
436
+ string_agg_expr = exp.GroupConcat(this=col_expr, separator=exp.convert(separator))
437
+ select_expr = exp.alias_(string_agg_expr, alias) if alias else string_agg_expr
438
+ return cast("Self", builder.select(select_expr))
439
+
440
+ def json_agg(self, column: Union[str, exp.Expression], alias: Optional[str] = None) -> Self:
441
+ """Add JSON_AGG aggregate function to SELECT clause.
442
+
443
+ Args:
444
+ column: The column to aggregate into a JSON array.
445
+ alias: Optional alias for the result.
446
+
447
+ Returns:
448
+ The current builder instance for method chaining.
449
+ """
450
+ builder = cast("SelectBuilderProtocol", self)
451
+ col_expr = exp.column(column) if isinstance(column, str) else column
452
+ json_agg_expr = exp.JSONArrayAgg(this=col_expr)
453
+ select_expr = exp.alias_(json_agg_expr, alias) if alias else json_agg_expr
454
+ return cast("Self", builder.select(select_expr))
455
+
456
+ def window(
457
+ self,
458
+ function_expr: Union[str, exp.Expression],
459
+ partition_by: Optional[Union[str, list[str], exp.Expression, list[exp.Expression]]] = None,
460
+ order_by: Optional[Union[str, list[str], exp.Expression, list[exp.Expression]]] = None,
461
+ frame: Optional[str] = None,
462
+ alias: Optional[str] = None,
463
+ ) -> Self:
464
+ """Add a window function to the SELECT clause.
465
+
466
+ Args:
467
+ function_expr: The window function expression (e.g., "COUNT(*)", "ROW_NUMBER()").
468
+ partition_by: Column(s) to partition by.
469
+ order_by: Column(s) to order by within the window.
470
+ frame: Window frame specification (e.g., "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW").
471
+ alias: Optional alias for the window function.
472
+
473
+ Raises:
474
+ SQLBuilderError: If the current expression is not a SELECT statement or function parsing fails.
475
+
476
+ Returns:
477
+ The current builder instance for method chaining.
478
+ """
479
+ if self._expression is None:
480
+ self._expression = exp.Select()
481
+ if not isinstance(self._expression, exp.Select):
482
+ msg = "Cannot add window function to a non-SELECT expression."
483
+ raise SQLBuilderError(msg)
484
+
485
+ func_expr_parsed: exp.Expression
486
+ if isinstance(function_expr, str):
487
+ parsed: Optional[exp.Expression] = exp.maybe_parse(function_expr, dialect=getattr(self, "dialect", None))
488
+ if not parsed:
489
+ msg = f"Could not parse function expression: {function_expr}"
490
+ raise SQLBuilderError(msg)
491
+ func_expr_parsed = parsed
492
+ else:
493
+ func_expr_parsed = function_expr
494
+
495
+ over_args: dict[str, Any] = {}
496
+ if partition_by:
497
+ if isinstance(partition_by, str):
498
+ over_args["partition_by"] = [exp.column(partition_by)]
499
+ elif isinstance(partition_by, list):
500
+ over_args["partition_by"] = [exp.column(col) if isinstance(col, str) else col for col in partition_by]
501
+ elif isinstance(partition_by, exp.Expression):
502
+ over_args["partition_by"] = [partition_by]
503
+
504
+ if order_by:
505
+ if isinstance(order_by, str):
506
+ over_args["order"] = exp.column(order_by).asc()
507
+ elif isinstance(order_by, list):
508
+ order_expressions: list[Union[exp.Expression, exp.Column]] = []
509
+ for col in order_by:
510
+ if isinstance(col, str):
511
+ order_expressions.append(exp.column(col).asc())
512
+ else:
513
+ order_expressions.append(col)
514
+ over_args["order"] = exp.Order(expressions=order_expressions)
515
+ elif isinstance(order_by, exp.Expression):
516
+ over_args["order"] = order_by
517
+
518
+ if frame:
519
+ frame_expr: Optional[exp.Expression] = exp.maybe_parse(frame, dialect=getattr(self, "dialect", None))
520
+ if frame_expr:
521
+ over_args["frame"] = frame_expr
522
+
523
+ window_expr = exp.Window(this=func_expr_parsed, **over_args)
524
+ self._expression.select(exp.alias_(window_expr, alias) if alias else window_expr, copy=False)
525
+ return self
526
+
527
+ def case_(self, alias: "Optional[str]" = None) -> "CaseBuilder":
528
+ """Create a CASE expression for the SELECT clause.
529
+
530
+ Args:
531
+ alias: Optional alias for the CASE expression.
532
+
533
+ Returns:
534
+ CaseBuilder: A CaseBuilder instance for building the CASE expression.
535
+ """
536
+ builder = cast("SelectBuilderProtocol", self)
537
+ return CaseBuilder(builder, alias)
538
+
539
+
540
+ @dataclass
541
+ class CaseBuilder:
542
+ """Builder for CASE expressions."""
543
+
544
+ _parent: "SelectBuilderProtocol"
545
+ _alias: Optional[str]
546
+ _case_expr: exp.Case
547
+
548
+ def __init__(self, parent: "SelectBuilderProtocol", alias: "Optional[str]" = None) -> None:
549
+ """Initialize CaseBuilder.
550
+
551
+ Args:
552
+ parent: The parent builder with select capabilities.
553
+ alias: Optional alias for the CASE expression.
554
+ """
555
+ self._parent = parent
556
+ self._alias = alias
557
+ self._case_expr = exp.Case()
558
+
559
+ def when(self, condition: "Union[str, exp.Expression]", value: "Any") -> "CaseBuilder":
560
+ """Add WHEN clause to CASE expression.
561
+
562
+ Args:
563
+ condition: The condition to test.
564
+ value: The value to return if condition is true.
565
+
566
+ Returns:
567
+ CaseBuilder: The current builder instance for method chaining.
568
+ """
569
+ cond_expr = exp.condition(condition) if isinstance(condition, str) else condition
570
+ param_name = self._parent._generate_unique_parameter_name("case_when_value")
571
+ param_name = self._parent.add_parameter(value, name=param_name)[1]
572
+ value_expr = exp.Placeholder(this=param_name)
573
+
574
+ when_clause = exp.When(this=cond_expr, then=value_expr)
575
+
576
+ if not self._case_expr.args.get("ifs"):
577
+ self._case_expr.set("ifs", [])
578
+ self._case_expr.args["ifs"].append(when_clause)
579
+ return self
580
+
581
+ def else_(self, value: "Any") -> "CaseBuilder":
582
+ """Add ELSE clause to CASE expression.
583
+
584
+ Args:
585
+ value: The value to return if no conditions match.
586
+
587
+ Returns:
588
+ CaseBuilder: The current builder instance for method chaining.
589
+ """
590
+ param_name = self._parent._generate_unique_parameter_name("case_else_value")
591
+ param_name = self._parent.add_parameter(value, name=param_name)[1]
592
+ value_expr = exp.Placeholder(this=param_name)
593
+ self._case_expr.set("default", value_expr)
594
+ return self
595
+
596
+ def end(self) -> "SelectBuilderProtocol":
597
+ """Finalize the CASE expression and add it to the SELECT clause.
598
+
599
+ Returns:
600
+ The parent builder instance.
601
+ """
602
+ select_expr = exp.alias_(self._case_expr, self._alias) if self._alias else self._case_expr
603
+ return self._parent.select(select_expr)