sqlspec 0.16.0__cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.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-39-x86_64-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 +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.cpython-39-x86_64-linux-gnu.so +0 -0
  76. sqlspec/core/cache.py +873 -0
  77. sqlspec/core/compiler.cpython-39-x86_64-linux-gnu.so +0 -0
  78. sqlspec/core/compiler.py +396 -0
  79. sqlspec/core/filters.cpython-39-x86_64-linux-gnu.so +0 -0
  80. sqlspec/core/filters.py +830 -0
  81. sqlspec/core/hashing.cpython-39-x86_64-linux-gnu.so +0 -0
  82. sqlspec/core/hashing.py +310 -0
  83. sqlspec/core/parameters.cpython-39-x86_64-linux-gnu.so +0 -0
  84. sqlspec/core/parameters.py +1209 -0
  85. sqlspec/core/result.cpython-39-x86_64-linux-gnu.so +0 -0
  86. sqlspec/core/result.py +664 -0
  87. sqlspec/core/splitter.cpython-39-x86_64-linux-gnu.so +0 -0
  88. sqlspec/core/splitter.py +819 -0
  89. sqlspec/core/statement.cpython-39-x86_64-linux-gnu.so +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.cpython-39-x86_64-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 +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.cpython-39-x86_64-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-39-x86_64-linux-gnu.so +0 -0
  138. sqlspec/utils/sync_tools.py +237 -0
  139. sqlspec/utils/text.cpython-39-x86_64-linux-gnu.so +0 -0
  140. sqlspec/utils/text.py +96 -0
  141. sqlspec/utils/type_guards.cpython-39-x86_64-linux-gnu.so +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
sqlspec/core/result.py ADDED
@@ -0,0 +1,664 @@
1
+ """SQL result classes for query execution results.
2
+
3
+ This module provides result classes for handling SQL query execution results
4
+ including regular results and Apache Arrow format results.
5
+
6
+ Components:
7
+ - StatementResult: Abstract base class for SQL results
8
+ - SQLResult: Main implementation for regular results
9
+ - ArrowResult: Arrow-based results for high-performance data interchange
10
+
11
+ Features:
12
+ - Consistent interface across all result types
13
+ - Support for both regular and Arrow format results
14
+ - Comprehensive result metadata and statistics
15
+ - Iterator support for result rows
16
+ """
17
+
18
+ from abc import ABC, abstractmethod
19
+ from typing import TYPE_CHECKING, Any, Optional, Union, cast
20
+
21
+ from mypy_extensions import mypyc_attr
22
+ from typing_extensions import TypeVar
23
+
24
+ from sqlspec.core.compiler import OperationType
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Iterator
28
+
29
+ from sqlspec.core.statement import SQL
30
+
31
+
32
+ __all__ = ("ArrowResult", "SQLResult", "StatementResult")
33
+
34
+ T = TypeVar("T")
35
+
36
+
37
+ @mypyc_attr(allow_interpreted_subclasses=True)
38
+ class StatementResult(ABC):
39
+ """Base class for SQL statement execution results.
40
+
41
+ Provides a common interface for handling different types of SQL operation
42
+ results. Subclasses implement specific behavior for SELECT, INSERT/UPDATE/DELETE,
43
+ and script operations.
44
+
45
+ Args:
46
+ statement: The original SQL statement that was executed.
47
+ data: The result data from the operation (type varies by subclass).
48
+ rows_affected: Number of rows affected by the operation (if applicable).
49
+ last_inserted_id: Last inserted ID (if applicable).
50
+ execution_time: Time taken to execute the statement in seconds.
51
+ metadata: Additional metadata about the operation.
52
+ """
53
+
54
+ __slots__ = ("data", "execution_time", "last_inserted_id", "metadata", "rows_affected", "statement")
55
+
56
+ def __init__(
57
+ self,
58
+ statement: "SQL",
59
+ data: Any = None,
60
+ rows_affected: int = 0,
61
+ last_inserted_id: Optional[Union[int, str]] = None,
62
+ execution_time: Optional[float] = None,
63
+ metadata: Optional["dict[str, Any]"] = None,
64
+ ) -> None:
65
+ """Initialize statement result.
66
+
67
+ Args:
68
+ statement: The original SQL statement that was executed.
69
+ data: The result data from the operation.
70
+ rows_affected: Number of rows affected by the operation.
71
+ last_inserted_id: Last inserted ID from the operation.
72
+ execution_time: Time taken to execute the statement in seconds.
73
+ metadata: Additional metadata about the operation.
74
+ """
75
+ self.statement = statement
76
+ self.data = data
77
+ self.rows_affected = rows_affected
78
+ self.last_inserted_id = last_inserted_id
79
+ self.execution_time = execution_time
80
+ self.metadata = metadata if metadata is not None else {}
81
+
82
+ @abstractmethod
83
+ def is_success(self) -> bool:
84
+ """Check if the operation was successful.
85
+
86
+ Returns:
87
+ True if the operation completed successfully, False otherwise.
88
+ """
89
+
90
+ @abstractmethod
91
+ def get_data(self) -> "Any":
92
+ """Get the processed data from the result.
93
+
94
+ Returns:
95
+ The processed result data in an appropriate format.
96
+ """
97
+
98
+ def get_metadata(self, key: str, default: Any = None) -> Any:
99
+ """Get metadata value by key.
100
+
101
+ Args:
102
+ key: The metadata key to retrieve.
103
+ default: Default value if key is not found.
104
+
105
+ Returns:
106
+ The metadata value or default.
107
+ """
108
+ return self.metadata.get(key, default)
109
+
110
+ def set_metadata(self, key: str, value: Any) -> None:
111
+ """Set metadata value by key.
112
+
113
+ Args:
114
+ key: The metadata key to set.
115
+ value: The value to set.
116
+ """
117
+ self.metadata[key] = value
118
+
119
+ @property
120
+ def operation_type(self) -> OperationType:
121
+ """Get operation type from the statement.
122
+
123
+ Returns:
124
+ The type of SQL operation that produced this result.
125
+ """
126
+ if hasattr(self.statement, "operation_type"):
127
+ return cast("OperationType", self.statement.operation_type)
128
+ return "SELECT"
129
+
130
+
131
+ @mypyc_attr(allow_interpreted_subclasses=True)
132
+ class SQLResult(StatementResult):
133
+ """Result class for SQL operations that return rows or affect rows.
134
+
135
+ Handles SELECT, INSERT, UPDATE, DELETE operations. For DML operations with
136
+ RETURNING clauses, the returned data will be in `self.data`. The `operation_type`
137
+ attribute helps distinguish the nature of the operation.
138
+
139
+ For script execution, this class also tracks multiple statement results and errors.
140
+ """
141
+
142
+ __slots__ = (
143
+ "_operation_type",
144
+ "column_names",
145
+ "error",
146
+ "errors",
147
+ "has_more",
148
+ "inserted_ids",
149
+ "operation_index",
150
+ "parameters",
151
+ "statement_results",
152
+ "successful_statements",
153
+ "total_count",
154
+ "total_statements",
155
+ )
156
+
157
+ def __init__(
158
+ self,
159
+ statement: "SQL",
160
+ data: Optional[list[dict[str, Any]]] = None,
161
+ rows_affected: int = 0,
162
+ last_inserted_id: Optional[Union[int, str]] = None,
163
+ execution_time: Optional[float] = None,
164
+ metadata: Optional["dict[str, Any]"] = None,
165
+ error: Optional[Exception] = None,
166
+ operation_type: OperationType = "SELECT",
167
+ operation_index: Optional[int] = None,
168
+ parameters: Optional[Any] = None,
169
+ column_names: Optional["list[str]"] = None,
170
+ total_count: Optional[int] = None,
171
+ has_more: bool = False,
172
+ inserted_ids: Optional["list[Union[int, str]]"] = None,
173
+ statement_results: Optional["list[SQLResult]"] = None,
174
+ errors: Optional["list[str]"] = None,
175
+ total_statements: int = 0,
176
+ successful_statements: int = 0,
177
+ ) -> None:
178
+ """Initialize SQL result."""
179
+ super().__init__(
180
+ statement=statement,
181
+ data=data,
182
+ rows_affected=rows_affected,
183
+ last_inserted_id=last_inserted_id,
184
+ execution_time=execution_time,
185
+ metadata=metadata,
186
+ )
187
+ self.error = error
188
+ self._operation_type = operation_type
189
+ self.operation_index = operation_index
190
+ self.parameters = parameters
191
+ self.column_names = column_names if column_names is not None else []
192
+ self.total_count = total_count
193
+ self.has_more = has_more
194
+ self.inserted_ids = inserted_ids if inserted_ids is not None else []
195
+ self.statement_results: list[SQLResult] = statement_results if statement_results is not None else []
196
+ self.errors = errors if errors is not None else []
197
+ self.total_statements = total_statements
198
+ self.successful_statements = successful_statements
199
+
200
+ if not self.column_names and self.data is not None and self.data:
201
+ self.column_names = list(self.data[0].keys())
202
+ if self.total_count is None:
203
+ self.total_count = len(self.data) if self.data is not None else 0
204
+
205
+ @property
206
+ def operation_type(self) -> "OperationType":
207
+ """Get operation type for this result."""
208
+ return cast("OperationType", self._operation_type) # type: ignore[redundant-cast]
209
+
210
+ def get_metadata(self, key: str, default: Any = None) -> Any:
211
+ """Get metadata value by key.
212
+
213
+ Args:
214
+ key: The metadata key to retrieve.
215
+ default: Default value if key is not found.
216
+
217
+ Returns:
218
+ The metadata value or default.
219
+ """
220
+ return self.metadata.get(key, default)
221
+
222
+ def set_metadata(self, key: str, value: Any) -> None:
223
+ """Set metadata value by key.
224
+
225
+ Args:
226
+ key: The metadata key to set.
227
+ value: The value to set.
228
+ """
229
+ self.metadata[key] = value
230
+
231
+ def is_success(self) -> bool:
232
+ """Check if the operation was successful.
233
+
234
+ Returns:
235
+ True if operation was successful, False otherwise.
236
+ """
237
+ op_type = self.operation_type.upper()
238
+
239
+ if op_type == "SCRIPT" or self.statement_results:
240
+ return not self.errors and self.total_statements == self.successful_statements
241
+
242
+ if op_type == "SELECT":
243
+ return self.data is not None and self.rows_affected >= 0
244
+
245
+ if op_type in {"INSERT", "UPDATE", "DELETE", "EXECUTE"}:
246
+ return self.rows_affected >= 0
247
+
248
+ return False
249
+
250
+ def get_data(self) -> "list[dict[str,Any]]":
251
+ """Get the data from the result.
252
+
253
+ For regular operations, returns the list of rows.
254
+ For script operations, returns a summary dictionary.
255
+
256
+ Returns:
257
+ List of result rows or script summary.
258
+ """
259
+ if self.operation_type.upper() == "SCRIPT":
260
+ return [
261
+ {
262
+ "total_statements": self.total_statements,
263
+ "successful_statements": self.successful_statements,
264
+ "failed_statements": self.total_statements - self.successful_statements,
265
+ "errors": self.errors,
266
+ "statement_results": self.statement_results,
267
+ "total_rows_affected": self.get_total_rows_affected(),
268
+ }
269
+ ]
270
+ return self.data if self.data is not None else []
271
+
272
+ def add_statement_result(self, result: "SQLResult") -> None:
273
+ """Add a statement result to the script execution results.
274
+
275
+ Args:
276
+ result: Statement result to add.
277
+ """
278
+ self.statement_results.append(result)
279
+ self.total_statements += 1
280
+ if result.is_success():
281
+ self.successful_statements += 1
282
+
283
+ def get_total_rows_affected(self) -> int:
284
+ """Get the total number of rows affected across all statements.
285
+
286
+ Returns:
287
+ Total rows affected.
288
+ """
289
+ if self.statement_results:
290
+ return sum(
291
+ stmt.rows_affected for stmt in self.statement_results if stmt.rows_affected and stmt.rows_affected > 0
292
+ )
293
+ return self.rows_affected if self.rows_affected and self.rows_affected > 0 else 0
294
+
295
+ @property
296
+ def num_rows(self) -> int:
297
+ """Get the number of rows affected (alias for get_total_rows_affected).
298
+
299
+ Returns:
300
+ Total rows affected.
301
+ """
302
+ return self.get_total_rows_affected()
303
+
304
+ @property
305
+ def num_columns(self) -> int:
306
+ """Get the number of columns in the result data.
307
+
308
+ Returns:
309
+ Number of columns.
310
+ """
311
+ return len(self.column_names) if self.column_names else 0
312
+
313
+ def get_first(self) -> "Optional[dict[str, Any]]":
314
+ """Get the first row from the result, if any.
315
+
316
+ Returns:
317
+ First row or None if no data.
318
+ """
319
+ return self.data[0] if self.data else None
320
+
321
+ def get_count(self) -> int:
322
+ """Get the number of rows in the current result set (e.g., a page of data).
323
+
324
+ Returns:
325
+ Number of rows in current result set.
326
+ """
327
+ return len(self.data) if self.data is not None else 0
328
+
329
+ def is_empty(self) -> bool:
330
+ """Check if the result set (self.data) is empty.
331
+
332
+ Returns:
333
+ True if result set is empty.
334
+ """
335
+ return not self.data if self.data is not None else True
336
+
337
+ def get_affected_count(self) -> int:
338
+ """Get the number of rows affected by a DML operation.
339
+
340
+ Returns:
341
+ Number of affected rows.
342
+ """
343
+ return self.rows_affected or 0
344
+
345
+ def was_inserted(self) -> bool:
346
+ """Check if this was an INSERT operation.
347
+
348
+ Returns:
349
+ True if INSERT operation.
350
+ """
351
+ return self.operation_type.upper() == "INSERT"
352
+
353
+ def was_updated(self) -> bool:
354
+ """Check if this was an UPDATE operation.
355
+
356
+ Returns:
357
+ True if UPDATE operation.
358
+ """
359
+ return self.operation_type.upper() == "UPDATE"
360
+
361
+ def was_deleted(self) -> bool:
362
+ """Check if this was a DELETE operation.
363
+
364
+ Returns:
365
+ True if DELETE operation.
366
+ """
367
+ return self.operation_type.upper() == "DELETE"
368
+
369
+ def __len__(self) -> int:
370
+ """Get the number of rows in the result set.
371
+
372
+ Returns:
373
+ Number of rows in the data.
374
+ """
375
+ return len(self.data) if self.data is not None else 0
376
+
377
+ def __getitem__(self, index: int) -> "dict[str, Any]":
378
+ """Get a row by index.
379
+
380
+ Args:
381
+ index: Row index
382
+
383
+ Returns:
384
+ The row at the specified index
385
+ """
386
+ if self.data is None:
387
+ msg = "No data available"
388
+ raise IndexError(msg)
389
+ return cast("dict[str, Any]", self.data[index])
390
+
391
+ def __iter__(self) -> "Iterator[dict[str, Any]]":
392
+ """Iterate over the rows in the result.
393
+
394
+ Returns:
395
+ Iterator that yields each row as a dictionary
396
+ """
397
+ if self.data is None:
398
+ return iter([])
399
+ return iter(self.data)
400
+
401
+ def all(self) -> list[dict[str, Any]]:
402
+ """Return all rows as a list.
403
+
404
+ Returns:
405
+ List of all rows in the result
406
+ """
407
+ return self.data or []
408
+
409
+ def one(self) -> "dict[str, Any]":
410
+ """Return exactly one row.
411
+
412
+ Returns:
413
+ The single row
414
+
415
+ Raises:
416
+ ValueError: If no results or more than one result
417
+ """
418
+ data_len = 0 if self.data is None else len(self.data)
419
+
420
+ if data_len == 0:
421
+ msg = "No result found, exactly one row expected"
422
+ raise ValueError(msg)
423
+ if data_len > 1:
424
+ msg = f"Multiple results found ({data_len}), exactly one row expected"
425
+ raise ValueError(msg)
426
+ return cast("dict[str, Any]", self.data[0])
427
+
428
+ def one_or_none(self) -> "Optional[dict[str, Any]]":
429
+ """Return at most one row.
430
+
431
+ Returns:
432
+ The single row or None if no results
433
+
434
+ Raises:
435
+ ValueError: If more than one result
436
+ """
437
+ if not self.data:
438
+ return None
439
+
440
+ data_len = len(self.data)
441
+ if data_len > 1:
442
+ msg = f"Multiple results found ({data_len}), at most one row expected"
443
+ raise ValueError(msg)
444
+ return cast("dict[str, Any]", self.data[0])
445
+
446
+ def scalar(self) -> Any:
447
+ """Return the first column of the first row.
448
+
449
+ Returns:
450
+ The scalar value from first column of first row
451
+ """
452
+ row = self.one()
453
+ return next(iter(row.values()))
454
+
455
+ def scalar_or_none(self) -> Any:
456
+ """Return the first column of the first row, or None if no results.
457
+
458
+ Returns:
459
+ The scalar value from first column of first row, or None
460
+ """
461
+ row = self.one_or_none()
462
+ if row is None:
463
+ return None
464
+
465
+ return next(iter(row.values()))
466
+
467
+
468
+ @mypyc_attr(allow_interpreted_subclasses=True)
469
+ class ArrowResult(StatementResult):
470
+ """Result class for SQL operations that return Apache Arrow data.
471
+
472
+ This class is used when database drivers support returning results as
473
+ Apache Arrow format for high-performance data interchange, especially
474
+ useful for analytics workloads and data science applications.
475
+
476
+ Performance Features:
477
+ - __slots__ optimization for memory efficiency
478
+ - Direct Arrow table access without intermediate copying
479
+ - Cached property evaluation for table metadata
480
+ - MyPyC compatibility for critical operations
481
+
482
+ Compatibility Features:
483
+ - Complete interface preservation with existing ArrowResult
484
+ - Same method signatures and behavior
485
+ - Same error handling and exceptions
486
+ - Identical Arrow table integration
487
+
488
+ Args:
489
+ statement: The original SQL statement that was executed.
490
+ data: The Apache Arrow Table containing the result data.
491
+ schema: Optional Arrow schema information.
492
+ """
493
+
494
+ __slots__ = ("schema",)
495
+
496
+ def __init__(
497
+ self,
498
+ statement: "SQL",
499
+ data: Any,
500
+ rows_affected: int = 0,
501
+ last_inserted_id: Optional[Union[int, str]] = None,
502
+ execution_time: Optional[float] = None,
503
+ metadata: Optional["dict[str, Any]"] = None,
504
+ schema: Optional["dict[str, Any]"] = None,
505
+ ) -> None:
506
+ """Initialize Arrow result with enhanced performance.
507
+
508
+ Args:
509
+ statement: The original SQL statement that was executed.
510
+ data: The Apache Arrow Table containing the result data.
511
+ rows_affected: Number of rows affected by the operation.
512
+ last_inserted_id: Last inserted ID (if applicable).
513
+ execution_time: Time taken to execute the statement in seconds.
514
+ metadata: Additional metadata about the operation.
515
+ schema: Optional Arrow schema information.
516
+ """
517
+ super().__init__(
518
+ statement=statement,
519
+ data=data,
520
+ rows_affected=rows_affected,
521
+ last_inserted_id=last_inserted_id,
522
+ execution_time=execution_time,
523
+ metadata=metadata,
524
+ )
525
+
526
+ self.schema = schema
527
+
528
+ def is_success(self) -> bool:
529
+ """Check if the operation was successful.
530
+
531
+ Returns:
532
+ True if Arrow table data is available, False otherwise.
533
+ """
534
+ return self.data is not None
535
+
536
+ def get_data(self) -> Any:
537
+ """Get the Apache Arrow Table from the result.
538
+
539
+ Returns:
540
+ The Arrow table containing the result data.
541
+
542
+ Raises:
543
+ ValueError: If no Arrow table is available.
544
+ """
545
+ if self.data is None:
546
+ msg = "No Arrow table available for this result"
547
+ raise ValueError(msg)
548
+ return self.data
549
+
550
+ @property
551
+ def column_names(self) -> "list[str]":
552
+ """Get the column names from the Arrow table.
553
+
554
+ Returns:
555
+ List of column names.
556
+
557
+ Raises:
558
+ ValueError: If no Arrow table is available.
559
+ """
560
+ if self.data is None:
561
+ msg = "No Arrow table available"
562
+ raise ValueError(msg)
563
+
564
+ return cast("list[str]", self.data.column_names)
565
+
566
+ @property
567
+ def num_rows(self) -> int:
568
+ """Get the number of rows in the Arrow table.
569
+
570
+ Returns:
571
+ Number of rows.
572
+
573
+ Raises:
574
+ ValueError: If no Arrow table is available.
575
+ """
576
+ if self.data is None:
577
+ msg = "No Arrow table available"
578
+ raise ValueError(msg)
579
+
580
+ return cast("int", self.data.num_rows)
581
+
582
+ @property
583
+ def num_columns(self) -> int:
584
+ """Get the number of columns in the Arrow table.
585
+
586
+ Returns:
587
+ Number of columns.
588
+
589
+ Raises:
590
+ ValueError: If no Arrow table is available.
591
+ """
592
+ if self.data is None:
593
+ msg = "No Arrow table available"
594
+ raise ValueError(msg)
595
+
596
+ return cast("int", self.data.num_columns)
597
+
598
+
599
+ def create_sql_result(
600
+ statement: "SQL",
601
+ data: Optional[list[dict[str, Any]]] = None,
602
+ rows_affected: int = 0,
603
+ last_inserted_id: Optional[Union[int, str]] = None,
604
+ execution_time: Optional[float] = None,
605
+ metadata: Optional["dict[str, Any]"] = None,
606
+ **kwargs: Any,
607
+ ) -> SQLResult:
608
+ """Create SQLResult instance.
609
+
610
+ Args:
611
+ statement: The SQL statement that produced this result.
612
+ data: Result data from query execution.
613
+ rows_affected: Number of rows affected by the operation.
614
+ last_inserted_id: Last inserted ID (for INSERT operations).
615
+ execution_time: Execution time in seconds.
616
+ metadata: Additional metadata about the result.
617
+ **kwargs: Additional arguments for SQLResult initialization.
618
+
619
+ Returns:
620
+ SQLResult instance.
621
+ """
622
+ return SQLResult(
623
+ statement=statement,
624
+ data=data,
625
+ rows_affected=rows_affected,
626
+ last_inserted_id=last_inserted_id,
627
+ execution_time=execution_time,
628
+ metadata=metadata,
629
+ **kwargs,
630
+ )
631
+
632
+
633
+ def create_arrow_result(
634
+ statement: "SQL",
635
+ data: Any,
636
+ rows_affected: int = 0,
637
+ last_inserted_id: Optional[Union[int, str]] = None,
638
+ execution_time: Optional[float] = None,
639
+ metadata: Optional["dict[str, Any]"] = None,
640
+ schema: Optional["dict[str, Any]"] = None,
641
+ ) -> ArrowResult:
642
+ """Create ArrowResult instance.
643
+
644
+ Args:
645
+ statement: The SQL statement that produced this result.
646
+ data: Arrow-based result data.
647
+ rows_affected: Number of rows affected by the operation.
648
+ last_inserted_id: Last inserted ID (for INSERT operations).
649
+ execution_time: Execution time in seconds.
650
+ metadata: Additional metadata about the result.
651
+ schema: Optional Arrow schema information.
652
+
653
+ Returns:
654
+ ArrowResult instance.
655
+ """
656
+ return ArrowResult(
657
+ statement=statement,
658
+ data=data,
659
+ rows_affected=rows_affected,
660
+ last_inserted_id=last_inserted_id,
661
+ execution_time=execution_time,
662
+ metadata=metadata,
663
+ schema=schema,
664
+ )