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