PyGreSQL 5.2.5__cp311-cp311-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.
pg.py ADDED
@@ -0,0 +1,2857 @@
1
+ #!/usr/bin/python
2
+ #
3
+ # PyGreSQL - a Python interface for the PostgreSQL database.
4
+ #
5
+ # This file contains the classic pg module.
6
+ #
7
+ # Copyright (c) 2023 by the PyGreSQL Development Team
8
+ #
9
+ # The notification handler is based on pgnotify which is
10
+ # Copyright (c) 2001 Ng Pheng Siong. All rights reserved.
11
+ #
12
+ # Please see the LICENSE.TXT file for specific restrictions.
13
+
14
+ """PyGreSQL classic interface.
15
+
16
+ This pg module implements some basic database management stuff.
17
+ It includes the _pg module and builds on it, providing the higher
18
+ level wrapper class named DB with additional functionality.
19
+ This is known as the "classic" ("old style") PyGreSQL interface.
20
+ For a DB-API 2 compliant interface use the newer pgdb module.
21
+ """
22
+
23
+ from __future__ import print_function, division
24
+
25
+ try:
26
+ from _pg import *
27
+ except ImportError as e:
28
+ import os
29
+ libpq = 'libpq.'
30
+ if os.name == 'nt':
31
+ libpq += 'dll'
32
+ import sys
33
+ paths = [path for path in os.environ["PATH"].split(os.pathsep)
34
+ if os.path.exists(os.path.join(path, libpq))]
35
+ if sys.version_info >= (3, 8):
36
+ # see https://docs.python.org/3/whatsnew/3.8.html#ctypes
37
+ for path in paths:
38
+ with os.add_dll_directory(os.path.abspath(path)):
39
+ try:
40
+ from _pg import *
41
+ except ImportError:
42
+ pass
43
+ else:
44
+ e = None
45
+ break
46
+ if paths:
47
+ libpq = 'compatible ' + libpq
48
+ else:
49
+ libpq += 'so'
50
+ if e:
51
+ # note: we could use "raise from e" here in Python 3
52
+ raise ImportError(
53
+ "Cannot import shared library for PyGreSQL,\n"
54
+ "probably because no %s is installed.\n%s" % (libpq, e))
55
+
56
+ __version__ = version
57
+
58
+ __all__ = [
59
+ 'DB', 'Adapter',
60
+ 'NotificationHandler', 'Typecasts',
61
+ 'Bytea', 'Hstore', 'Json', 'Literal',
62
+ 'Error', 'Warning',
63
+ 'DataError', 'DatabaseError',
64
+ 'IntegrityError', 'InterfaceError', 'InternalError',
65
+ 'InvalidResultError', 'MultipleResultsError',
66
+ 'NoResultError', 'NotSupportedError',
67
+ 'OperationalError', 'ProgrammingError',
68
+ 'INV_READ', 'INV_WRITE',
69
+ 'POLLING_OK', 'POLLING_FAILED', 'POLLING_READING', 'POLLING_WRITING',
70
+ 'SEEK_CUR', 'SEEK_END', 'SEEK_SET',
71
+ 'TRANS_ACTIVE', 'TRANS_IDLE', 'TRANS_INERROR',
72
+ 'TRANS_INTRANS', 'TRANS_UNKNOWN',
73
+ 'cast_array', 'cast_hstore', 'cast_record',
74
+ 'connect', 'escape_bytea', 'escape_string', 'unescape_bytea',
75
+ 'get_array', 'get_bool', 'get_bytea_escaped',
76
+ 'get_datestyle', 'get_decimal', 'get_decimal_point',
77
+ 'get_defbase', 'get_defhost', 'get_defopt', 'get_defport', 'get_defuser',
78
+ 'get_jsondecode', 'get_typecast',
79
+ 'set_array', 'set_bool', 'set_bytea_escaped',
80
+ 'set_datestyle', 'set_decimal', 'set_decimal_point',
81
+ 'set_defbase', 'set_defhost', 'set_defopt',
82
+ 'set_defpasswd', 'set_defport', 'set_defuser',
83
+ 'set_jsondecode', 'set_query_helpers', 'set_typecast',
84
+ 'version', '__version__']
85
+
86
+ import select
87
+ import warnings
88
+ import weakref
89
+
90
+ from datetime import date, time, datetime, timedelta, tzinfo
91
+ from decimal import Decimal
92
+ from math import isnan, isinf
93
+ from collections import namedtuple, OrderedDict
94
+ from operator import itemgetter
95
+ from functools import partial
96
+ from re import compile as regex
97
+ from json import loads as jsondecode, dumps as jsonencode
98
+ from uuid import UUID
99
+
100
+ try:
101
+ # noinspection PyUnresolvedReferences
102
+ from typing import Dict, List, Union # noqa: F401
103
+ has_typing = True
104
+ except ImportError: # Python < 3.5
105
+ has_typing = False
106
+
107
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
108
+ long
109
+ except NameError: # Python >= 3.0
110
+ long = int
111
+
112
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
113
+ unicode
114
+ except NameError: # Python >= 3.0
115
+ unicode = str
116
+
117
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
118
+ basestring
119
+ except NameError: # Python >= 3.0
120
+ basestring = (str, bytes)
121
+
122
+ try:
123
+ from functools import lru_cache
124
+ except ImportError: # Python < 3.2
125
+ from functools import update_wrapper
126
+ try: # noinspection PyCompatibility
127
+ from _thread import RLock
128
+ except ImportError:
129
+ class RLock: # for builds without threads
130
+ def __enter__(self):
131
+ pass
132
+
133
+ def __exit__(self, exctype, excinst, exctb):
134
+ pass
135
+
136
+ def lru_cache(maxsize=128):
137
+ """Simplified functools.lru_cache decorator for one argument."""
138
+
139
+ def decorator(function):
140
+ sentinel = object()
141
+ cache = {}
142
+ get = cache.get
143
+ lock = RLock()
144
+ root = []
145
+ root_full = [root, False]
146
+ root[:] = [root, root, None, None]
147
+
148
+ if maxsize == 0:
149
+
150
+ def wrapper(arg):
151
+ res = function(arg)
152
+ return res
153
+
154
+ elif maxsize is None:
155
+
156
+ def wrapper(arg):
157
+ res = get(arg, sentinel)
158
+ if res is not sentinel:
159
+ return res
160
+ res = function(arg)
161
+ cache[arg] = res
162
+ return res
163
+
164
+ else:
165
+
166
+ def wrapper(arg):
167
+ with lock:
168
+ link = get(arg)
169
+ if link is not None:
170
+ root = root_full[0]
171
+ prv, nxt, _arg, res = link
172
+ prv[1] = nxt
173
+ nxt[0] = prv
174
+ last = root[0]
175
+ last[1] = root[0] = link
176
+ link[0] = last
177
+ link[1] = root
178
+ return res
179
+ res = function(arg)
180
+ with lock:
181
+ root, full = root_full
182
+ if arg in cache:
183
+ pass
184
+ elif full:
185
+ oldroot = root
186
+ oldroot[2] = arg
187
+ oldroot[3] = res
188
+ root = root_full[0] = oldroot[1]
189
+ oldarg = root[2]
190
+ oldres = root[3] # noqa F481 (keep reference)
191
+ root[2] = root[3] = None
192
+ del cache[oldarg]
193
+ cache[arg] = oldroot
194
+ else:
195
+ last = root[0]
196
+ link = [last, root, arg, res]
197
+ last[1] = root[0] = cache[arg] = link
198
+ if len(cache) >= maxsize:
199
+ root_full[1] = True
200
+ return res
201
+
202
+ wrapper.__wrapped__ = function
203
+ return update_wrapper(wrapper, function)
204
+
205
+ return decorator
206
+
207
+
208
+ # Auxiliary classes and functions that are independent of a DB connection:
209
+
210
+ try: # noinspection PyUnresolvedReferences
211
+ from inspect import signature
212
+ except ImportError: # Python < 3.3
213
+ from inspect import getargspec
214
+
215
+ def get_args(func):
216
+ return getargspec(func).args
217
+ else:
218
+
219
+ def get_args(func):
220
+ return list(signature(func).parameters)
221
+
222
+ try:
223
+ from datetime import timezone
224
+ except ImportError: # Python < 3.2
225
+
226
+ class timezone(tzinfo):
227
+ """Simple timezone implementation."""
228
+
229
+ def __init__(self, offset, name=None):
230
+ self.offset = offset
231
+ if not name:
232
+ minutes = self.offset.days * 1440 + self.offset.seconds // 60
233
+ if minutes < 0:
234
+ hours, minutes = divmod(-minutes, 60)
235
+ hours = -hours
236
+ else:
237
+ hours, minutes = divmod(minutes, 60)
238
+ name = 'UTC%+03d:%02d' % (hours, minutes)
239
+ self.name = name
240
+
241
+ def utcoffset(self, dt):
242
+ return self.offset
243
+
244
+ def tzname(self, dt):
245
+ return self.name
246
+
247
+ def dst(self, dt):
248
+ return None
249
+
250
+ timezone.utc = timezone(timedelta(0), 'UTC')
251
+
252
+ _has_timezone = False
253
+ else:
254
+ _has_timezone = True
255
+
256
+ # time zones used in Postgres timestamptz output
257
+ _timezones = dict(CET='+0100', EET='+0200', EST='-0500',
258
+ GMT='+0000', HST='-1000', MET='+0100', MST='-0700',
259
+ UCT='+0000', UTC='+0000', WET='+0000')
260
+
261
+
262
+ def _timezone_as_offset(tz):
263
+ if tz.startswith(('+', '-')):
264
+ if len(tz) < 5:
265
+ return tz + '00'
266
+ return tz.replace(':', '')
267
+ return _timezones.get(tz, '+0000')
268
+
269
+
270
+ def _get_timezone(tz):
271
+ tz = _timezone_as_offset(tz)
272
+ minutes = 60 * int(tz[1:3]) + int(tz[3:5])
273
+ if tz[0] == '-':
274
+ minutes = -minutes
275
+ return timezone(timedelta(minutes=minutes), tz)
276
+
277
+
278
+ def _oid_key(table):
279
+ """Build oid key from a table name."""
280
+ return 'oid(%s)' % table
281
+
282
+
283
+ class Bytea(bytes):
284
+ """Wrapper class for marking Bytea values."""
285
+
286
+
287
+ class Hstore(dict):
288
+ """Wrapper class for marking hstore values."""
289
+
290
+ _re_quote = regex('^[Nn][Uu][Ll][Ll]$|[ ,=>]')
291
+
292
+ @classmethod
293
+ def _quote(cls, s):
294
+ if s is None:
295
+ return 'NULL'
296
+ if not isinstance(s, basestring):
297
+ s = str(s)
298
+ if not s:
299
+ return '""'
300
+ s = s.replace('"', '\\"')
301
+ if cls._re_quote.search(s):
302
+ s = '"%s"' % s
303
+ return s
304
+
305
+ def __str__(self):
306
+ q = self._quote
307
+ return ','.join('%s=>%s' % (q(k), q(v)) for k, v in self.items())
308
+
309
+
310
+ class Json:
311
+ """Wrapper class for marking Json values."""
312
+
313
+ def __init__(self, obj, encode=None):
314
+ self.obj = obj
315
+ self.encode = encode or jsonencode
316
+
317
+ def __str__(self):
318
+ obj = self.obj
319
+ if isinstance(obj, basestring):
320
+ return obj
321
+ return self.encode(obj)
322
+
323
+
324
+ class _SimpleTypes(dict):
325
+ """Dictionary mapping pg_type names to simple type names.
326
+
327
+ The corresponding Python types and simple names are also mapped.
328
+ """
329
+
330
+ _type_aliases = {
331
+ 'bool': [bool],
332
+ 'bytea': [Bytea],
333
+ 'date': ['interval', 'time', 'timetz', 'timestamp', 'timestamptz',
334
+ 'abstime', 'reltime', # these are very old
335
+ 'datetime', 'timedelta', # these do not really exist
336
+ date, time, datetime, timedelta],
337
+ 'float': ['float4', 'float8', float],
338
+ 'int': ['cid', 'int2', 'int4', 'int8', 'oid', 'xid', int],
339
+ 'hstore': [Hstore], 'json': ['jsonb', Json], 'uuid': [UUID],
340
+ 'num': ['numeric', Decimal], 'money': [],
341
+ 'text': ['bpchar', 'char', 'name', 'varchar',
342
+ bytes, unicode, basestring]
343
+ } # type: Dict[str, List[Union[str, type]]]
344
+
345
+ if long is not int: # Python 2 has a separate long type
346
+ _type_aliases['num'].append(long)
347
+
348
+ # noinspection PyMissingConstructor
349
+ def __init__(self):
350
+ """Initialize type mapping."""
351
+ for typ, keys in self._type_aliases.items():
352
+ keys = [typ] + keys
353
+ for key in keys:
354
+ self[key] = typ
355
+ if isinstance(key, str):
356
+ self['_%s' % key] = '%s[]' % typ
357
+ elif has_typing and not isinstance(key, tuple):
358
+ self[List[key]] = '%s[]' % typ
359
+
360
+ @staticmethod
361
+ def __missing__(key):
362
+ """Unmapped types are interpreted as text."""
363
+ return 'text'
364
+
365
+ def get_type_dict(self):
366
+ """Get a plain dictionary of only the types."""
367
+ return dict((key, typ) for key, typ in self.items()
368
+ if not isinstance(key, (str, tuple)))
369
+
370
+
371
+ _simpletypes = _SimpleTypes()
372
+ _simple_type_dict = _simpletypes.get_type_dict()
373
+
374
+
375
+ def _quote_if_unqualified(param, name):
376
+ """Quote parameter representing a qualified name.
377
+
378
+ Puts a quote_ident() call around the given parameter unless
379
+ the name contains a dot, in which case the name is ambiguous
380
+ (could be a qualified name or just a name with a dot in it)
381
+ and must be quoted manually by the caller.
382
+ """
383
+ if isinstance(name, basestring) and '.' not in name:
384
+ return 'quote_ident(%s)' % (param,)
385
+ return param
386
+
387
+
388
+ class _ParameterList(list):
389
+ """Helper class for building typed parameter lists."""
390
+
391
+ def add(self, value, typ=None):
392
+ """Typecast value with known database type and build parameter list.
393
+
394
+ If this is a literal value, it will be returned as is. Otherwise, a
395
+ placeholder will be returned and the parameter list will be augmented.
396
+ """
397
+ # noinspection PyUnresolvedReferences
398
+ value = self.adapt(value, typ)
399
+ if isinstance(value, Literal):
400
+ return value
401
+ self.append(value)
402
+ return '$%d' % len(self)
403
+
404
+
405
+ class Literal(str):
406
+ """Wrapper class for marking literal SQL values."""
407
+
408
+
409
+ class AttrDict(OrderedDict):
410
+ """Simple read-only ordered dictionary for storing attribute names."""
411
+
412
+ def __init__(self, *args, **kw):
413
+ self._read_only = False
414
+ OrderedDict.__init__(self, *args, **kw)
415
+ self._read_only = True
416
+ error = self._read_only_error
417
+ self.clear = self.update = error
418
+ self.pop = self.setdefault = self.popitem = error
419
+
420
+ def __setitem__(self, key, value):
421
+ if self._read_only:
422
+ self._read_only_error()
423
+ OrderedDict.__setitem__(self, key, value)
424
+
425
+ def __delitem__(self, key):
426
+ if self._read_only:
427
+ self._read_only_error()
428
+ OrderedDict.__delitem__(self, key)
429
+
430
+ @staticmethod
431
+ def _read_only_error(*args, **kw):
432
+ raise TypeError('This object is read-only')
433
+
434
+
435
+ class Adapter:
436
+ """Class providing methods for adapting parameters to the database."""
437
+
438
+ _bool_true_values = frozenset('t true 1 y yes on'.split())
439
+
440
+ _date_literals = frozenset(
441
+ 'current_date current_time'
442
+ ' current_timestamp localtime localtimestamp'.split())
443
+
444
+ _re_array_quote = regex(r'[{},"\\\s]|^[Nn][Uu][Ll][Ll]$')
445
+ _re_record_quote = regex(r'[(,"\\]')
446
+ _re_array_escape = _re_record_escape = regex(r'(["\\])')
447
+
448
+ def __init__(self, db):
449
+ self.db = weakref.proxy(db)
450
+
451
+ @classmethod
452
+ def _adapt_bool(cls, v):
453
+ """Adapt a boolean parameter."""
454
+ if isinstance(v, basestring):
455
+ if not v:
456
+ return None
457
+ v = v.lower() in cls._bool_true_values
458
+ return 't' if v else 'f'
459
+
460
+ @classmethod
461
+ def _adapt_date(cls, v):
462
+ """Adapt a date parameter."""
463
+ if not v:
464
+ return None
465
+ if isinstance(v, basestring) and v.lower() in cls._date_literals:
466
+ return Literal(v)
467
+ return v
468
+
469
+ @staticmethod
470
+ def _adapt_num(v):
471
+ """Adapt a numeric parameter."""
472
+ if not v and v != 0:
473
+ return None
474
+ return v
475
+
476
+ _adapt_int = _adapt_float = _adapt_money = _adapt_num
477
+
478
+ def _adapt_bytea(self, v):
479
+ """Adapt a bytea parameter."""
480
+ return self.db.escape_bytea(v)
481
+
482
+ def _adapt_json(self, v):
483
+ """Adapt a json parameter."""
484
+ if not v:
485
+ return None
486
+ if isinstance(v, basestring):
487
+ return v
488
+ if isinstance(v, Json):
489
+ return str(v)
490
+ return self.db.encode_json(v)
491
+
492
+ def _adapt_hstore(self, v):
493
+ """Adapt a hstore parameter."""
494
+ if not v:
495
+ return None
496
+ if isinstance(v, basestring):
497
+ return v
498
+ if isinstance(v, Hstore):
499
+ return str(v)
500
+ if isinstance(v, dict):
501
+ return str(Hstore(v))
502
+ raise TypeError('Hstore parameter %s has wrong type' % v)
503
+
504
+ def _adapt_uuid(self, v):
505
+ """Adapt a UUID parameter."""
506
+ if not v:
507
+ return None
508
+ if isinstance(v, basestring):
509
+ return v
510
+ return str(v)
511
+
512
+ @classmethod
513
+ def _adapt_text_array(cls, v):
514
+ """Adapt a text type array parameter."""
515
+ if isinstance(v, list):
516
+ adapt = cls._adapt_text_array
517
+ return '{%s}' % ','.join(adapt(v) for v in v)
518
+ if v is None:
519
+ return 'null'
520
+ if not v:
521
+ return '""'
522
+ v = str(v)
523
+ if cls._re_array_quote.search(v):
524
+ v = '"%s"' % cls._re_array_escape.sub(r'\\\1', v)
525
+ return v
526
+
527
+ _adapt_date_array = _adapt_text_array
528
+
529
+ @classmethod
530
+ def _adapt_bool_array(cls, v):
531
+ """Adapt a boolean array parameter."""
532
+ if isinstance(v, list):
533
+ adapt = cls._adapt_bool_array
534
+ return '{%s}' % ','.join(adapt(v) for v in v)
535
+ if v is None:
536
+ return 'null'
537
+ if isinstance(v, basestring):
538
+ if not v:
539
+ return 'null'
540
+ v = v.lower() in cls._bool_true_values
541
+ return 't' if v else 'f'
542
+
543
+ @classmethod
544
+ def _adapt_num_array(cls, v):
545
+ """Adapt a numeric array parameter."""
546
+ if isinstance(v, list):
547
+ adapt = cls._adapt_num_array
548
+ return '{%s}' % ','.join(adapt(v) for v in v)
549
+ if not v and v != 0:
550
+ return 'null'
551
+ return str(v)
552
+
553
+ _adapt_int_array = _adapt_float_array = _adapt_money_array = \
554
+ _adapt_num_array
555
+
556
+ def _adapt_bytea_array(self, v):
557
+ """Adapt a bytea array parameter."""
558
+ if isinstance(v, list):
559
+ return b'{' + b','.join(
560
+ self._adapt_bytea_array(v) for v in v) + b'}'
561
+ if v is None:
562
+ return b'null'
563
+ return self.db.escape_bytea(v).replace(b'\\', b'\\\\')
564
+
565
+ def _adapt_json_array(self, v):
566
+ """Adapt a json array parameter."""
567
+ if isinstance(v, list):
568
+ adapt = self._adapt_json_array
569
+ return '{%s}' % ','.join(adapt(v) for v in v)
570
+ if not v:
571
+ return 'null'
572
+ if not isinstance(v, basestring):
573
+ v = self.db.encode_json(v)
574
+ if self._re_array_quote.search(v):
575
+ v = '"%s"' % self._re_array_escape.sub(r'\\\1', v)
576
+ return v
577
+
578
+ def _adapt_record(self, v, typ):
579
+ """Adapt a record parameter with given type."""
580
+ typ = self.get_attnames(typ).values()
581
+ if len(typ) != len(v):
582
+ raise TypeError('Record parameter %s has wrong size' % v)
583
+ adapt = self.adapt
584
+ value = []
585
+ for v, t in zip(v, typ):
586
+ v = adapt(v, t)
587
+ if v is None:
588
+ v = ''
589
+ elif not v:
590
+ v = '""'
591
+ else:
592
+ if isinstance(v, bytes):
593
+ if str is not bytes:
594
+ v = v.decode('ascii')
595
+ else:
596
+ v = str(v)
597
+ if self._re_record_quote.search(v):
598
+ v = '"%s"' % self._re_record_escape.sub(r'\\\1', v)
599
+ value.append(v)
600
+ return '(%s)' % ','.join(value)
601
+
602
+ def adapt(self, value, typ=None):
603
+ """Adapt a value with known database type."""
604
+ if value is not None and not isinstance(value, Literal):
605
+ if typ:
606
+ simple = self.get_simple_name(typ)
607
+ else:
608
+ typ = simple = self.guess_simple_type(value) or 'text'
609
+ pg_str = getattr(value, '__pg_str__', None)
610
+ if pg_str:
611
+ value = pg_str(typ)
612
+ if simple == 'text':
613
+ pass
614
+ elif simple == 'record':
615
+ if isinstance(value, tuple):
616
+ value = self._adapt_record(value, typ)
617
+ elif simple.endswith('[]'):
618
+ if isinstance(value, list):
619
+ adapt = getattr(self, '_adapt_%s_array' % simple[:-2])
620
+ value = adapt(value)
621
+ else:
622
+ adapt = getattr(self, '_adapt_%s' % simple)
623
+ value = adapt(value)
624
+ return value
625
+
626
+ @staticmethod
627
+ def simple_type(name):
628
+ """Create a simple database type with given attribute names."""
629
+ typ = DbType(name)
630
+ typ.simple = name
631
+ return typ
632
+
633
+ @staticmethod
634
+ def get_simple_name(typ):
635
+ """Get the simple name of a database type."""
636
+ if isinstance(typ, DbType):
637
+ # noinspection PyUnresolvedReferences
638
+ return typ.simple
639
+ return _simpletypes[typ]
640
+
641
+ @staticmethod
642
+ def get_attnames(typ):
643
+ """Get the attribute names of a composite database type."""
644
+ if isinstance(typ, DbType):
645
+ return typ.attnames
646
+ return {}
647
+
648
+ @classmethod
649
+ def guess_simple_type(cls, value):
650
+ """Try to guess which database type the given value has."""
651
+ # optimize for most frequent types
652
+ try:
653
+ return _simple_type_dict[type(value)]
654
+ except KeyError:
655
+ pass
656
+ if isinstance(value, basestring):
657
+ return 'text'
658
+ if isinstance(value, bool):
659
+ return 'bool'
660
+ if isinstance(value, (int, long)):
661
+ return 'int'
662
+ if isinstance(value, float):
663
+ return 'float'
664
+ if isinstance(value, Decimal):
665
+ return 'num'
666
+ if isinstance(value, (date, time, datetime, timedelta)):
667
+ return 'date'
668
+ if isinstance(value, Bytea):
669
+ return 'bytea'
670
+ if isinstance(value, Json):
671
+ return 'json'
672
+ if isinstance(value, Hstore):
673
+ return 'hstore'
674
+ if isinstance(value, UUID):
675
+ return 'uuid'
676
+ if isinstance(value, list):
677
+ return '%s[]' % (cls.guess_simple_base_type(value) or 'text',)
678
+ if isinstance(value, tuple):
679
+ simple_type = cls.simple_type
680
+ guess = cls.guess_simple_type
681
+
682
+ # noinspection PyUnusedLocal
683
+ def get_attnames(self):
684
+ return AttrDict((str(n + 1), simple_type(guess(v)))
685
+ for n, v in enumerate(value))
686
+
687
+ typ = simple_type('record')
688
+ typ._get_attnames = get_attnames
689
+ return typ
690
+
691
+ @classmethod
692
+ def guess_simple_base_type(cls, value):
693
+ """Try to guess the base type of a given array."""
694
+ for v in value:
695
+ if isinstance(v, list):
696
+ typ = cls.guess_simple_base_type(v)
697
+ else:
698
+ typ = cls.guess_simple_type(v)
699
+ if typ:
700
+ return typ
701
+
702
+ def adapt_inline(self, value, nested=False):
703
+ """Adapt a value that is put into the SQL and needs to be quoted."""
704
+ if value is None:
705
+ return 'NULL'
706
+ if isinstance(value, Literal):
707
+ return value
708
+ if isinstance(value, Bytea):
709
+ value = self.db.escape_bytea(value)
710
+ if bytes is not str: # Python >= 3.0
711
+ value = value.decode('ascii')
712
+ elif isinstance(value, (datetime, date, time, timedelta)):
713
+ value = str(value)
714
+ if isinstance(value, basestring):
715
+ value = self.db.escape_string(value)
716
+ return "'%s'" % value
717
+ if isinstance(value, bool):
718
+ return 'true' if value else 'false'
719
+ if isinstance(value, float):
720
+ if isinf(value):
721
+ return "'-Infinity'" if value < 0 else "'Infinity'"
722
+ if isnan(value):
723
+ return "'NaN'"
724
+ return value
725
+ if isinstance(value, (int, long, Decimal)):
726
+ return value
727
+ if isinstance(value, list):
728
+ q = self.adapt_inline
729
+ s = '[%s]' if nested else 'ARRAY[%s]'
730
+ return s % ','.join(str(q(v, nested=True)) for v in value)
731
+ if isinstance(value, tuple):
732
+ q = self.adapt_inline
733
+ return '(%s)' % ','.join(str(q(v)) for v in value)
734
+ if isinstance(value, Json):
735
+ value = self.db.escape_string(str(value))
736
+ return "'%s'::json" % value
737
+ if isinstance(value, Hstore):
738
+ value = self.db.escape_string(str(value))
739
+ return "'%s'::hstore" % value
740
+ pg_repr = getattr(value, '__pg_repr__', None)
741
+ if not pg_repr:
742
+ raise InterfaceError(
743
+ 'Do not know how to adapt type %s' % type(value))
744
+ value = pg_repr()
745
+ if isinstance(value, (tuple, list)):
746
+ value = self.adapt_inline(value)
747
+ return value
748
+
749
+ def parameter_list(self):
750
+ """Return a parameter list for parameters with known database types.
751
+
752
+ The list has an add(value, typ) method that will build up the
753
+ list and return either the literal value or a placeholder.
754
+ """
755
+ params = _ParameterList()
756
+ params.adapt = self.adapt
757
+ return params
758
+
759
+ def format_query(self, command, values=None, types=None, inline=False):
760
+ """Format a database query using the given values and types.
761
+
762
+ The optional types describe the values and must be passed as a list,
763
+ tuple or string (that will be split on whitespace) when values are
764
+ passed as a list or tuple, or as a dict if values are passed as a dict.
765
+
766
+ If inline is set to True, then parameters will be passed inline
767
+ together with the query string.
768
+ """
769
+ if not values:
770
+ return command, []
771
+ if inline and types:
772
+ raise ValueError('Typed parameters must be sent separately')
773
+ params = self.parameter_list()
774
+ if isinstance(values, (list, tuple)):
775
+ if inline:
776
+ adapt = self.adapt_inline
777
+ literals = [adapt(value) for value in values]
778
+ else:
779
+ add = params.add
780
+ if types:
781
+ if isinstance(types, basestring):
782
+ types = types.split()
783
+ if (not isinstance(types, (list, tuple))
784
+ or len(types) != len(values)):
785
+ raise TypeError('The values and types do not match')
786
+ literals = [add(value, typ)
787
+ for value, typ in zip(values, types)]
788
+ else:
789
+ literals = [add(value) for value in values]
790
+ command %= tuple(literals)
791
+ elif isinstance(values, dict):
792
+ # we want to allow extra keys in the dictionary,
793
+ # so we first must find the values actually used in the command
794
+ used_values = {}
795
+ literals = dict.fromkeys(values, '')
796
+ for key in values:
797
+ del literals[key]
798
+ try:
799
+ command % literals
800
+ except KeyError:
801
+ used_values[key] = values[key]
802
+ literals[key] = ''
803
+ values = used_values
804
+ if inline:
805
+ adapt = self.adapt_inline
806
+ literals = {key: adapt(value)
807
+ for key, value in values.items()}
808
+ else:
809
+ add = params.add
810
+ if types:
811
+ if not isinstance(types, dict):
812
+ raise TypeError('The values and types do not match')
813
+ literals = {key: add(values[key], types.get(key))
814
+ for key in sorted(values)}
815
+ else:
816
+ literals = {key: add(values[key])
817
+ for key in sorted(values)}
818
+ command %= literals
819
+ else:
820
+ raise TypeError('The values must be passed as tuple, list or dict')
821
+ return command, params
822
+
823
+
824
+ def cast_bool(value):
825
+ """Cast a boolean value."""
826
+ if not get_bool():
827
+ return value
828
+ return value[0] == 't'
829
+
830
+
831
+ def cast_json(value):
832
+ """Cast a JSON value."""
833
+ cast = get_jsondecode()
834
+ if not cast:
835
+ return value
836
+ return cast(value)
837
+
838
+
839
+ def cast_num(value):
840
+ """Cast a numeric value."""
841
+ return (get_decimal() or float)(value)
842
+
843
+
844
+ def cast_money(value):
845
+ """Cast a money value."""
846
+ point = get_decimal_point()
847
+ if not point:
848
+ return value
849
+ if point != '.':
850
+ value = value.replace(point, '.')
851
+ value = value.replace('(', '-')
852
+ value = ''.join(c for c in value if c.isdigit() or c in '.-')
853
+ return (get_decimal() or float)(value)
854
+
855
+
856
+ def cast_int2vector(value):
857
+ """Cast an int2vector value."""
858
+ return [int(v) for v in value.split()]
859
+
860
+
861
+ def cast_date(value, connection):
862
+ """Cast a date value."""
863
+ # The output format depends on the server setting DateStyle. The default
864
+ # setting ISO and the setting for German are actually unambiguous. The
865
+ # order of days and months in the other two settings is however ambiguous,
866
+ # so at least here we need to consult the setting to properly parse values.
867
+ if value == '-infinity':
868
+ return date.min
869
+ if value == 'infinity':
870
+ return date.max
871
+ value = value.split()
872
+ if value[-1] == 'BC':
873
+ return date.min
874
+ value = value[0]
875
+ if len(value) > 10:
876
+ return date.max
877
+ fmt = connection.date_format()
878
+ return datetime.strptime(value, fmt).date()
879
+
880
+
881
+ def cast_time(value):
882
+ """Cast a time value."""
883
+ fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
884
+ return datetime.strptime(value, fmt).time()
885
+
886
+
887
+ _re_timezone = regex('(.*)([+-].*)')
888
+
889
+
890
+ def cast_timetz(value):
891
+ """Cast a timetz value."""
892
+ tz = _re_timezone.match(value)
893
+ if tz:
894
+ value, tz = tz.groups()
895
+ else:
896
+ tz = '+0000'
897
+ fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
898
+ if _has_timezone:
899
+ value += _timezone_as_offset(tz)
900
+ fmt += '%z'
901
+ return datetime.strptime(value, fmt).timetz()
902
+ return datetime.strptime(value, fmt).timetz().replace(
903
+ tzinfo=_get_timezone(tz))
904
+
905
+
906
+ def cast_timestamp(value, connection):
907
+ """Cast a timestamp value."""
908
+ if value == '-infinity':
909
+ return datetime.min
910
+ if value == 'infinity':
911
+ return datetime.max
912
+ value = value.split()
913
+ if value[-1] == 'BC':
914
+ return datetime.min
915
+ fmt = connection.date_format()
916
+ if fmt.endswith('-%Y') and len(value) > 2:
917
+ value = value[1:5]
918
+ if len(value[3]) > 4:
919
+ return datetime.max
920
+ fmt = ['%d %b' if fmt.startswith('%d') else '%b %d',
921
+ '%H:%M:%S.%f' if len(value[2]) > 8 else '%H:%M:%S', '%Y']
922
+ else:
923
+ if len(value[0]) > 10:
924
+ return datetime.max
925
+ fmt = [fmt, '%H:%M:%S.%f' if len(value[1]) > 8 else '%H:%M:%S']
926
+ return datetime.strptime(' '.join(value), ' '.join(fmt))
927
+
928
+
929
+ def cast_timestamptz(value, connection):
930
+ """Cast a timestamptz value."""
931
+ if value == '-infinity':
932
+ return datetime.min
933
+ if value == 'infinity':
934
+ return datetime.max
935
+ value = value.split()
936
+ if value[-1] == 'BC':
937
+ return datetime.min
938
+ fmt = connection.date_format()
939
+ if fmt.endswith('-%Y') and len(value) > 2:
940
+ value = value[1:]
941
+ if len(value[3]) > 4:
942
+ return datetime.max
943
+ fmt = ['%d %b' if fmt.startswith('%d') else '%b %d',
944
+ '%H:%M:%S.%f' if len(value[2]) > 8 else '%H:%M:%S', '%Y']
945
+ value, tz = value[:-1], value[-1]
946
+ else:
947
+ if fmt.startswith('%Y-'):
948
+ tz = _re_timezone.match(value[1])
949
+ if tz:
950
+ value[1], tz = tz.groups()
951
+ else:
952
+ tz = '+0000'
953
+ else:
954
+ value, tz = value[:-1], value[-1]
955
+ if len(value[0]) > 10:
956
+ return datetime.max
957
+ fmt = [fmt, '%H:%M:%S.%f' if len(value[1]) > 8 else '%H:%M:%S']
958
+ if _has_timezone:
959
+ value.append(_timezone_as_offset(tz))
960
+ fmt.append('%z')
961
+ return datetime.strptime(' '.join(value), ' '.join(fmt))
962
+ return datetime.strptime(' '.join(value), ' '.join(fmt)).replace(
963
+ tzinfo=_get_timezone(tz))
964
+
965
+
966
+ _re_interval_sql_standard = regex(
967
+ '(?:([+-])?([0-9]+)-([0-9]+) ?)?'
968
+ '(?:([+-]?[0-9]+)(?!:) ?)?'
969
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
970
+
971
+ _re_interval_postgres = regex(
972
+ '(?:([+-]?[0-9]+) ?years? ?)?'
973
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
974
+ '(?:([+-]?[0-9]+) ?days? ?)?'
975
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
976
+
977
+ _re_interval_postgres_verbose = regex(
978
+ '@ ?(?:([+-]?[0-9]+) ?years? ?)?'
979
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
980
+ '(?:([+-]?[0-9]+) ?days? ?)?'
981
+ '(?:([+-]?[0-9]+) ?hours? ?)?'
982
+ '(?:([+-]?[0-9]+) ?mins? ?)?'
983
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
984
+
985
+ _re_interval_iso_8601 = regex(
986
+ 'P(?:([+-]?[0-9]+)Y)?'
987
+ '(?:([+-]?[0-9]+)M)?'
988
+ '(?:([+-]?[0-9]+)D)?'
989
+ '(?:T(?:([+-]?[0-9]+)H)?'
990
+ '(?:([+-]?[0-9]+)M)?'
991
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
992
+
993
+
994
+ def cast_interval(value):
995
+ """Cast an interval value."""
996
+ # The output format depends on the server setting IntervalStyle, but it's
997
+ # not necessary to consult this setting to parse it. It's faster to just
998
+ # check all possible formats, and there is no ambiguity here.
999
+ m = _re_interval_iso_8601.match(value)
1000
+ if m:
1001
+ m = [d or '0' for d in m.groups()]
1002
+ secs_ago = m.pop(5) == '-'
1003
+ m = [int(d) for d in m]
1004
+ years, mons, days, hours, mins, secs, usecs = m
1005
+ if secs_ago:
1006
+ secs = -secs
1007
+ usecs = -usecs
1008
+ else:
1009
+ m = _re_interval_postgres_verbose.match(value)
1010
+ if m:
1011
+ m, ago = [d or '0' for d in m.groups()[:8]], m.group(9)
1012
+ secs_ago = m.pop(5) == '-'
1013
+ m = [-int(d) for d in m] if ago else [int(d) for d in m]
1014
+ years, mons, days, hours, mins, secs, usecs = m
1015
+ if secs_ago:
1016
+ secs = - secs
1017
+ usecs = -usecs
1018
+ else:
1019
+ m = _re_interval_postgres.match(value)
1020
+ if m and any(m.groups()):
1021
+ m = [d or '0' for d in m.groups()]
1022
+ hours_ago = m.pop(3) == '-'
1023
+ m = [int(d) for d in m]
1024
+ years, mons, days, hours, mins, secs, usecs = m
1025
+ if hours_ago:
1026
+ hours = -hours
1027
+ mins = -mins
1028
+ secs = -secs
1029
+ usecs = -usecs
1030
+ else:
1031
+ m = _re_interval_sql_standard.match(value)
1032
+ if m and any(m.groups()):
1033
+ m = [d or '0' for d in m.groups()]
1034
+ years_ago = m.pop(0) == '-'
1035
+ hours_ago = m.pop(3) == '-'
1036
+ m = [int(d) for d in m]
1037
+ years, mons, days, hours, mins, secs, usecs = m
1038
+ if years_ago:
1039
+ years = -years
1040
+ mons = -mons
1041
+ if hours_ago:
1042
+ hours = -hours
1043
+ mins = -mins
1044
+ secs = -secs
1045
+ usecs = -usecs
1046
+ else:
1047
+ raise ValueError('Cannot parse interval: %s' % value)
1048
+ days += 365 * years + 30 * mons
1049
+ return timedelta(days=days, hours=hours, minutes=mins,
1050
+ seconds=secs, microseconds=usecs)
1051
+
1052
+
1053
+ class Typecasts(dict):
1054
+ """Dictionary mapping database types to typecast functions.
1055
+
1056
+ The cast functions get passed the string representation of a value in
1057
+ the database which they need to convert to a Python object. The
1058
+ passed string will never be None since NULL values are already
1059
+ handled before the cast function is called.
1060
+
1061
+ Note that the basic types are already handled by the C extension.
1062
+ They only need to be handled here as record or array components.
1063
+ """
1064
+
1065
+ # the default cast functions
1066
+ # (str functions are ignored but have been added for faster access)
1067
+ defaults = {
1068
+ 'char': str, 'bpchar': str, 'name': str,
1069
+ 'text': str, 'varchar': str, 'sql_identifier': str,
1070
+ 'bool': cast_bool, 'bytea': unescape_bytea,
1071
+ 'int2': int, 'int4': int, 'serial': int, 'int8': long, 'oid': int,
1072
+ 'hstore': cast_hstore, 'json': cast_json, 'jsonb': cast_json,
1073
+ 'float4': float, 'float8': float,
1074
+ 'numeric': cast_num, 'money': cast_money,
1075
+ 'date': cast_date, 'interval': cast_interval,
1076
+ 'time': cast_time, 'timetz': cast_timetz,
1077
+ 'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
1078
+ 'int2vector': cast_int2vector, 'uuid': UUID,
1079
+ 'anyarray': cast_array, 'record': cast_record}
1080
+
1081
+ connection = None # will be set in a connection specific instance
1082
+
1083
+ def __missing__(self, typ):
1084
+ """Create a cast function if it is not cached.
1085
+
1086
+ Note that this class never raises a KeyError,
1087
+ but returns None when no special cast function exists.
1088
+ """
1089
+ if not isinstance(typ, str):
1090
+ raise TypeError('Invalid type: %s' % typ)
1091
+ cast = self.defaults.get(typ)
1092
+ if cast:
1093
+ # store default for faster access
1094
+ cast = self._add_connection(cast)
1095
+ self[typ] = cast
1096
+ elif typ.startswith('_'):
1097
+ base_cast = self[typ[1:]]
1098
+ cast = self.create_array_cast(base_cast)
1099
+ if base_cast:
1100
+ self[typ] = cast
1101
+ else:
1102
+ attnames = self.get_attnames(typ)
1103
+ if attnames:
1104
+ casts = [self[v.pgtype] for v in attnames.values()]
1105
+ cast = self.create_record_cast(typ, attnames, casts)
1106
+ self[typ] = cast
1107
+ return cast
1108
+
1109
+ @staticmethod
1110
+ def _needs_connection(func):
1111
+ """Check if a typecast function needs a connection argument."""
1112
+ try:
1113
+ args = get_args(func)
1114
+ except (TypeError, ValueError):
1115
+ return False
1116
+ else:
1117
+ return 'connection' in args[1:]
1118
+
1119
+ def _add_connection(self, cast):
1120
+ """Add a connection argument to the typecast function if necessary."""
1121
+ if not self.connection or not self._needs_connection(cast):
1122
+ return cast
1123
+ return partial(cast, connection=self.connection)
1124
+
1125
+ def get(self, typ, default=None):
1126
+ """Get the typecast function for the given database type."""
1127
+ return self[typ] or default
1128
+
1129
+ def set(self, typ, cast):
1130
+ """Set a typecast function for the specified database type(s)."""
1131
+ if isinstance(typ, basestring):
1132
+ typ = [typ]
1133
+ if cast is None:
1134
+ for t in typ:
1135
+ self.pop(t, None)
1136
+ self.pop('_%s' % t, None)
1137
+ else:
1138
+ if not callable(cast):
1139
+ raise TypeError("Cast parameter must be callable")
1140
+ for t in typ:
1141
+ self[t] = self._add_connection(cast)
1142
+ self.pop('_%s' % t, None)
1143
+
1144
+ def reset(self, typ=None):
1145
+ """Reset the typecasts for the specified type(s) to their defaults.
1146
+
1147
+ When no type is specified, all typecasts will be reset.
1148
+ """
1149
+ if typ is None:
1150
+ self.clear()
1151
+ else:
1152
+ if isinstance(typ, basestring):
1153
+ typ = [typ]
1154
+ for t in typ:
1155
+ self.pop(t, None)
1156
+
1157
+ @classmethod
1158
+ def get_default(cls, typ):
1159
+ """Get the default typecast function for the given database type."""
1160
+ return cls.defaults.get(typ)
1161
+
1162
+ @classmethod
1163
+ def set_default(cls, typ, cast):
1164
+ """Set a default typecast function for the given database type(s)."""
1165
+ if isinstance(typ, basestring):
1166
+ typ = [typ]
1167
+ defaults = cls.defaults
1168
+ if cast is None:
1169
+ for t in typ:
1170
+ defaults.pop(t, None)
1171
+ defaults.pop('_%s' % t, None)
1172
+ else:
1173
+ if not callable(cast):
1174
+ raise TypeError("Cast parameter must be callable")
1175
+ for t in typ:
1176
+ defaults[t] = cast
1177
+ defaults.pop('_%s' % t, None)
1178
+
1179
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
1180
+ def get_attnames(self, typ):
1181
+ """Return the fields for the given record type.
1182
+
1183
+ This method will be replaced with the get_attnames() method of DbTypes.
1184
+ """
1185
+ return {}
1186
+
1187
+ # noinspection PyMethodMayBeStatic
1188
+ def dateformat(self):
1189
+ """Return the current date format.
1190
+
1191
+ This method will be replaced with the dateformat() method of DbTypes.
1192
+ """
1193
+ return '%Y-%m-%d'
1194
+
1195
+ def create_array_cast(self, basecast):
1196
+ """Create an array typecast for the given base cast."""
1197
+ cast_array = self['anyarray']
1198
+
1199
+ def cast(v):
1200
+ return cast_array(v, basecast)
1201
+ return cast
1202
+
1203
+ def create_record_cast(self, name, fields, casts):
1204
+ """Create a named record typecast for the given fields and casts."""
1205
+ cast_record = self['record']
1206
+ record = namedtuple(name, fields)
1207
+
1208
+ def cast(v):
1209
+ # noinspection PyArgumentList
1210
+ return record(*cast_record(v, casts))
1211
+ return cast
1212
+
1213
+
1214
+ def get_typecast(typ):
1215
+ """Get the global typecast function for the given database type(s)."""
1216
+ return Typecasts.get_default(typ)
1217
+
1218
+
1219
+ def set_typecast(typ, cast):
1220
+ """Set a global typecast function for the given database type(s).
1221
+
1222
+ Note that connections cache cast functions. To be sure a global change
1223
+ is picked up by a running connection, call db.db_types.reset_typecast().
1224
+ """
1225
+ Typecasts.set_default(typ, cast)
1226
+
1227
+
1228
+ class DbType(str):
1229
+ """Class augmenting the simple type name with additional info.
1230
+
1231
+ The following additional information is provided:
1232
+
1233
+ oid: the PostgreSQL type OID
1234
+ pgtype: the internal PostgreSQL data type name
1235
+ regtype: the registered PostgreSQL data type name
1236
+ simple: the more coarse-grained PyGreSQL type name
1237
+ typlen: the internal size, negative if variable
1238
+ typtype: b = base type, c = composite type etc.
1239
+ category: A = Array, b = Boolean, C = Composite etc.
1240
+ delim: delimiter for array types
1241
+ relid: corresponding table for composite types
1242
+ attnames: attributes for composite types
1243
+ """
1244
+
1245
+ @property
1246
+ def attnames(self):
1247
+ """Get names and types of the fields of a composite type."""
1248
+ # noinspection PyUnresolvedReferences
1249
+ return self._get_attnames(self)
1250
+
1251
+
1252
+ class DbTypes(dict):
1253
+ """Cache for PostgreSQL data types.
1254
+
1255
+ This cache maps type OIDs and names to DbType objects containing
1256
+ information on the associated database type.
1257
+ """
1258
+
1259
+ _num_types = frozenset('int float num money int2 int4 int8'
1260
+ ' float4 float8 numeric money'.split())
1261
+
1262
+ def __init__(self, db):
1263
+ """Initialize type cache for connection."""
1264
+ super(DbTypes, self).__init__()
1265
+ self._db = weakref.proxy(db)
1266
+ self._regtypes = False
1267
+ self._typecasts = Typecasts()
1268
+ self._typecasts.get_attnames = self.get_attnames
1269
+ self._typecasts.connection = self._db
1270
+ if db.server_version < 80400:
1271
+ # very old remote databases (not officially supported)
1272
+ self._query_pg_type = (
1273
+ "SELECT oid, typname, oid::pg_catalog.regtype,"
1274
+ " typlen, typtype, null as typcategory, typdelim, typrelid"
1275
+ " FROM pg_catalog.pg_type"
1276
+ " WHERE oid OPERATOR(pg_catalog.=) %s::pg_catalog.regtype")
1277
+ else:
1278
+ self._query_pg_type = (
1279
+ "SELECT oid, typname, oid::pg_catalog.regtype,"
1280
+ " typlen, typtype, typcategory, typdelim, typrelid"
1281
+ " FROM pg_catalog.pg_type"
1282
+ " WHERE oid OPERATOR(pg_catalog.=) %s::pg_catalog.regtype")
1283
+
1284
+ def add(self, oid, pgtype, regtype,
1285
+ typlen, typtype, category, delim, relid):
1286
+ """Create a PostgreSQL type name with additional info."""
1287
+ if oid in self:
1288
+ return self[oid]
1289
+ simple = 'record' if relid else _simpletypes[pgtype]
1290
+ typ = DbType(regtype if self._regtypes else simple)
1291
+ typ.oid = oid
1292
+ typ.simple = simple
1293
+ typ.pgtype = pgtype
1294
+ typ.regtype = regtype
1295
+ typ.typlen = typlen
1296
+ typ.typtype = typtype
1297
+ typ.category = category
1298
+ typ.delim = delim
1299
+ typ.relid = relid
1300
+ typ._get_attnames = self.get_attnames
1301
+ return typ
1302
+
1303
+ def __missing__(self, key):
1304
+ """Get the type info from the database if it is not cached."""
1305
+ try:
1306
+ q = self._query_pg_type % (_quote_if_unqualified('$1', key),)
1307
+ res = self._db.query(q, (key,)).getresult()
1308
+ except ProgrammingError:
1309
+ res = None
1310
+ if not res:
1311
+ raise KeyError('Type %s could not be found' % (key,))
1312
+ res = res[0]
1313
+ typ = self.add(*res)
1314
+ self[typ.oid] = self[typ.pgtype] = typ
1315
+ return typ
1316
+
1317
+ def get(self, key, default=None):
1318
+ """Get the type even if it is not cached."""
1319
+ try:
1320
+ return self[key]
1321
+ except KeyError:
1322
+ return default
1323
+
1324
+ def get_attnames(self, typ):
1325
+ """Get names and types of the fields of a composite type."""
1326
+ if not isinstance(typ, DbType):
1327
+ typ = self.get(typ)
1328
+ if not typ:
1329
+ return None
1330
+ if not typ.relid:
1331
+ return None
1332
+ return self._db.get_attnames(typ.relid, with_oid=False)
1333
+
1334
+ def get_typecast(self, typ):
1335
+ """Get the typecast function for the given database type."""
1336
+ return self._typecasts.get(typ)
1337
+
1338
+ def set_typecast(self, typ, cast):
1339
+ """Set a typecast function for the specified database type(s)."""
1340
+ self._typecasts.set(typ, cast)
1341
+
1342
+ def reset_typecast(self, typ=None):
1343
+ """Reset the typecast function for the specified database type(s)."""
1344
+ self._typecasts.reset(typ)
1345
+
1346
+ def typecast(self, value, typ):
1347
+ """Cast the given value according to the given database type."""
1348
+ if value is None:
1349
+ # for NULL values, no typecast is necessary
1350
+ return None
1351
+ if not isinstance(typ, DbType):
1352
+ typ = self.get(typ)
1353
+ if typ:
1354
+ typ = typ.pgtype
1355
+ cast = self.get_typecast(typ) if typ else None
1356
+ if not cast or cast is str:
1357
+ # no typecast is necessary
1358
+ return value
1359
+ return cast(value)
1360
+
1361
+
1362
+ _re_fieldname = regex('^[A-Za-z][_a-zA-Z0-9]*$')
1363
+
1364
+
1365
+ # The result rows for database operations are returned as named tuples
1366
+ # by default. Since creating namedtuple classes is a somewhat expensive
1367
+ # operation, we cache up to 1024 of these classes by default.
1368
+
1369
+ # noinspection PyUnresolvedReferences
1370
+ @lru_cache(maxsize=1024)
1371
+ def _row_factory(names):
1372
+ """Get a namedtuple factory for row results with the given names."""
1373
+ try:
1374
+ return namedtuple('Row', names, rename=True)._make
1375
+ except ValueError: # there is still a problem with the field names
1376
+ names = ['column_%d' % (n,) for n in range(len(names))]
1377
+ return namedtuple('Row', names)._make
1378
+
1379
+
1380
+ def set_row_factory_size(maxsize):
1381
+ """Change the size of the namedtuple factory cache.
1382
+
1383
+ If maxsize is set to None, the cache can grow without bound.
1384
+ """
1385
+ # noinspection PyGlobalUndefined
1386
+ global _row_factory
1387
+ _row_factory = lru_cache(maxsize)(_row_factory.__wrapped__)
1388
+
1389
+
1390
+ # Helper functions used by the query object
1391
+
1392
+ def _dictiter(q):
1393
+ """Get query result as an iterator of dictionaries."""
1394
+ fields = q.listfields()
1395
+ for r in q:
1396
+ yield dict(zip(fields, r))
1397
+
1398
+
1399
+ def _namediter(q):
1400
+ """Get query result as an iterator of named tuples."""
1401
+ row = _row_factory(q.listfields())
1402
+ for r in q:
1403
+ yield row(r)
1404
+
1405
+
1406
+ def _namednext(q):
1407
+ """Get next row from query result as a named tuple."""
1408
+ return _row_factory(q.listfields())(next(q))
1409
+
1410
+
1411
+ def _scalariter(q):
1412
+ """Get query result as an iterator of scalar values."""
1413
+ for r in q:
1414
+ yield r[0]
1415
+
1416
+
1417
+ class _MemoryQuery:
1418
+ """Class that embodies a given query result."""
1419
+
1420
+ def __init__(self, result, fields):
1421
+ """Create query from given result rows and field names."""
1422
+ self.result = result
1423
+ self.fields = tuple(fields)
1424
+
1425
+ def listfields(self):
1426
+ """Return the stored field names of this query."""
1427
+ return self.fields
1428
+
1429
+ def getresult(self):
1430
+ """Return the stored result of this query."""
1431
+ return self.result
1432
+
1433
+ def __iter__(self):
1434
+ return iter(self.result)
1435
+
1436
+
1437
+ def _db_error(msg, cls=DatabaseError):
1438
+ """Return DatabaseError with empty sqlstate attribute."""
1439
+ error = cls(msg)
1440
+ error.sqlstate = None
1441
+ return error
1442
+
1443
+
1444
+ def _int_error(msg):
1445
+ """Return InternalError."""
1446
+ return _db_error(msg, InternalError)
1447
+
1448
+
1449
+ def _prg_error(msg):
1450
+ """Return ProgrammingError."""
1451
+ return _db_error(msg, ProgrammingError)
1452
+
1453
+
1454
+ # Initialize the C module
1455
+
1456
+ set_decimal(Decimal)
1457
+ set_jsondecode(jsondecode)
1458
+ set_query_helpers(_dictiter, _namediter, _namednext, _scalariter)
1459
+
1460
+
1461
+ # The notification handler
1462
+
1463
+ class NotificationHandler(object):
1464
+ """A PostgreSQL client-side asynchronous notification handler."""
1465
+
1466
+ def __init__(self, db, event, callback=None,
1467
+ arg_dict=None, timeout=None, stop_event=None):
1468
+ """Initialize the notification handler.
1469
+
1470
+ You must pass a PyGreSQL database connection, the name of an
1471
+ event (notification channel) to listen for and a callback function.
1472
+
1473
+ You can also specify a dictionary arg_dict that will be passed as
1474
+ the single argument to the callback function, and a timeout value
1475
+ in seconds (a floating point number denotes fractions of seconds).
1476
+ If it is absent or None, the callers will never time out. If the
1477
+ timeout is reached, the callback function will be called with a
1478
+ single argument that is None. If you set the timeout to zero,
1479
+ the handler will poll notifications synchronously and return.
1480
+
1481
+ You can specify the name of the event that will be used to signal
1482
+ the handler to stop listening as stop_event. By default, it will
1483
+ be the event name prefixed with 'stop_'.
1484
+ """
1485
+ self.db = db
1486
+ self.event = event
1487
+ self.stop_event = stop_event or 'stop_%s' % event
1488
+ self.listening = False
1489
+ self.callback = callback
1490
+ if arg_dict is None:
1491
+ arg_dict = {}
1492
+ self.arg_dict = arg_dict
1493
+ self.timeout = timeout
1494
+
1495
+ def __del__(self):
1496
+ self.unlisten()
1497
+
1498
+ def close(self):
1499
+ """Stop listening and close the connection."""
1500
+ if self.db:
1501
+ self.unlisten()
1502
+ self.db.close()
1503
+ self.db = None
1504
+
1505
+ def listen(self):
1506
+ """Start listening for the event and the stop event."""
1507
+ if not self.listening:
1508
+ self.db.query('listen "%s"' % self.event)
1509
+ self.db.query('listen "%s"' % self.stop_event)
1510
+ self.listening = True
1511
+
1512
+ def unlisten(self):
1513
+ """Stop listening for the event and the stop event."""
1514
+ if self.listening:
1515
+ self.db.query('unlisten "%s"' % self.event)
1516
+ self.db.query('unlisten "%s"' % self.stop_event)
1517
+ self.listening = False
1518
+
1519
+ def notify(self, db=None, stop=False, payload=None):
1520
+ """Generate a notification.
1521
+
1522
+ Optionally, you can pass a payload with the notification.
1523
+
1524
+ If you set the stop flag, a stop notification will be sent that
1525
+ will cause the handler to stop listening.
1526
+
1527
+ Note: If the notification handler is running in another thread, you
1528
+ must pass a different database connection since PyGreSQL database
1529
+ connections are not thread-safe.
1530
+ """
1531
+ if self.listening:
1532
+ if not db:
1533
+ db = self.db
1534
+ q = 'notify "%s"' % (self.stop_event if stop else self.event)
1535
+ if payload:
1536
+ q += ", '%s'" % payload
1537
+ return db.query(q)
1538
+
1539
+ def __call__(self):
1540
+ """Invoke the notification handler.
1541
+
1542
+ The handler is a loop that listens for notifications on the event
1543
+ and stop event channels. When either of these notifications are
1544
+ received, its associated 'pid', 'event' and 'extra' (the payload
1545
+ passed with the notification) are inserted into its arg_dict
1546
+ dictionary and the callback is invoked with this dictionary as
1547
+ a single argument. When the handler receives a stop event, it
1548
+ stops listening to both events and return.
1549
+
1550
+ In the special case that the timeout of the handler has been set
1551
+ to zero, the handler will poll all events synchronously and return.
1552
+ If will keep listening until it receives a stop event.
1553
+
1554
+ Note: If you run this loop in another thread, don't use the same
1555
+ database connection for database operations in the main thread.
1556
+ """
1557
+ self.listen()
1558
+ poll = self.timeout == 0
1559
+ if not poll:
1560
+ rlist = [self.db.fileno()]
1561
+ while self.listening:
1562
+ # noinspection PyUnboundLocalVariable
1563
+ if poll or select.select(rlist, [], [], self.timeout)[0]:
1564
+ while self.listening:
1565
+ notice = self.db.getnotify()
1566
+ if not notice: # no more messages
1567
+ break
1568
+ event, pid, extra = notice
1569
+ if event not in (self.event, self.stop_event):
1570
+ self.unlisten()
1571
+ raise _db_error(
1572
+ 'Listening for "%s" and "%s", but notified of "%s"'
1573
+ % (self.event, self.stop_event, event))
1574
+ if event == self.stop_event:
1575
+ self.unlisten()
1576
+ self.arg_dict.update(pid=pid, event=event, extra=extra)
1577
+ self.callback(self.arg_dict)
1578
+ if poll:
1579
+ break
1580
+ else: # we timed out
1581
+ self.unlisten()
1582
+ self.callback(None)
1583
+
1584
+
1585
+ def pgnotify(*args, **kw):
1586
+ """Same as NotificationHandler, under the traditional name."""
1587
+ warnings.warn("pgnotify is deprecated, use NotificationHandler instead",
1588
+ DeprecationWarning, stacklevel=2)
1589
+ return NotificationHandler(*args, **kw)
1590
+
1591
+
1592
+ # The actual PostgreSQL database connection interface:
1593
+
1594
+ class DB:
1595
+ """Wrapper class for the _pg connection type."""
1596
+
1597
+ db = None # invalid fallback for underlying connection
1598
+
1599
+ def __init__(self, *args, **kw):
1600
+ """Create a new connection
1601
+
1602
+ You can pass either the connection parameters or an existing
1603
+ _pg or pgdb connection. This allows you to use the methods
1604
+ of the classic pg interface with a DB-API 2 pgdb connection.
1605
+ """
1606
+ if not args and len(kw) == 1:
1607
+ db = kw.get('db')
1608
+ elif not kw and len(args) == 1:
1609
+ db = args[0]
1610
+ else:
1611
+ db = None
1612
+ if db:
1613
+ if isinstance(db, DB):
1614
+ db = db.db
1615
+ else:
1616
+ try:
1617
+ # noinspection PyUnresolvedReferences
1618
+ db = db._cnx
1619
+ except AttributeError:
1620
+ pass
1621
+ if not db or not hasattr(db, 'db') or not hasattr(db, 'query'):
1622
+ db = connect(*args, **kw)
1623
+ self._db_args = args, kw
1624
+ self._closeable = True
1625
+ else:
1626
+ self._db_args = db
1627
+ self._closeable = False
1628
+ self.db = db
1629
+ self.dbname = db.db
1630
+ self._regtypes = False
1631
+ self._attnames = {}
1632
+ self._generated = {}
1633
+ self._pkeys = {}
1634
+ self._privileges = {}
1635
+ self.adapter = Adapter(self)
1636
+ self.dbtypes = DbTypes(self)
1637
+ if db.server_version < 80400:
1638
+ # very old remote databases (not officially supported)
1639
+ self._query_attnames = (
1640
+ "SELECT a.attname,"
1641
+ " t.oid, t.typname, t.oid::pg_catalog.regtype,"
1642
+ " t.typlen, t.typtype, null as typcategory,"
1643
+ " t.typdelim, t.typrelid"
1644
+ " FROM pg_catalog.pg_attribute a"
1645
+ " JOIN pg_catalog.pg_type t"
1646
+ " ON t.oid OPERATOR(pg_catalog.=) a.atttypid"
1647
+ " WHERE a.attrelid OPERATOR(pg_catalog.=)"
1648
+ " %s::pg_catalog.regclass"
1649
+ " AND %s AND NOT a.attisdropped ORDER BY a.attnum")
1650
+ else:
1651
+ self._query_attnames = (
1652
+ "SELECT a.attname,"
1653
+ " t.oid, t.typname, t.oid::pg_catalog.regtype,"
1654
+ " t.typlen, t.typtype, t.typcategory, t.typdelim, t.typrelid"
1655
+ " FROM pg_catalog.pg_attribute a"
1656
+ " JOIN pg_catalog.pg_type t"
1657
+ " ON t.oid OPERATOR(pg_catalog.=) a.atttypid"
1658
+ " WHERE a.attrelid OPERATOR(pg_catalog.=)"
1659
+ " %s::pg_catalog.regclass"
1660
+ " AND %s AND NOT a.attisdropped ORDER BY a.attnum")
1661
+ if db.server_version < 100000:
1662
+ self._query_generated = None
1663
+ elif db.server_version < 120000:
1664
+ self._query_generated = (
1665
+ "a.attidentity OPERATOR(pg_catalog.=) 'a'"
1666
+ )
1667
+ else:
1668
+ self._query_generated = (
1669
+ "(a.attidentity OPERATOR(pg_catalog.=) 'a' OR"
1670
+ " a.attgenerated OPERATOR(pg_catalog.!=) '')"
1671
+ )
1672
+ db.set_cast_hook(self.dbtypes.typecast)
1673
+ # For debugging scripts, self.debug can be set
1674
+ # * to a string format specification (e.g. in CGI set to "%s<BR>"),
1675
+ # * to a file object to write debug statements or
1676
+ # * to a callable object which takes a string argument
1677
+ # * to any other true value to just print debug statements
1678
+ self.debug = None
1679
+
1680
+ def __getattr__(self, name):
1681
+ # All undefined members are same as in underlying connection:
1682
+ if self.db:
1683
+ return getattr(self.db, name)
1684
+ else:
1685
+ raise _int_error('Connection is not valid')
1686
+
1687
+ def __dir__(self):
1688
+ # Custom dir function including the attributes of the connection:
1689
+ attrs = set(self.__class__.__dict__)
1690
+ attrs.update(self.__dict__)
1691
+ attrs.update(dir(self.db))
1692
+ return sorted(attrs)
1693
+
1694
+ # Context manager methods
1695
+
1696
+ def __enter__(self):
1697
+ """Enter the runtime context. This will start a transaction."""
1698
+ self.begin()
1699
+ return self
1700
+
1701
+ def __exit__(self, et, ev, tb):
1702
+ """Exit the runtime context. This will end the transaction."""
1703
+ if et is None and ev is None and tb is None:
1704
+ self.commit()
1705
+ else:
1706
+ self.rollback()
1707
+
1708
+ def __del__(self):
1709
+ try:
1710
+ db = self.db
1711
+ except AttributeError:
1712
+ db = None
1713
+ if db:
1714
+ try:
1715
+ db.set_cast_hook(None)
1716
+ except TypeError:
1717
+ pass # probably already closed
1718
+ if self._closeable:
1719
+ try:
1720
+ db.close()
1721
+ except InternalError:
1722
+ pass # probably already closed
1723
+
1724
+ # Auxiliary methods
1725
+
1726
+ def _do_debug(self, *args):
1727
+ """Print a debug message"""
1728
+ if self.debug:
1729
+ s = '\n'.join(str(arg) for arg in args)
1730
+ if isinstance(self.debug, basestring):
1731
+ print(self.debug % s)
1732
+ elif hasattr(self.debug, 'write'):
1733
+ # noinspection PyCallingNonCallable
1734
+ self.debug.write(s + '\n')
1735
+ elif callable(self.debug):
1736
+ self.debug(s)
1737
+ else:
1738
+ print(s)
1739
+
1740
+ def _escape_qualified_name(self, s):
1741
+ """Escape a qualified name.
1742
+
1743
+ Escapes the name for use as an SQL identifier, unless the
1744
+ name contains a dot, in which case the name is ambiguous
1745
+ (could be a qualified name or just a name with a dot in it)
1746
+ and must be quoted manually by the caller.
1747
+ """
1748
+ if '.' not in s:
1749
+ s = self.escape_identifier(s)
1750
+ return s
1751
+
1752
+ @staticmethod
1753
+ def _make_bool(d):
1754
+ """Get boolean value corresponding to d."""
1755
+ return bool(d) if get_bool() else ('t' if d else 'f')
1756
+
1757
+ @staticmethod
1758
+ def _list_params(params):
1759
+ """Create a human readable parameter list."""
1760
+ return ', '.join('$%d=%r' % (n, v) for n, v in enumerate(params, 1))
1761
+
1762
+ # Public methods
1763
+
1764
+ # escape_string and escape_bytea exist as methods,
1765
+ # so we define unescape_bytea as a method as well
1766
+ unescape_bytea = staticmethod(unescape_bytea)
1767
+
1768
+ @staticmethod
1769
+ def decode_json(s):
1770
+ """Decode a JSON string coming from the database."""
1771
+ return (get_jsondecode() or jsondecode)(s)
1772
+
1773
+ @staticmethod
1774
+ def encode_json(d):
1775
+ """Encode a JSON string for use within SQL."""
1776
+ return jsonencode(d)
1777
+
1778
+ def close(self):
1779
+ """Close the database connection."""
1780
+ # Wraps shared library function so we can track state.
1781
+ db = self.db
1782
+ if db:
1783
+ try:
1784
+ db.set_cast_hook(None)
1785
+ except TypeError:
1786
+ pass # probably already closed
1787
+ if self._closeable:
1788
+ db.close()
1789
+ self.db = None
1790
+ else:
1791
+ raise _int_error('Connection already closed')
1792
+
1793
+ def reset(self):
1794
+ """Reset connection with current parameters.
1795
+
1796
+ All derived queries and large objects derived from this connection
1797
+ will not be usable after this call.
1798
+
1799
+ """
1800
+ if self.db:
1801
+ self.db.reset()
1802
+ else:
1803
+ raise _int_error('Connection already closed')
1804
+
1805
+ def reopen(self):
1806
+ """Reopen connection to the database.
1807
+
1808
+ Used in case we need another connection to the same database.
1809
+ Note that we can still reopen a database that we have closed.
1810
+
1811
+ """
1812
+ # There is no such shared library function.
1813
+ if self._closeable:
1814
+ db = connect(*self._db_args[0], **self._db_args[1])
1815
+ if self.db:
1816
+ self.db.set_cast_hook(None)
1817
+ self.db.close()
1818
+ db.set_cast_hook(self.dbtypes.typecast)
1819
+ self.db = db
1820
+ else:
1821
+ self.db = self._db_args
1822
+
1823
+ def begin(self, mode=None):
1824
+ """Begin a transaction."""
1825
+ qstr = 'BEGIN'
1826
+ if mode:
1827
+ qstr += ' ' + mode
1828
+ return self.query(qstr)
1829
+
1830
+ start = begin
1831
+
1832
+ def commit(self):
1833
+ """Commit the current transaction."""
1834
+ return self.query('COMMIT')
1835
+
1836
+ end = commit
1837
+
1838
+ def rollback(self, name=None):
1839
+ """Roll back the current transaction."""
1840
+ qstr = 'ROLLBACK'
1841
+ if name:
1842
+ qstr += ' TO ' + name
1843
+ return self.query(qstr)
1844
+
1845
+ abort = rollback
1846
+
1847
+ def savepoint(self, name):
1848
+ """Define a new savepoint within the current transaction."""
1849
+ return self.query('SAVEPOINT ' + name)
1850
+
1851
+ def release(self, name):
1852
+ """Destroy a previously defined savepoint."""
1853
+ return self.query('RELEASE ' + name)
1854
+
1855
+ def get_parameter(self, parameter):
1856
+ """Get the value of a run-time parameter.
1857
+
1858
+ If the parameter is a string, the return value will also be a string
1859
+ that is the current setting of the run-time parameter with that name.
1860
+
1861
+ You can get several parameters at once by passing a list, set or dict.
1862
+ When passing a list of parameter names, the return value will be a
1863
+ corresponding list of parameter settings. When passing a set of
1864
+ parameter names, a new dict will be returned, mapping these parameter
1865
+ names to their settings. Finally, if you pass a dict as parameter,
1866
+ its values will be set to the current parameter settings corresponding
1867
+ to its keys.
1868
+
1869
+ By passing the special name 'all' as the parameter, you can get a dict
1870
+ of all existing configuration parameters.
1871
+ """
1872
+ if isinstance(parameter, basestring):
1873
+ parameter = [parameter]
1874
+ values = None
1875
+ elif isinstance(parameter, (list, tuple)):
1876
+ values = []
1877
+ elif isinstance(parameter, (set, frozenset)):
1878
+ values = {}
1879
+ elif isinstance(parameter, dict):
1880
+ values = parameter
1881
+ else:
1882
+ raise TypeError(
1883
+ 'The parameter must be a string, list, set or dict')
1884
+ if not parameter:
1885
+ raise TypeError('No parameter has been specified')
1886
+ params = {} if isinstance(values, dict) else []
1887
+ for key in parameter:
1888
+ param = key.strip().lower() if isinstance(
1889
+ key, basestring) else None
1890
+ if not param:
1891
+ raise TypeError('Invalid parameter')
1892
+ if param == 'all':
1893
+ q = 'SHOW ALL'
1894
+ values = self.db.query(q).getresult()
1895
+ values = {value[0]: value[1] for value in values}
1896
+ break
1897
+ if isinstance(values, dict):
1898
+ params[param] = key
1899
+ else:
1900
+ params.append(param)
1901
+ else:
1902
+ for param in params:
1903
+ q = 'SHOW %s' % (param,)
1904
+ value = self.db.query(q).singlescalar()
1905
+ if values is None:
1906
+ values = value
1907
+ elif isinstance(values, list):
1908
+ values.append(value)
1909
+ else:
1910
+ values[params[param]] = value
1911
+ return values
1912
+
1913
+ def set_parameter(self, parameter, value=None, local=False):
1914
+ """Set the value of a run-time parameter.
1915
+
1916
+ If the parameter and the value are strings, the run-time parameter
1917
+ will be set to that value. If no value or None is passed as a value,
1918
+ then the run-time parameter will be restored to its default value.
1919
+
1920
+ You can set several parameters at once by passing a list of parameter
1921
+ names, together with a single value that all parameters should be
1922
+ set to or with a corresponding list of values. You can also pass
1923
+ the parameters as a set if you only provide a single value.
1924
+ Finally, you can pass a dict with parameter names as keys. In this
1925
+ case, you should not pass a value, since the values for the parameters
1926
+ will be taken from the dict.
1927
+
1928
+ By passing the special name 'all' as the parameter, you can reset
1929
+ all existing settable run-time parameters to their default values.
1930
+
1931
+ If you set local to True, then the command takes effect for only the
1932
+ current transaction. After commit() or rollback(), the session-level
1933
+ setting takes effect again. Setting local to True will appear to
1934
+ have no effect if it is executed outside a transaction, since the
1935
+ transaction will end immediately.
1936
+ """
1937
+ if isinstance(parameter, basestring):
1938
+ parameter = {parameter: value}
1939
+ elif isinstance(parameter, (list, tuple)):
1940
+ if isinstance(value, (list, tuple)):
1941
+ parameter = dict(zip(parameter, value))
1942
+ else:
1943
+ parameter = dict.fromkeys(parameter, value)
1944
+ elif isinstance(parameter, (set, frozenset)):
1945
+ if isinstance(value, (list, tuple, set, frozenset)):
1946
+ value = set(value)
1947
+ if len(value) == 1:
1948
+ value = value.pop()
1949
+ if not (value is None or isinstance(value, basestring)):
1950
+ raise ValueError(
1951
+ 'A single value must be specified'
1952
+ ' when parameter is a set')
1953
+ parameter = dict.fromkeys(parameter, value)
1954
+ elif isinstance(parameter, dict):
1955
+ if value is not None:
1956
+ raise ValueError(
1957
+ 'A value must not be specified'
1958
+ ' when parameter is a dictionary')
1959
+ else:
1960
+ raise TypeError(
1961
+ 'The parameter must be a string, list, set or dict')
1962
+ if not parameter:
1963
+ raise TypeError('No parameter has been specified')
1964
+ params = {}
1965
+ for key, value in parameter.items():
1966
+ param = key.strip().lower() if isinstance(
1967
+ key, basestring) else None
1968
+ if not param:
1969
+ raise TypeError('Invalid parameter')
1970
+ if param == 'all':
1971
+ if value is not None:
1972
+ raise ValueError(
1973
+ 'A value must ot be specified'
1974
+ " when parameter is 'all'")
1975
+ params = {'all': None}
1976
+ break
1977
+ params[param] = value
1978
+ local = ' LOCAL' if local else ''
1979
+ for param, value in params.items():
1980
+ if value is None:
1981
+ q = 'RESET%s %s' % (local, param)
1982
+ else:
1983
+ q = 'SET%s %s TO %s' % (local, param, value)
1984
+ self._do_debug(q)
1985
+ self.db.query(q)
1986
+
1987
+ def query(self, command, *args):
1988
+ """Execute a SQL command string.
1989
+
1990
+ This method simply sends a SQL query to the database. If the query is
1991
+ an insert statement that inserted exactly one row into a table that
1992
+ has OIDs, the return value is the OID of the newly inserted row.
1993
+ If the query is an update or delete statement, or an insert statement
1994
+ that did not insert exactly one row in a table with OIDs, then the
1995
+ number of rows affected is returned as a string. If it is a statement
1996
+ that returns rows as a result (usually a select statement, but maybe
1997
+ also an "insert/update ... returning" statement), this method returns
1998
+ a Query object that can be accessed via getresult() or dictresult()
1999
+ or simply printed. Otherwise, it returns `None`.
2000
+
2001
+ The query can contain numbered parameters of the form $1 in place
2002
+ of any data constant. Arguments given after the query string will
2003
+ be substituted for the corresponding numbered parameter. Parameter
2004
+ values can also be given as a single list or tuple argument.
2005
+ """
2006
+ # Wraps shared library function for debugging.
2007
+ if not self.db:
2008
+ raise _int_error('Connection is not valid')
2009
+ if args:
2010
+ self._do_debug(command, args)
2011
+ return self.db.query(command, args)
2012
+ self._do_debug(command)
2013
+ return self.db.query(command)
2014
+
2015
+ def query_formatted(self, command,
2016
+ parameters=None, types=None, inline=False):
2017
+ """Execute a formatted SQL command string.
2018
+
2019
+ Similar to query, but using Python format placeholders of the form
2020
+ %s or %(names)s instead of PostgreSQL placeholders of the form $1.
2021
+ The parameters must be passed as a tuple, list or dict. You can
2022
+ also pass a corresponding tuple, list or dict of database types in
2023
+ order to format the parameters properly in case there is ambiguity.
2024
+
2025
+ If you set inline to True, the parameters will be sent to the database
2026
+ embedded in the SQL command, otherwise they will be sent separately.
2027
+ """
2028
+ return self.query(*self.adapter.format_query(
2029
+ command, parameters, types, inline))
2030
+
2031
+ def query_prepared(self, name, *args):
2032
+ """Execute a prepared SQL statement.
2033
+
2034
+ This works like the query() method, except that instead of passing
2035
+ the SQL command, you pass the name of a prepared statement. If you
2036
+ pass an empty name, the unnamed statement will be executed.
2037
+ """
2038
+ if not self.db:
2039
+ raise _int_error('Connection is not valid')
2040
+ if name is None:
2041
+ name = ''
2042
+ if args:
2043
+ self._do_debug('EXECUTE', name, args)
2044
+ return self.db.query_prepared(name, args)
2045
+ self._do_debug('EXECUTE', name)
2046
+ return self.db.query_prepared(name)
2047
+
2048
+ def prepare(self, name, command):
2049
+ """Create a prepared SQL statement.
2050
+
2051
+ This creates a prepared statement for the given command with the
2052
+ given name for later execution with the query_prepared() method.
2053
+
2054
+ The name can be empty to create an unnamed statement, in which case
2055
+ any pre-existing unnamed statement is automatically replaced;
2056
+ otherwise it is an error if the statement name is already
2057
+ defined in the current database session. We recommend always using
2058
+ named queries, since unnamed queries have a limited lifetime and
2059
+ can be automatically replaced or destroyed by various operations.
2060
+ """
2061
+ if not self.db:
2062
+ raise _int_error('Connection is not valid')
2063
+ if name is None:
2064
+ name = ''
2065
+ self._do_debug('prepare', name, command)
2066
+ return self.db.prepare(name, command)
2067
+
2068
+ def describe_prepared(self, name=None):
2069
+ """Describe a prepared SQL statement.
2070
+
2071
+ This method returns a Query object describing the result columns of
2072
+ the prepared statement with the given name. If you omit the name,
2073
+ the unnamed statement will be described if you created one before.
2074
+ """
2075
+ if name is None:
2076
+ name = ''
2077
+ return self.db.describe_prepared(name)
2078
+
2079
+ def delete_prepared(self, name=None):
2080
+ """Delete a prepared SQL statement
2081
+
2082
+ This deallocates a previously prepared SQL statement with the given
2083
+ name, or deallocates all prepared statements if you do not specify a
2084
+ name. Note that prepared statements are also deallocated automatically
2085
+ when the current session ends.
2086
+ """
2087
+ q = "DEALLOCATE %s" % (name or 'ALL',)
2088
+ self._do_debug(q)
2089
+ return self.db.query(q)
2090
+
2091
+ def pkey(self, table, composite=False, flush=False):
2092
+ """Get or set the primary key of a table.
2093
+
2094
+ Single primary keys are returned as strings unless you
2095
+ set the composite flag. Composite primary keys are always
2096
+ represented as tuples. Note that this raises a KeyError
2097
+ if the table does not have a primary key.
2098
+
2099
+ If flush is set then the internal cache for primary keys will
2100
+ be flushed. This may be necessary after the database schema or
2101
+ the search path has been changed.
2102
+ """
2103
+ pkeys = self._pkeys
2104
+ if flush:
2105
+ pkeys.clear()
2106
+ self._do_debug('The pkey cache has been flushed')
2107
+ try: # cache lookup
2108
+ pkey = pkeys[table]
2109
+ except KeyError: # cache miss, check the database
2110
+ q = ("SELECT a.attname, a.attnum, i.indkey"
2111
+ " FROM pg_catalog.pg_index i"
2112
+ " JOIN pg_catalog.pg_attribute a"
2113
+ " ON a.attrelid OPERATOR(pg_catalog.=) i.indrelid"
2114
+ " AND a.attnum OPERATOR(pg_catalog.=) ANY(i.indkey)"
2115
+ " AND NOT a.attisdropped"
2116
+ " WHERE i.indrelid OPERATOR(pg_catalog.=)"
2117
+ " %s::pg_catalog.regclass"
2118
+ " AND i.indisprimary ORDER BY a.attnum") % (
2119
+ _quote_if_unqualified('$1', table),)
2120
+ pkey = self.db.query(q, (table,)).getresult()
2121
+ if not pkey:
2122
+ raise KeyError('Table %s has no primary key' % table)
2123
+ # we want to use the order defined in the primary key index here,
2124
+ # not the order as defined by the columns in the table
2125
+ if len(pkey) > 1:
2126
+ indkey = pkey[0][2]
2127
+ pkey = sorted(pkey, key=lambda row: indkey.index(row[1]))
2128
+ pkey = tuple(row[0] for row in pkey)
2129
+ else:
2130
+ pkey = pkey[0][0]
2131
+ pkeys[table] = pkey # cache it
2132
+ if composite and not isinstance(pkey, tuple):
2133
+ pkey = (pkey,)
2134
+ return pkey
2135
+
2136
+ def get_databases(self):
2137
+ """Get list of databases in the system."""
2138
+ return [s[0] for s in self.db.query(
2139
+ 'SELECT datname FROM pg_catalog.pg_database').getresult()]
2140
+
2141
+ def get_relations(self, kinds=None, system=False):
2142
+ """Get list of relations in connected database of specified kinds.
2143
+
2144
+ If kinds is None or empty, all kinds of relations are returned.
2145
+ Otherwise, kinds can be a string or sequence of type letters
2146
+ specifying which kind of relations you want to list.
2147
+
2148
+ Set the system flag if you want to get the system relations as well.
2149
+ """
2150
+ where = []
2151
+ if kinds:
2152
+ where.append("r.relkind IN (%s)" %
2153
+ ','.join("'%s'" % k for k in kinds))
2154
+ if not system:
2155
+ where.append("s.nspname NOT SIMILAR"
2156
+ " TO 'pg/_%|information/_schema' ESCAPE '/'")
2157
+ where = " WHERE %s" % ' AND '.join(where) if where else ''
2158
+ q = ("SELECT pg_catalog.quote_ident(s.nspname) OPERATOR(pg_catalog.||)"
2159
+ " '.' OPERATOR(pg_catalog.||) pg_catalog.quote_ident(r.relname)"
2160
+ " FROM pg_catalog.pg_class r"
2161
+ " JOIN pg_catalog.pg_namespace s"
2162
+ " ON s.oid OPERATOR(pg_catalog.=) r.relnamespace%s"
2163
+ " ORDER BY s.nspname, r.relname") % where
2164
+ return [r[0] for r in self.db.query(q).getresult()]
2165
+
2166
+ def get_tables(self, system=False):
2167
+ """Return list of tables in connected database.
2168
+
2169
+ Set the system flag if you want to get the system tables as well.
2170
+ """
2171
+ return self.get_relations('r', system)
2172
+
2173
+ def get_attnames(self, table, with_oid=True, flush=False):
2174
+ """Given the name of a table, dig out the set of attribute names.
2175
+
2176
+ Returns a read-only dictionary of attribute names (the names are
2177
+ the keys, the values are the names of the attributes' types)
2178
+ with the column names in the proper order if you iterate over it.
2179
+
2180
+ If flush is set, then the internal cache for attribute names will
2181
+ be flushed. This may be necessary after the database schema or
2182
+ the search path has been changed.
2183
+
2184
+ By default, only a limited number of simple types will be returned.
2185
+ You can get the registered types after calling use_regtypes(True).
2186
+ """
2187
+ attnames = self._attnames
2188
+ if flush:
2189
+ attnames.clear()
2190
+ self._do_debug('The attnames cache has been flushed')
2191
+ try: # cache lookup
2192
+ names = attnames[table]
2193
+ except KeyError: # cache miss, check the database
2194
+ q = "a.attnum OPERATOR(pg_catalog.>) 0"
2195
+ if with_oid:
2196
+ q = "(%s OR a.attname OPERATOR(pg_catalog.=) 'oid')" % q
2197
+ q = self._query_attnames % (_quote_if_unqualified('$1', table), q)
2198
+ names = self.db.query(q, (table,)).getresult()
2199
+ types = self.dbtypes
2200
+ names = ((name[0], types.add(*name[1:])) for name in names)
2201
+ names = AttrDict(names)
2202
+ attnames[table] = names # cache it
2203
+ return names
2204
+
2205
+ def get_generated(self, table, flush=False):
2206
+ """Given the name of a table, dig out the set of generated columns.
2207
+
2208
+ Returns a set of column names that are generated and unalterable.
2209
+
2210
+ If flush is set, then the internal cache for generated columns will
2211
+ be flushed. This may be necessary after the database schema or
2212
+ the search path has been changed.
2213
+ """
2214
+ query_generated = self._query_generated
2215
+ if not query_generated:
2216
+ return frozenset()
2217
+ generated = self._generated
2218
+ if flush:
2219
+ generated.clear()
2220
+ self._do_debug('The generated cache has been flushed')
2221
+ try: # cache lookup
2222
+ names = generated[table]
2223
+ except KeyError: # cache miss, check the database
2224
+ q = "a.attnum OPERATOR(pg_catalog.>) 0 AND " + query_generated
2225
+ q = self._query_attnames % (_quote_if_unqualified('$1', table), q)
2226
+ names = self.db.query(q, (table,)).getresult()
2227
+ names = frozenset(name[0] for name in names)
2228
+ generated[table] = names # cache it
2229
+ return names
2230
+
2231
+ def use_regtypes(self, regtypes=None):
2232
+ """Use registered type names instead of simplified type names."""
2233
+ if regtypes is None:
2234
+ return self.dbtypes._regtypes
2235
+ else:
2236
+ regtypes = bool(regtypes)
2237
+ if regtypes != self.dbtypes._regtypes:
2238
+ self.dbtypes._regtypes = regtypes
2239
+ self._attnames.clear()
2240
+ self.dbtypes.clear()
2241
+ return regtypes
2242
+
2243
+ def has_table_privilege(self, table, privilege='select', flush=False):
2244
+ """Check whether current user has specified table privilege.
2245
+
2246
+ If flush is set, then the internal cache for table privileges will
2247
+ be flushed. This may be necessary after privileges have been changed.
2248
+ """
2249
+ privileges = self._privileges
2250
+ if flush:
2251
+ privileges.clear()
2252
+ self._do_debug('The privileges cache has been flushed')
2253
+ privilege = privilege.lower()
2254
+ try: # ask cache
2255
+ ret = privileges[table, privilege]
2256
+ except KeyError: # cache miss, ask the database
2257
+ q = "SELECT pg_catalog.has_table_privilege(%s, $2)" % (
2258
+ _quote_if_unqualified('$1', table),)
2259
+ q = self.db.query(q, (table, privilege))
2260
+ ret = q.singlescalar() == self._make_bool(True)
2261
+ privileges[table, privilege] = ret # cache it
2262
+ return ret
2263
+
2264
+ def get(self, table, row, keyname=None):
2265
+ """Get a row from a database table or view.
2266
+
2267
+ This method is the basic mechanism to get a single row. It assumes
2268
+ that the keyname specifies a unique row. It must be the name of a
2269
+ single column or a tuple of column names. If the keyname is not
2270
+ specified, then the primary key for the table is used.
2271
+
2272
+ If row is a dictionary, then the value for the key is taken from it.
2273
+ Otherwise, the row must be a single value or a tuple of values
2274
+ corresponding to the passed keyname or primary key. The fetched row
2275
+ from the table will be returned as a new dictionary or used to replace
2276
+ the existing values when row was passed as a dictionary.
2277
+
2278
+ The OID is also put into the dictionary if the table has one, but
2279
+ in order to allow the caller to work with multiple tables, it is
2280
+ munged as "oid(table)" using the actual name of the table.
2281
+ """
2282
+ if table.endswith('*'): # hint for descendant tables can be ignored
2283
+ table = table[:-1].rstrip()
2284
+ attnames = self.get_attnames(table)
2285
+ qoid = _oid_key(table) if 'oid' in attnames else None
2286
+ if keyname and isinstance(keyname, basestring):
2287
+ keyname = (keyname,)
2288
+ if qoid and isinstance(row, dict) and qoid in row and 'oid' not in row:
2289
+ row['oid'] = row[qoid]
2290
+ if not keyname:
2291
+ try: # if keyname is not specified, try using the primary key
2292
+ keyname = self.pkey(table, True)
2293
+ except KeyError: # the table has no primary key
2294
+ # try using the oid instead
2295
+ if qoid and isinstance(row, dict) and 'oid' in row:
2296
+ keyname = ('oid',)
2297
+ else:
2298
+ raise _prg_error('Table %s has no primary key' % table)
2299
+ else: # the table has a primary key
2300
+ # check whether all key columns have values
2301
+ if isinstance(row, dict) and not set(keyname).issubset(row):
2302
+ # try using the oid instead
2303
+ if qoid and 'oid' in row:
2304
+ keyname = ('oid',)
2305
+ else:
2306
+ raise KeyError(
2307
+ 'Missing value in row for specified keyname')
2308
+ if not isinstance(row, dict):
2309
+ if not isinstance(row, (tuple, list)):
2310
+ row = [row]
2311
+ if len(keyname) != len(row):
2312
+ raise KeyError(
2313
+ 'Differing number of items in keyname and row')
2314
+ row = dict(zip(keyname, row))
2315
+ params = self.adapter.parameter_list()
2316
+ adapt = params.add
2317
+ col = self.escape_identifier
2318
+ what = 'oid, *' if qoid else '*'
2319
+ where = ' AND '.join('%s OPERATOR(pg_catalog.=) %s' % (
2320
+ col(k), adapt(row[k], attnames[k])) for k in keyname)
2321
+ if 'oid' in row:
2322
+ if qoid:
2323
+ row[qoid] = row['oid']
2324
+ del row['oid']
2325
+ q = 'SELECT %s FROM %s WHERE %s LIMIT 1' % (
2326
+ what, self._escape_qualified_name(table), where)
2327
+ self._do_debug(q, params)
2328
+ q = self.db.query(q, params)
2329
+ res = q.dictresult()
2330
+ if not res:
2331
+ # make where clause in error message better readable
2332
+ where = where.replace('OPERATOR(pg_catalog.=)', '=')
2333
+ raise _db_error('No such record in %s\nwhere %s\nwith %s' % (
2334
+ table, where, self._list_params(params)))
2335
+ for n, value in res[0].items():
2336
+ if qoid and n == 'oid':
2337
+ n = qoid
2338
+ row[n] = value
2339
+ return row
2340
+
2341
+ def insert(self, table, row=None, **kw):
2342
+ """Insert a row into a database table.
2343
+
2344
+ This method inserts a row into a table. The name of the table must
2345
+ be passed as the first parameter. The other parameters are used for
2346
+ providing the data of the row that shall be inserted into the table.
2347
+ If a dictionary is supplied as the second parameter, it starts with
2348
+ that. Otherwise, it uses a blank dictionary.
2349
+ Either way the dictionary is updated from the keywords.
2350
+
2351
+ The dictionary is then reloaded with the values actually inserted in
2352
+ order to pick up values modified by rules, triggers, etc.
2353
+ """
2354
+ if table.endswith('*'): # hint for descendant tables can be ignored
2355
+ table = table[:-1].rstrip()
2356
+ if row is None:
2357
+ row = {}
2358
+ row.update(kw)
2359
+ if 'oid' in row:
2360
+ del row['oid'] # do not insert oid
2361
+ attnames = self.get_attnames(table)
2362
+ generated = self.get_generated(table)
2363
+ qoid = _oid_key(table) if 'oid' in attnames else None
2364
+ params = self.adapter.parameter_list()
2365
+ adapt = params.add
2366
+ col = self.escape_identifier
2367
+ names, values = [], []
2368
+ for n in attnames:
2369
+ if n in row and n not in generated:
2370
+ names.append(col(n))
2371
+ values.append(adapt(row[n], attnames[n]))
2372
+ if not names:
2373
+ raise _prg_error('No column found that can be inserted')
2374
+ names, values = ', '.join(names), ', '.join(values)
2375
+ ret = 'oid, *' if qoid else '*'
2376
+ q = 'INSERT INTO %s (%s) VALUES (%s) RETURNING %s' % (
2377
+ self._escape_qualified_name(table), names, values, ret)
2378
+ self._do_debug(q, params)
2379
+ q = self.db.query(q, params)
2380
+ res = q.dictresult()
2381
+ if res: # this should always be true
2382
+ for n, value in res[0].items():
2383
+ if qoid and n == 'oid':
2384
+ n = qoid
2385
+ row[n] = value
2386
+ return row
2387
+
2388
+ def update(self, table, row=None, **kw):
2389
+ """Update an existing row in a database table.
2390
+
2391
+ Similar to insert, but updates an existing row. The update is based
2392
+ on the primary key of the table or the OID value as munged by get()
2393
+ or passed as keyword. The OID will take precedence if provided, so
2394
+ that it is possible to update the primary key itself.
2395
+
2396
+ The dictionary is then modified to reflect any changes caused by the
2397
+ update due to triggers, rules, default values, etc.
2398
+ """
2399
+ if table.endswith('*'):
2400
+ table = table[:-1].rstrip() # need parent table name
2401
+ attnames = self.get_attnames(table)
2402
+ generated = self.get_generated(table)
2403
+ qoid = _oid_key(table) if 'oid' in attnames else None
2404
+ if row is None:
2405
+ row = {}
2406
+ elif 'oid' in row:
2407
+ del row['oid'] # only accept oid key from named args for safety
2408
+ row.update(kw)
2409
+ if qoid and qoid in row and 'oid' not in row:
2410
+ row['oid'] = row[qoid]
2411
+ if qoid and 'oid' in row: # try using the oid
2412
+ keyname = ('oid',)
2413
+ else: # try using the primary key
2414
+ try:
2415
+ keyname = self.pkey(table, True)
2416
+ except KeyError: # the table has no primary key
2417
+ raise _prg_error('Table %s has no primary key' % table)
2418
+ # check whether all key columns have values
2419
+ if not set(keyname).issubset(row):
2420
+ raise KeyError('Missing value for primary key in row')
2421
+ params = self.adapter.parameter_list()
2422
+ adapt = params.add
2423
+ col = self.escape_identifier
2424
+ where = ' AND '.join('%s OPERATOR(pg_catalog.=) %s' % (
2425
+ col(k), adapt(row[k], attnames[k])) for k in keyname)
2426
+ if 'oid' in row:
2427
+ if qoid:
2428
+ row[qoid] = row['oid']
2429
+ del row['oid']
2430
+ values = []
2431
+ keyname = set(keyname)
2432
+ for n in attnames:
2433
+ if n in row and n not in keyname and n not in generated:
2434
+ values.append('%s = %s' % (col(n), adapt(row[n], attnames[n])))
2435
+ if not values:
2436
+ return row
2437
+ values = ', '.join(values)
2438
+ ret = 'oid, *' if qoid else '*'
2439
+ q = 'UPDATE %s SET %s WHERE %s RETURNING %s' % (
2440
+ self._escape_qualified_name(table), values, where, ret)
2441
+ self._do_debug(q, params)
2442
+ q = self.db.query(q, params)
2443
+ res = q.dictresult()
2444
+ if res: # may be empty when row does not exist
2445
+ for n, value in res[0].items():
2446
+ if qoid and n == 'oid':
2447
+ n = qoid
2448
+ row[n] = value
2449
+ return row
2450
+
2451
+ def upsert(self, table, row=None, **kw):
2452
+ """Insert a row into a database table with conflict resolution
2453
+
2454
+ This method inserts a row into a table, but instead of raising a
2455
+ ProgrammingError exception in case a row with the same primary key
2456
+ already exists, an update will be executed instead. This will be
2457
+ performed as a single atomic operation on the database, so race
2458
+ conditions can be avoided.
2459
+
2460
+ Like the insert method, the first parameter is the name of the
2461
+ table and the second parameter can be used to pass the values to
2462
+ be inserted as a dictionary.
2463
+
2464
+ Unlike the insert und update statement, keyword parameters are not
2465
+ used to modify the dictionary, but to specify which columns shall
2466
+ be updated in case of a conflict, and in which way:
2467
+
2468
+ A value of False or None means the column shall not be updated,
2469
+ a value of True means the column shall be updated with the value
2470
+ that has been proposed for insertion, i.e. has been passed as value
2471
+ in the dictionary. Columns that are not specified by keywords but
2472
+ appear as keys in the dictionary are also updated like in the case
2473
+ keywords had been passed with the value True.
2474
+
2475
+ So if in the case of a conflict you want to update every column
2476
+ that has been passed in the dictionary row, you would call
2477
+ upsert(table, row). If you don't want to do anything in case
2478
+ of a conflict, i.e. leave the existing row as it is, call
2479
+ upsert(table, row, **dict.fromkeys(row)).
2480
+
2481
+ If you need more fine-grained control of what gets updated, you can
2482
+ also pass strings in the keyword parameters. These strings will
2483
+ be used as SQL expressions for the update columns. In these
2484
+ expressions you can refer to the value that already exists in
2485
+ the table by prefixing the column name with "included.", and to
2486
+ the value that has been proposed for insertion by prefixing the
2487
+ column name with the "excluded."
2488
+
2489
+ The dictionary is modified in any case to reflect the values in
2490
+ the database after the operation has completed.
2491
+
2492
+ Note: The method uses the PostgreSQL "upsert" feature which is
2493
+ only available since PostgreSQL 9.5.
2494
+ """
2495
+ if table.endswith('*'): # hint for descendant tables can be ignored
2496
+ table = table[:-1].rstrip()
2497
+ if row is None:
2498
+ row = {}
2499
+ if 'oid' in row:
2500
+ del row['oid'] # do not insert oid
2501
+ if 'oid' in kw:
2502
+ del kw['oid'] # do not update oid
2503
+ attnames = self.get_attnames(table)
2504
+ generated = self.get_generated(table)
2505
+ qoid = _oid_key(table) if 'oid' in attnames else None
2506
+ params = self.adapter.parameter_list()
2507
+ adapt = params.add
2508
+ col = self.escape_identifier
2509
+ names, values = [], []
2510
+ for n in attnames:
2511
+ if n in row and n not in generated:
2512
+ names.append(col(n))
2513
+ values.append(adapt(row[n], attnames[n]))
2514
+ names, values = ', '.join(names), ', '.join(values)
2515
+ try:
2516
+ keyname = self.pkey(table, True)
2517
+ except KeyError:
2518
+ raise _prg_error('Table %s has no primary key' % table)
2519
+ target = ', '.join(col(k) for k in keyname)
2520
+ update = []
2521
+ keyname = set(keyname)
2522
+ keyname.add('oid')
2523
+ for n in attnames:
2524
+ if n not in keyname and n not in generated:
2525
+ value = kw.get(n, n in row)
2526
+ if value:
2527
+ if not isinstance(value, basestring):
2528
+ value = 'excluded.%s' % col(n)
2529
+ update.append('%s = %s' % (col(n), value))
2530
+ if not values:
2531
+ return row
2532
+ do = 'update set %s' % ', '.join(update) if update else 'nothing'
2533
+ ret = 'oid, *' if qoid else '*'
2534
+ q = ('INSERT INTO %s AS included (%s) VALUES (%s)'
2535
+ ' ON CONFLICT (%s) DO %s RETURNING %s') % (
2536
+ self._escape_qualified_name(table), names, values, target, do, ret)
2537
+ self._do_debug(q, params)
2538
+ try:
2539
+ q = self.db.query(q, params)
2540
+ except ProgrammingError:
2541
+ if self.server_version < 90500:
2542
+ raise _prg_error(
2543
+ 'Upsert operation is not supported by PostgreSQL version')
2544
+ raise # re-raise original error
2545
+ res = q.dictresult()
2546
+ if res: # may be empty with "do nothing"
2547
+ for n, value in res[0].items():
2548
+ if qoid and n == 'oid':
2549
+ n = qoid
2550
+ row[n] = value
2551
+ else:
2552
+ self.get(table, row)
2553
+ return row
2554
+
2555
+ def clear(self, table, row=None):
2556
+ """Clear all the attributes to values determined by the types.
2557
+
2558
+ Numeric types are set to 0, Booleans are set to false, and everything
2559
+ else is set to the empty string. If the row argument is present,
2560
+ it is used as the row dictionary and any entries matching attribute
2561
+ names are cleared with everything else left unchanged.
2562
+ """
2563
+ # At some point we will need a way to get defaults from a table.
2564
+ if row is None:
2565
+ row = {} # empty if argument is not present
2566
+ attnames = self.get_attnames(table)
2567
+ for n, t in attnames.items():
2568
+ if n == 'oid':
2569
+ continue
2570
+ t = t.simple
2571
+ if t in DbTypes._num_types:
2572
+ row[n] = 0
2573
+ elif t == 'bool':
2574
+ row[n] = self._make_bool(False)
2575
+ else:
2576
+ row[n] = ''
2577
+ return row
2578
+
2579
+ def delete(self, table, row=None, **kw):
2580
+ """Delete an existing row in a database table.
2581
+
2582
+ This method deletes the row from a table. It deletes based on the
2583
+ primary key of the table or the OID value as munged by get() or
2584
+ passed as keyword. The OID will take precedence if provided.
2585
+
2586
+ The return value is the number of deleted rows (i.e. 0 if the row
2587
+ did not exist and 1 if the row was deleted).
2588
+
2589
+ Note that if the row cannot be deleted because e.g. it is still
2590
+ referenced by another table, this method raises a ProgrammingError.
2591
+ """
2592
+ if table.endswith('*'): # hint for descendant tables can be ignored
2593
+ table = table[:-1].rstrip()
2594
+ attnames = self.get_attnames(table)
2595
+ qoid = _oid_key(table) if 'oid' in attnames else None
2596
+ if row is None:
2597
+ row = {}
2598
+ elif 'oid' in row:
2599
+ del row['oid'] # only accept oid key from named args for safety
2600
+ row.update(kw)
2601
+ if qoid and qoid in row and 'oid' not in row:
2602
+ row['oid'] = row[qoid]
2603
+ if qoid and 'oid' in row: # try using the oid
2604
+ keyname = ('oid',)
2605
+ else: # try using the primary key
2606
+ try:
2607
+ keyname = self.pkey(table, True)
2608
+ except KeyError: # the table has no primary key
2609
+ raise _prg_error('Table %s has no primary key' % table)
2610
+ # check whether all key columns have values
2611
+ if not set(keyname).issubset(row):
2612
+ raise KeyError('Missing value for primary key in row')
2613
+ params = self.adapter.parameter_list()
2614
+ adapt = params.add
2615
+ col = self.escape_identifier
2616
+ where = ' AND '.join('%s OPERATOR(pg_catalog.=) %s' % (
2617
+ col(k), adapt(row[k], attnames[k])) for k in keyname)
2618
+ if 'oid' in row:
2619
+ if qoid:
2620
+ row[qoid] = row['oid']
2621
+ del row['oid']
2622
+ q = 'DELETE FROM %s WHERE %s' % (
2623
+ self._escape_qualified_name(table), where)
2624
+ self._do_debug(q, params)
2625
+ res = self.db.query(q, params)
2626
+ return int(res)
2627
+
2628
+ def truncate(self, table, restart=False, cascade=False, only=False):
2629
+ """Empty a table or set of tables.
2630
+
2631
+ This method quickly removes all rows from the given table or set
2632
+ of tables. It has the same effect as an unqualified DELETE on each
2633
+ table, but since it does not actually scan the tables it is faster.
2634
+ Furthermore, it reclaims disk space immediately, rather than requiring
2635
+ a subsequent VACUUM operation. This is most useful on large tables.
2636
+
2637
+ If restart is set to True, sequences owned by columns of the truncated
2638
+ table(s) are automatically restarted. If cascade is set to True, it
2639
+ also truncates all tables that have foreign-key references to any of
2640
+ the named tables. If the parameter only is not set to True, all the
2641
+ descendant tables (if any) will also be truncated. Optionally, a '*'
2642
+ can be specified after the table name to explicitly indicate that
2643
+ descendant tables are included.
2644
+ """
2645
+ if isinstance(table, basestring):
2646
+ only = {table: only}
2647
+ table = [table]
2648
+ elif isinstance(table, (list, tuple)):
2649
+ if isinstance(only, (list, tuple)):
2650
+ only = dict(zip(table, only))
2651
+ else:
2652
+ only = dict.fromkeys(table, only)
2653
+ elif isinstance(table, (set, frozenset)):
2654
+ only = dict.fromkeys(table, only)
2655
+ else:
2656
+ raise TypeError('The table must be a string, list or set')
2657
+ if not (restart is None or isinstance(restart, (bool, int))):
2658
+ raise TypeError('Invalid type for the restart option')
2659
+ if not (cascade is None or isinstance(cascade, (bool, int))):
2660
+ raise TypeError('Invalid type for the cascade option')
2661
+ tables = []
2662
+ for t in table:
2663
+ u = only.get(t)
2664
+ if not (u is None or isinstance(u, (bool, int))):
2665
+ raise TypeError('Invalid type for the only option')
2666
+ if t.endswith('*'):
2667
+ if u:
2668
+ raise ValueError(
2669
+ 'Contradictory table name and only options')
2670
+ t = t[:-1].rstrip()
2671
+ t = self._escape_qualified_name(t)
2672
+ if u:
2673
+ t = 'ONLY %s' % t
2674
+ tables.append(t)
2675
+ q = ['TRUNCATE', ', '.join(tables)]
2676
+ if restart:
2677
+ q.append('RESTART IDENTITY')
2678
+ if cascade:
2679
+ q.append('CASCADE')
2680
+ q = ' '.join(q)
2681
+ self._do_debug(q)
2682
+ return self.db.query(q)
2683
+
2684
+ def get_as_list(self, table, what=None, where=None,
2685
+ order=None, limit=None, offset=None, scalar=False):
2686
+ """Get a table as a list.
2687
+
2688
+ This gets a convenient representation of the table as a list
2689
+ of named tuples in Python. You only need to pass the name of
2690
+ the table (or any other SQL expression returning rows). Note that
2691
+ by default this will return the full content of the table which
2692
+ can be huge and overflow your memory. However, you can control
2693
+ the amount of data returned using the other optional parameters.
2694
+
2695
+ The parameter 'what' can restrict the query to only return a
2696
+ subset of the table columns. It can be a string, list or a tuple.
2697
+ The parameter 'where' can restrict the query to only return a
2698
+ subset of the table rows. It can be a string, list or a tuple
2699
+ of SQL expressions that all need to be fulfilled. The parameter
2700
+ 'order' specifies the ordering of the rows. It can also be a
2701
+ other string, list or a tuple. If no ordering is specified,
2702
+ the result will be ordered by the primary key(s) or all columns
2703
+ if no primary key exists. You can set 'order' to False if you
2704
+ don't care about the ordering. The parameters 'limit' and 'offset'
2705
+ can be integers specifying the maximum number of rows returned
2706
+ and a number of rows skipped over.
2707
+
2708
+ If you set the 'scalar' option to True, then instead of the
2709
+ named tuples you will get the first items of these tuples.
2710
+ This is useful if the result has only one column anyway.
2711
+ """
2712
+ if not table:
2713
+ raise TypeError('The table name is missing')
2714
+ if what:
2715
+ if isinstance(what, (list, tuple)):
2716
+ what = ', '.join(map(str, what))
2717
+ if order is None:
2718
+ order = what
2719
+ else:
2720
+ what = '*'
2721
+ q = ['SELECT', what, 'FROM', table]
2722
+ if where:
2723
+ if isinstance(where, (list, tuple)):
2724
+ where = ' AND '.join(map(str, where))
2725
+ q.extend(['WHERE', where])
2726
+ if order is None:
2727
+ try:
2728
+ order = self.pkey(table, True)
2729
+ except (KeyError, ProgrammingError):
2730
+ try:
2731
+ order = list(self.get_attnames(table))
2732
+ except (KeyError, ProgrammingError):
2733
+ pass
2734
+ if order:
2735
+ if isinstance(order, (list, tuple)):
2736
+ order = ', '.join(map(str, order))
2737
+ q.extend(['ORDER BY', order])
2738
+ if limit:
2739
+ q.append('LIMIT %d' % limit)
2740
+ if offset:
2741
+ q.append('OFFSET %d' % offset)
2742
+ q = ' '.join(q)
2743
+ self._do_debug(q)
2744
+ q = self.db.query(q)
2745
+ res = q.namedresult()
2746
+ if res and scalar:
2747
+ res = [row[0] for row in res]
2748
+ return res
2749
+
2750
+ def get_as_dict(self, table, keyname=None, what=None, where=None,
2751
+ order=None, limit=None, offset=None, scalar=False):
2752
+ """Get a table as a dictionary.
2753
+
2754
+ This method is similar to get_as_list(), but returns the table
2755
+ as a Python dict instead of a Python list, which can be even
2756
+ more convenient. The primary key column(s) of the table will
2757
+ be used as the keys of the dictionary, while the other column(s)
2758
+ will be the corresponding values. The keys will be named tuples
2759
+ if the table has a composite primary key. The rows will be also
2760
+ named tuples unless the 'scalar' option has been set to True.
2761
+ With the optional parameter 'keyname' you can specify an alternative
2762
+ set of columns to be used as the keys of the dictionary. It must
2763
+ be set as a string, list or a tuple.
2764
+
2765
+ If the Python version supports it, the dictionary will be an
2766
+ OrderedDict using the order specified with the 'order' parameter
2767
+ or the key column(s) if not specified. You can set 'order' to False
2768
+ if you don't care about the ordering. In this case the returned
2769
+ dictionary will be an ordinary one.
2770
+ """
2771
+ if not table:
2772
+ raise TypeError('The table name is missing')
2773
+ if not keyname:
2774
+ try:
2775
+ keyname = self.pkey(table, True)
2776
+ except (KeyError, ProgrammingError):
2777
+ raise _prg_error('Table %s has no primary key' % table)
2778
+ if isinstance(keyname, basestring):
2779
+ keyname = [keyname]
2780
+ elif not isinstance(keyname, (list, tuple)):
2781
+ raise KeyError('The keyname must be a string, list or tuple')
2782
+ if what:
2783
+ if isinstance(what, (list, tuple)):
2784
+ what = ', '.join(map(str, what))
2785
+ if order is None:
2786
+ order = what
2787
+ else:
2788
+ what = '*'
2789
+ q = ['SELECT', what, 'FROM', table]
2790
+ if where:
2791
+ if isinstance(where, (list, tuple)):
2792
+ where = ' AND '.join(map(str, where))
2793
+ q.extend(['WHERE', where])
2794
+ if order is None:
2795
+ order = keyname
2796
+ if order:
2797
+ if isinstance(order, (list, tuple)):
2798
+ order = ', '.join(map(str, order))
2799
+ q.extend(['ORDER BY', order])
2800
+ if limit:
2801
+ q.append('LIMIT %d' % limit)
2802
+ if offset:
2803
+ q.append('OFFSET %d' % offset)
2804
+ q = ' '.join(q)
2805
+ self._do_debug(q)
2806
+ q = self.db.query(q)
2807
+ res = q.getresult()
2808
+ cls = OrderedDict if order else dict
2809
+ if not res:
2810
+ return cls()
2811
+ keyset = set(keyname)
2812
+ fields = q.listfields()
2813
+ if not keyset.issubset(fields):
2814
+ raise KeyError('Missing keyname in row')
2815
+ keyind, rowind = [], []
2816
+ for i, f in enumerate(fields):
2817
+ (keyind if f in keyset else rowind).append(i)
2818
+ keytuple = len(keyind) > 1
2819
+ getkey = itemgetter(*keyind)
2820
+ keys = map(getkey, res)
2821
+ if scalar:
2822
+ rowind = rowind[:1]
2823
+ rowtuple = False
2824
+ else:
2825
+ rowtuple = len(rowind) > 1
2826
+ if scalar or rowtuple:
2827
+ getrow = itemgetter(*rowind)
2828
+ else:
2829
+ rowind = rowind[0]
2830
+
2831
+ def getrow(row):
2832
+ return row[rowind], # tuple with one item
2833
+
2834
+ rowtuple = True
2835
+ rows = map(getrow, res)
2836
+ if keytuple or rowtuple:
2837
+ if keytuple:
2838
+ keys = _namediter(_MemoryQuery(keys, keyname))
2839
+ if rowtuple:
2840
+ fields = [f for f in fields if f not in keyset]
2841
+ rows = _namediter(_MemoryQuery(rows, fields))
2842
+ # noinspection PyArgumentList
2843
+ return cls(zip(keys, rows))
2844
+
2845
+ def notification_handler(self, event, callback,
2846
+ arg_dict=None, timeout=None, stop_event=None):
2847
+ """Get notification handler that will run the given callback."""
2848
+ return NotificationHandler(self, event, callback,
2849
+ arg_dict, timeout, stop_event)
2850
+
2851
+
2852
+ # if run as script, print some information
2853
+
2854
+ if __name__ == '__main__':
2855
+ print('PyGreSQL version' + version)
2856
+ print('')
2857
+ print(__doc__)