sqlspec 0.16.1__cp311-cp311-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-311-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-311-aarch64-linux-gnu.so +0 -0
  76. sqlspec/core/cache.py +871 -0
  77. sqlspec/core/compiler.cpython-311-aarch64-linux-gnu.so +0 -0
  78. sqlspec/core/compiler.py +417 -0
  79. sqlspec/core/filters.cpython-311-aarch64-linux-gnu.so +0 -0
  80. sqlspec/core/filters.py +830 -0
  81. sqlspec/core/hashing.cpython-311-aarch64-linux-gnu.so +0 -0
  82. sqlspec/core/hashing.py +310 -0
  83. sqlspec/core/parameters.cpython-311-aarch64-linux-gnu.so +0 -0
  84. sqlspec/core/parameters.py +1237 -0
  85. sqlspec/core/result.cpython-311-aarch64-linux-gnu.so +0 -0
  86. sqlspec/core/result.py +677 -0
  87. sqlspec/core/splitter.cpython-311-aarch64-linux-gnu.so +0 -0
  88. sqlspec/core/splitter.py +819 -0
  89. sqlspec/core/statement.cpython-311-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-311-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-311-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-311-aarch64-linux-gnu.so +0 -0
  138. sqlspec/utils/sync_tools.py +237 -0
  139. sqlspec/utils/text.cpython-311-aarch64-linux-gnu.so +0 -0
  140. sqlspec/utils/text.py +96 -0
  141. sqlspec/utils/type_guards.cpython-311-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,502 @@
1
+ """Asynchronous driver protocol implementation.
2
+
3
+ This module provides the async driver infrastructure for database adapters,
4
+ including connection management, transaction support, and result processing.
5
+ """
6
+
7
+ from abc import abstractmethod
8
+ from typing import TYPE_CHECKING, Any, Final, NoReturn, Optional, Union, cast, overload
9
+
10
+ from sqlspec.core import SQL, Statement
11
+ from sqlspec.driver._common import CommonDriverAttributesMixin, ExecutionResult
12
+ from sqlspec.driver.mixins import SQLTranslatorMixin, ToSchemaMixin
13
+ from sqlspec.exceptions import NotFoundError
14
+ from sqlspec.utils.logging import get_logger
15
+ from sqlspec.utils.type_guards import is_dict_row, is_indexable_row
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Sequence
19
+ from contextlib import AbstractAsyncContextManager
20
+
21
+ from sqlspec.builder import QueryBuilder
22
+ from sqlspec.core import SQLResult, StatementConfig, StatementFilter
23
+ from sqlspec.typing import ModelDTOT, StatementParameters
24
+
25
+ _LOGGER_NAME: Final[str] = "sqlspec"
26
+ logger = get_logger(_LOGGER_NAME)
27
+
28
+ __all__ = ("AsyncDriverAdapterBase",)
29
+
30
+
31
+ EMPTY_FILTERS: Final["list[StatementFilter]"] = []
32
+
33
+
34
+ class AsyncDriverAdapterBase(CommonDriverAttributesMixin, SQLTranslatorMixin, ToSchemaMixin):
35
+ """Base class for asynchronous database drivers.
36
+
37
+ Provides the foundation for async database adapters, including connection management,
38
+ transaction support, and SQL execution methods. All database operations are performed
39
+ asynchronously and support context manager patterns for proper resource cleanup.
40
+ """
41
+
42
+ __slots__ = ()
43
+
44
+ async def dispatch_statement_execution(self, statement: "SQL", connection: "Any") -> "SQLResult":
45
+ """Central execution dispatcher using the Template Method Pattern.
46
+
47
+ Orchestrates the common execution flow, delegating database-specific steps
48
+ to abstract methods that concrete adapters must implement.
49
+ All database operations are wrapped in exception handling.
50
+
51
+ Args:
52
+ statement: The SQL statement to execute
53
+ connection: The database connection to use
54
+
55
+ Returns:
56
+ The result of the SQL execution
57
+ """
58
+ async with self.handle_database_exceptions(), self.with_cursor(connection) as cursor:
59
+ special_result = await self._try_special_handling(cursor, statement)
60
+ if special_result is not None:
61
+ return special_result
62
+
63
+ if statement.is_script:
64
+ execution_result = await self._execute_script(cursor, statement)
65
+ elif statement.is_many:
66
+ execution_result = await self._execute_many(cursor, statement)
67
+ else:
68
+ execution_result = await self._execute_statement(cursor, statement)
69
+
70
+ return self.build_statement_result(statement, execution_result)
71
+
72
+ @abstractmethod
73
+ def with_cursor(self, connection: Any) -> Any:
74
+ """Create and return an async context manager for cursor acquisition and cleanup.
75
+
76
+ Returns an async context manager that yields a cursor for database operations.
77
+ Concrete implementations handle database-specific cursor creation and cleanup.
78
+ """
79
+
80
+ @abstractmethod
81
+ def handle_database_exceptions(self) -> "AbstractAsyncContextManager[None]":
82
+ """Handle database-specific exceptions and wrap them appropriately.
83
+
84
+ Returns:
85
+ AsyncContextManager that can be used in async with statements
86
+ """
87
+
88
+ @abstractmethod
89
+ async def begin(self) -> None:
90
+ """Begin a database transaction on the current connection."""
91
+
92
+ @abstractmethod
93
+ async def rollback(self) -> None:
94
+ """Rollback the current transaction on the current connection."""
95
+
96
+ @abstractmethod
97
+ async def commit(self) -> None:
98
+ """Commit the current transaction on the current connection."""
99
+
100
+ @abstractmethod
101
+ async def _try_special_handling(self, cursor: Any, statement: "SQL") -> "Optional[SQLResult]":
102
+ """Hook for database-specific special operations (e.g., PostgreSQL COPY, bulk operations).
103
+
104
+ This method is called first in dispatch_statement_execution() to allow drivers to handle
105
+ special operations that don't follow the standard SQL execution pattern.
106
+
107
+ Args:
108
+ cursor: Database cursor/connection object
109
+ statement: SQL statement to analyze
110
+
111
+ Returns:
112
+ SQLResult if the special operation was handled and completed,
113
+ None if standard execution should proceed
114
+ """
115
+
116
+ async def _execute_script(self, cursor: Any, statement: "SQL") -> ExecutionResult:
117
+ """Execute a SQL script containing multiple statements.
118
+
119
+ Default implementation splits the script and executes statements individually.
120
+ Drivers can override for database-specific script execution methods.
121
+
122
+ Args:
123
+ cursor: Database cursor/connection object
124
+ statement: SQL statement object with all necessary data and configuration
125
+
126
+ Returns:
127
+ ExecutionResult with script execution data including statement counts
128
+ """
129
+ sql, prepared_parameters = self._get_compiled_sql(statement, self.statement_config)
130
+ statements = self.split_script_statements(sql, self.statement_config, strip_trailing_semicolon=True)
131
+
132
+ statement_count: int = len(statements)
133
+ successful_count: int = 0
134
+
135
+ for stmt in statements:
136
+ single_stmt = statement.copy(statement=stmt, parameters=prepared_parameters)
137
+ await self._execute_statement(cursor, single_stmt)
138
+ successful_count += 1
139
+
140
+ return self.create_execution_result(
141
+ cursor, statement_count=statement_count, successful_statements=successful_count, is_script_result=True
142
+ )
143
+
144
+ @abstractmethod
145
+ async def _execute_many(self, cursor: Any, statement: "SQL") -> ExecutionResult:
146
+ """Execute SQL with multiple parameter sets (executemany).
147
+
148
+ Must be implemented by each driver for database-specific executemany logic.
149
+
150
+ Args:
151
+ cursor: Database cursor/connection object
152
+ statement: SQL statement object with all necessary data and configuration
153
+
154
+ Returns:
155
+ ExecutionResult with execution data for the many operation
156
+ """
157
+
158
+ @abstractmethod
159
+ async def _execute_statement(self, cursor: Any, statement: "SQL") -> ExecutionResult:
160
+ """Execute a single SQL statement.
161
+
162
+ Must be implemented by each driver for database-specific execution logic.
163
+
164
+ Args:
165
+ cursor: Database cursor/connection object
166
+ statement: SQL statement object with all necessary data and configuration
167
+
168
+ Returns:
169
+ ExecutionResult with execution data
170
+ """
171
+
172
+ async def execute(
173
+ self,
174
+ statement: "Union[SQL, Statement, QueryBuilder]",
175
+ /,
176
+ *parameters: "Union[StatementParameters, StatementFilter]",
177
+ statement_config: "Optional[StatementConfig]" = None,
178
+ **kwargs: Any,
179
+ ) -> "SQLResult":
180
+ """Execute a statement with parameter handling."""
181
+ sql_statement = self.prepare_statement(
182
+ statement, parameters, statement_config=statement_config or self.statement_config, kwargs=kwargs
183
+ )
184
+ return await self.dispatch_statement_execution(statement=sql_statement, connection=self.connection)
185
+
186
+ async def execute_many(
187
+ self,
188
+ statement: "Union[SQL, Statement, QueryBuilder]",
189
+ /,
190
+ parameters: "Sequence[StatementParameters]",
191
+ *filters: "Union[StatementParameters, StatementFilter]",
192
+ statement_config: "Optional[StatementConfig]" = None,
193
+ **kwargs: Any,
194
+ ) -> "SQLResult":
195
+ """Execute statement multiple times with different parameters.
196
+
197
+ Parameters passed will be used as the batch execution sequence.
198
+ """
199
+ config = statement_config or self.statement_config
200
+
201
+ if isinstance(statement, SQL):
202
+ sql_statement = SQL(statement._raw_sql, parameters, statement_config=config, is_many=True, **kwargs)
203
+ else:
204
+ base_statement = self.prepare_statement(statement, filters, statement_config=config, kwargs=kwargs)
205
+ sql_statement = SQL(base_statement._raw_sql, parameters, statement_config=config, is_many=True, **kwargs)
206
+
207
+ return await self.dispatch_statement_execution(statement=sql_statement, connection=self.connection)
208
+
209
+ async def execute_script(
210
+ self,
211
+ statement: "Union[str, SQL]",
212
+ /,
213
+ *parameters: "Union[StatementParameters, StatementFilter]",
214
+ statement_config: "Optional[StatementConfig]" = None,
215
+ **kwargs: Any,
216
+ ) -> "SQLResult":
217
+ """Execute a multi-statement script.
218
+
219
+ By default, validates each statement and logs warnings for dangerous
220
+ operations. Use suppress_warnings=True for migrations and admin scripts.
221
+ """
222
+ config = statement_config or self.statement_config
223
+ sql_statement = self.prepare_statement(statement, parameters, statement_config=config, kwargs=kwargs)
224
+
225
+ return await self.dispatch_statement_execution(statement=sql_statement.as_script(), connection=self.connection)
226
+
227
+ @overload
228
+ async def select_one(
229
+ self,
230
+ statement: "Union[Statement, QueryBuilder]",
231
+ /,
232
+ *parameters: "Union[StatementParameters, StatementFilter]",
233
+ schema_type: "type[ModelDTOT]",
234
+ statement_config: "Optional[StatementConfig]" = None,
235
+ **kwargs: Any,
236
+ ) -> "ModelDTOT": ...
237
+
238
+ @overload
239
+ async def select_one(
240
+ self,
241
+ statement: "Union[Statement, QueryBuilder]",
242
+ /,
243
+ *parameters: "Union[StatementParameters, StatementFilter]",
244
+ schema_type: None = None,
245
+ statement_config: "Optional[StatementConfig]" = None,
246
+ **kwargs: Any,
247
+ ) -> "dict[str, Any]": ...
248
+
249
+ async def select_one(
250
+ self,
251
+ statement: "Union[Statement, QueryBuilder]",
252
+ /,
253
+ *parameters: "Union[StatementParameters, StatementFilter]",
254
+ schema_type: "Optional[type[ModelDTOT]]" = None,
255
+ statement_config: "Optional[StatementConfig]" = None,
256
+ **kwargs: Any,
257
+ ) -> "Union[dict[str, Any], ModelDTOT]":
258
+ """Execute a select statement and return exactly one row.
259
+
260
+ Raises an exception if no rows or more than one row is returned.
261
+ """
262
+ result = await self.execute(statement, *parameters, statement_config=statement_config, **kwargs)
263
+ data = result.get_data()
264
+ data_len: int = len(data)
265
+ if data_len == 0:
266
+ self._raise_no_rows_found()
267
+ if data_len > 1:
268
+ self._raise_expected_one_row(data_len)
269
+ first_row = data[0]
270
+ return self.to_schema(first_row, schema_type=schema_type) if schema_type else first_row
271
+
272
+ @overload
273
+ async def select_one_or_none(
274
+ self,
275
+ statement: "Union[Statement, QueryBuilder]",
276
+ /,
277
+ *parameters: "Union[StatementParameters, StatementFilter]",
278
+ schema_type: "type[ModelDTOT]",
279
+ statement_config: "Optional[StatementConfig]" = None,
280
+ **kwargs: Any,
281
+ ) -> "Optional[ModelDTOT]": ...
282
+
283
+ @overload
284
+ async def select_one_or_none(
285
+ self,
286
+ statement: "Union[Statement, QueryBuilder]",
287
+ /,
288
+ *parameters: "Union[StatementParameters, StatementFilter]",
289
+ schema_type: None = None,
290
+ statement_config: "Optional[StatementConfig]" = None,
291
+ **kwargs: Any,
292
+ ) -> "Optional[dict[str, Any]]": ...
293
+
294
+ async def select_one_or_none(
295
+ self,
296
+ statement: "Union[Statement, QueryBuilder]",
297
+ /,
298
+ *parameters: "Union[StatementParameters, StatementFilter]",
299
+ schema_type: "Optional[type[ModelDTOT]]" = None,
300
+ statement_config: "Optional[StatementConfig]" = None,
301
+ **kwargs: Any,
302
+ ) -> "Optional[Union[dict[str, Any], ModelDTOT]]":
303
+ """Execute a select statement and return at most one row.
304
+
305
+ Returns None if no rows are found.
306
+ Raises an exception if more than one row is returned.
307
+ """
308
+ result = await self.execute(statement, *parameters, statement_config=statement_config, **kwargs)
309
+ data = result.get_data()
310
+ data_len: int = len(data)
311
+ if data_len == 0:
312
+ return None
313
+ if data_len > 1:
314
+ self._raise_expected_at_most_one_row(data_len)
315
+ first_row = data[0]
316
+ return cast(
317
+ "Optional[Union[dict[str, Any], ModelDTOT]]",
318
+ self.to_schema(first_row, schema_type=schema_type) if schema_type else first_row,
319
+ )
320
+
321
+ @overload
322
+ async def select(
323
+ self,
324
+ statement: "Union[Statement, QueryBuilder]",
325
+ /,
326
+ *parameters: "Union[StatementParameters, StatementFilter]",
327
+ schema_type: "type[ModelDTOT]",
328
+ statement_config: "Optional[StatementConfig]" = None,
329
+ **kwargs: Any,
330
+ ) -> "list[ModelDTOT]": ...
331
+
332
+ @overload
333
+ async def select(
334
+ self,
335
+ statement: "Union[Statement, QueryBuilder]",
336
+ /,
337
+ *parameters: "Union[StatementParameters, StatementFilter]",
338
+ schema_type: None = None,
339
+ statement_config: "Optional[StatementConfig]" = None,
340
+ **kwargs: Any,
341
+ ) -> "list[dict[str, Any]]": ...
342
+
343
+ async def select(
344
+ self,
345
+ statement: "Union[Statement, QueryBuilder]",
346
+ /,
347
+ *parameters: "Union[StatementParameters, StatementFilter]",
348
+ schema_type: "Optional[type[ModelDTOT]]" = None,
349
+ statement_config: "Optional[StatementConfig]" = None,
350
+ **kwargs: Any,
351
+ ) -> "Union[list[dict[str, Any]], list[ModelDTOT]]":
352
+ """Execute a select statement and return all rows."""
353
+ result = await self.execute(statement, *parameters, statement_config=statement_config, **kwargs)
354
+ return cast(
355
+ "Union[list[dict[str, Any]], list[ModelDTOT]]", self.to_schema(result.get_data(), schema_type=schema_type)
356
+ )
357
+
358
+ async def select_value(
359
+ self,
360
+ statement: "Union[Statement, QueryBuilder]",
361
+ /,
362
+ *parameters: "Union[StatementParameters, StatementFilter]",
363
+ statement_config: "Optional[StatementConfig]" = None,
364
+ **kwargs: Any,
365
+ ) -> Any:
366
+ """Execute a select statement and return a single scalar value.
367
+
368
+ Expects exactly one row with one column.
369
+ Raises an exception if no rows or more than one row/column is returned.
370
+ """
371
+ result = await self.execute(statement, *parameters, statement_config=statement_config, **kwargs)
372
+ try:
373
+ row = result.one()
374
+ except ValueError as e:
375
+ self._raise_no_rows_found_from_exception(e)
376
+ if not row:
377
+ self._raise_no_rows_found()
378
+ if is_dict_row(row):
379
+ if not row:
380
+ self._raise_row_no_columns()
381
+ return next(iter(row.values()))
382
+ if is_indexable_row(row):
383
+ if not row:
384
+ self._raise_row_no_columns()
385
+ return row[0]
386
+ self._raise_unexpected_row_type(type(row))
387
+ return None
388
+
389
+ async def select_value_or_none(
390
+ self,
391
+ statement: "Union[Statement, QueryBuilder]",
392
+ /,
393
+ *parameters: "Union[StatementParameters, StatementFilter]",
394
+ statement_config: "Optional[StatementConfig]" = None,
395
+ **kwargs: Any,
396
+ ) -> Any:
397
+ """Execute a select statement and return a single scalar value or None.
398
+
399
+ Returns None if no rows are found.
400
+ Expects at most one row with one column.
401
+ Raises an exception if more than one row is returned.
402
+ """
403
+ result = await self.execute(statement, *parameters, statement_config=statement_config, **kwargs)
404
+ data = result.get_data()
405
+ data_len: int = len(data)
406
+ if data_len == 0:
407
+ return None
408
+ if data_len > 1:
409
+ self._raise_expected_at_most_one_row(data_len)
410
+ row = data[0]
411
+ if is_dict_row(row):
412
+ if not row:
413
+ return None
414
+ return next(iter(row.values()))
415
+ if is_indexable_row(row):
416
+ return row[0]
417
+ self._raise_cannot_extract_value_from_row_type(type(row).__name__)
418
+ return None
419
+
420
+ @overload
421
+ async def select_with_total(
422
+ self,
423
+ statement: "Union[Statement, QueryBuilder]",
424
+ /,
425
+ *parameters: "Union[StatementParameters, StatementFilter]",
426
+ schema_type: "type[ModelDTOT]",
427
+ statement_config: "Optional[StatementConfig]" = None,
428
+ **kwargs: Any,
429
+ ) -> "tuple[list[ModelDTOT], int]": ...
430
+
431
+ @overload
432
+ async def select_with_total(
433
+ self,
434
+ statement: "Union[Statement, QueryBuilder]",
435
+ /,
436
+ *parameters: "Union[StatementParameters, StatementFilter]",
437
+ schema_type: None = None,
438
+ statement_config: "Optional[StatementConfig]" = None,
439
+ **kwargs: Any,
440
+ ) -> "tuple[list[dict[str, Any]], int]": ...
441
+
442
+ async def select_with_total(
443
+ self,
444
+ statement: "Union[Statement, QueryBuilder]",
445
+ /,
446
+ *parameters: "Union[StatementParameters, StatementFilter]",
447
+ schema_type: "Optional[type[ModelDTOT]]" = None,
448
+ statement_config: "Optional[StatementConfig]" = None,
449
+ **kwargs: Any,
450
+ ) -> "tuple[Union[list[dict[str, Any]], list[ModelDTOT]], int]":
451
+ """Execute a select statement and return both the data and total count.
452
+
453
+ This method is designed for pagination scenarios where you need both
454
+ the current page of data and the total number of rows that match the query.
455
+
456
+ Args:
457
+ statement: The SQL statement, QueryBuilder, or raw SQL string
458
+ *parameters: Parameters for the SQL statement
459
+ schema_type: Optional schema type for data transformation
460
+ statement_config: Optional SQL configuration
461
+ **kwargs: Additional keyword arguments
462
+
463
+ Returns:
464
+ A tuple containing:
465
+ - List of data rows (transformed by schema_type if provided)
466
+ - Total count of rows matching the query (ignoring LIMIT/OFFSET)
467
+ """
468
+ sql_statement = self.prepare_statement(
469
+ statement, parameters, statement_config=statement_config or self.statement_config, kwargs=kwargs
470
+ )
471
+ count_result = await self.dispatch_statement_execution(self._create_count_query(sql_statement), self.connection)
472
+ select_result = await self.execute(sql_statement)
473
+
474
+ return (self.to_schema(select_result.get_data(), schema_type=schema_type), count_result.scalar())
475
+
476
+ def _raise_no_rows_found(self) -> NoReturn:
477
+ msg = "No rows found"
478
+ raise NotFoundError(msg)
479
+
480
+ def _raise_no_rows_found_from_exception(self, e: ValueError) -> NoReturn:
481
+ msg = "No rows found"
482
+ raise NotFoundError(msg) from e
483
+
484
+ def _raise_expected_one_row(self, data_len: int) -> NoReturn:
485
+ msg = f"Expected exactly one row, found {data_len}"
486
+ raise ValueError(msg)
487
+
488
+ def _raise_expected_at_most_one_row(self, data_len: int) -> NoReturn:
489
+ msg = f"Expected at most one row, found {data_len}"
490
+ raise ValueError(msg)
491
+
492
+ def _raise_row_no_columns(self) -> NoReturn:
493
+ msg = "Row has no columns"
494
+ raise ValueError(msg)
495
+
496
+ def _raise_unexpected_row_type(self, row_type: type) -> NoReturn:
497
+ msg = f"Unexpected row type: {row_type}"
498
+ raise ValueError(msg)
499
+
500
+ def _raise_cannot_extract_value_from_row_type(self, type_name: str) -> NoReturn:
501
+ msg = f"Cannot extract value from row type {type_name}"
502
+ raise TypeError(msg)