sqlspec 0.16.0__cp312-cp312-win_amd64.whl

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

Potentially problematic release.


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

Files changed (148) hide show
  1. 51ff5a9eadfdefd49f98__mypyc.cp312-win_amd64.pyd +0 -0
  2. sqlspec/__init__.py +92 -0
  3. sqlspec/__main__.py +12 -0
  4. sqlspec/__metadata__.py +14 -0
  5. sqlspec/_serialization.py +77 -0
  6. sqlspec/_sql.py +1347 -0
  7. sqlspec/_typing.py +680 -0
  8. sqlspec/adapters/__init__.py +0 -0
  9. sqlspec/adapters/adbc/__init__.py +5 -0
  10. sqlspec/adapters/adbc/_types.py +12 -0
  11. sqlspec/adapters/adbc/config.py +361 -0
  12. sqlspec/adapters/adbc/driver.py +512 -0
  13. sqlspec/adapters/aiosqlite/__init__.py +19 -0
  14. sqlspec/adapters/aiosqlite/_types.py +13 -0
  15. sqlspec/adapters/aiosqlite/config.py +253 -0
  16. sqlspec/adapters/aiosqlite/driver.py +248 -0
  17. sqlspec/adapters/asyncmy/__init__.py +19 -0
  18. sqlspec/adapters/asyncmy/_types.py +12 -0
  19. sqlspec/adapters/asyncmy/config.py +180 -0
  20. sqlspec/adapters/asyncmy/driver.py +274 -0
  21. sqlspec/adapters/asyncpg/__init__.py +21 -0
  22. sqlspec/adapters/asyncpg/_types.py +17 -0
  23. sqlspec/adapters/asyncpg/config.py +229 -0
  24. sqlspec/adapters/asyncpg/driver.py +344 -0
  25. sqlspec/adapters/bigquery/__init__.py +18 -0
  26. sqlspec/adapters/bigquery/_types.py +12 -0
  27. sqlspec/adapters/bigquery/config.py +298 -0
  28. sqlspec/adapters/bigquery/driver.py +558 -0
  29. sqlspec/adapters/duckdb/__init__.py +22 -0
  30. sqlspec/adapters/duckdb/_types.py +12 -0
  31. sqlspec/adapters/duckdb/config.py +504 -0
  32. sqlspec/adapters/duckdb/driver.py +368 -0
  33. sqlspec/adapters/oracledb/__init__.py +32 -0
  34. sqlspec/adapters/oracledb/_types.py +14 -0
  35. sqlspec/adapters/oracledb/config.py +317 -0
  36. sqlspec/adapters/oracledb/driver.py +538 -0
  37. sqlspec/adapters/psqlpy/__init__.py +16 -0
  38. sqlspec/adapters/psqlpy/_types.py +11 -0
  39. sqlspec/adapters/psqlpy/config.py +214 -0
  40. sqlspec/adapters/psqlpy/driver.py +530 -0
  41. sqlspec/adapters/psycopg/__init__.py +32 -0
  42. sqlspec/adapters/psycopg/_types.py +17 -0
  43. sqlspec/adapters/psycopg/config.py +426 -0
  44. sqlspec/adapters/psycopg/driver.py +796 -0
  45. sqlspec/adapters/sqlite/__init__.py +15 -0
  46. sqlspec/adapters/sqlite/_types.py +11 -0
  47. sqlspec/adapters/sqlite/config.py +240 -0
  48. sqlspec/adapters/sqlite/driver.py +294 -0
  49. sqlspec/base.py +571 -0
  50. sqlspec/builder/__init__.py +62 -0
  51. sqlspec/builder/_base.py +440 -0
  52. sqlspec/builder/_column.py +324 -0
  53. sqlspec/builder/_ddl.py +1383 -0
  54. sqlspec/builder/_ddl_utils.py +104 -0
  55. sqlspec/builder/_delete.py +77 -0
  56. sqlspec/builder/_insert.py +241 -0
  57. sqlspec/builder/_merge.py +56 -0
  58. sqlspec/builder/_parsing_utils.py +140 -0
  59. sqlspec/builder/_select.py +174 -0
  60. sqlspec/builder/_update.py +186 -0
  61. sqlspec/builder/mixins/__init__.py +55 -0
  62. sqlspec/builder/mixins/_cte_and_set_ops.py +195 -0
  63. sqlspec/builder/mixins/_delete_operations.py +36 -0
  64. sqlspec/builder/mixins/_insert_operations.py +152 -0
  65. sqlspec/builder/mixins/_join_operations.py +115 -0
  66. sqlspec/builder/mixins/_merge_operations.py +416 -0
  67. sqlspec/builder/mixins/_order_limit_operations.py +123 -0
  68. sqlspec/builder/mixins/_pivot_operations.py +144 -0
  69. sqlspec/builder/mixins/_select_operations.py +599 -0
  70. sqlspec/builder/mixins/_update_operations.py +164 -0
  71. sqlspec/builder/mixins/_where_clause.py +609 -0
  72. sqlspec/cli.py +247 -0
  73. sqlspec/config.py +395 -0
  74. sqlspec/core/__init__.py +63 -0
  75. sqlspec/core/cache.cp312-win_amd64.pyd +0 -0
  76. sqlspec/core/cache.py +873 -0
  77. sqlspec/core/compiler.cp312-win_amd64.pyd +0 -0
  78. sqlspec/core/compiler.py +396 -0
  79. sqlspec/core/filters.cp312-win_amd64.pyd +0 -0
  80. sqlspec/core/filters.py +830 -0
  81. sqlspec/core/hashing.cp312-win_amd64.pyd +0 -0
  82. sqlspec/core/hashing.py +310 -0
  83. sqlspec/core/parameters.cp312-win_amd64.pyd +0 -0
  84. sqlspec/core/parameters.py +1209 -0
  85. sqlspec/core/result.cp312-win_amd64.pyd +0 -0
  86. sqlspec/core/result.py +664 -0
  87. sqlspec/core/splitter.cp312-win_amd64.pyd +0 -0
  88. sqlspec/core/splitter.py +819 -0
  89. sqlspec/core/statement.cp312-win_amd64.pyd +0 -0
  90. sqlspec/core/statement.py +666 -0
  91. sqlspec/driver/__init__.py +19 -0
  92. sqlspec/driver/_async.py +472 -0
  93. sqlspec/driver/_common.py +612 -0
  94. sqlspec/driver/_sync.py +473 -0
  95. sqlspec/driver/mixins/__init__.py +6 -0
  96. sqlspec/driver/mixins/_result_tools.py +164 -0
  97. sqlspec/driver/mixins/_sql_translator.py +36 -0
  98. sqlspec/exceptions.py +193 -0
  99. sqlspec/extensions/__init__.py +0 -0
  100. sqlspec/extensions/aiosql/__init__.py +10 -0
  101. sqlspec/extensions/aiosql/adapter.py +461 -0
  102. sqlspec/extensions/litestar/__init__.py +6 -0
  103. sqlspec/extensions/litestar/_utils.py +52 -0
  104. sqlspec/extensions/litestar/cli.py +48 -0
  105. sqlspec/extensions/litestar/config.py +92 -0
  106. sqlspec/extensions/litestar/handlers.py +260 -0
  107. sqlspec/extensions/litestar/plugin.py +145 -0
  108. sqlspec/extensions/litestar/providers.py +454 -0
  109. sqlspec/loader.cp312-win_amd64.pyd +0 -0
  110. sqlspec/loader.py +760 -0
  111. sqlspec/migrations/__init__.py +35 -0
  112. sqlspec/migrations/base.py +414 -0
  113. sqlspec/migrations/commands.py +443 -0
  114. sqlspec/migrations/loaders.py +402 -0
  115. sqlspec/migrations/runner.py +213 -0
  116. sqlspec/migrations/tracker.py +140 -0
  117. sqlspec/migrations/utils.py +129 -0
  118. sqlspec/protocols.py +400 -0
  119. sqlspec/py.typed +0 -0
  120. sqlspec/storage/__init__.py +23 -0
  121. sqlspec/storage/backends/__init__.py +0 -0
  122. sqlspec/storage/backends/base.py +163 -0
  123. sqlspec/storage/backends/fsspec.py +386 -0
  124. sqlspec/storage/backends/obstore.py +459 -0
  125. sqlspec/storage/capabilities.py +102 -0
  126. sqlspec/storage/registry.py +239 -0
  127. sqlspec/typing.py +299 -0
  128. sqlspec/utils/__init__.py +3 -0
  129. sqlspec/utils/correlation.py +150 -0
  130. sqlspec/utils/deprecation.py +106 -0
  131. sqlspec/utils/fixtures.cp312-win_amd64.pyd +0 -0
  132. sqlspec/utils/fixtures.py +58 -0
  133. sqlspec/utils/logging.py +127 -0
  134. sqlspec/utils/module_loader.py +89 -0
  135. sqlspec/utils/serializers.py +4 -0
  136. sqlspec/utils/singleton.py +32 -0
  137. sqlspec/utils/sync_tools.cp312-win_amd64.pyd +0 -0
  138. sqlspec/utils/sync_tools.py +237 -0
  139. sqlspec/utils/text.cp312-win_amd64.pyd +0 -0
  140. sqlspec/utils/text.py +96 -0
  141. sqlspec/utils/type_guards.cp312-win_amd64.pyd +0 -0
  142. sqlspec/utils/type_guards.py +1135 -0
  143. sqlspec-0.16.0.dist-info/METADATA +365 -0
  144. sqlspec-0.16.0.dist-info/RECORD +148 -0
  145. sqlspec-0.16.0.dist-info/WHEEL +4 -0
  146. sqlspec-0.16.0.dist-info/entry_points.txt +2 -0
  147. sqlspec-0.16.0.dist-info/licenses/LICENSE +21 -0
  148. sqlspec-0.16.0.dist-info/licenses/NOTICE +29 -0
@@ -0,0 +1,612 @@
1
+ """Common driver attributes and utilities.
2
+
3
+ This module provides core driver infrastructure including execution result handling,
4
+ common driver attributes, parameter processing, and SQL compilation utilities.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, Any, Final, NamedTuple, Optional, Union, cast
8
+
9
+ from mypy_extensions import trait
10
+ from sqlglot import exp
11
+
12
+ from sqlspec.builder import QueryBuilder
13
+ from sqlspec.core import SQL, OperationType, ParameterStyle, SQLResult, Statement, StatementConfig, TypedParameter
14
+ from sqlspec.core.cache import get_cache_config, sql_cache
15
+ from sqlspec.core.splitter import split_sql_script
16
+ from sqlspec.exceptions import ImproperConfigurationError
17
+ from sqlspec.utils.logging import get_logger
18
+
19
+ if TYPE_CHECKING:
20
+ from sqlspec.core.filters import StatementFilter
21
+ from sqlspec.typing import StatementParameters
22
+
23
+
24
+ __all__ = (
25
+ "DEFAULT_EXECUTION_RESULT",
26
+ "EXEC_CURSOR_RESULT",
27
+ "EXEC_ROWCOUNT_OVERRIDE",
28
+ "EXEC_SPECIAL_DATA",
29
+ "CommonDriverAttributesMixin",
30
+ "ExecutionResult",
31
+ "ScriptExecutionResult",
32
+ )
33
+
34
+
35
+ logger = get_logger("driver")
36
+
37
+
38
+ class ScriptExecutionResult(NamedTuple):
39
+ """Result from script execution with statement count information.
40
+
41
+ This named tuple eliminates the need for redundant script splitting
42
+ by providing statement count information during execution rather than
43
+ requiring re-parsing after execution.
44
+
45
+ Attributes:
46
+ cursor_result: The result returned by the database cursor/driver
47
+ rowcount_override: Optional override for the number of affected rows
48
+ special_data: Any special metadata or additional information
49
+ statement_count: Total number of statements in the script
50
+ successful_statements: Number of statements that executed successfully
51
+ """
52
+
53
+ cursor_result: Any
54
+ rowcount_override: Optional[int]
55
+ special_data: Any
56
+ statement_count: int
57
+ successful_statements: int
58
+
59
+
60
+ class ExecutionResult(NamedTuple):
61
+ """Comprehensive execution result containing all data needed for SQLResult building.
62
+
63
+ This named tuple consolidates all execution result data to eliminate the need
64
+ for additional data extraction calls and script re-parsing in build_statement_result.
65
+
66
+ Attributes:
67
+ cursor_result: The raw result returned by the database cursor/driver
68
+ rowcount_override: Optional override for the number of affected rows
69
+ special_data: Any special metadata or additional information from execution
70
+ selected_data: For SELECT operations, the extracted row data
71
+ column_names: For SELECT operations, the column names
72
+ data_row_count: For SELECT operations, the number of rows returned
73
+ statement_count: For script operations, total number of statements
74
+ successful_statements: For script operations, number of successful statements
75
+ is_script_result: Whether this result is from script execution
76
+ is_select_result: Whether this result is from a SELECT operation
77
+ is_many_result: Whether this result is from an execute_many operation
78
+ """
79
+
80
+ cursor_result: Any
81
+ rowcount_override: Optional[int]
82
+ special_data: Any
83
+ selected_data: Optional["list[dict[str, Any]]"]
84
+ column_names: Optional["list[str]"]
85
+ data_row_count: Optional[int]
86
+ statement_count: Optional[int]
87
+ successful_statements: Optional[int]
88
+ is_script_result: bool
89
+ is_select_result: bool
90
+ is_many_result: bool
91
+ last_inserted_id: Optional[Union[int, str]] = None
92
+
93
+
94
+ EXEC_CURSOR_RESULT = 0
95
+ EXEC_ROWCOUNT_OVERRIDE = 1
96
+ EXEC_SPECIAL_DATA = 2
97
+ DEFAULT_EXECUTION_RESULT: Final[tuple[Any, Optional[int], Any]] = (None, None, None)
98
+
99
+
100
+ @trait
101
+ class CommonDriverAttributesMixin:
102
+ """Common attributes and methods for driver adapters.
103
+
104
+ This mixin provides the foundation for all SQLSpec drivers, including
105
+ connection and configuration management, parameter processing, caching,
106
+ and SQL compilation.
107
+ """
108
+
109
+ __slots__ = ("connection", "driver_features", "statement_config")
110
+ connection: "Any"
111
+ statement_config: "StatementConfig"
112
+ driver_features: "dict[str, Any]"
113
+
114
+ def __init__(
115
+ self, connection: "Any", statement_config: "StatementConfig", driver_features: "Optional[dict[str, Any]]" = None
116
+ ) -> None:
117
+ """Initialize driver adapter with connection and configuration.
118
+
119
+ Args:
120
+ connection: Database connection instance
121
+ statement_config: Statement configuration for the driver
122
+ driver_features: Driver-specific features like extensions, secrets, and connection callbacks
123
+ """
124
+ self.connection = connection
125
+ self.statement_config = statement_config
126
+ self.driver_features = driver_features or {}
127
+
128
+ def create_execution_result(
129
+ self,
130
+ cursor_result: Any,
131
+ *,
132
+ rowcount_override: Optional[int] = None,
133
+ special_data: Any = None,
134
+ selected_data: Optional["list[dict[str, Any]]"] = None,
135
+ column_names: Optional["list[str]"] = None,
136
+ data_row_count: Optional[int] = None,
137
+ statement_count: Optional[int] = None,
138
+ successful_statements: Optional[int] = None,
139
+ is_script_result: bool = False,
140
+ is_select_result: bool = False,
141
+ is_many_result: bool = False,
142
+ last_inserted_id: Optional[Union[int, str]] = None,
143
+ ) -> ExecutionResult:
144
+ """Create ExecutionResult with all necessary data for any operation type.
145
+
146
+ Args:
147
+ cursor_result: The raw result returned by the database cursor/driver
148
+ rowcount_override: Optional override for the number of affected rows
149
+ special_data: Any special metadata or additional information
150
+ selected_data: For SELECT operations, the extracted row data
151
+ column_names: For SELECT operations, the column names
152
+ data_row_count: For SELECT operations, the number of rows returned
153
+ statement_count: For script operations, total number of statements
154
+ successful_statements: For script operations, number of successful statements
155
+ is_script_result: Whether this result is from script execution
156
+ is_select_result: Whether this result is from a SELECT operation
157
+ is_many_result: Whether this result is from an execute_many operation
158
+ last_inserted_id: The ID of the last inserted row (if applicable)
159
+
160
+ Returns:
161
+ ExecutionResult configured for the specified operation type
162
+ """
163
+ return ExecutionResult(
164
+ cursor_result=cursor_result,
165
+ rowcount_override=rowcount_override,
166
+ special_data=special_data,
167
+ selected_data=selected_data,
168
+ column_names=column_names,
169
+ data_row_count=data_row_count,
170
+ statement_count=statement_count,
171
+ successful_statements=successful_statements,
172
+ is_script_result=is_script_result,
173
+ is_select_result=is_select_result,
174
+ is_many_result=is_many_result,
175
+ last_inserted_id=last_inserted_id,
176
+ )
177
+
178
+ def build_statement_result(self, statement: "SQL", execution_result: ExecutionResult) -> "SQLResult":
179
+ """Build and return the SQLResult from ExecutionResult data.
180
+
181
+ Creates SQLResult objects from ExecutionResult data without requiring
182
+ additional data extraction calls or script re-parsing.
183
+
184
+ Args:
185
+ statement: SQL statement that was executed
186
+ execution_result: ExecutionResult containing all necessary data
187
+
188
+ Returns:
189
+ SQLResult with complete execution data
190
+ """
191
+ if execution_result.is_script_result:
192
+ return SQLResult(
193
+ statement=statement,
194
+ data=[],
195
+ rows_affected=execution_result.rowcount_override or 0,
196
+ operation_type="SCRIPT",
197
+ total_statements=execution_result.statement_count or 0,
198
+ successful_statements=execution_result.successful_statements or 0,
199
+ metadata=execution_result.special_data or {"status_message": "OK"},
200
+ )
201
+
202
+ if execution_result.is_select_result:
203
+ return SQLResult(
204
+ statement=statement,
205
+ data=execution_result.selected_data or [],
206
+ column_names=execution_result.column_names or [],
207
+ rows_affected=execution_result.data_row_count or 0,
208
+ operation_type="SELECT",
209
+ metadata=execution_result.special_data or {},
210
+ )
211
+
212
+ return SQLResult(
213
+ statement=statement,
214
+ data=[],
215
+ rows_affected=execution_result.rowcount_override or 0,
216
+ operation_type=self._determine_operation_type(statement),
217
+ last_inserted_id=execution_result.last_inserted_id,
218
+ metadata=execution_result.special_data or {"status_message": "OK"},
219
+ )
220
+
221
+ def _determine_operation_type(self, statement: "Any") -> OperationType:
222
+ """Determine operation type from SQL statement expression.
223
+
224
+ Examines the statement's expression type to determine if it's
225
+ INSERT, UPDATE, DELETE, SELECT, SCRIPT, or generic EXECUTE.
226
+
227
+ Args:
228
+ statement: SQL statement object with expression attribute
229
+
230
+ Returns:
231
+ OperationType literal value
232
+ """
233
+ if statement.is_script:
234
+ return "SCRIPT"
235
+
236
+ try:
237
+ expression = statement.expression
238
+ except AttributeError:
239
+ return "EXECUTE"
240
+
241
+ if not expression:
242
+ return "EXECUTE"
243
+
244
+ expr_type = type(expression).__name__.upper()
245
+
246
+ if "ANONYMOUS" in expr_type and statement.is_script:
247
+ return "SCRIPT"
248
+
249
+ if "INSERT" in expr_type:
250
+ return "INSERT"
251
+ if "UPDATE" in expr_type:
252
+ return "UPDATE"
253
+ if "DELETE" in expr_type:
254
+ return "DELETE"
255
+ if "SELECT" in expr_type:
256
+ return "SELECT"
257
+ if "COPY" in expr_type:
258
+ return "COPY"
259
+ return "EXECUTE"
260
+
261
+ def prepare_statement(
262
+ self,
263
+ statement: "Union[Statement, QueryBuilder]",
264
+ parameters: "tuple[Union[StatementParameters, StatementFilter], ...]" = (),
265
+ *,
266
+ statement_config: "StatementConfig",
267
+ kwargs: "Optional[dict[str, Any]]" = None,
268
+ ) -> "SQL":
269
+ """Build SQL statement from various input types.
270
+
271
+ Ensures dialect is set and preserves existing state when rebuilding SQL objects.
272
+ """
273
+ kwargs = kwargs or {}
274
+
275
+ if isinstance(statement, QueryBuilder):
276
+ return statement.to_statement(statement_config)
277
+ if isinstance(statement, SQL):
278
+ if parameters or kwargs:
279
+ merged_parameters = (
280
+ (*statement._positional_parameters, *parameters) if parameters else statement._positional_parameters
281
+ )
282
+ return SQL(statement.sql, *merged_parameters, statement_config=statement_config, **kwargs)
283
+ needs_rebuild = False
284
+
285
+ if statement_config.dialect and (
286
+ not statement.statement_config.dialect or statement.statement_config.dialect != statement_config.dialect
287
+ ):
288
+ needs_rebuild = True
289
+
290
+ if (
291
+ statement.statement_config.parameter_config.default_execution_parameter_style
292
+ != statement_config.parameter_config.default_execution_parameter_style
293
+ ):
294
+ needs_rebuild = True
295
+
296
+ if needs_rebuild:
297
+ sql_text = statement._raw_sql or statement.sql
298
+
299
+ if statement.is_many and statement.parameters:
300
+ new_sql = SQL(sql_text, statement.parameters, statement_config=statement_config, is_many=True)
301
+ elif statement._named_parameters:
302
+ new_sql = SQL(sql_text, statement_config=statement_config, **statement._named_parameters)
303
+ else:
304
+ new_sql = SQL(sql_text, *statement._positional_parameters, statement_config=statement_config)
305
+
306
+ return new_sql
307
+ return statement
308
+ return SQL(statement, *parameters, statement_config=statement_config, **kwargs)
309
+
310
+ def split_script_statements(
311
+ self, script: str, statement_config: "StatementConfig", strip_trailing_semicolon: bool = False
312
+ ) -> list[str]:
313
+ """Split a SQL script into individual statements.
314
+
315
+ Uses a lexer-driven state machine to handle multi-statement scripts,
316
+ including complex constructs like PL/SQL blocks, T-SQL batches, and nested blocks.
317
+
318
+ Args:
319
+ script: The SQL script to split
320
+ statement_config: Statement configuration containing dialect information
321
+ strip_trailing_semicolon: If True, remove trailing semicolons from statements
322
+
323
+ Returns:
324
+ A list of individual SQL statements
325
+ """
326
+ return [
327
+ sql_script.strip()
328
+ for sql_script in split_sql_script(
329
+ script, dialect=str(statement_config.dialect), strip_trailing_terminator=strip_trailing_semicolon
330
+ )
331
+ if sql_script.strip()
332
+ ]
333
+
334
+ def prepare_driver_parameters(
335
+ self, parameters: Any, statement_config: "StatementConfig", is_many: bool = False
336
+ ) -> Any:
337
+ """Prepare parameters for database driver consumption.
338
+
339
+ Normalizes parameter structure and unwraps TypedParameter objects
340
+ to their underlying values, which database drivers expect.
341
+
342
+ Args:
343
+ parameters: Parameters in any format (dict, list, tuple, scalar, TypedParameter)
344
+ statement_config: Statement configuration for parameter style detection
345
+ is_many: If True, handle as executemany parameter sequence
346
+
347
+ Returns:
348
+ Parameters with TypedParameter objects unwrapped to primitive values
349
+ """
350
+ if parameters is None and statement_config.parameter_config.needs_static_script_compilation:
351
+ return None
352
+
353
+ if not parameters:
354
+ return []
355
+
356
+ if is_many:
357
+ if isinstance(parameters, list):
358
+ return [self._format_parameter_set_for_many(param_set, statement_config) for param_set in parameters]
359
+ return [self._format_parameter_set_for_many(parameters, statement_config)]
360
+ return self._format_parameter_set(parameters, statement_config)
361
+
362
+ def _format_parameter_set_for_many(self, parameters: Any, statement_config: "StatementConfig") -> Any:
363
+ """Prepare a single parameter set for execute_many operations.
364
+
365
+ Unlike _format_parameter_set, this method handles parameter sets without
366
+ converting the structure itself to array format.
367
+
368
+ Args:
369
+ parameters: Single parameter set (tuple, list, or dict)
370
+ statement_config: Statement configuration for parameter style detection
371
+
372
+ Returns:
373
+ Processed parameter set with individual values coerced but structure preserved
374
+ """
375
+ if not parameters:
376
+ return []
377
+
378
+ def apply_type_coercion(value: Any) -> Any:
379
+ """Apply type coercion to a single value."""
380
+ unwrapped_value = value.value if isinstance(value, TypedParameter) else value
381
+
382
+ if statement_config.parameter_config.type_coercion_map:
383
+ for type_check, converter in statement_config.parameter_config.type_coercion_map.items():
384
+ if type_check in {list, tuple} and isinstance(unwrapped_value, (list, tuple)):
385
+ continue
386
+ if isinstance(unwrapped_value, type_check):
387
+ return converter(unwrapped_value)
388
+
389
+ return unwrapped_value
390
+
391
+ if isinstance(parameters, dict):
392
+ return {k: apply_type_coercion(v) for k, v in parameters.items()}
393
+
394
+ if isinstance(parameters, (list, tuple)):
395
+ coerced_params = [apply_type_coercion(p) for p in parameters]
396
+ return tuple(coerced_params) if isinstance(parameters, tuple) else coerced_params
397
+
398
+ return apply_type_coercion(parameters)
399
+
400
+ def _format_parameter_set(self, parameters: Any, statement_config: "StatementConfig") -> Any:
401
+ """Prepare a single parameter set for database driver consumption.
402
+
403
+ Args:
404
+ parameters: Single parameter set in any format
405
+ statement_config: Statement configuration for parameter style detection
406
+
407
+ Returns:
408
+ Processed parameter set with TypedParameter objects unwrapped and type coercion applied
409
+ """
410
+ if not parameters:
411
+ return []
412
+
413
+ def apply_type_coercion(value: Any) -> Any:
414
+ """Apply type coercion to a single value."""
415
+ unwrapped_value = value.value if isinstance(value, TypedParameter) else value
416
+
417
+ if statement_config.parameter_config.type_coercion_map:
418
+ for type_check, converter in statement_config.parameter_config.type_coercion_map.items():
419
+ if isinstance(unwrapped_value, type_check):
420
+ return converter(unwrapped_value)
421
+
422
+ return unwrapped_value
423
+
424
+ if isinstance(parameters, dict):
425
+ if not parameters:
426
+ return []
427
+ if (
428
+ statement_config.parameter_config.supported_execution_parameter_styles
429
+ and ParameterStyle.NAMED_PYFORMAT
430
+ in statement_config.parameter_config.supported_execution_parameter_styles
431
+ ):
432
+ return {k: apply_type_coercion(v) for k, v in parameters.items()}
433
+ if statement_config.parameter_config.default_parameter_style in {
434
+ ParameterStyle.NUMERIC,
435
+ ParameterStyle.QMARK,
436
+ ParameterStyle.POSITIONAL_PYFORMAT,
437
+ }:
438
+ ordered_parameters = []
439
+ sorted_items = sorted(
440
+ parameters.items(),
441
+ key=lambda item: int(item[0])
442
+ if item[0].isdigit()
443
+ else (int(item[0][6:]) if item[0].startswith("param_") and item[0][6:].isdigit() else float("inf")),
444
+ )
445
+ for _, value in sorted_items:
446
+ ordered_parameters.append(apply_type_coercion(value))
447
+ return ordered_parameters
448
+
449
+ return {k: apply_type_coercion(v) for k, v in parameters.items()}
450
+
451
+ if isinstance(parameters, (list, tuple)):
452
+ coerced_params = [apply_type_coercion(p) for p in parameters]
453
+ if statement_config.parameter_config.preserve_parameter_format and isinstance(parameters, tuple):
454
+ return tuple(coerced_params)
455
+ return coerced_params
456
+
457
+ return [apply_type_coercion(parameters)]
458
+
459
+ def _get_compiled_sql(
460
+ self, statement: "SQL", statement_config: "StatementConfig", flatten_single_parameters: bool = False
461
+ ) -> tuple[str, Any]:
462
+ """Get compiled SQL with parameter style conversion and caching.
463
+
464
+ Compiles the SQL statement and applies parameter style conversion.
465
+ Results are cached when caching is enabled.
466
+
467
+ Args:
468
+ statement: SQL statement to compile
469
+ statement_config: Complete statement configuration including parameter config, dialect, etc.
470
+ flatten_single_parameters: If True, flatten single-element lists for scalar parameters
471
+
472
+ Returns:
473
+ Tuple of (compiled_sql, parameters)
474
+ """
475
+ cache_config = get_cache_config()
476
+ cache_key = None
477
+ if cache_config.compiled_cache_enabled and statement_config.enable_caching:
478
+ cache_key = self._generate_compilation_cache_key(statement, statement_config, flatten_single_parameters)
479
+ cached_result = sql_cache.get(cache_key)
480
+ if cached_result is not None:
481
+ return cached_result
482
+
483
+ compiled_sql, execution_parameters = statement.compile()
484
+
485
+ prepared_parameters = self.prepare_driver_parameters(
486
+ execution_parameters, statement_config, is_many=statement.is_many
487
+ )
488
+
489
+ if statement_config.parameter_config.output_transformer:
490
+ compiled_sql, prepared_parameters = statement_config.parameter_config.output_transformer(
491
+ compiled_sql, prepared_parameters
492
+ )
493
+
494
+ if cache_key is not None:
495
+ sql_cache.set(cache_key, (compiled_sql, prepared_parameters))
496
+
497
+ return compiled_sql, prepared_parameters
498
+
499
+ def _generate_compilation_cache_key(
500
+ self, statement: "SQL", config: "StatementConfig", flatten_single_parameters: bool
501
+ ) -> str:
502
+ """Generate cache key that includes all compilation context.
503
+
504
+ Creates a deterministic cache key that includes all factors that affect SQL compilation,
505
+ preventing cache contamination between different compilation contexts.
506
+ """
507
+ context_hash = hash(
508
+ (
509
+ config.parameter_config.hash(),
510
+ config.dialect,
511
+ statement.is_script,
512
+ statement.is_many,
513
+ flatten_single_parameters,
514
+ bool(config.parameter_config.output_transformer),
515
+ bool(config.parameter_config.ast_transformer),
516
+ bool(config.parameter_config.needs_static_script_compilation),
517
+ )
518
+ )
519
+
520
+ params = statement.parameters
521
+ params_key: Any
522
+
523
+ def make_hashable(obj: Any) -> Any:
524
+ """Recursively convert unhashable types to hashable ones."""
525
+ if isinstance(obj, (list, tuple)):
526
+ return tuple(make_hashable(item) for item in obj)
527
+ if isinstance(obj, dict):
528
+ return tuple(sorted((k, make_hashable(v)) for k, v in obj.items()))
529
+ if isinstance(obj, set):
530
+ return frozenset(make_hashable(item) for item in obj)
531
+ return obj
532
+
533
+ try:
534
+ if isinstance(params, dict):
535
+ params_key = make_hashable(params)
536
+ elif isinstance(params, (list, tuple)) and params:
537
+ if isinstance(params[0], dict):
538
+ params_key = tuple(make_hashable(d) for d in params)
539
+ else:
540
+ params_key = make_hashable(params)
541
+ elif isinstance(params, (list, tuple)):
542
+ params_key = ()
543
+ else:
544
+ params_key = params
545
+ except (TypeError, AttributeError):
546
+ params_key = str(params)
547
+
548
+ base_hash = hash((statement.sql, params_key, statement.is_many, statement.is_script))
549
+ return f"compiled:{base_hash}:{context_hash}"
550
+
551
+ def _get_dominant_parameter_style(self, parameters: "list[Any]") -> "Optional[ParameterStyle]":
552
+ """Determine the dominant parameter style from parameter info list.
553
+
554
+ Args:
555
+ parameters: List of ParameterInfo objects from validator.extract_parameters()
556
+
557
+ Returns:
558
+ The dominant parameter style, or None if no parameters
559
+ """
560
+ if not parameters:
561
+ return None
562
+
563
+ style_counts: dict[ParameterStyle, int] = {}
564
+ for param in parameters:
565
+ style_counts[param.style] = style_counts.get(param.style, 0) + 1
566
+
567
+ precedence = {
568
+ ParameterStyle.QMARK: 1,
569
+ ParameterStyle.NUMERIC: 2,
570
+ ParameterStyle.POSITIONAL_COLON: 3,
571
+ ParameterStyle.POSITIONAL_PYFORMAT: 4,
572
+ ParameterStyle.NAMED_AT: 5,
573
+ ParameterStyle.NAMED_DOLLAR: 6,
574
+ ParameterStyle.NAMED_COLON: 7,
575
+ ParameterStyle.NAMED_PYFORMAT: 8,
576
+ }
577
+
578
+ return max(style_counts.keys(), key=lambda style: (style_counts[style], -precedence.get(style, 99)))
579
+
580
+ def _create_count_query(self, original_sql: "SQL") -> "SQL":
581
+ """Create a COUNT query from the original SQL statement.
582
+
583
+ Transforms the original SELECT statement to count total rows while preserving
584
+ WHERE, HAVING, and GROUP BY clauses but removing ORDER BY, LIMIT, and OFFSET.
585
+ """
586
+ if not original_sql.expression:
587
+ msg = "Cannot create COUNT query from empty SQL expression"
588
+ raise ImproperConfigurationError(msg)
589
+ expr = original_sql.expression.copy()
590
+
591
+ if isinstance(expr, exp.Select):
592
+ if expr.args.get("group"):
593
+ subquery = expr.subquery(alias="grouped_data")
594
+ count_expr = exp.select(exp.Count(this=exp.Star())).from_(subquery)
595
+ else:
596
+ count_expr = exp.select(exp.Count(this=exp.Star())).from_(
597
+ cast("exp.Expression", expr.args.get("from")), copy=False
598
+ )
599
+ if expr.args.get("where"):
600
+ count_expr = count_expr.where(cast("exp.Expression", expr.args.get("where")), copy=False)
601
+ if expr.args.get("having"):
602
+ count_expr = count_expr.having(cast("exp.Expression", expr.args.get("having")), copy=False)
603
+
604
+ count_expr.set("order", None)
605
+ count_expr.set("limit", None)
606
+ count_expr.set("offset", None)
607
+
608
+ return SQL(count_expr, *original_sql._positional_parameters, statement_config=original_sql.statement_config)
609
+
610
+ subquery = cast("exp.Select", expr).subquery(alias="total_query")
611
+ count_expr = exp.select(exp.Count(this=exp.Star())).from_(subquery)
612
+ return SQL(count_expr, *original_sql._positional_parameters, statement_config=original_sql.statement_config)