PyGreSQL 6.1.0__cp313-cp313-win32.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.
pg/adapt.py ADDED
@@ -0,0 +1,686 @@
1
+ """Adaptation of parameters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import weakref
6
+ from datetime import date, datetime, time, timedelta
7
+ from decimal import Decimal
8
+ from json import dumps as jsonencode
9
+ from math import isinf, isnan
10
+ from re import compile as regex
11
+ from types import MappingProxyType
12
+ from typing import TYPE_CHECKING, Any, Callable, List, Mapping, Sequence
13
+ from uuid import UUID
14
+
15
+ from .attrs import AttrDict
16
+ from .cast import Typecasts
17
+ from .core import InterfaceError, ProgrammingError
18
+ from .helpers import quote_if_unqualified
19
+
20
+ if TYPE_CHECKING:
21
+ from .db import DB
22
+
23
+ __all__ = [
24
+ 'UUID',
25
+ 'Adapter',
26
+ 'Bytea',
27
+ 'DbType',
28
+ 'DbTypes',
29
+ 'Hstore',
30
+ 'Json',
31
+ 'Literal'
32
+ ]
33
+
34
+
35
+ class Bytea(bytes):
36
+ """Wrapper class for marking Bytea values."""
37
+
38
+
39
+ class Hstore(dict):
40
+ """Wrapper class for marking hstore values."""
41
+
42
+ _re_quote = regex('^[Nn][Uu][Ll][Ll]$|[ ,=>]')
43
+
44
+ @classmethod
45
+ def _quote(cls, s: Any) -> str:
46
+ if s is None:
47
+ return 'NULL'
48
+ if not isinstance(s, str):
49
+ s = str(s)
50
+ if not s:
51
+ return '""'
52
+ s = s.replace('"', '\\"')
53
+ if cls._re_quote.search(s):
54
+ s = f'"{s}"'
55
+ return s
56
+
57
+ def __str__(self) -> str:
58
+ """Create a printable representation of the hstore value."""
59
+ q = self._quote
60
+ return ','.join(f'{q(k)}=>{q(v)}' for k, v in self.items())
61
+
62
+
63
+ class Json:
64
+ """Wrapper class for marking Json values."""
65
+
66
+ def __init__(self, obj: Any,
67
+ encode: Callable[[Any], str] | None = None) -> None:
68
+ """Initialize the JSON object."""
69
+ self.obj = obj
70
+ self.encode = encode or jsonencode
71
+
72
+ def __str__(self) -> str:
73
+ """Create a printable representation of the JSON object."""
74
+ obj = self.obj
75
+ if isinstance(obj, str):
76
+ return obj
77
+ return self.encode(obj)
78
+
79
+
80
+ class Literal(str):
81
+ """Wrapper class for marking literal SQL values."""
82
+
83
+
84
+
85
+ class _SimpleTypes(dict):
86
+ """Dictionary mapping pg_type names to simple type names.
87
+
88
+ The corresponding Python types and simple names are also mapped.
89
+ """
90
+
91
+ _type_aliases: Mapping[str, list[str | type]] = MappingProxyType({
92
+ 'bool': [bool],
93
+ 'bytea': [Bytea],
94
+ 'date': ['interval', 'time', 'timetz', 'timestamp', 'timestamptz',
95
+ 'abstime', 'reltime', # these are very old
96
+ 'datetime', 'timedelta', # these do not really exist
97
+ date, time, datetime, timedelta],
98
+ 'float': ['float4', 'float8', float],
99
+ 'int': ['cid', 'int2', 'int4', 'int8', 'oid', 'xid', int],
100
+ 'hstore': [Hstore], 'json': ['jsonb', Json], 'uuid': [UUID],
101
+ 'num': ['numeric', Decimal], 'money': [],
102
+ 'text': ['bpchar', 'char', 'name', 'varchar', bytes, str]
103
+ })
104
+
105
+ # noinspection PyMissingConstructor
106
+ def __init__(self) -> None:
107
+ """Initialize type mapping."""
108
+ for typ, keys in self._type_aliases.items():
109
+ keys = [typ, *keys]
110
+ for key in keys:
111
+ self[key] = typ
112
+ if isinstance(key, str):
113
+ self[f'_{key}'] = f'{typ}[]'
114
+ elif not isinstance(key, tuple):
115
+ self[List[key]] = f'{typ}[]' # type: ignore
116
+
117
+ @staticmethod
118
+ def __missing__(key: str) -> str:
119
+ """Unmapped types are interpreted as text."""
120
+ return 'text'
121
+
122
+ def get_type_dict(self) -> dict[type, str]:
123
+ """Get a plain dictionary of only the types."""
124
+ return {key: typ for key, typ in self.items()
125
+ if not isinstance(key, (str, tuple))}
126
+
127
+
128
+ _simpletypes = _SimpleTypes()
129
+ _simple_type_dict = _simpletypes.get_type_dict()
130
+
131
+
132
+ class _ParameterList(list):
133
+ """Helper class for building typed parameter lists."""
134
+
135
+ adapt: Callable
136
+
137
+ def add(self, value: Any, typ:Any = None) -> str:
138
+ """Typecast value with known database type and build parameter list.
139
+
140
+ If this is a literal value, it will be returned as is. Otherwise, a
141
+ placeholder will be returned and the parameter list will be augmented.
142
+ """
143
+ # noinspection PyUnresolvedReferences
144
+ value = self.adapt(value, typ)
145
+ if isinstance(value, Literal):
146
+ return value
147
+ self.append(value)
148
+ return f'${len(self)}'
149
+
150
+
151
+
152
+ class DbType(str):
153
+ """Class augmenting the simple type name with additional info.
154
+
155
+ The following additional information is provided:
156
+
157
+ oid: the PostgreSQL type OID
158
+ pgtype: the internal PostgreSQL data type name
159
+ regtype: the registered PostgreSQL data type name
160
+ simple: the more coarse-grained PyGreSQL type name
161
+ typlen: the internal size, negative if variable
162
+ typtype: b = base type, c = composite type etc.
163
+ category: A = Array, b = Boolean, C = Composite etc.
164
+ delim: delimiter for array types
165
+ relid: corresponding table for composite types
166
+ attnames: attributes for composite types
167
+ """
168
+
169
+ oid: int
170
+ pgtype: str
171
+ regtype: str
172
+ simple: str
173
+ typlen: int
174
+ typtype: str
175
+ category: str
176
+ delim: str
177
+ relid: int
178
+
179
+ _get_attnames: Callable[[DbType], AttrDict]
180
+
181
+ @property
182
+ def attnames(self) -> AttrDict:
183
+ """Get names and types of the fields of a composite type."""
184
+ # noinspection PyUnresolvedReferences
185
+ return self._get_attnames(self)
186
+
187
+
188
+ class DbTypes(dict):
189
+ """Cache for PostgreSQL data types.
190
+
191
+ This cache maps type OIDs and names to DbType objects containing
192
+ information on the associated database type.
193
+ """
194
+
195
+ _num_types = frozenset('int float num money int2 int4 int8'
196
+ ' float4 float8 numeric money'.split())
197
+
198
+ def __init__(self, db: DB) -> None:
199
+ """Initialize type cache for connection."""
200
+ super().__init__()
201
+ self._db = weakref.proxy(db)
202
+ self._regtypes = False
203
+ self._typecasts = Typecasts()
204
+ self._typecasts.get_attnames = self.get_attnames # type: ignore
205
+ self._typecasts.connection = self._db.db
206
+ self._query_pg_type = (
207
+ "SELECT oid, typname, oid::pg_catalog.regtype,"
208
+ " typlen, typtype, typcategory, typdelim, typrelid"
209
+ " FROM pg_catalog.pg_type"
210
+ " WHERE oid OPERATOR(pg_catalog.=) {}::pg_catalog.regtype")
211
+
212
+ def add(self, oid: int, pgtype: str, regtype: str,
213
+ typlen: int, typtype: str, category: str, delim: str, relid: int
214
+ ) -> DbType:
215
+ """Create a PostgreSQL type name with additional info."""
216
+ if oid in self:
217
+ return self[oid]
218
+ simple = 'record' if relid else _simpletypes[pgtype]
219
+ typ = DbType(regtype if self._regtypes else simple)
220
+ typ.oid = oid
221
+ typ.simple = simple
222
+ typ.pgtype = pgtype
223
+ typ.regtype = regtype
224
+ typ.typlen = typlen
225
+ typ.typtype = typtype
226
+ typ.category = category
227
+ typ.delim = delim
228
+ typ.relid = relid
229
+ typ._get_attnames = self.get_attnames # type: ignore
230
+ return typ
231
+
232
+ def __missing__(self, key: int | str) -> DbType:
233
+ """Get the type info from the database if it is not cached."""
234
+ try:
235
+ cmd = self._query_pg_type.format(quote_if_unqualified('$1', key))
236
+ res = self._db.query(cmd, (key,)).getresult()
237
+ except ProgrammingError:
238
+ res = None
239
+ if not res:
240
+ raise KeyError(f'Type {key} could not be found')
241
+ res = res[0]
242
+ typ = self.add(*res)
243
+ self[typ.oid] = self[typ.pgtype] = typ
244
+ return typ
245
+
246
+ def get(self, key: int | str, # type: ignore
247
+ default: DbType | None = None) -> DbType | None:
248
+ """Get the type even if it is not cached."""
249
+ try:
250
+ return self[key]
251
+ except KeyError:
252
+ return default
253
+
254
+ def get_attnames(self, typ: Any) -> AttrDict | None:
255
+ """Get names and types of the fields of a composite type."""
256
+ if not isinstance(typ, DbType):
257
+ typ = self.get(typ)
258
+ if not typ:
259
+ return None
260
+ if not typ.relid:
261
+ return None
262
+ return self._db.get_attnames(typ.relid, with_oid=False)
263
+
264
+ def get_typecast(self, typ: Any) -> Callable | None:
265
+ """Get the typecast function for the given database type."""
266
+ return self._typecasts.get(typ)
267
+
268
+ def set_typecast(self, typ: str | Sequence[str], cast: Callable) -> None:
269
+ """Set a typecast function for the specified database type(s)."""
270
+ self._typecasts.set(typ, cast)
271
+
272
+ def reset_typecast(self, typ: str | Sequence[str] | None = None) -> None:
273
+ """Reset the typecast function for the specified database type(s)."""
274
+ self._typecasts.reset(typ)
275
+
276
+ def typecast(self, value: Any, typ: str) -> Any:
277
+ """Cast the given value according to the given database type."""
278
+ if value is None:
279
+ # for NULL values, no typecast is necessary
280
+ return None
281
+ if not isinstance(typ, DbType):
282
+ db_type = self.get(typ)
283
+ if db_type:
284
+ typ = db_type.pgtype
285
+ cast = self.get_typecast(typ) if typ else None
286
+ if not cast or cast is str:
287
+ # no typecast is necessary
288
+ return value
289
+ return cast(value)
290
+
291
+
292
+ class Adapter:
293
+ """Class providing methods for adapting parameters to the database."""
294
+
295
+ _bool_true_values = frozenset('t true 1 y yes on'.split())
296
+
297
+ _date_literals = frozenset(
298
+ 'current_date current_time'
299
+ ' current_timestamp localtime localtimestamp'.split())
300
+
301
+ _re_array_quote = regex(r'[{},"\\\s]|^[Nn][Uu][Ll][Ll]$')
302
+ _re_record_quote = regex(r'[(,"\\]')
303
+ _re_array_escape = _re_record_escape = regex(r'(["\\])')
304
+
305
+ def __init__(self, db: DB):
306
+ """Initialize the adapter object with the given connection."""
307
+ self.db = weakref.proxy(db)
308
+
309
+ @classmethod
310
+ def _adapt_bool(cls, v: Any) -> str | None:
311
+ """Adapt a boolean parameter."""
312
+ if isinstance(v, str):
313
+ if not v:
314
+ return None
315
+ v = v.lower() in cls._bool_true_values
316
+ return 't' if v else 'f'
317
+
318
+ @classmethod
319
+ def _adapt_date(cls, v: Any) -> Any:
320
+ """Adapt a date parameter."""
321
+ if not v:
322
+ return None
323
+ if isinstance(v, str) and v.lower() in cls._date_literals:
324
+ return Literal(v)
325
+ return v
326
+
327
+ @staticmethod
328
+ def _adapt_num(v: Any) -> Any:
329
+ """Adapt a numeric parameter."""
330
+ if not v and v != 0:
331
+ return None
332
+ return v
333
+
334
+ _adapt_int = _adapt_float = _adapt_money = _adapt_num
335
+
336
+ def _adapt_bytea(self, v: Any) -> str:
337
+ """Adapt a bytea parameter."""
338
+ return self.db.escape_bytea(v)
339
+
340
+ def _adapt_json(self, v: Any) -> str | None:
341
+ """Adapt a json parameter."""
342
+ if v is None:
343
+ return None
344
+ if isinstance(v, str):
345
+ return v
346
+ if isinstance(v, Json):
347
+ return str(v)
348
+ return self.db.encode_json(v)
349
+
350
+ def _adapt_hstore(self, v: Any) -> str | None:
351
+ """Adapt a hstore parameter."""
352
+ if not v:
353
+ return None
354
+ if isinstance(v, str):
355
+ return v
356
+ if isinstance(v, Hstore):
357
+ return str(v)
358
+ if isinstance(v, dict):
359
+ return str(Hstore(v))
360
+ raise TypeError(f'Hstore parameter {v} has wrong type')
361
+
362
+ def _adapt_uuid(self, v: Any) -> str | None:
363
+ """Adapt a UUID parameter."""
364
+ if not v:
365
+ return None
366
+ if isinstance(v, str):
367
+ return v
368
+ return str(v)
369
+
370
+ @classmethod
371
+ def _adapt_text_array(cls, v: Any) -> str:
372
+ """Adapt a text type array parameter."""
373
+ if isinstance(v, list):
374
+ adapt = cls._adapt_text_array
375
+ return '{' + ','.join(adapt(v) for v in v) + '}'
376
+ if v is None:
377
+ return 'null'
378
+ if not v:
379
+ return '""'
380
+ v = str(v)
381
+ if cls._re_array_quote.search(v):
382
+ v = cls._re_array_escape.sub(r'\\\1', v)
383
+ v = f'"{v}"'
384
+ return v
385
+
386
+ _adapt_date_array = _adapt_text_array
387
+
388
+ @classmethod
389
+ def _adapt_bool_array(cls, v: Any) -> str:
390
+ """Adapt a boolean array parameter."""
391
+ if isinstance(v, list):
392
+ adapt = cls._adapt_bool_array
393
+ return '{' + ','.join(adapt(v) for v in v) + '}'
394
+ if v is None:
395
+ return 'null'
396
+ if isinstance(v, str):
397
+ if not v:
398
+ return 'null'
399
+ v = v.lower() in cls._bool_true_values
400
+ return 't' if v else 'f'
401
+
402
+ @classmethod
403
+ def _adapt_num_array(cls, v: Any) -> str:
404
+ """Adapt a numeric array parameter."""
405
+ if isinstance(v, list):
406
+ adapt = cls._adapt_num_array
407
+ v = '{' + ','.join(adapt(v) for v in v) + '}'
408
+ if not v and v != 0:
409
+ return 'null'
410
+ return str(v)
411
+
412
+ _adapt_int_array = _adapt_float_array = _adapt_money_array = \
413
+ _adapt_num_array
414
+
415
+ def _adapt_bytea_array(self, v: Any) -> bytes:
416
+ """Adapt a bytea array parameter."""
417
+ if isinstance(v, list):
418
+ return b'{' + b','.join(
419
+ self._adapt_bytea_array(v) for v in v) + b'}'
420
+ if v is None:
421
+ return b'null'
422
+ return self.db.escape_bytea(v).replace(b'\\', b'\\\\')
423
+
424
+ def _adapt_json_array(self, v: Any) -> str:
425
+ """Adapt a json array parameter."""
426
+ if isinstance(v, list):
427
+ adapt = self._adapt_json_array
428
+ return '{' + ','.join(adapt(v) for v in v) + '}'
429
+ if not v:
430
+ return 'null'
431
+ if not isinstance(v, str):
432
+ v = self.db.encode_json(v)
433
+ if self._re_array_quote.search(v):
434
+ v = self._re_array_escape.sub(r'\\\1', v)
435
+ v = f'"{v}"'
436
+ return v
437
+
438
+ def _adapt_record(self, v: Any, typ: Any) -> str:
439
+ """Adapt a record parameter with given type."""
440
+ typ = self.get_attnames(typ).values()
441
+ if len(typ) != len(v):
442
+ raise TypeError(f'Record parameter {v} has wrong size')
443
+ adapt = self.adapt
444
+ value = []
445
+ for v, t in zip(v, typ): # noqa: B020
446
+ v = adapt(v, t)
447
+ if v is None:
448
+ v = ''
449
+ else:
450
+ if isinstance(v, bytes):
451
+ v = v.decode('ascii')
452
+ elif not isinstance(v, str):
453
+ v = str(v)
454
+ if v:
455
+ if self._re_record_quote.search(v):
456
+ v = self._re_record_escape.sub(r'\\\1', v)
457
+ v = f'"{v}"'
458
+ else:
459
+ v = '""'
460
+ value.append(v)
461
+ v = ','.join(value)
462
+ return f'({v})'
463
+
464
+ def adapt(self, value: Any, typ: Any = None) -> str:
465
+ """Adapt a value with known database type."""
466
+ if value is not None and not isinstance(value, Literal):
467
+ if typ:
468
+ simple = self.get_simple_name(typ)
469
+ else:
470
+ typ = simple = self.guess_simple_type(value) or 'text'
471
+ pg_str = getattr(value, '__pg_str__', None)
472
+ if pg_str:
473
+ value = pg_str(typ)
474
+ if simple == 'text':
475
+ pass
476
+ elif simple == 'record':
477
+ if isinstance(value, tuple):
478
+ value = self._adapt_record(value, typ)
479
+ elif simple.endswith('[]'):
480
+ if isinstance(value, list):
481
+ adapt = getattr(self, f'_adapt_{simple[:-2]}_array')
482
+ value = adapt(value)
483
+ else:
484
+ adapt = getattr(self, f'_adapt_{simple}')
485
+ value = adapt(value)
486
+ return value
487
+
488
+ @staticmethod
489
+ def simple_type(name: str) -> DbType:
490
+ """Create a simple database type with given attribute names."""
491
+ typ = DbType(name)
492
+ typ.simple = name
493
+ return typ
494
+
495
+ @staticmethod
496
+ def get_simple_name(typ: Any) -> str:
497
+ """Get the simple name of a database type."""
498
+ if isinstance(typ, DbType):
499
+ # noinspection PyUnresolvedReferences
500
+ return typ.simple
501
+ return _simpletypes[typ]
502
+
503
+ @staticmethod
504
+ def get_attnames(typ: Any) -> dict[str, dict[str, str]]:
505
+ """Get the attribute names of a composite database type."""
506
+ if isinstance(typ, DbType):
507
+ return typ.attnames
508
+ return {}
509
+
510
+ @classmethod
511
+ def guess_simple_type(cls, value: Any) -> str | None:
512
+ """Try to guess which database type the given value has."""
513
+ # optimize for most frequent types
514
+ try:
515
+ return _simple_type_dict[type(value)]
516
+ except KeyError:
517
+ pass
518
+ if isinstance(value, (bytes, str)):
519
+ return 'text'
520
+ if isinstance(value, bool):
521
+ return 'bool'
522
+ if isinstance(value, int):
523
+ return 'int'
524
+ if isinstance(value, float):
525
+ return 'float'
526
+ if isinstance(value, Decimal):
527
+ return 'num'
528
+ if isinstance(value, (date, time, datetime, timedelta)):
529
+ return 'date'
530
+ if isinstance(value, Bytea):
531
+ return 'bytea'
532
+ if isinstance(value, Json):
533
+ return 'json'
534
+ if isinstance(value, Hstore):
535
+ return 'hstore'
536
+ if isinstance(value, UUID):
537
+ return 'uuid'
538
+ if isinstance(value, list):
539
+ return (cls.guess_simple_base_type(value) or 'text') + '[]'
540
+ if isinstance(value, tuple):
541
+ simple_type = cls.simple_type
542
+ guess = cls.guess_simple_type
543
+
544
+ # noinspection PyUnusedLocal
545
+ def get_attnames(self: DbType) -> AttrDict:
546
+ return AttrDict((str(n + 1), simple_type(guess(v) or 'text'))
547
+ for n, v in enumerate(value))
548
+
549
+ typ = simple_type('record')
550
+ typ._get_attnames = get_attnames
551
+ return typ
552
+ return None
553
+
554
+ @classmethod
555
+ def guess_simple_base_type(cls, value: Any) -> str | None:
556
+ """Try to guess the base type of a given array."""
557
+ for v in value:
558
+ if isinstance(v, list):
559
+ typ = cls.guess_simple_base_type(v)
560
+ else:
561
+ typ = cls.guess_simple_type(v)
562
+ if typ:
563
+ return typ
564
+ return None
565
+
566
+ def adapt_inline(self, value: Any, nested: bool=False) -> Any:
567
+ """Adapt a value that is put into the SQL and needs to be quoted."""
568
+ if value is None:
569
+ return 'NULL'
570
+ if isinstance(value, Literal):
571
+ return value
572
+ if isinstance(value, Bytea):
573
+ value = self.db.escape_bytea(value).decode('ascii')
574
+ elif isinstance(value, (datetime, date, time, timedelta)):
575
+ value = str(value)
576
+ if isinstance(value, (bytes, str)):
577
+ value = self.db.escape_string(value)
578
+ return f"'{value}'"
579
+ if isinstance(value, bool):
580
+ return 'true' if value else 'false'
581
+ if isinstance(value, float):
582
+ if isinf(value):
583
+ return "'-Infinity'" if value < 0 else "'Infinity'"
584
+ if isnan(value):
585
+ return "'NaN'"
586
+ return value
587
+ if isinstance(value, (int, Decimal)):
588
+ return value
589
+ if isinstance(value, list):
590
+ q = self.adapt_inline
591
+ s = '[{}]' if nested else 'ARRAY[{}]'
592
+ return s.format(','.join(str(q(v, nested=True)) for v in value))
593
+ if isinstance(value, tuple):
594
+ q = self.adapt_inline
595
+ return '({})'.format(','.join(str(q(v)) for v in value))
596
+ if isinstance(value, Json):
597
+ value = self.db.escape_string(str(value))
598
+ return f"'{value}'::json"
599
+ if isinstance(value, Hstore):
600
+ value = self.db.escape_string(str(value))
601
+ return f"'{value}'::hstore"
602
+ pg_repr = getattr(value, '__pg_repr__', None)
603
+ if not pg_repr:
604
+ raise InterfaceError(
605
+ f'Do not know how to adapt type {type(value)}')
606
+ value = pg_repr()
607
+ if isinstance(value, (tuple, list)):
608
+ value = self.adapt_inline(value)
609
+ return value
610
+
611
+ def parameter_list(self) -> _ParameterList:
612
+ """Return a parameter list for parameters with known database types.
613
+
614
+ The list has an add(value, typ) method that will build up the
615
+ list and return either the literal value or a placeholder.
616
+ """
617
+ params = _ParameterList()
618
+ params.adapt = self.adapt
619
+ return params
620
+
621
+ def format_query(self, command: str,
622
+ values: list | tuple | dict | None = None,
623
+ types: list | tuple | dict | None = None,
624
+ inline: bool=False
625
+ ) -> tuple[str, _ParameterList]:
626
+ """Format a database query using the given values and types.
627
+
628
+ The optional types describe the values and must be passed as a list,
629
+ tuple or string (that will be split on whitespace) when values are
630
+ passed as a list or tuple, or as a dict if values are passed as a dict.
631
+
632
+ If inline is set to True, then parameters will be passed inline
633
+ together with the query string.
634
+ """
635
+ params = self.parameter_list()
636
+ if not values:
637
+ return command, params
638
+ if inline and types:
639
+ raise ValueError('Typed parameters must be sent separately')
640
+ if isinstance(values, (list, tuple)):
641
+ if inline:
642
+ adapt = self.adapt_inline
643
+ seq_literals = [adapt(value) for value in values]
644
+ else:
645
+ add = params.add
646
+ if types:
647
+ if isinstance(types, str):
648
+ types = types.split()
649
+ if (not isinstance(types, (list, tuple))
650
+ or len(types) != len(values)):
651
+ raise TypeError('The values and types do not match')
652
+ seq_literals = [add(value, typ)
653
+ for value, typ in zip(values, types)]
654
+ else:
655
+ seq_literals = [add(value) for value in values]
656
+ command %= tuple(seq_literals)
657
+ elif isinstance(values, dict):
658
+ # we want to allow extra keys in the dictionary,
659
+ # so we first must find the values actually used in the command
660
+ used_values = {}
661
+ map_literals = dict.fromkeys(values, '')
662
+ for key in values:
663
+ del map_literals[key]
664
+ try:
665
+ command % map_literals
666
+ except KeyError:
667
+ used_values[key] = values[key] # pyright: ignore
668
+ map_literals[key] = ''
669
+ if inline:
670
+ adapt = self.adapt_inline
671
+ map_literals = {key: adapt(value)
672
+ for key, value in used_values.items()}
673
+ else:
674
+ add = params.add
675
+ if types:
676
+ if not isinstance(types, dict):
677
+ raise TypeError('The values and types do not match')
678
+ map_literals = {key: add(used_values[key], types.get(key))
679
+ for key in sorted(used_values)}
680
+ else:
681
+ map_literals = {key: add(used_values[key])
682
+ for key in sorted(used_values)}
683
+ command %= map_literals
684
+ else:
685
+ raise TypeError('The values must be passed as tuple, list or dict')
686
+ return command, params