gres 1.0.0__cp315-cp315t-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.
Files changed (61) hide show
  1. gres/__init__.py +128 -0
  2. gres/_adapters.py +422 -0
  3. gres/_array.py +40 -0
  4. gres/_arrow.py +85 -0
  5. gres/_arrow_input.py +212 -0
  6. gres/_arrow_nested.py +133 -0
  7. gres/_arrow_schema.py +528 -0
  8. gres/_authentication.py +193 -0
  9. gres/_batch.py +187 -0
  10. gres/_buffer.py +24 -0
  11. gres/_catalog.py +24 -0
  12. gres/_client_files.py +57 -0
  13. gres/_command.py +25 -0
  14. gres/_composite.py +635 -0
  15. gres/_composition.py +192 -0
  16. gres/_connection.py +817 -0
  17. gres/_conninfo.py +352 -0
  18. gres/_copy.py +63 -0
  19. gres/_copy_arrow.py +412 -0
  20. gres/_copy_rows.py +178 -0
  21. gres/_copy_spatial.py +119 -0
  22. gres/_copy_target.py +86 -0
  23. gres/_deadline.py +119 -0
  24. gres/_decoding.py +50 -0
  25. gres/_endpoints.py +82 -0
  26. gres/_executor.py +1158 -0
  27. gres/_geoarrow.py +106 -0
  28. gres/_identifier.py +25 -0
  29. gres/_iteration.py +17 -0
  30. gres/_json.py +94 -0
  31. gres/_kerberos.py +54 -0
  32. gres/_lib.cp315t-win_amd64.pyd +0 -0
  33. gres/_lib.pyi +960 -0
  34. gres/_listener.py +86 -0
  35. gres/_pgvalue.py +37 -0
  36. gres/_pool.py +673 -0
  37. gres/_postgis.py +466 -0
  38. gres/_prepared.py +187 -0
  39. gres/_query.py +278 -0
  40. gres/_range.py +85 -0
  41. gres/_resource.py +12 -0
  42. gres/_rows.py +523 -0
  43. gres/_spatial.py +37 -0
  44. gres/_sqlalchemy/__init__.py +311 -0
  45. gres/_sqlalchemy/dbapi.py +263 -0
  46. gres/_stream.py +255 -0
  47. gres/_telemetry.py +197 -0
  48. gres/_temporal.py +10 -0
  49. gres/_tls.py +133 -0
  50. gres/_transaction.py +380 -0
  51. gres/_type_plan.py +734 -0
  52. gres/errors.py +322 -0
  53. gres/py.typed +0 -0
  54. gres-1.0.0.dist-info/METADATA +134 -0
  55. gres-1.0.0.dist-info/RECORD +61 -0
  56. gres-1.0.0.dist-info/WHEEL +4 -0
  57. gres-1.0.0.dist-info/entry_points.txt +2 -0
  58. gres-1.0.0.dist-info/licenses/LICENSE-APACHE.md +162 -0
  59. gres-1.0.0.dist-info/licenses/LICENSE-MIT.md +21 -0
  60. gres-1.0.0.dist-info/licenses/LICENSE-THIRD-PARTY.md +4983 -0
  61. gres-1.0.0.dist-info/sboms/gres.cyclonedx.json +7168 -0
gres/__init__.py ADDED
@@ -0,0 +1,128 @@
1
+ """Asyncio PostgreSQL connections and command execution."""
2
+
3
+ from gres._adapters import Adapter, Codec, CompositeBinding, EnumBinding
4
+ from gres._array import Array
5
+ from gres._arrow import ArrowStream
6
+ from gres._authentication import (
7
+ ConnectionTarget,
8
+ KeyPasswordProvider,
9
+ KeyPasswordRequest,
10
+ OAuthDiscovery,
11
+ OAuthProvider,
12
+ OAuthRequest,
13
+ PasswordProvider,
14
+ PasswordRequest,
15
+ )
16
+ from gres._command import BatchResult, Command
17
+ from gres._composition import (
18
+ Literal,
19
+ and_,
20
+ assignments,
21
+ cast,
22
+ insert,
23
+ join,
24
+ or_,
25
+ values,
26
+ )
27
+ from gres._connection import Connection
28
+ from gres._deadline import INHERIT, InheritType
29
+ from gres._decoding import Decoding
30
+ from gres._executor import Executor
31
+ from gres._identifier import Identifier
32
+ from gres._json import Json, JsonDocument
33
+ from gres._lib import (
34
+ BitString,
35
+ EwkbGeography,
36
+ EwkbGeometry,
37
+ HalfVector,
38
+ Interval,
39
+ Notification,
40
+ PgBox,
41
+ PgCircle,
42
+ PgDate,
43
+ PgLine,
44
+ PgLineSegment,
45
+ PgPath,
46
+ PgPoint,
47
+ PgPolygon,
48
+ PgTime,
49
+ PgTimestamp,
50
+ PreparedStatement,
51
+ SparseVector,
52
+ Vector,
53
+ )
54
+ from gres._pgvalue import PgValue
55
+ from gres._pool import Pool, PoolStats
56
+ from gres._query import Query, raw_sql
57
+ from gres._range import MultiRange, Range
58
+ from gres._rows import scalar
59
+ from gres._spatial import SpatialParameter
60
+ from gres._temporal import Infinity
61
+ from gres._transaction import Transaction
62
+ from gres.errors import Error
63
+
64
+ __all__ = [
65
+ 'INHERIT',
66
+ 'Adapter',
67
+ 'Array',
68
+ 'ArrowStream',
69
+ 'BatchResult',
70
+ 'BitString',
71
+ 'Codec',
72
+ 'Command',
73
+ 'CompositeBinding',
74
+ 'Connection',
75
+ 'ConnectionTarget',
76
+ 'Decoding',
77
+ 'EnumBinding',
78
+ 'Error',
79
+ 'EwkbGeography',
80
+ 'EwkbGeometry',
81
+ 'Executor',
82
+ 'HalfVector',
83
+ 'Identifier',
84
+ 'Infinity',
85
+ 'InheritType',
86
+ 'Interval',
87
+ 'Json',
88
+ 'JsonDocument',
89
+ 'KeyPasswordProvider',
90
+ 'KeyPasswordRequest',
91
+ 'Literal',
92
+ 'MultiRange',
93
+ 'Notification',
94
+ 'OAuthDiscovery',
95
+ 'OAuthProvider',
96
+ 'OAuthRequest',
97
+ 'PasswordProvider',
98
+ 'PasswordRequest',
99
+ 'PgBox',
100
+ 'PgCircle',
101
+ 'PgDate',
102
+ 'PgLine',
103
+ 'PgLineSegment',
104
+ 'PgPath',
105
+ 'PgPoint',
106
+ 'PgPolygon',
107
+ 'PgTime',
108
+ 'PgTimestamp',
109
+ 'PgValue',
110
+ 'Pool',
111
+ 'PoolStats',
112
+ 'PreparedStatement',
113
+ 'Query',
114
+ 'Range',
115
+ 'SparseVector',
116
+ 'SpatialParameter',
117
+ 'Transaction',
118
+ 'Vector',
119
+ 'and_',
120
+ 'assignments',
121
+ 'cast',
122
+ 'insert',
123
+ 'join',
124
+ 'or_',
125
+ 'raw_sql',
126
+ 'scalar',
127
+ 'values',
128
+ ]
gres/_adapters.py ADDED
@@ -0,0 +1,422 @@
1
+ """Immutable application bindings keyed by qualified PostgreSQL type, never by a process-global OID."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from dataclasses import KW_ONLY, dataclass
7
+ from enum import Enum
8
+ from functools import partial
9
+ from types import MappingProxyType
10
+ from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, TypeVar, cast
11
+
12
+ from gres import errors
13
+ from gres._array import Array
14
+ from gres._buffer import Buffer, snapshot
15
+ from gres._identifier import Identifier
16
+
17
+ if TYPE_CHECKING:
18
+ from gres._lib import ArrayElement, Entry, SessionHandle
19
+
20
+ _E = TypeVar('_E', bound=Enum)
21
+
22
+
23
+ @dataclass(frozen=True, slots=True, init=False, eq=False)
24
+ class EnumBinding(Generic[_E]):
25
+ """Bind a schema-qualified two-part `Identifier` for a PostgreSQL enum to a Python `Enum`.
26
+
27
+ Match members by `'name'`, by `'value'`, or via an explicit `{member: label}` mapping.
28
+ """
29
+
30
+ type: Identifier
31
+ enum: type[_E]
32
+ _by_member: Mapping[_E, str]
33
+ _by_label: Mapping[str, _E]
34
+
35
+ def __init__(
36
+ self,
37
+ type: Identifier,
38
+ enum: type[_E],
39
+ *,
40
+ labels: Literal['name', 'value'] | Mapping[_E, str],
41
+ ) -> None:
42
+ if not isinstance(type, Identifier) or len(type.parts) != 2: # pyright: ignore[reportUnnecessaryIsInstance] - validate untyped callers.
43
+ raise ValueError('enum binding requires a schema-qualified type')
44
+ if not issubclass(enum, Enum): # pyright: ignore[reportUnnecessaryIsInstance] - reject invalid declarations from untyped callers.
45
+ raise TypeError('enum binding requires an Enum class')
46
+ if isinstance(labels, Mapping):
47
+ mapping = dict(labels)
48
+ elif labels == 'name':
49
+ mapping = {member: member.name for member in enum}
50
+ elif labels == 'value':
51
+ mapping = {member: member.value for member in enum}
52
+ else:
53
+ raise ValueError('labels must be name, value, or a member-to-label mapping')
54
+ reverse: dict[str, _E] = {}
55
+ for member, label in mapping.items():
56
+ if member.__class__ is not enum or not isinstance(label, str): # pyright: ignore[reportUnnecessaryIsInstance] - runtime label contract includes untyped mappings and Enum.value.
57
+ raise ValueError(
58
+ 'enum labels must map members of the selected Enum to strings'
59
+ )
60
+ if label in reverse:
61
+ raise ValueError(
62
+ 'distinct enum members cannot have the same PostgreSQL label'
63
+ )
64
+ reverse[label] = member
65
+ object.__setattr__(self, 'type', type)
66
+ object.__setattr__(self, 'enum', enum)
67
+ object.__setattr__(self, '_by_member', MappingProxyType(mapping))
68
+ object.__setattr__(self, '_by_label', MappingProxyType(reverse))
69
+
70
+ def _decode(self, label: str) -> _E:
71
+ try:
72
+ return self._by_label[label]
73
+ except KeyError:
74
+ raise errors.DecodingError(
75
+ f'unmapped label {label!r} for {self.type._sql()}'
76
+ ) from None
77
+
78
+ def _encode(self, value: object) -> str:
79
+ if isinstance(value, self.enum) and value in self._by_member:
80
+ return self._by_member[value]
81
+ raise errors.EncodingError(
82
+ f'expected a mapped {self.enum.__qualname__} member for {self.type._sql()}'
83
+ )
84
+
85
+ def _bytes(self, value: object) -> bytes:
86
+ return self._encode(value).encode('utf-8')
87
+
88
+
89
+ _T = TypeVar('_T')
90
+
91
+
92
+ @dataclass(frozen=True, slots=True, eq=False)
93
+ class CompositeBinding(Generic[_T]):
94
+ """Bind a schema-qualified two-part `Identifier` for a PostgreSQL composite type to a Python factory.
95
+
96
+ Decoding passes SQL attributes to `factory` as keyword arguments. `fields`,
97
+ when given, maps `{sql_attr: python_kwarg}`; `encode`, when given, returns
98
+ `{sql_attr: value}`.
99
+ """
100
+
101
+ type: Identifier
102
+ factory: Callable[..., _T]
103
+ _: KW_ONLY
104
+ fields: Mapping[str, str] | None = None
105
+ encode: Callable[[_T], Mapping[str, object]] | None = None
106
+
107
+ def __post_init__(self) -> None:
108
+ if not isinstance(self.type, Identifier) or len(self.type.parts) != 2: # pyright: ignore[reportUnnecessaryIsInstance] - runtime boundary.
109
+ raise ValueError('composite binding requires a schema-qualified type')
110
+ if not callable(self.factory) or (
111
+ self.encode is not None and not callable(self.encode)
112
+ ):
113
+ raise TypeError('composite factory and encoder must be callable')
114
+ if self.fields is not None:
115
+ names = dict(self.fields)
116
+ if not all(
117
+ isinstance(k, str) and isinstance(v, str) # pyright: ignore[reportUnnecessaryIsInstance] - validate untyped mappings.
118
+ for k, v in names.items()
119
+ ):
120
+ raise TypeError('composite field names must be strings')
121
+ if len(set(names.values())) != len(names):
122
+ raise ValueError('duplicate composite field name')
123
+ object.__setattr__(self, 'fields', MappingProxyType(names))
124
+
125
+
126
+ _Native = TypeVar('_Native')
127
+
128
+
129
+ @dataclass(frozen=True, slots=True, eq=False)
130
+ class Adapter(Generic[_T, _Native]):
131
+ """Map an application value to or from the native Python representation of a SQL type.
132
+
133
+ `type` must be a schema-qualified two-part `Identifier`. Provide `decode`,
134
+ `encode`, or both; omitted directions use native conversion.
135
+ """
136
+
137
+ type: Identifier
138
+ python_type: type[_T]
139
+ _: KW_ONLY
140
+ decode: Callable[[_Native], _T] | None = None
141
+ encode: Callable[[_T], _Native] | None = None
142
+
143
+ def __post_init__(self) -> None:
144
+ _check_binding(self.type, self.python_type, self.encode, self.decode)
145
+
146
+
147
+ def _check_binding(
148
+ identity: object, python_type: object, encode: object, decode: object
149
+ ) -> None:
150
+ if not isinstance(identity, Identifier) or len(identity.parts) != 2:
151
+ raise ValueError('binding requires a schema-qualified type')
152
+ if not isinstance(python_type, type):
153
+ raise TypeError('python_type must be a class')
154
+ if encode is None and decode is None:
155
+ raise ValueError('binding requires an encoder or decoder')
156
+ if (encode is not None and not callable(encode)) or (
157
+ decode is not None and not callable(decode)
158
+ ):
159
+ raise TypeError('encoders and decoders must be callable')
160
+
161
+
162
+ @dataclass(frozen=True, slots=True, eq=False)
163
+ class Codec(Generic[_T]):
164
+ """Encode or decode raw field bytes in PostgreSQL `'text'` or `'binary'` format.
165
+
166
+ `type` must be a schema-qualified two-part `Identifier`. Provide `decode`,
167
+ `encode`, or both; omitted directions use native conversion.
168
+ """
169
+
170
+ type: Identifier
171
+ python_type: type[_T]
172
+ _: KW_ONLY
173
+ format: Literal['text', 'binary']
174
+ decode: Callable[[memoryview], _T] | None = None
175
+ encode: Callable[[_T], Buffer] | None = None
176
+
177
+ def __post_init__(self) -> None:
178
+ _check_binding(self.type, self.python_type, self.encode, self.decode)
179
+ if self.format not in ('text', 'binary'):
180
+ raise ValueError('codec format must be text or binary')
181
+
182
+ def _bytes(self, value: _T) -> bytes:
183
+ assert self.encode is not None
184
+ return snapshot(self.encode(value))
185
+
186
+ def _read(self, payload: bytes) -> _T:
187
+ assert self.decode is not None
188
+ return self.decode(memoryview(payload))
189
+
190
+
191
+ @dataclass(frozen=True, slots=True)
192
+ class WireBinding:
193
+ """One field's reached wire codec and optional array frame; planned independently per direction."""
194
+
195
+ codec: Codec[Any]
196
+ element: ArrayElement | None
197
+
198
+ @property
199
+ def binary(self) -> bool:
200
+ return self.codec.format == 'binary'
201
+
202
+ def parameter(self, value: object, limit: int | None) -> tuple[object, bool]:
203
+ if self.element is not None and not self.binary:
204
+ return self.element.encode_text(value, self.codec._bytes, limit=limit)
205
+ return self.encoder(limit)(value), False
206
+
207
+ def literal_encoder(self) -> Callable[[object], tuple[str, bool]]:
208
+ if self.binary:
209
+ raise errors.EncodingError(
210
+ f'{self.codec.type._sql()} requires a text encoder for SQL literals'
211
+ )
212
+ if self.element is not None:
213
+ return partial(self.element.encode_text, convert=self.codec._bytes)
214
+
215
+ def encode(value: object) -> tuple[str, bool]:
216
+ payload = self.codec._bytes(value)
217
+ try:
218
+ return payload.decode('utf-8'), False
219
+ except UnicodeDecodeError as exc:
220
+ raise errors.EncodingError('text codec did not produce UTF-8') from exc
221
+
222
+ return encode
223
+
224
+ def encoder(self, limit: int | None) -> Callable[[object], bytes]:
225
+ if self.element is None:
226
+ return self.codec._bytes
227
+ return partial(self.element.wire_codec(limit).encode, convert=self.codec._bytes)
228
+
229
+ def decoder(self, exact: bool) -> Callable[[bytes], object]:
230
+ if self.element is None:
231
+ return self.codec._read
232
+ if self.binary:
233
+ return partial(
234
+ self.element.wire_codec().decode,
235
+ exact=exact,
236
+ carrier=Array,
237
+ convert=self.codec._read,
238
+ )
239
+ return partial(
240
+ self.element.decode_text,
241
+ exact=exact,
242
+ carrier=Array,
243
+ convert=self.codec._read,
244
+ raw=True,
245
+ )
246
+
247
+
248
+ Binding: TypeAlias = (
249
+ EnumBinding[Any] | Codec[Any] | Adapter[Any, Any] | CompositeBinding[Any]
250
+ )
251
+
252
+ Transform: TypeAlias = Callable[[object], object]
253
+
254
+
255
+ def compose(first: Transform | None, second: Transform | None) -> Transform | None:
256
+ if first is None:
257
+ return second
258
+ if second is None:
259
+ return first
260
+ return lambda v: second(first(v))
261
+
262
+
263
+ def compose_input(first: Transform | None, second: Transform) -> Transform:
264
+ """An input adapter may lower its value to SQL NULL, bypassing the next encoder."""
265
+ if first is None:
266
+ return second
267
+ return lambda v: None if (lowered := first(v)) is None else second(lowered)
268
+
269
+
270
+ @dataclass(frozen=True, slots=True)
271
+ class FieldBinding:
272
+ """Reached application hooks for one direction, in structural order. A wire hook terminates descent."""
273
+
274
+ whole: Transform | None
275
+ leaf: Transform | None
276
+ wire: WireBinding | None
277
+
278
+ def input(self, entry: Entry) -> Transform | None:
279
+ if self.leaf is None:
280
+ return self.whole
281
+ element = entry.element
282
+ assert element is not None
283
+ return compose_input(
284
+ self.whole, partial(element.map_values, carrier=Array, convert=self.leaf)
285
+ )
286
+
287
+
288
+ ColumnBindings: TypeAlias = Mapping[str | int, Binding]
289
+
290
+
291
+ def column_bindings(selectors: ColumnBindings, names: list[str]) -> dict[int, Binding]:
292
+ """Resolve unique names and zero-based positions before catalog access or callbacks."""
293
+ positions: dict[str, int] = {}
294
+ for i, name in enumerate(names):
295
+ positions[name] = -1 if name in positions else i
296
+ result: dict[int, Binding] = {}
297
+ for key, binding in selectors.items():
298
+ i = positions.get(key, -1) if isinstance(key, str) else key
299
+ if type(i) is not int or not 0 <= i < len(names) or i in result:
300
+ raise errors.QueryShapeError(
301
+ f'invalid, ambiguous or repeated column adapter selector {key!r}'
302
+ )
303
+ if not isinstance(binding, (EnumBinding, Adapter, Codec, CompositeBinding)): # pyright: ignore[reportUnnecessaryIsInstance] - runtime admission for untyped callers.
304
+ raise TypeError('column adapter must be a type binding')
305
+ if isinstance(binding, (Adapter, Codec)) and binding.decode is None:
306
+ raise errors.UnsupportedTypeError('column adapter has no decoder')
307
+ result[i] = binding
308
+ return result
309
+
310
+
311
+ async def check_column_types(
312
+ backend: SessionHandle,
313
+ columns: dict[int, Binding],
314
+ oids: list[int],
315
+ catalog: dict[int, Entry],
316
+ ) -> None:
317
+ """A different qualified identity must be a domain over the reported type, not a lookalike."""
318
+ unresolved = {
319
+ b.type.parts
320
+ for i, b in columns.items()
321
+ if b.type.parts != catalog[oids[i]].parts
322
+ }
323
+ if not unresolved:
324
+ return
325
+ # Parameterize the names. Only generated parameter positions enter the query text.
326
+ names = sorted(unresolved)
327
+ pairs = ','.join(
328
+ f'(${i * 2 + 1}::pg_catalog.text,${i * 2 + 2}::pg_catalog.text)'
329
+ for i in range(len(names))
330
+ )
331
+ rows = await backend.catalog(
332
+ f'SELECT n.nspname,t.typname,t.typtype,pg_catalog.pg_basetype(t.oid)::pg_catalog.oid FROM (VALUES {pairs}) AS q(ns,typ) JOIN pg_catalog.pg_namespace n ON n.nspname::pg_catalog.text=q.ns JOIN pg_catalog.pg_type t ON t.typnamespace=n.oid AND t.typname::pg_catalog.text=q.typ',
333
+ [part for qualified in names for part in qualified],
334
+ )
335
+ identities: dict[tuple[str, str], tuple[str | None, int]] = {}
336
+ for ns, name, kind, base in rows:
337
+ assert ns is not None and name is not None and base is not None
338
+ identities[ns, name] = (kind, int(base))
339
+ for i, binding in columns.items():
340
+ parts = binding.type.parts
341
+ if parts == catalog[oids[i]].parts:
342
+ continue
343
+ found = identities.get((parts[0], parts[1]))
344
+ if found is None:
345
+ raise errors.UnsupportedTypeError(
346
+ f'unknown column adapter type {binding.type._sql()}'
347
+ )
348
+ if found != ('d', oids[i]) or isinstance(binding, EnumBinding):
349
+ raise errors.UnsupportedTypeError(
350
+ f'{binding.type._sql()} is incompatible with result column {i}'
351
+ )
352
+
353
+
354
+ class BindingsByType:
355
+ """A resource or operation's selected declarations. Omitted overrides inherit; empty overrides replace."""
356
+
357
+ def __init__(self, bindings: Sequence[Binding]) -> None:
358
+ self.by_name = {b.type.parts: b for b in bindings}
359
+ if len(self.by_name) != len(bindings):
360
+ raise ValueError('duplicate binding for a PostgreSQL type')
361
+
362
+ def field(
363
+ self, entry: Entry, *, output: bool, override: Binding | None = None
364
+ ) -> FieldBinding | None:
365
+ whole = leaf = None
366
+ element = entry.element
367
+ for target in (entry, element):
368
+ if target is None:
369
+ break
370
+ b = (override if target is entry else None) or self.by_name.get(
371
+ target.parts
372
+ )
373
+ if b is None:
374
+ continue
375
+ if isinstance(b, CompositeBinding):
376
+ if target.kind != 'c':
377
+ raise errors.UnsupportedTypeError(
378
+ f'{b.type._sql()} is not a PostgreSQL composite'
379
+ )
380
+ # The record codec compiles names and construction with the live attribute list.
381
+ continue
382
+ if isinstance(b, EnumBinding):
383
+ if target.kind != 'e':
384
+ raise errors.UnsupportedTypeError(
385
+ f'{b.type._sql()} is not a PostgreSQL enum'
386
+ )
387
+ hook: Transform | None = (
388
+ cast('Transform', b._decode) if output else b._encode
389
+ )
390
+ else:
391
+ if (b.decode if output else b.encode) is None:
392
+ continue
393
+ if isinstance(b, Codec):
394
+ binary = b.format == 'binary'
395
+ for io in (entry.io, target.io):
396
+ supported = (
397
+ (io.binary_output if binary else io.text_output)
398
+ if output
399
+ else (io.binary_input if binary else io.text_input)
400
+ )
401
+ if not supported:
402
+ raise errors.UnsupportedTypeError(
403
+ f'{b.type._sql()} does not support {b.format} in this direction'
404
+ )
405
+ return FieldBinding(
406
+ whole,
407
+ None,
408
+ WireBinding(b, element if target is element else None),
409
+ )
410
+ hook = b.decode if output else b.encode
411
+ if target is entry:
412
+ whole = hook
413
+ else:
414
+ leaf = hook
415
+ return (
416
+ FieldBinding(whole, leaf, None)
417
+ if whole is not None or leaf is not None
418
+ else None
419
+ )
420
+
421
+ def select(self, override: Sequence[Binding] | None) -> BindingsByType:
422
+ return self if override is None else BindingsByType(override)
gres/_array.py ADDED
@@ -0,0 +1,40 @@
1
+ """Shape-preserving PostgreSQL arrays. The flat values are in database element order."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Generic, TypeAlias, TypeVar, cast
7
+
8
+ from gres._lib import array_dimensions, array_to_list
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterable, Sequence
12
+
13
+ _T_co = TypeVar('_T_co', covariant=True)
14
+ _Nested: TypeAlias = '_T_co | list[_Nested[_T_co]]'
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, init=False)
18
+ class Array(Generic[_T_co]):
19
+ """Shape-preserving PostgreSQL array owning flat elements, dimension lengths, and lower bounds. Empty arrays have no axes."""
20
+
21
+ values: tuple[_T_co, ...]
22
+ dimensions: tuple[int, ...]
23
+ lower_bounds: tuple[int, ...]
24
+
25
+ def __init__(
26
+ self,
27
+ values: Iterable[_T_co],
28
+ *,
29
+ dimensions: Sequence[int] | None = None,
30
+ lower_bounds: Sequence[int] | None = None,
31
+ ) -> None:
32
+ flat = tuple(values)
33
+ shape, bounds = array_dimensions(len(flat), dimensions, lower_bounds)
34
+ object.__setattr__(self, 'values', flat)
35
+ object.__setattr__(self, 'dimensions', shape)
36
+ object.__setattr__(self, 'lower_bounds', bounds)
37
+
38
+ def to_list(self) -> list[_Nested[_T_co]]:
39
+ """Return nested lists in storage order, deliberately discarding lower bounds."""
40
+ return cast('list[_Nested[_T_co]]', array_to_list(self.values, self.dimensions))
gres/_arrow.py ADDED
@@ -0,0 +1,85 @@
1
+ """Expose the fixed result schema and transfer ownership of each native batch to arro3."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Callable
6
+ from typing import TYPE_CHECKING
7
+
8
+ from gres import errors
9
+ from gres._resource import SessionResource
10
+
11
+ if TYPE_CHECKING:
12
+ from arro3.core import RecordBatch, Schema
13
+ from arro3.core.types import ArrowArrayExportable
14
+
15
+ from gres._arrow_schema import ResultSchema
16
+
17
+
18
+ class Prefetched(AsyncIterator['ArrowArrayExportable']):
19
+ """Deliver a batch read ahead of the consumer, then continue with its source.
20
+
21
+ `None` stands for an empty result; the source is not read again after it ends.
22
+ """
23
+
24
+ def __init__(
25
+ self, first: RecordBatch | None, rest: AsyncIterator[ArrowArrayExportable]
26
+ ) -> None:
27
+ self._first = first
28
+ self._rest = None if first is None else rest
29
+
30
+ async def __anext__(self) -> ArrowArrayExportable:
31
+ if (first := self._first) is not None:
32
+ self._first = None
33
+ return first
34
+ if self._rest is None:
35
+ raise StopAsyncIteration
36
+ return await anext(self._rest)
37
+
38
+
39
+ class ArrowStream(SessionResource, AsyncIterator['RecordBatch']):
40
+ """Arrow record batches of one query, read inside its `async with` block.
41
+
42
+ Obtained from `Executor.stream_arrow()`; not constructed directly. The
43
+ schema and any batches already delivered remain valid after the block exits.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ reader: AsyncIterator[ArrowArrayExportable],
49
+ schema: Schema,
50
+ conversion: ResultSchema | None,
51
+ first_result: Callable[[], None] | None,
52
+ ) -> None:
53
+ from arro3.core import RecordBatch
54
+
55
+ self._import = RecordBatch.from_arrow
56
+ self._schema = schema
57
+ self._reader: AsyncIterator[ArrowArrayExportable] | None = reader
58
+ self._conversion = conversion
59
+ self._first_result = first_result
60
+
61
+ @property
62
+ def schema(self) -> Schema:
63
+ """The PostgreSQL projection's Arrow schema, including for an empty result."""
64
+ return self._schema
65
+
66
+ def __arrow_c_schema__(self) -> object:
67
+ """Export the stream schema through the Arrow PyCapsule interface."""
68
+ return self._schema.__arrow_c_schema__()
69
+
70
+ async def __anext__(self) -> RecordBatch:
71
+ if self._reader is None:
72
+ raise errors.InterfaceError('result stream is closed')
73
+ batch = await anext(self._reader)
74
+ if self._reader is None: # pyright: ignore[reportUnnecessaryComparison] - context exit may run during await.
75
+ raise errors.InterfaceError('result stream is closed')
76
+ record = self._import(batch)
77
+ if self._conversion is not None:
78
+ record = self._conversion.convert(record)
79
+ if self._first_result is not None:
80
+ self._first_result()
81
+ self._first_result = None
82
+ return record
83
+
84
+ def _release(self) -> None:
85
+ self._reader = self._conversion = self._first_result = None