PyGreSQL 6.3.0b1__cp315-cp315-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.
pgdb/cast.py ADDED
@@ -0,0 +1,775 @@
1
+ """Internal type handling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import namedtuple
6
+ from collections.abc import Callable, Sequence
7
+ from datetime import date, datetime, time, timedelta
8
+ from decimal import Decimal as _Decimal
9
+ from functools import partial
10
+ from inspect import signature
11
+ from json import loads as jsondecode
12
+ from keyword import iskeyword
13
+ from re import compile as regex
14
+ from typing import Any, ClassVar, NamedTuple
15
+ from uuid import UUID as Uuid # noqa: N811
16
+
17
+ from pg.cast import cast_cidr, cast_inet
18
+ from pg.core import Connection as Cnx
19
+ from pg.core import (
20
+ cast_array,
21
+ cast_hstore,
22
+ cast_record,
23
+ unescape_bytea,
24
+ )
25
+ from pg.helpers import is_array_type, type_lookup_condition
26
+
27
+ from .typecode import TypeCode
28
+
29
+ __all__ = [
30
+ 'Decimal',
31
+ 'FieldInfo',
32
+ 'LocalTypecasts',
33
+ 'TypeCache',
34
+ 'Typecasts',
35
+ 'cast_bool',
36
+ 'cast_cidr',
37
+ 'cast_date',
38
+ 'cast_inet',
39
+ 'cast_int2vector',
40
+ 'cast_interval',
41
+ 'cast_money',
42
+ 'cast_time',
43
+ 'cast_timestamp',
44
+ 'cast_timestamptz',
45
+ 'cast_timetz',
46
+ 'decimal_type',
47
+ 'get_typecast',
48
+ 'reset_typecast',
49
+ 'set_typecast'
50
+ ]
51
+
52
+
53
+ Decimal: type = _Decimal
54
+
55
+
56
+ def get_args(func: Callable) -> list:
57
+ return list(signature(func).parameters)
58
+
59
+
60
+ # time zones used in Postgres timestamptz output
61
+ _timezones: dict[str, str] = {
62
+ 'CET': '+0100', 'EET': '+0200', 'EST': '-0500',
63
+ 'GMT': '+0000', 'HST': '-1000', 'MET': '+0100', 'MST': '-0700',
64
+ 'UCT': '+0000', 'UTC': '+0000', 'WET': '+0000'
65
+ }
66
+
67
+
68
+ def _timezone_as_offset(tz: str) -> str:
69
+ if tz.startswith(('+', '-')):
70
+ if len(tz) < 5:
71
+ return tz + '00'
72
+ return tz.replace(':', '')
73
+ return _timezones.get(tz, '+0000')
74
+
75
+
76
+ def decimal_type(decimal_type: type | None = None) -> type:
77
+ """Get or set global type to be used for decimal values.
78
+
79
+ Note that connections cache cast functions. To be sure a global change
80
+ is picked up by a running connection, call con.type_cache.reset_typecast().
81
+ """
82
+ global Decimal
83
+ if decimal_type is not None:
84
+ Decimal = decimal_type
85
+ set_typecast('numeric', decimal_type)
86
+ return Decimal
87
+
88
+
89
+ def cast_bool(value: str) -> bool | None:
90
+ """Cast boolean value in database format to bool."""
91
+ return value[0] in ('t', 'T') if value else None
92
+
93
+
94
+ def cast_money(value: str) -> _Decimal | None:
95
+ """Cast money value in database format to Decimal."""
96
+ if not value:
97
+ return None
98
+ value = value.replace('(', '-')
99
+ return Decimal(''.join(c for c in value if c.isdigit() or c in '.-'))
100
+
101
+
102
+ def cast_int2vector(value: str) -> list[int]:
103
+ """Cast an int2vector value."""
104
+ return [int(v) for v in value.split()]
105
+
106
+
107
+ def cast_date(value: str, cnx: Cnx) -> date:
108
+ """Cast a date value."""
109
+ # The output format depends on the server setting DateStyle. The default
110
+ # setting ISO and the setting for German are actually unambiguous. The
111
+ # order of days and months in the other two settings is however ambiguous,
112
+ # so at least here we need to consult the setting to properly parse values.
113
+ if value == '-infinity':
114
+ return date.min
115
+ if value == 'infinity':
116
+ return date.max
117
+ values = value.split()
118
+ if values[-1] == 'BC':
119
+ return date.min
120
+ value = values[0]
121
+ if len(value) > 10:
122
+ return date.max
123
+ format = cnx.date_format()
124
+ return datetime.strptime(value, format).date()
125
+
126
+
127
+ def cast_time(value: str) -> time:
128
+ """Cast a time value."""
129
+ fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
130
+ return datetime.strptime(value, fmt).time()
131
+
132
+
133
+ _re_timezone = regex('(.*)([+-].*)')
134
+ _re_placeholder = regex(r'\$(\d)')
135
+ _re_placeholder_bytes = regex(rb'\$(\d)')
136
+
137
+
138
+ def cast_timetz(value: str) -> time:
139
+ """Cast a timetz value."""
140
+ m = _re_timezone.match(value)
141
+ if m:
142
+ value, tz = m.groups()
143
+ else:
144
+ tz = '+0000'
145
+ format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
146
+ value += _timezone_as_offset(tz)
147
+ format += '%z'
148
+ return datetime.strptime(value, format).timetz()
149
+
150
+
151
+ def cast_timestamp(value: str, cnx: Cnx) -> datetime:
152
+ """Cast a timestamp value."""
153
+ if value == '-infinity':
154
+ return datetime.min
155
+ if value == 'infinity':
156
+ return datetime.max
157
+ values = value.split()
158
+ if values[-1] == 'BC':
159
+ return datetime.min
160
+ format = cnx.date_format()
161
+ if format.endswith('-%Y') and len(values) > 2:
162
+ values = values[1:5]
163
+ if len(values[3]) > 4:
164
+ return datetime.max
165
+ formats = ['%d %b' if format.startswith('%d') else '%b %d',
166
+ '%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
167
+ else:
168
+ if len(values[0]) > 10:
169
+ return datetime.max
170
+ formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
171
+ return datetime.strptime(' '.join(values), ' '.join(formats))
172
+
173
+
174
+ def cast_timestamptz(value: str, cnx: Cnx) -> datetime:
175
+ """Cast a timestamptz value."""
176
+ if value == '-infinity':
177
+ return datetime.min
178
+ if value == 'infinity':
179
+ return datetime.max
180
+ values = value.split()
181
+ if values[-1] == 'BC':
182
+ return datetime.min
183
+ format = cnx.date_format()
184
+ if format.endswith('-%Y') and len(values) > 2:
185
+ values = values[1:]
186
+ if len(values[3]) > 4:
187
+ return datetime.max
188
+ formats = ['%d %b' if format.startswith('%d') else '%b %d',
189
+ '%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
190
+ values, tz = values[:-1], values[-1]
191
+ else:
192
+ if format.startswith('%Y-'):
193
+ m = _re_timezone.match(values[1])
194
+ if m:
195
+ values[1], tz = m.groups()
196
+ else:
197
+ tz = '+0000'
198
+ else:
199
+ values, tz = values[:-1], values[-1]
200
+ if len(values[0]) > 10:
201
+ return datetime.max
202
+ formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
203
+ values.append(_timezone_as_offset(tz))
204
+ formats.append('%z')
205
+ return datetime.strptime(' '.join(values), ' '.join(formats))
206
+
207
+
208
+ _re_interval_sql_standard = regex(
209
+ '(?:([+-])?([0-9]+)-([0-9]+) ?)?'
210
+ '(?:([+-]?[0-9]+)(?!:) ?)?'
211
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
212
+
213
+ _re_interval_postgres = regex(
214
+ '(?:([+-]?[0-9]+) ?years? ?)?'
215
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
216
+ '(?:([+-]?[0-9]+) ?days? ?)?'
217
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
218
+
219
+ _re_interval_postgres_verbose = regex(
220
+ '@ ?(?:([+-]?[0-9]+) ?years? ?)?'
221
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
222
+ '(?:([+-]?[0-9]+) ?days? ?)?'
223
+ '(?:([+-]?[0-9]+) ?hours? ?)?'
224
+ '(?:([+-]?[0-9]+) ?mins? ?)?'
225
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
226
+
227
+ _re_interval_iso_8601 = regex(
228
+ 'P(?:([+-]?[0-9]+)Y)?'
229
+ '(?:([+-]?[0-9]+)M)?'
230
+ '(?:([+-]?[0-9]+)D)?'
231
+ '(?:T(?:([+-]?[0-9]+)H)?'
232
+ '(?:([+-]?[0-9]+)M)?'
233
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
234
+
235
+
236
+ def cast_interval(value: str) -> timedelta:
237
+ """Cast an interval value."""
238
+ # The output format depends on the server setting IntervalStyle, but it's
239
+ # not necessary to consult this setting to parse it. It's faster to just
240
+ # check all possible formats, and there is no ambiguity here.
241
+ if value == 'infinity': # possible since PostgreSQL 17
242
+ return timedelta.max
243
+ if value == '-infinity':
244
+ return timedelta.min
245
+ m = _re_interval_iso_8601.match(value)
246
+ if m:
247
+ s = [v or '0' for v in m.groups()]
248
+ secs_ago = s.pop(5) == '-'
249
+ d = [int(v) for v in s]
250
+ years, mons, days, hours, mins, secs, usecs = d
251
+ if secs_ago:
252
+ secs = -secs
253
+ usecs = -usecs
254
+ else:
255
+ m = _re_interval_postgres_verbose.match(value)
256
+ if m:
257
+ s, ago = [v or '0' for v in m.groups()[:8]], m.group(9)
258
+ secs_ago = s.pop(5) == '-'
259
+ d = [-int(v) for v in s] if ago else [int(v) for v in s]
260
+ years, mons, days, hours, mins, secs, usecs = d
261
+ if secs_ago:
262
+ secs = - secs
263
+ usecs = -usecs
264
+ else:
265
+ m = _re_interval_postgres.match(value)
266
+ if m and any(m.groups()):
267
+ s = [v or '0' for v in m.groups()]
268
+ hours_ago = s.pop(3) == '-'
269
+ d = [int(v) for v in s]
270
+ years, mons, days, hours, mins, secs, usecs = d
271
+ if hours_ago:
272
+ hours = -hours
273
+ mins = -mins
274
+ secs = -secs
275
+ usecs = -usecs
276
+ else:
277
+ m = _re_interval_sql_standard.match(value)
278
+ if m and any(m.groups()):
279
+ s = [v or '0' for v in m.groups()]
280
+ years_ago = s.pop(0) == '-'
281
+ hours_ago = s.pop(3) == '-'
282
+ d = [int(v) for v in s]
283
+ years, mons, days, hours, mins, secs, usecs = d
284
+ if years_ago:
285
+ years = -years
286
+ mons = -mons
287
+ if hours_ago:
288
+ hours = -hours
289
+ mins = -mins
290
+ secs = -secs
291
+ usecs = -usecs
292
+ else:
293
+ raise ValueError(f'Cannot parse interval: {value}')
294
+ days += 365 * years + 30 * mons
295
+ return timedelta(days=days, hours=hours, minutes=mins,
296
+ seconds=secs, microseconds=usecs)
297
+
298
+
299
+ class Typecasts(dict):
300
+ """Dictionary mapping database types to typecast functions.
301
+
302
+ The cast functions get passed the string representation of a value in
303
+ the database which they need to convert to a Python object. The
304
+ passed string will never be None since NULL values are already
305
+ handled before the cast function is called.
306
+ """
307
+
308
+ # the default cast functions
309
+ # (str functions are ignored but have been added for faster access)
310
+ defaults: ClassVar[dict[str, Callable]] = {
311
+ 'char': str, 'bpchar': str, 'name': str,
312
+ 'text': str, 'varchar': str, 'sql_identifier': str,
313
+ 'bool': cast_bool, 'bytea': unescape_bytea,
314
+ 'int2': int, 'int4': int, 'serial': int, 'int8': int, 'oid': int,
315
+ 'oid8': int,
316
+ 'hstore': cast_hstore, 'json': jsondecode, 'jsonb': jsondecode,
317
+ 'float4': float, 'float8': float,
318
+ 'numeric': Decimal, 'money': cast_money,
319
+ 'date': cast_date, 'interval': cast_interval,
320
+ 'time': cast_time, 'timetz': cast_timetz,
321
+ 'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
322
+ 'int2vector': cast_int2vector, 'uuid': Uuid,
323
+ 'anyarray': cast_array, 'record': cast_record}
324
+
325
+ cnx: Cnx | None = None # for local connection specific instances
326
+
327
+ # incremented when the global typecasts change, so that connections can
328
+ # drop the typecasts they have derived from the old global typecasts
329
+ defaults_changed: ClassVar[int] = 0
330
+
331
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
332
+ """Initialize the typecasts."""
333
+ super().__init__(*args, **kwargs)
334
+ self._records: set[str] = set() # types with cached record casts
335
+
336
+ def _drop_record_casts(self) -> None:
337
+ """Drop the cached casts for composite types.
338
+
339
+ These casts use the casts for their fields, which may change.
340
+ They will be created again when needed.
341
+ """
342
+ for typ in self._records:
343
+ self.pop(typ, None)
344
+ self._records.clear()
345
+
346
+ def __missing__(self, typ: str) -> Callable | None:
347
+ """Create a cast function if it is not cached.
348
+
349
+ Note that this class never raises a KeyError,
350
+ but returns None when no special cast function exists.
351
+ """
352
+ if not isinstance(typ, str):
353
+ raise TypeError(f'Invalid type: {typ}')
354
+ cast = self.defaults.get(typ)
355
+ if cast:
356
+ # store default for faster access
357
+ cast = self._add_connection(cast)
358
+ self[typ] = cast
359
+ elif typ.startswith('_'):
360
+ # create array cast, but do not cache it, since
361
+ # the name might not be the name of an array type
362
+ cast = self.create_array_cast(self[typ[1:]])
363
+ return cast
364
+
365
+ @staticmethod
366
+ def _connection_arg(func: Callable) -> str | None:
367
+ """Get the name of the connection argument of a typecast function.
368
+
369
+ Like in the pg module, the argument is named 'connection'. The name
370
+ 'cnx' used by the built-in typecast functions is also accepted.
371
+ """
372
+ try:
373
+ args = get_args(func)[1:]
374
+ except (TypeError, ValueError):
375
+ return None
376
+ for name in ('connection', 'cnx'):
377
+ if name in args:
378
+ return name
379
+ return None
380
+
381
+ def _add_connection(self, cast: Callable) -> Callable:
382
+ """Add a connection argument to the typecast function if necessary."""
383
+ if not self.cnx:
384
+ return cast
385
+ name = self._connection_arg(cast)
386
+ if not name:
387
+ return cast
388
+ return partial(cast, **{name: self.cnx})
389
+
390
+ def get(self, typ: str, default: Callable | None = None # type: ignore[override]
391
+ ) -> Callable | None:
392
+ """Get the typecast function for the given database type."""
393
+ return self[typ] or default
394
+
395
+ def set(self, typ: str | Sequence[str], cast: Callable | None) -> None:
396
+ """Set a typecast function for the specified database type(s)."""
397
+ self._drop_record_casts()
398
+ if isinstance(typ, str):
399
+ typ = [typ]
400
+ if cast is None:
401
+ for t in typ:
402
+ self.pop(t, None)
403
+ else:
404
+ if not callable(cast):
405
+ raise TypeError("Cast parameter must be callable")
406
+ for t in typ:
407
+ self[t] = self._add_connection(cast)
408
+
409
+ def reset(self, typ: str | Sequence[str] | None = None) -> None:
410
+ """Reset the typecasts for the specified type(s) to their defaults.
411
+
412
+ When no type is specified, all typecasts will be reset.
413
+ """
414
+ self._drop_record_casts()
415
+ if typ is None:
416
+ # the defaults will be fetched and bound again when needed
417
+ self.clear()
418
+ else:
419
+ if isinstance(typ, str):
420
+ typ = [typ]
421
+ for t in typ:
422
+ cast = self._get_default(t)
423
+ if cast:
424
+ self[t] = self._add_connection(cast)
425
+ else:
426
+ self.pop(t, None)
427
+
428
+ def _get_default(self, typ: str) -> Callable | None:
429
+ """Get the default typecast that has been set for the given type.
430
+
431
+ Array casts are not derived from the names of the element types,
432
+ since the names might not be the names of array types.
433
+ """
434
+ defaults = self.defaults
435
+ if typ in defaults:
436
+ return defaults[typ]
437
+ if typ.startswith('_'):
438
+ return None
439
+ return defaults.get(typ)
440
+
441
+ def create_array_cast(self, basecast: Callable | None,
442
+ delim: str = ',') -> Callable:
443
+ """Create an array typecast for the given base cast and delimiter."""
444
+ cast_array = self['anyarray']
445
+ # values that cannot be decoded are passed as bytes, keep them
446
+ elemcast = None if basecast is str else basecast
447
+
448
+ if delim != ',':
449
+ delim_bytes = delim.encode('ascii')
450
+
451
+ def cast(v: Any) -> list:
452
+ return cast_array(v, elemcast, delim_bytes)
453
+ else:
454
+ def cast(v: Any) -> list:
455
+ return cast_array(v, elemcast)
456
+ return cast
457
+
458
+ def create_record_cast(self, name: str, fields: Sequence[str],
459
+ casts: Sequence[Callable | None]) -> Callable:
460
+ """Create a named record typecast for the given fields and casts."""
461
+ cast_record = self['record']
462
+ if not name.isidentifier() or iskeyword(name):
463
+ name = 'Record' # the type name cannot be used in Python
464
+ # field names that cannot be used in Python are renamed
465
+ record = namedtuple(name, fields, rename=True) # type: ignore[misc]
466
+ # values that cannot be decoded are passed as bytes, keep them
467
+ fieldcasts = [None if c is str else c for c in casts]
468
+
469
+ def cast(v: Any) -> record:
470
+ # noinspection PyArgumentList
471
+ return record(*cast_record(v, fieldcasts))
472
+ return cast
473
+
474
+
475
+ _typecasts = Typecasts() # this is the global typecast dictionary
476
+
477
+
478
+ def is_builtin_typecast(typ: str, cast: Callable | None) -> bool:
479
+ """Check whether this is the built-in default typecast for the type.
480
+
481
+ The built-in default typecasts are made for the base types of
482
+ PostgreSQL. They should not be used for composite types, domains,
483
+ enums and ranges that happen to have the same name in another schema,
484
+ unlike typecasts that have been set explicitly for the name.
485
+ """
486
+ if isinstance(cast, partial): # with an added connection
487
+ cast = cast.func
488
+ return cast is not None and cast is Typecasts.defaults.get(typ)
489
+
490
+
491
+ def get_typecast(typ: str) -> Callable | None:
492
+ """Get the global typecast function for the given database type."""
493
+ return _typecasts.get(typ)
494
+
495
+
496
+ def set_typecast(typ: str | Sequence[str], cast: Callable | None) -> None:
497
+ """Set a global typecast function for the given database type(s).
498
+
499
+ Note that connections cache cast functions. To be sure a global change
500
+ is picked up by a running connection, call con.type_cache.reset_typecast().
501
+ """
502
+ _typecasts.set(typ, cast)
503
+ Typecasts.defaults_changed += 1
504
+
505
+
506
+ def reset_typecast(typ: str | Sequence[str] | None = None) -> None:
507
+ """Reset the global typecasts for the given type(s) to their default.
508
+
509
+ When no type is specified, all typecasts will be reset.
510
+
511
+ Note that connections cache cast functions. To be sure a global change
512
+ is picked up by a running connection, call con.type_cache.reset_typecast().
513
+ """
514
+ _typecasts.reset(typ)
515
+ Typecasts.defaults_changed += 1
516
+
517
+
518
+ class LocalTypecasts(Typecasts):
519
+ """Map typecasts, including local composite types, to cast functions."""
520
+
521
+ defaults = _typecasts
522
+
523
+ cnx: Cnx | None = None # set in connection specific instances
524
+
525
+ def __missing__(self, typ: str) -> Callable | None:
526
+ """Create a cast function if it is not cached."""
527
+ if not isinstance(typ, str):
528
+ raise TypeError(f'Invalid type: {typ}')
529
+ cast: Callable | None = self._get_default(typ)
530
+ if cast:
531
+ cast = self._add_connection(cast)
532
+ self[typ] = cast
533
+ elif typ.startswith('_'):
534
+ # create array cast, but do not cache it, since
535
+ # the name might not be the name of an array type
536
+ cast = self.create_array_cast(self[typ[1:]])
537
+ else:
538
+ fields = self.get_fields(typ)
539
+ if fields:
540
+ casts = [self[field.type] for field in fields]
541
+ field_names = [field.name for field in fields]
542
+ cast = self.create_record_cast(typ, field_names, casts)
543
+ self[typ] = cast
544
+ self._records.add(typ)
545
+ return cast
546
+
547
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
548
+ def get_fields(self, typ: str) -> list[FieldInfo]:
549
+ """Return the fields for the given record type.
550
+
551
+ This method can be overridden in subclasses to support casting
552
+ composite types by name. Connections do not use it, since the
553
+ TypeCache creates the typecasts for composite types from their
554
+ type codes.
555
+ """
556
+ return []
557
+
558
+
559
+ class FieldInfo(NamedTuple):
560
+ """Name and type of a field of a composite type."""
561
+
562
+ name: str
563
+ type: TypeCode | None
564
+
565
+
566
+ class TypeCache(dict):
567
+ """Cache for database types.
568
+
569
+ This cache maps type OIDs and names to TypeCode strings containing
570
+ important information on the associated database type.
571
+ """
572
+
573
+ def __init__(self, cnx: Cnx) -> None:
574
+ """Initialize type cache for connection."""
575
+ super().__init__()
576
+ self._escape_string = cnx.escape_string
577
+ self._src = cnx.source()
578
+ self._typecasts = LocalTypecasts()
579
+ self._typecasts.cnx = cnx
580
+ # typecasts for type codes, cached by OID
581
+ self._type_casts: dict[int, Callable | None] = {}
582
+ self._defaults_changed = Typecasts.defaults_changed
583
+ self._query_pg_type = (
584
+ "SELECT t.oid, t.typname, t.typlen, t.typtype, t.typcategory,"
585
+ " t.typdelim, t.typrelid, t.typbasetype, t.typelem,"
586
+ " (SELECT e.typtype FROM pg_catalog.pg_type e"
587
+ " WHERE e.oid OPERATOR(pg_catalog.=) t.typelem)"
588
+ " FROM pg_catalog.pg_type t WHERE {}")
589
+
590
+ def __missing__(self, key: int | str | bytes) -> TypeCode:
591
+ """Get the type info from the database if it is not cached."""
592
+ try:
593
+ condition, params = type_lookup_condition(key)
594
+ except ValueError:
595
+ res = None
596
+ else:
597
+ # the source object does not support parameters
598
+ cmd = self._query_pg_type.format(condition)
599
+ if isinstance(key, bytes): # raw name in the client encoding
600
+ raw_values = [b"'" + self._escape_string(param) + b"'"
601
+ for param in params if isinstance(param, bytes)]
602
+ self._src.execute(_re_placeholder_bytes.sub(
603
+ lambda m: raw_values[int(m.group(1)) - 1],
604
+ cmd.encode('ascii')))
605
+ else:
606
+ values = [str(param) if isinstance(param, int)
607
+ else f"'{self._escape_string(param)}'"
608
+ for param in params if not isinstance(param, bytes)]
609
+ self._src.execute(_re_placeholder.sub(
610
+ lambda m: values[int(m.group(1)) - 1], cmd))
611
+ res = self._src.fetch(1)
612
+ if not res:
613
+ raise KeyError(f'Type {key!r} could not be found')
614
+ r = res[0]
615
+ oid = int(r[0])
616
+ if oid in self: # already cached under another name
617
+ type_code = self[oid]
618
+ else:
619
+ delim, relid, elem, base = r[5], int(r[6]), int(r[8]), None
620
+ elem_type = r[9] or '' # the type of the element type
621
+ if r[3] == 'd' and int(r[7]):
622
+ # domains are handled like their base types
623
+ base = self[int(r[7])]
624
+ base = base.base or base # resolve domains over domains
625
+ delim, relid, elem = base.delim, base.relid, base.elem
626
+ elem_type = base._elem_type
627
+ type_code = TypeCode.create(
628
+ oid, r[1], int(r[2]), r[3], r[4], delim, relid, base, elem)
629
+ type_code._elem_type = elem_type
630
+ # a type found by OID is not cached under its name, since this name
631
+ # could refer to a different type that comes first in the search path
632
+ self[type_code.oid] = self[key] = type_code
633
+ return type_code
634
+
635
+ def get(self, key: int | str, # type: ignore[override]
636
+ default: TypeCode | None = None) -> TypeCode | None:
637
+ """Get the type even if it is not cached."""
638
+ try:
639
+ return self[key]
640
+ except KeyError:
641
+ return default
642
+
643
+ def get_fields(self, typ: int | str | TypeCode) -> list[FieldInfo] | None:
644
+ """Get the names and types of the fields of composite types."""
645
+ if isinstance(typ, TypeCode):
646
+ relid = typ.relid
647
+ else:
648
+ type_code = self.get(typ)
649
+ if not type_code:
650
+ return None
651
+ relid = type_code.relid
652
+ if not relid:
653
+ return None # this type is not composite
654
+ self._src.execute(
655
+ "SELECT attname, atttypid" # noqa: S608
656
+ " FROM pg_catalog.pg_attribute"
657
+ f" WHERE attrelid OPERATOR(pg_catalog.=) {relid}"
658
+ " AND attnum OPERATOR(pg_catalog.>) 0"
659
+ " AND NOT attisdropped ORDER BY attnum")
660
+ return [FieldInfo(name, self.get(int(oid)))
661
+ for name, oid in self._src.fetch(-1)]
662
+
663
+ def _get_named_cast(self, typ: str) -> Callable | None:
664
+ """Get the typecast function set for the given type name.
665
+
666
+ Returns None if no typecast and no default has been set for it.
667
+ Typecasts for arrays are never derived from the name here.
668
+ """
669
+ typecasts = self._typecasts
670
+ if typ in typecasts:
671
+ return typecasts[typ]
672
+ cast = typecasts._get_default(typ)
673
+ return typecasts[typ] if cast else None # bind and cache it
674
+
675
+ def _get_cast(self, typ: TypeCode) -> Callable | None:
676
+ """Get the typecast function for the given type code.
677
+
678
+ A typecast set for the name of the type is used first, but the
679
+ built-in default typecasts only for base types. Otherwise,
680
+ the typecast is created from the base type of domains, the fields
681
+ of composite types or the element type of arrays. These are
682
+ looked up by their OIDs, not by their names, which might be
683
+ ambiguous. The result is cached under the OID of the type until
684
+ typecasts are set or reset.
685
+ """
686
+ type_casts = self._type_casts
687
+ if self._defaults_changed != Typecasts.defaults_changed:
688
+ # the typecasts may depend on changed global typecasts
689
+ type_casts.clear()
690
+ self._defaults_changed = Typecasts.defaults_changed
691
+ oid = typ.oid
692
+ try:
693
+ return type_casts[oid]
694
+ except KeyError:
695
+ pass
696
+ name = str(typ)
697
+ cast = self._get_named_cast(name)
698
+ if cast and typ.type not in 'bp' and is_builtin_typecast(name, cast):
699
+ # built-in typecasts are only used for base types
700
+ cast = None
701
+ if not cast:
702
+ cast = self._create_cast(typ)
703
+ type_casts[oid] = cast
704
+ return cast
705
+
706
+ def _create_cast(self, typ: TypeCode) -> Callable | None:
707
+ """Create a typecast function from the structure of the given type."""
708
+ if typ.base:
709
+ # domains are cast like their base types,
710
+ # unless a typecast has been set for the domain
711
+ return self._get_cast(typ.base)
712
+ typecasts = self._typecasts
713
+ if typ.relid:
714
+ fields = self.get_fields(typ)
715
+ if not fields:
716
+ return None
717
+ casts = [self._get_cast(field.type) if field.type else None
718
+ for field in fields]
719
+ field_names = [field.name for field in fields]
720
+ return typecasts.create_record_cast(str(typ), field_names, casts)
721
+ if is_array_type(str(typ), typ.len, typ.elem):
722
+ elem_type = self.get(typ.elem)
723
+ if not elem_type: # pragma: no cover (always exists)
724
+ return typecasts.create_array_cast(None)
725
+ return typecasts.create_array_cast(
726
+ self._get_cast(elem_type), elem_type.delim)
727
+ return None
728
+
729
+ def get_typecast(self, typ: int | str | TypeCode) -> Callable | None:
730
+ """Get the typecast function for the given database type."""
731
+ if isinstance(typ, TypeCode) and hasattr(typ, 'oid'):
732
+ return self._get_cast(typ)
733
+ if isinstance(typ, str):
734
+ cast = self._get_named_cast(typ)
735
+ if cast:
736
+ return cast
737
+ type_code = self.get(typ)
738
+ if type_code:
739
+ return self._get_cast(type_code)
740
+ return self._typecasts[typ] if isinstance(typ, str) else None
741
+
742
+ def set_typecast(self, typ: str | Sequence[str],
743
+ cast: Callable | None) -> None:
744
+ """Set a typecast function for the specified database type(s)."""
745
+ self._typecasts.set(typ, cast)
746
+ self._type_casts.clear()
747
+
748
+ def reset_typecast(self, typ: str | Sequence[str] | None = None) -> None:
749
+ """Reset the typecast function for the specified database type(s)."""
750
+ self._typecasts.reset(typ)
751
+ self._type_casts.clear()
752
+
753
+ def typecast(self, value: Any, typ: int | str | TypeCode) -> Any:
754
+ """Cast the given value according to the given database type."""
755
+ if value is None:
756
+ # for NULL values, no typecast is necessary
757
+ return None
758
+ cast = self.get_typecast(typ)
759
+ if cast is None or cast is str:
760
+ # no typecast is necessary
761
+ return value
762
+ return cast(value)
763
+
764
+ def get_row_caster(self, types: Sequence[int | str | TypeCode]
765
+ ) -> Callable:
766
+ """Get a typecast function for a complete row of values."""
767
+ get_typecast = self.get_typecast
768
+ casts = [get_typecast(typ) for typ in types]
769
+ casts = [cast if cast is not str else None for cast in casts]
770
+
771
+ def row_caster(row: Sequence) -> Sequence:
772
+ return [value if cast is None or value is None else cast(value)
773
+ for cast, value in zip(casts, row, strict=True)]
774
+
775
+ return row_caster