PyGreSQL 5.2.5__cp311-cp311-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pgdb.py ADDED
@@ -0,0 +1,1941 @@
1
+ #!/usr/bin/python
2
+ #
3
+ # PyGreSQL - a Python interface for the PostgreSQL database.
4
+ #
5
+ # This file contains the DB-API 2 compatible pgdb module.
6
+ #
7
+ # Copyright (c) 2023 by the PyGreSQL Development Team
8
+ #
9
+ # Please see the LICENSE.TXT file for specific restrictions.
10
+
11
+ """pgdb - DB-API 2.0 compliant module for PyGreSQL.
12
+
13
+ (c) 1999, Pascal Andre <andre@via.ecp.fr>.
14
+ See package documentation for further information on copyright.
15
+
16
+ Inline documentation is sparse.
17
+ See DB-API 2.0 specification for usage information:
18
+ http://www.python.org/peps/pep-0249.html
19
+
20
+ Basic usage:
21
+
22
+ pgdb.connect(connect_string) # open a connection
23
+ # connect_string = 'host:database:user:password:opt'
24
+ # All parts are optional. You may also pass host through
25
+ # password as keyword arguments. To pass a port,
26
+ # pass it in the host keyword parameter:
27
+ connection = pgdb.connect(host='localhost:5432')
28
+
29
+ cursor = connection.cursor() # open a cursor
30
+
31
+ cursor.execute(query[, params])
32
+ # Execute a query, binding params (a dictionary) if they are
33
+ # passed. The binding syntax is the same as the % operator
34
+ # for dictionaries, and no quoting is done.
35
+
36
+ cursor.executemany(query, list of params)
37
+ # Execute a query many times, binding each param dictionary
38
+ # from the list.
39
+
40
+ cursor.fetchone() # fetch one row, [value, value, ...]
41
+
42
+ cursor.fetchall() # fetch all rows, [[value, value, ...], ...]
43
+
44
+ cursor.fetchmany([size])
45
+ # returns size or cursor.arraysize number of rows,
46
+ # [[value, value, ...], ...] from result set.
47
+ # Default cursor.arraysize is 1.
48
+
49
+ cursor.description # returns information about the columns
50
+ # [(column_name, type_name, display_size,
51
+ # internal_size, precision, scale, null_ok), ...]
52
+ # Note that display_size, precision, scale and null_ok
53
+ # are not implemented.
54
+
55
+ cursor.rowcount # number of rows available in the result set
56
+ # Available after a call to execute.
57
+
58
+ connection.commit() # commit transaction
59
+
60
+ connection.rollback() # or rollback transaction
61
+
62
+ cursor.close() # close the cursor
63
+
64
+ connection.close() # close the connection
65
+ """
66
+
67
+ from __future__ import print_function, division
68
+
69
+ try:
70
+ from _pg import *
71
+ except ImportError as e:
72
+ import os
73
+ libpq = 'libpq.'
74
+ if os.name == 'nt':
75
+ libpq += 'dll'
76
+ import sys
77
+ paths = [path for path in os.environ["PATH"].split(os.pathsep)
78
+ if os.path.exists(os.path.join(path, libpq))]
79
+ if sys.version_info >= (3, 8):
80
+ # see https://docs.python.org/3/whatsnew/3.8.html#ctypes
81
+ for path in paths:
82
+ with os.add_dll_directory(os.path.abspath(path)):
83
+ try:
84
+ from _pg import *
85
+ except ImportError:
86
+ pass
87
+ else:
88
+ e = None
89
+ break
90
+ if paths:
91
+ libpq = 'compatible ' + libpq
92
+ else:
93
+ libpq += 'so'
94
+ if e:
95
+ # note: we could use "raise from e" here in Python 3
96
+ raise ImportError(
97
+ "Cannot import shared library for PyGreSQL,\n"
98
+ "probably because no %s is installed.\n%s" % (libpq, e))
99
+
100
+ __version__ = version
101
+
102
+ __all__ = [
103
+ 'Connection', 'Cursor',
104
+ 'Date', 'Time', 'Timestamp',
105
+ 'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
106
+ 'Binary', 'Interval', 'Uuid',
107
+ 'Hstore', 'Json', 'Literal', 'Type',
108
+ 'STRING', 'BINARY', 'NUMBER', 'DATETIME', 'ROWID', 'BOOL',
109
+ 'SMALLINT', 'INTEGER', 'LONG', 'FLOAT', 'NUMERIC', 'MONEY',
110
+ 'DATE', 'TIME', 'TIMESTAMP', 'INTERVAL',
111
+ 'UUID', 'HSTORE', 'JSON', 'ARRAY', 'RECORD',
112
+ 'Error', 'Warning',
113
+ 'InterfaceError', 'DatabaseError', 'DataError', 'OperationalError',
114
+ 'IntegrityError', 'InternalError', 'ProgrammingError', 'NotSupportedError',
115
+ 'apilevel', 'connect', 'paramstyle', 'threadsafety',
116
+ 'get_typecast', 'set_typecast', 'reset_typecast',
117
+ 'version', '__version__']
118
+
119
+ from datetime import date, time, datetime, timedelta, tzinfo
120
+ from time import localtime
121
+ from decimal import Decimal as StdDecimal
122
+ from uuid import UUID as Uuid
123
+ from math import isnan, isinf
124
+ try: # noinspection PyCompatibility
125
+ from collections.abc import Iterable
126
+ except ImportError: # Python < 3.3
127
+ from collections import Iterable
128
+ from collections import namedtuple
129
+ from functools import partial
130
+ from re import compile as regex
131
+ from json import loads as jsondecode, dumps as jsonencode
132
+
133
+ Decimal = StdDecimal
134
+
135
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
136
+ long
137
+ except NameError: # Python >= 3.0
138
+ long = int
139
+
140
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
141
+ unicode
142
+ except NameError: # Python >= 3.0
143
+ unicode = str
144
+
145
+ try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
146
+ basestring
147
+ except NameError: # Python >= 3.0
148
+ basestring = (str, bytes)
149
+
150
+ try:
151
+ from functools import lru_cache
152
+ except ImportError: # Python < 3.2
153
+ from functools import update_wrapper
154
+ try: # noinspection PyCompatibility
155
+ from _thread import RLock
156
+ except ImportError:
157
+ class RLock: # for builds without threads
158
+ def __enter__(self):
159
+ pass
160
+
161
+ def __exit__(self, exctype, excinst, exctb):
162
+ pass
163
+
164
+ def lru_cache(maxsize=128):
165
+ """Simplified functools.lru_cache decorator for one argument."""
166
+
167
+ def decorator(function):
168
+ sentinel = object()
169
+ cache = {}
170
+ get = cache.get
171
+ lock = RLock()
172
+ root = []
173
+ root_full = [root, False]
174
+ root[:] = [root, root, None, None]
175
+
176
+ if maxsize == 0:
177
+
178
+ def wrapper(arg):
179
+ res = function(arg)
180
+ return res
181
+
182
+ elif maxsize is None:
183
+
184
+ def wrapper(arg):
185
+ res = get(arg, sentinel)
186
+ if res is not sentinel:
187
+ return res
188
+ res = function(arg)
189
+ cache[arg] = res
190
+ return res
191
+
192
+ else:
193
+
194
+ def wrapper(arg):
195
+ with lock:
196
+ link = get(arg)
197
+ if link is not None:
198
+ root = root_full[0]
199
+ prv, nxt, _arg, res = link
200
+ prv[1] = nxt
201
+ nxt[0] = prv
202
+ last = root[0]
203
+ last[1] = root[0] = link
204
+ link[0] = last
205
+ link[1] = root
206
+ return res
207
+ res = function(arg)
208
+ with lock:
209
+ root, full = root_full
210
+ if arg in cache:
211
+ pass
212
+ elif full:
213
+ oldroot = root
214
+ oldroot[2] = arg
215
+ oldroot[3] = res
216
+ root = root_full[0] = oldroot[1]
217
+ oldarg = root[2]
218
+ oldres = root[3] # noqa F481 (keep reference)
219
+ root[2] = root[3] = None
220
+ del cache[oldarg]
221
+ cache[arg] = oldroot
222
+ else:
223
+ last = root[0]
224
+ link = [last, root, arg, res]
225
+ last[1] = root[0] = cache[arg] = link
226
+ if len(cache) >= maxsize:
227
+ root_full[1] = True
228
+ return res
229
+
230
+ wrapper.__wrapped__ = function
231
+ return update_wrapper(wrapper, function)
232
+
233
+ return decorator
234
+
235
+
236
+ # *** Module Constants ***
237
+
238
+ # compliant with DB API 2.0
239
+ apilevel = '2.0'
240
+
241
+ # module may be shared, but not connections
242
+ threadsafety = 1
243
+
244
+ # this module use extended python format codes
245
+ paramstyle = 'pyformat'
246
+
247
+ # shortcut methods have been excluded from DB API 2 and
248
+ # are not recommended by the DB SIG, but they can be handy
249
+ shortcutmethods = 1
250
+
251
+
252
+ # *** Internal Type Handling ***
253
+
254
+ try: # noinspection PyUnresolvedReferences
255
+ from inspect import signature
256
+ except ImportError: # Python < 3.3
257
+ from inspect import getargspec
258
+
259
+ def get_args(func):
260
+ return getargspec(func).args
261
+ else:
262
+
263
+ def get_args(func):
264
+ return list(signature(func).parameters)
265
+
266
+ try:
267
+ from datetime import timezone
268
+ except ImportError: # Python < 3.2
269
+
270
+ class timezone(tzinfo):
271
+ """Simple timezone implementation."""
272
+
273
+ def __init__(self, offset, name=None):
274
+ self.offset = offset
275
+ if not name:
276
+ minutes = self.offset.days * 1440 + self.offset.seconds // 60
277
+ if minutes < 0:
278
+ hours, minutes = divmod(-minutes, 60)
279
+ hours = -hours
280
+ else:
281
+ hours, minutes = divmod(minutes, 60)
282
+ name = 'UTC%+03d:%02d' % (hours, minutes)
283
+ self.name = name
284
+
285
+ def utcoffset(self, dt):
286
+ return self.offset
287
+
288
+ def tzname(self, dt):
289
+ return self.name
290
+
291
+ def dst(self, dt):
292
+ return None
293
+
294
+ timezone.utc = timezone(timedelta(0), 'UTC')
295
+
296
+ _has_timezone = False
297
+ else:
298
+ _has_timezone = True
299
+
300
+ # time zones used in Postgres timestamptz output
301
+ _timezones = dict(CET='+0100', EET='+0200', EST='-0500',
302
+ GMT='+0000', HST='-1000', MET='+0100', MST='-0700',
303
+ UCT='+0000', UTC='+0000', WET='+0000')
304
+
305
+
306
+ def _timezone_as_offset(tz):
307
+ if tz.startswith(('+', '-')):
308
+ if len(tz) < 5:
309
+ return tz + '00'
310
+ return tz.replace(':', '')
311
+ return _timezones.get(tz, '+0000')
312
+
313
+
314
+ def _get_timezone(tz):
315
+ tz = _timezone_as_offset(tz)
316
+ minutes = 60 * int(tz[1:3]) + int(tz[3:5])
317
+ if tz[0] == '-':
318
+ minutes = -minutes
319
+ return timezone(timedelta(minutes=minutes), tz)
320
+
321
+
322
+ def decimal_type(decimal_type=None):
323
+ """Get or set global type to be used for decimal values.
324
+
325
+ Note that connections cache cast functions. To be sure a global change
326
+ is picked up by a running connection, call con.type_cache.reset_typecast().
327
+ """
328
+ global Decimal
329
+ if decimal_type is not None:
330
+ Decimal = decimal_type
331
+ set_typecast('numeric', decimal_type)
332
+ return Decimal
333
+
334
+
335
+ def cast_bool(value):
336
+ """Cast boolean value in database format to bool."""
337
+ if value:
338
+ return value[0] in ('t', 'T')
339
+
340
+
341
+ def cast_money(value):
342
+ """Cast money value in database format to Decimal."""
343
+ if value:
344
+ value = value.replace('(', '-')
345
+ return Decimal(''.join(c for c in value if c.isdigit() or c in '.-'))
346
+
347
+
348
+ def cast_int2vector(value):
349
+ """Cast an int2vector value."""
350
+ return [int(v) for v in value.split()]
351
+
352
+
353
+ def cast_date(value, connection):
354
+ """Cast a date value."""
355
+ # The output format depends on the server setting DateStyle. The default
356
+ # setting ISO and the setting for German are actually unambiguous. The
357
+ # order of days and months in the other two settings is however ambiguous,
358
+ # so at least here we need to consult the setting to properly parse values.
359
+ if value == '-infinity':
360
+ return date.min
361
+ if value == 'infinity':
362
+ return date.max
363
+ value = value.split()
364
+ if value[-1] == 'BC':
365
+ return date.min
366
+ value = value[0]
367
+ if len(value) > 10:
368
+ return date.max
369
+ fmt = connection.date_format()
370
+ return datetime.strptime(value, fmt).date()
371
+
372
+
373
+ def cast_time(value):
374
+ """Cast a time value."""
375
+ fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
376
+ return datetime.strptime(value, fmt).time()
377
+
378
+
379
+ _re_timezone = regex('(.*)([+-].*)')
380
+
381
+
382
+ def cast_timetz(value):
383
+ """Cast a timetz value."""
384
+ tz = _re_timezone.match(value)
385
+ if tz:
386
+ value, tz = tz.groups()
387
+ else:
388
+ tz = '+0000'
389
+ fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
390
+ if _has_timezone:
391
+ value += _timezone_as_offset(tz)
392
+ fmt += '%z'
393
+ return datetime.strptime(value, fmt).timetz()
394
+ return datetime.strptime(value, fmt).timetz().replace(
395
+ tzinfo=_get_timezone(tz))
396
+
397
+
398
+ def cast_timestamp(value, connection):
399
+ """Cast a timestamp value."""
400
+ if value == '-infinity':
401
+ return datetime.min
402
+ if value == 'infinity':
403
+ return datetime.max
404
+ value = value.split()
405
+ if value[-1] == 'BC':
406
+ return datetime.min
407
+ fmt = connection.date_format()
408
+ if fmt.endswith('-%Y') and len(value) > 2:
409
+ value = value[1:5]
410
+ if len(value[3]) > 4:
411
+ return datetime.max
412
+ fmt = ['%d %b' if fmt.startswith('%d') else '%b %d',
413
+ '%H:%M:%S.%f' if len(value[2]) > 8 else '%H:%M:%S', '%Y']
414
+ else:
415
+ if len(value[0]) > 10:
416
+ return datetime.max
417
+ fmt = [fmt, '%H:%M:%S.%f' if len(value[1]) > 8 else '%H:%M:%S']
418
+ return datetime.strptime(' '.join(value), ' '.join(fmt))
419
+
420
+
421
+ def cast_timestamptz(value, connection):
422
+ """Cast a timestamptz value."""
423
+ if value == '-infinity':
424
+ return datetime.min
425
+ if value == 'infinity':
426
+ return datetime.max
427
+ value = value.split()
428
+ if value[-1] == 'BC':
429
+ return datetime.min
430
+ fmt = connection.date_format()
431
+ if fmt.endswith('-%Y') and len(value) > 2:
432
+ value = value[1:]
433
+ if len(value[3]) > 4:
434
+ return datetime.max
435
+ fmt = ['%d %b' if fmt.startswith('%d') else '%b %d',
436
+ '%H:%M:%S.%f' if len(value[2]) > 8 else '%H:%M:%S', '%Y']
437
+ value, tz = value[:-1], value[-1]
438
+ else:
439
+ if fmt.startswith('%Y-'):
440
+ tz = _re_timezone.match(value[1])
441
+ if tz:
442
+ value[1], tz = tz.groups()
443
+ else:
444
+ tz = '+0000'
445
+ else:
446
+ value, tz = value[:-1], value[-1]
447
+ if len(value[0]) > 10:
448
+ return datetime.max
449
+ fmt = [fmt, '%H:%M:%S.%f' if len(value[1]) > 8 else '%H:%M:%S']
450
+ if _has_timezone:
451
+ value.append(_timezone_as_offset(tz))
452
+ fmt.append('%z')
453
+ return datetime.strptime(' '.join(value), ' '.join(fmt))
454
+ return datetime.strptime(' '.join(value), ' '.join(fmt)).replace(
455
+ tzinfo=_get_timezone(tz))
456
+
457
+
458
+ _re_interval_sql_standard = regex(
459
+ '(?:([+-])?([0-9]+)-([0-9]+) ?)?'
460
+ '(?:([+-]?[0-9]+)(?!:) ?)?'
461
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
462
+
463
+ _re_interval_postgres = regex(
464
+ '(?:([+-]?[0-9]+) ?years? ?)?'
465
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
466
+ '(?:([+-]?[0-9]+) ?days? ?)?'
467
+ '(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
468
+
469
+ _re_interval_postgres_verbose = regex(
470
+ '@ ?(?:([+-]?[0-9]+) ?years? ?)?'
471
+ '(?:([+-]?[0-9]+) ?mons? ?)?'
472
+ '(?:([+-]?[0-9]+) ?days? ?)?'
473
+ '(?:([+-]?[0-9]+) ?hours? ?)?'
474
+ '(?:([+-]?[0-9]+) ?mins? ?)?'
475
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
476
+
477
+ _re_interval_iso_8601 = regex(
478
+ 'P(?:([+-]?[0-9]+)Y)?'
479
+ '(?:([+-]?[0-9]+)M)?'
480
+ '(?:([+-]?[0-9]+)D)?'
481
+ '(?:T(?:([+-]?[0-9]+)H)?'
482
+ '(?:([+-]?[0-9]+)M)?'
483
+ '(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
484
+
485
+
486
+ def cast_interval(value):
487
+ """Cast an interval value."""
488
+ # The output format depends on the server setting IntervalStyle, but it's
489
+ # not necessary to consult this setting to parse it. It's faster to just
490
+ # check all possible formats, and there is no ambiguity here.
491
+ m = _re_interval_iso_8601.match(value)
492
+ if m:
493
+ m = [d or '0' for d in m.groups()]
494
+ secs_ago = m.pop(5) == '-'
495
+ m = [int(d) for d in m]
496
+ years, mons, days, hours, mins, secs, usecs = m
497
+ if secs_ago:
498
+ secs = -secs
499
+ usecs = -usecs
500
+ else:
501
+ m = _re_interval_postgres_verbose.match(value)
502
+ if m:
503
+ m, ago = [d or '0' for d in m.groups()[:8]], m.group(9)
504
+ secs_ago = m.pop(5) == '-'
505
+ m = [-int(d) for d in m] if ago else [int(d) for d in m]
506
+ years, mons, days, hours, mins, secs, usecs = m
507
+ if secs_ago:
508
+ secs = - secs
509
+ usecs = -usecs
510
+ else:
511
+ m = _re_interval_postgres.match(value)
512
+ if m and any(m.groups()):
513
+ m = [d or '0' for d in m.groups()]
514
+ hours_ago = m.pop(3) == '-'
515
+ m = [int(d) for d in m]
516
+ years, mons, days, hours, mins, secs, usecs = m
517
+ if hours_ago:
518
+ hours = -hours
519
+ mins = -mins
520
+ secs = -secs
521
+ usecs = -usecs
522
+ else:
523
+ m = _re_interval_sql_standard.match(value)
524
+ if m and any(m.groups()):
525
+ m = [d or '0' for d in m.groups()]
526
+ years_ago = m.pop(0) == '-'
527
+ hours_ago = m.pop(3) == '-'
528
+ m = [int(d) for d in m]
529
+ years, mons, days, hours, mins, secs, usecs = m
530
+ if years_ago:
531
+ years = -years
532
+ mons = -mons
533
+ if hours_ago:
534
+ hours = -hours
535
+ mins = -mins
536
+ secs = -secs
537
+ usecs = -usecs
538
+ else:
539
+ raise ValueError('Cannot parse interval: %s' % value)
540
+ days += 365 * years + 30 * mons
541
+ return timedelta(days=days, hours=hours, minutes=mins,
542
+ seconds=secs, microseconds=usecs)
543
+
544
+
545
+ class Typecasts(dict):
546
+ """Dictionary mapping database types to typecast functions.
547
+
548
+ The cast functions get passed the string representation of a value in
549
+ the database which they need to convert to a Python object. The
550
+ passed string will never be None since NULL values are already
551
+ handled before the cast function is called.
552
+ """
553
+
554
+ # the default cast functions
555
+ # (str functions are ignored but have been added for faster access)
556
+ defaults = {
557
+ 'char': str, 'bpchar': str, 'name': str,
558
+ 'text': str, 'varchar': str, 'sql_identifier': str,
559
+ 'bool': cast_bool, 'bytea': unescape_bytea,
560
+ 'int2': int, 'int4': int, 'serial': int, 'int8': long, 'oid': int,
561
+ 'hstore': cast_hstore, 'json': jsondecode, 'jsonb': jsondecode,
562
+ 'float4': float, 'float8': float,
563
+ 'numeric': Decimal, 'money': cast_money,
564
+ 'date': cast_date, 'interval': cast_interval,
565
+ 'time': cast_time, 'timetz': cast_timetz,
566
+ 'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
567
+ 'int2vector': cast_int2vector, 'uuid': Uuid,
568
+ 'anyarray': cast_array, 'record': cast_record}
569
+
570
+ connection = None # will be set in local connection specific instances
571
+
572
+ def __missing__(self, typ):
573
+ """Create a cast function if it is not cached.
574
+
575
+ Note that this class never raises a KeyError,
576
+ but returns None when no special cast function exists.
577
+ """
578
+ if not isinstance(typ, str):
579
+ raise TypeError('Invalid type: %s' % typ)
580
+ cast = self.defaults.get(typ)
581
+ if cast:
582
+ # store default for faster access
583
+ cast = self._add_connection(cast)
584
+ self[typ] = cast
585
+ elif typ.startswith('_'):
586
+ # create array cast
587
+ base_cast = self[typ[1:]]
588
+ cast = self.create_array_cast(base_cast)
589
+ if base_cast:
590
+ # store only if base type exists
591
+ self[typ] = cast
592
+ return cast
593
+
594
+ @staticmethod
595
+ def _needs_connection(func):
596
+ """Check if a typecast function needs a connection argument."""
597
+ try:
598
+ args = get_args(func)
599
+ except (TypeError, ValueError):
600
+ return False
601
+ else:
602
+ return 'connection' in args[1:]
603
+
604
+ def _add_connection(self, cast):
605
+ """Add a connection argument to the typecast function if necessary."""
606
+ if not self.connection or not self._needs_connection(cast):
607
+ return cast
608
+ return partial(cast, connection=self.connection)
609
+
610
+ def get(self, typ, default=None):
611
+ """Get the typecast function for the given database type."""
612
+ return self[typ] or default
613
+
614
+ def set(self, typ, cast):
615
+ """Set a typecast function for the specified database type(s)."""
616
+ if isinstance(typ, basestring):
617
+ typ = [typ]
618
+ if cast is None:
619
+ for t in typ:
620
+ self.pop(t, None)
621
+ self.pop('_%s' % t, None)
622
+ else:
623
+ if not callable(cast):
624
+ raise TypeError("Cast parameter must be callable")
625
+ for t in typ:
626
+ self[t] = self._add_connection(cast)
627
+ self.pop('_%s' % t, None)
628
+
629
+ def reset(self, typ=None):
630
+ """Reset the typecasts for the specified type(s) to their defaults.
631
+
632
+ When no type is specified, all typecasts will be reset.
633
+ """
634
+ defaults = self.defaults
635
+ if typ is None:
636
+ self.clear()
637
+ self.update(defaults)
638
+ else:
639
+ if isinstance(typ, basestring):
640
+ typ = [typ]
641
+ for t in typ:
642
+ cast = defaults.get(t)
643
+ if cast:
644
+ self[t] = self._add_connection(cast)
645
+ t = '_%s' % t
646
+ cast = defaults.get(t)
647
+ if cast:
648
+ self[t] = self._add_connection(cast)
649
+ else:
650
+ self.pop(t, None)
651
+ else:
652
+ self.pop(t, None)
653
+ self.pop('_%s' % t, None)
654
+
655
+ def create_array_cast(self, basecast):
656
+ """Create an array typecast for the given base cast."""
657
+ cast_array = self['anyarray']
658
+
659
+ def cast(v):
660
+ return cast_array(v, basecast)
661
+ return cast
662
+
663
+ def create_record_cast(self, name, fields, casts):
664
+ """Create a named record typecast for the given fields and casts."""
665
+ cast_record = self['record']
666
+ record = namedtuple(name, fields)
667
+
668
+ def cast(v):
669
+ # noinspection PyArgumentList
670
+ return record(*cast_record(v, casts))
671
+ return cast
672
+
673
+
674
+ _typecasts = Typecasts() # this is the global typecast dictionary
675
+
676
+
677
+ def get_typecast(typ):
678
+ """Get the global typecast function for the given database type(s)."""
679
+ return _typecasts.get(typ)
680
+
681
+
682
+ def set_typecast(typ, cast):
683
+ """Set a global typecast function for the given database type(s).
684
+
685
+ Note that connections cache cast functions. To be sure a global change
686
+ is picked up by a running connection, call con.type_cache.reset_typecast().
687
+ """
688
+ _typecasts.set(typ, cast)
689
+
690
+
691
+ def reset_typecast(typ=None):
692
+ """Reset the global typecasts for the given type(s) to their default.
693
+
694
+ When no type is specified, all typecasts will be reset.
695
+
696
+ Note that connections cache cast functions. To be sure a global change
697
+ is picked up by a running connection, call con.type_cache.reset_typecast().
698
+ """
699
+ _typecasts.reset(typ)
700
+
701
+
702
+ class LocalTypecasts(Typecasts):
703
+ """Map typecasts, including local composite types, to cast functions."""
704
+
705
+ defaults = _typecasts
706
+
707
+ connection = None # will be set in a connection specific instance
708
+
709
+ def __missing__(self, typ):
710
+ """Create a cast function if it is not cached."""
711
+ if typ.startswith('_'):
712
+ base_cast = self[typ[1:]]
713
+ cast = self.create_array_cast(base_cast)
714
+ if base_cast:
715
+ self[typ] = cast
716
+ else:
717
+ cast = self.defaults.get(typ)
718
+ if cast:
719
+ cast = self._add_connection(cast)
720
+ self[typ] = cast
721
+ else:
722
+ fields = self.get_fields(typ)
723
+ if fields:
724
+ casts = [self[field.type] for field in fields]
725
+ fields = [field.name for field in fields]
726
+ cast = self.create_record_cast(typ, fields, casts)
727
+ self[typ] = cast
728
+ return cast
729
+
730
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
731
+ def get_fields(self, typ):
732
+ """Return the fields for the given record type.
733
+
734
+ This method will be replaced with a method that looks up the fields
735
+ using the type cache of the connection.
736
+ """
737
+ return []
738
+
739
+
740
+ class TypeCode(str):
741
+ """Class representing the type_code used by the DB-API 2.0.
742
+
743
+ TypeCode objects are strings equal to the PostgreSQL type name,
744
+ but carry some additional information.
745
+ """
746
+
747
+ # noinspection PyShadowingBuiltins
748
+ @classmethod
749
+ def create(cls, oid, name, len, type, category, delim, relid):
750
+ """Create a type code for a PostgreSQL data type."""
751
+ self = cls(name)
752
+ self.oid = oid
753
+ self.len = len
754
+ self.type = type
755
+ self.category = category
756
+ self.delim = delim
757
+ self.relid = relid
758
+ return self
759
+
760
+
761
+ FieldInfo = namedtuple('FieldInfo', ('name', 'type'))
762
+
763
+
764
+ class TypeCache(dict):
765
+ """Cache for database types.
766
+
767
+ This cache maps type OIDs and names to TypeCode strings containing
768
+ important information on the associated database type.
769
+ """
770
+
771
+ def __init__(self, cnx):
772
+ """Initialize type cache for connection."""
773
+ super(TypeCache, self).__init__()
774
+ self._escape_string = cnx.escape_string
775
+ self._src = cnx.source()
776
+ self._typecasts = LocalTypecasts()
777
+ self._typecasts.get_fields = self.get_fields
778
+ self._typecasts.connection = cnx
779
+ if cnx.server_version < 80400:
780
+ # older remote databases (not officially supported)
781
+ self._query_pg_type = (
782
+ "SELECT oid, typname,"
783
+ " typlen, typtype, null as typcategory, typdelim, typrelid"
784
+ " FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %s")
785
+ else:
786
+ self._query_pg_type = (
787
+ "SELECT oid, typname,"
788
+ " typlen, typtype, typcategory, typdelim, typrelid"
789
+ " FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %s")
790
+
791
+ def __missing__(self, key):
792
+ """Get the type info from the database if it is not cached."""
793
+ if isinstance(key, int):
794
+ oid = key
795
+ else:
796
+ if '.' not in key and '"' not in key:
797
+ key = '"%s"' % (key,)
798
+ oid = "'%s'::pg_catalog.regtype" % (self._escape_string(key),)
799
+ try:
800
+ self._src.execute(self._query_pg_type % (oid,))
801
+ except ProgrammingError:
802
+ res = None
803
+ else:
804
+ res = self._src.fetch(1)
805
+ if not res:
806
+ raise KeyError('Type %s could not be found' % (key,))
807
+ res = res[0]
808
+ type_code = TypeCode.create(
809
+ int(res[0]), res[1], int(res[2]),
810
+ res[3], res[4], res[5], int(res[6]))
811
+ # noinspection PyUnresolvedReferences
812
+ self[type_code.oid] = self[str(type_code)] = type_code
813
+ return type_code
814
+
815
+ def get(self, key, default=None):
816
+ """Get the type even if it is not cached."""
817
+ try:
818
+ return self[key]
819
+ except KeyError:
820
+ return default
821
+
822
+ def get_fields(self, typ):
823
+ """Get the names and types of the fields of composite types."""
824
+ if not isinstance(typ, TypeCode):
825
+ typ = self.get(typ)
826
+ if not typ:
827
+ return None
828
+ if not typ.relid:
829
+ return None # this type is not composite
830
+ self._src.execute(
831
+ "SELECT attname, atttypid"
832
+ " FROM pg_catalog.pg_attribute"
833
+ " WHERE attrelid OPERATOR(pg_catalog.=) %s"
834
+ " AND attnum OPERATOR(pg_catalog.>) 0"
835
+ " AND NOT attisdropped ORDER BY attnum" % (typ.relid,))
836
+ return [FieldInfo(name, self.get(int(oid)))
837
+ for name, oid in self._src.fetch(-1)]
838
+
839
+ def get_typecast(self, typ):
840
+ """Get the typecast function for the given database type."""
841
+ return self._typecasts[typ]
842
+
843
+ def set_typecast(self, typ, cast):
844
+ """Set a typecast function for the specified database type(s)."""
845
+ self._typecasts.set(typ, cast)
846
+
847
+ def reset_typecast(self, typ=None):
848
+ """Reset the typecast function for the specified database type(s)."""
849
+ self._typecasts.reset(typ)
850
+
851
+ def typecast(self, value, typ):
852
+ """Cast the given value according to the given database type."""
853
+ if value is None:
854
+ # for NULL values, no typecast is necessary
855
+ return None
856
+ cast = self._typecasts[typ]
857
+ if cast is None or cast is str:
858
+ # no typecast is necessary
859
+ return value
860
+ return cast(value)
861
+
862
+ def get_row_caster(self, types):
863
+ """Get a typecast function for a complete row of values."""
864
+ typecasts = self._typecasts
865
+ casts = [typecasts[typ] for typ in types]
866
+ casts = [cast if cast is not str else None for cast in casts]
867
+
868
+ def row_caster(row):
869
+ return [value if cast is None or value is None else cast(value)
870
+ for cast, value in zip(casts, row)]
871
+
872
+ return row_caster
873
+
874
+
875
+ class _quotedict(dict):
876
+ """Dictionary with auto quoting of its items.
877
+
878
+ The quote attribute must be set to the desired quote function.
879
+ """
880
+
881
+ def __getitem__(self, key):
882
+ # noinspection PyUnresolvedReferences
883
+ return self.quote(super(_quotedict, self).__getitem__(key))
884
+
885
+
886
+ # *** Error Messages ***
887
+
888
+
889
+ def _db_error(msg, cls=DatabaseError):
890
+ """Return DatabaseError with empty sqlstate attribute."""
891
+ error = cls(msg)
892
+ error.sqlstate = None
893
+ return error
894
+
895
+
896
+ def _op_error(msg):
897
+ """Return OperationalError."""
898
+ return _db_error(msg, OperationalError)
899
+
900
+
901
+ # *** Row Tuples ***
902
+
903
+
904
+ _re_fieldname = regex('^[A-Za-z][_a-zA-Z0-9]*$')
905
+
906
+
907
+ # The result rows for database operations are returned as named tuples
908
+ # by default. Since creating namedtuple classes is a somewhat expensive
909
+ # operation, we cache up to 1024 of these classes by default.
910
+
911
+ # noinspection PyUnresolvedReferences
912
+ @lru_cache(maxsize=1024)
913
+ def _row_factory(names):
914
+ """Get a namedtuple factory for row results with the given names."""
915
+ try:
916
+ return namedtuple('Row', names, rename=True)._make
917
+ except ValueError: # there is still a problem with the field names
918
+ names = ['column_%d' % (n,) for n in range(len(names))]
919
+ return namedtuple('Row', names)._make
920
+
921
+
922
+ def set_row_factory_size(maxsize):
923
+ """Change the size of the namedtuple factory cache.
924
+
925
+ If maxsize is set to None, the cache can grow without bound.
926
+ """
927
+ # noinspection PyGlobalUndefined
928
+ global _row_factory
929
+ _row_factory = lru_cache(maxsize)(_row_factory.__wrapped__)
930
+
931
+
932
+ # *** Cursor Object ***
933
+
934
+ class Cursor(object):
935
+ """Cursor object."""
936
+
937
+ def __init__(self, dbcnx):
938
+ """Create a cursor object for the database connection."""
939
+ self.connection = self._dbcnx = dbcnx
940
+ self._cnx = dbcnx._cnx
941
+ self.type_cache = dbcnx.type_cache
942
+ self._src = self._cnx.source()
943
+ # the official attribute for describing the result columns
944
+ self._description = None
945
+ if self.row_factory is Cursor.row_factory:
946
+ # the row factory needs to be determined dynamically
947
+ self.row_factory = None
948
+ else:
949
+ self.build_row_factory = None
950
+ self.rowcount = -1
951
+ self.arraysize = 1
952
+ self.lastrowid = None
953
+
954
+ def __iter__(self):
955
+ """Make cursor compatible to the iteration protocol."""
956
+ return self
957
+
958
+ def __enter__(self):
959
+ """Enter the runtime context for the cursor object."""
960
+ return self
961
+
962
+ def __exit__(self, et, ev, tb):
963
+ """Exit the runtime context for the cursor object."""
964
+ self.close()
965
+
966
+ def _quote(self, value):
967
+ """Quote value depending on its type."""
968
+ if value is None:
969
+ return 'NULL'
970
+ if isinstance(value, (Hstore, Json)):
971
+ value = str(value)
972
+ if isinstance(value, basestring):
973
+ if isinstance(value, Binary):
974
+ value = self._cnx.escape_bytea(value)
975
+ if bytes is not str: # Python >= 3.0
976
+ value = value.decode('ascii')
977
+ else:
978
+ value = self._cnx.escape_string(value)
979
+ return "'%s'" % (value,)
980
+ if isinstance(value, float):
981
+ if isinf(value):
982
+ return "'-Infinity'" if value < 0 else "'Infinity'"
983
+ if isnan(value):
984
+ return "'NaN'"
985
+ return value
986
+ if isinstance(value, (int, long, Decimal, Literal)):
987
+ return value
988
+ if isinstance(value, datetime):
989
+ if value.tzinfo:
990
+ return "'%s'::timestamptz" % (value,)
991
+ return "'%s'::timestamp" % (value,)
992
+ if isinstance(value, date):
993
+ return "'%s'::date" % (value,)
994
+ if isinstance(value, time):
995
+ if value.tzinfo:
996
+ return "'%s'::timetz" % (value,)
997
+ return "'%s'::time" % value
998
+ if isinstance(value, timedelta):
999
+ return "'%s'::interval" % (value,)
1000
+ if isinstance(value, Uuid):
1001
+ return "'%s'::uuid" % (value,)
1002
+ if isinstance(value, list):
1003
+ # Quote value as an ARRAY constructor. This is better than using
1004
+ # an array literal because it carries the information that this is
1005
+ # an array and not a string. One issue with this syntax is that
1006
+ # you need to add an explicit typecast when passing empty arrays.
1007
+ # The ARRAY keyword is actually only necessary at the top level.
1008
+ if not value: # exception for empty array
1009
+ return "'{}'"
1010
+ q = self._quote
1011
+ try:
1012
+ return 'ARRAY[%s]' % (','.join(str(q(v)) for v in value),)
1013
+ except UnicodeEncodeError: # Python 2 with non-ascii values
1014
+ return u'ARRAY[%s]' % (','.join(unicode(q(v)) for v in value),)
1015
+ if isinstance(value, tuple):
1016
+ # Quote as a ROW constructor. This is better than using a record
1017
+ # literal because it carries the information that this is a record
1018
+ # and not a string. We don't use the keyword ROW in order to make
1019
+ # this usable with the IN syntax as well. It is only necessary
1020
+ # when the records has a single column which is not really useful.
1021
+ q = self._quote
1022
+ try:
1023
+ return '(%s)' % (','.join(str(q(v)) for v in value),)
1024
+ except UnicodeEncodeError: # Python 2 with non-ascii values
1025
+ return u'(%s)' % (','.join(unicode(q(v)) for v in value),)
1026
+ try: # noinspection PyUnresolvedReferences
1027
+ value = value.__pg_repr__()
1028
+ except AttributeError:
1029
+ raise InterfaceError(
1030
+ 'Do not know how to adapt type %s' % (type(value),))
1031
+ if isinstance(value, (tuple, list)):
1032
+ value = self._quote(value)
1033
+ return value
1034
+
1035
+ def _quoteparams(self, string, parameters):
1036
+ """Quote parameters.
1037
+
1038
+ This function works for both mappings and sequences.
1039
+
1040
+ The function should be used even when there are no parameters,
1041
+ so that we have a consistent behavior regarding percent signs.
1042
+ """
1043
+ if not parameters:
1044
+ try:
1045
+ return string % () # unescape literal quotes if possible
1046
+ except (TypeError, ValueError):
1047
+ return string # silently accept unescaped quotes
1048
+ if isinstance(parameters, dict):
1049
+ parameters = _quotedict(parameters)
1050
+ parameters.quote = self._quote
1051
+ else:
1052
+ parameters = tuple(map(self._quote, parameters))
1053
+ return string % parameters
1054
+
1055
+ def _make_description(self, info):
1056
+ """Make the description tuple for the given field info."""
1057
+ name, typ, size, mod = info[1:]
1058
+ type_code = self.type_cache[typ]
1059
+ if mod > 0:
1060
+ mod -= 4
1061
+ if type_code == 'numeric':
1062
+ precision, scale = mod >> 16, mod & 0xffff
1063
+ size = precision
1064
+ else:
1065
+ if not size:
1066
+ size = type_code.size
1067
+ if size == -1:
1068
+ size = mod
1069
+ precision = scale = None
1070
+ return CursorDescription(name, type_code,
1071
+ None, size, precision, scale, None)
1072
+
1073
+ @property
1074
+ def description(self):
1075
+ """Read-only attribute describing the result columns."""
1076
+ descr = self._description
1077
+ if self._description is True:
1078
+ make = self._make_description
1079
+ descr = [make(info) for info in self._src.listinfo()]
1080
+ self._description = descr
1081
+ return descr
1082
+
1083
+ @property
1084
+ def colnames(self):
1085
+ """Unofficial convenience method for getting the column names."""
1086
+ return [d[0] for d in self.description]
1087
+
1088
+ @property
1089
+ def coltypes(self):
1090
+ """Unofficial convenience method for getting the column types."""
1091
+ return [d[1] for d in self.description]
1092
+
1093
+ def close(self):
1094
+ """Close the cursor object."""
1095
+ self._src.close()
1096
+
1097
+ def execute(self, operation, parameters=None):
1098
+ """Prepare and execute a database operation (query or command)."""
1099
+ # The parameters may also be specified as list of tuples to e.g.
1100
+ # insert multiple rows in a single operation, but this kind of
1101
+ # usage is deprecated. We make several plausibility checks because
1102
+ # tuples can also be passed with the meaning of ROW constructors.
1103
+ if (parameters and isinstance(parameters, list)
1104
+ and len(parameters) > 1
1105
+ and all(isinstance(p, tuple) for p in parameters)
1106
+ and all(len(p) == len(parameters[0]) for p in parameters[1:])):
1107
+ return self.executemany(operation, parameters)
1108
+ else:
1109
+ # not a list of tuples
1110
+ return self.executemany(operation, [parameters])
1111
+
1112
+ def executemany(self, operation, seq_of_parameters):
1113
+ """Prepare operation and execute it against a parameter sequence."""
1114
+ if not seq_of_parameters:
1115
+ # don't do anything without parameters
1116
+ return
1117
+ self._description = None
1118
+ self.rowcount = -1
1119
+ # first try to execute all queries
1120
+ rowcount = 0
1121
+ sql = "BEGIN"
1122
+ try:
1123
+ if not self._dbcnx._tnx and not self._dbcnx.autocommit:
1124
+ try:
1125
+ self._src.execute(sql)
1126
+ except DatabaseError:
1127
+ raise # database provides error message
1128
+ except Exception:
1129
+ raise _op_error("Can't start transaction")
1130
+ else:
1131
+ self._dbcnx._tnx = True
1132
+ for parameters in seq_of_parameters:
1133
+ sql = operation
1134
+ sql = self._quoteparams(sql, parameters)
1135
+ rows = self._src.execute(sql)
1136
+ if rows: # true if not DML
1137
+ rowcount += rows
1138
+ else:
1139
+ self.rowcount = -1
1140
+ except DatabaseError:
1141
+ raise # database provides error message
1142
+ except Error as err:
1143
+ # noinspection PyTypeChecker
1144
+ raise _db_error(
1145
+ "Error in '%s': '%s' " % (sql, err), InterfaceError)
1146
+ except Exception as err:
1147
+ raise _op_error("Internal error in '%s': %s" % (sql, err))
1148
+ # then initialize result raw count and description
1149
+ if self._src.resulttype == RESULT_DQL:
1150
+ self._description = True # fetch on demand
1151
+ self.rowcount = self._src.ntuples
1152
+ self.lastrowid = None
1153
+ if self.build_row_factory:
1154
+ self.row_factory = self.build_row_factory()
1155
+ else:
1156
+ self.rowcount = rowcount
1157
+ self.lastrowid = self._src.oidstatus()
1158
+ # return the cursor object, so you can write statements such as
1159
+ # "cursor.execute(...).fetchall()" or "for row in cursor.execute(...)"
1160
+ return self
1161
+
1162
+ def fetchone(self):
1163
+ """Fetch the next row of a query result set."""
1164
+ res = self.fetchmany(1, False)
1165
+ try:
1166
+ return res[0]
1167
+ except IndexError:
1168
+ return None
1169
+
1170
+ def fetchall(self):
1171
+ """Fetch all (remaining) rows of a query result."""
1172
+ return self.fetchmany(-1, False)
1173
+
1174
+ def fetchmany(self, size=None, keep=False):
1175
+ """Fetch the next set of rows of a query result.
1176
+
1177
+ The number of rows to fetch per call is specified by the
1178
+ size parameter. If it is not given, the cursor's arraysize
1179
+ determines the number of rows to be fetched. If you set
1180
+ the keep parameter to true, this is kept as new arraysize.
1181
+ """
1182
+ if size is None:
1183
+ size = self.arraysize
1184
+ if keep:
1185
+ self.arraysize = size
1186
+ try:
1187
+ result = self._src.fetch(size)
1188
+ except DatabaseError:
1189
+ raise
1190
+ except Error as err:
1191
+ raise _db_error(str(err))
1192
+ row_factory = self.row_factory
1193
+ coltypes = self.coltypes
1194
+ if len(result) > 5:
1195
+ # optimize the case where we really fetch many values
1196
+ # by looking up all type casting functions upfront
1197
+ cast_row = self.type_cache.get_row_caster(coltypes)
1198
+ return [row_factory(cast_row(row)) for row in result]
1199
+ cast_value = self.type_cache.typecast
1200
+ return [row_factory([cast_value(value, typ)
1201
+ for typ, value in zip(coltypes, row)]) for row in result]
1202
+
1203
+ def callproc(self, procname, parameters=None):
1204
+ """Call a stored database procedure with the given name.
1205
+
1206
+ The sequence of parameters must contain one entry for each input
1207
+ argument that the procedure expects. The result of the call is the
1208
+ same as this input sequence; replacement of output and input/output
1209
+ parameters in the return value is currently not supported.
1210
+
1211
+ The procedure may also provide a result set as output. These can be
1212
+ requested through the standard fetch methods of the cursor.
1213
+ """
1214
+ n = parameters and len(parameters) or 0
1215
+ query = 'select * from "%s"(%s)' % (procname, ','.join(n * ['%s']))
1216
+ self.execute(query, parameters)
1217
+ return parameters
1218
+
1219
+ # noinspection PyShadowingBuiltins
1220
+ def copy_from(self, stream, table,
1221
+ format=None, sep=None, null=None, size=None, columns=None):
1222
+ """Copy data from an input stream to the specified table.
1223
+
1224
+ The input stream can be a file-like object with a read() method or
1225
+ it can also be an iterable returning a row or multiple rows of input
1226
+ on each iteration.
1227
+
1228
+ The format must be text, csv or binary. The sep option sets the
1229
+ column separator (delimiter) used in the non binary formats.
1230
+ The null option sets the textual representation of NULL in the input.
1231
+
1232
+ The size option sets the size of the buffer used when reading data
1233
+ from file-like objects.
1234
+
1235
+ The copy operation can be restricted to a subset of columns. If no
1236
+ columns are specified, all of them will be copied.
1237
+ """
1238
+ binary_format = format == 'binary'
1239
+ try:
1240
+ read = stream.read
1241
+ except AttributeError:
1242
+ if size:
1243
+ raise ValueError("Size must only be set for file-like objects")
1244
+ if binary_format:
1245
+ input_type = bytes
1246
+ type_name = 'byte strings'
1247
+ else:
1248
+ input_type = basestring
1249
+ type_name = 'strings'
1250
+
1251
+ if isinstance(stream, basestring):
1252
+ if not isinstance(stream, input_type):
1253
+ raise ValueError("The input must be %s" % (type_name,))
1254
+ if not binary_format:
1255
+ if isinstance(stream, str):
1256
+ if not stream.endswith('\n'):
1257
+ stream += '\n'
1258
+ else:
1259
+ if not stream.endswith(b'\n'):
1260
+ stream += b'\n'
1261
+
1262
+ def chunks():
1263
+ yield stream
1264
+
1265
+ elif isinstance(stream, Iterable):
1266
+
1267
+ def chunks():
1268
+ for chunk in stream:
1269
+ if not isinstance(chunk, input_type):
1270
+ raise ValueError(
1271
+ "Input stream must consist of %s"
1272
+ % (type_name,))
1273
+ if isinstance(chunk, str):
1274
+ if not chunk.endswith('\n'):
1275
+ chunk += '\n'
1276
+ else:
1277
+ if not chunk.endswith(b'\n'):
1278
+ chunk += b'\n'
1279
+ yield chunk
1280
+
1281
+ else:
1282
+ raise TypeError("Need an input stream to copy from")
1283
+ else:
1284
+ if size is None:
1285
+ size = 8192
1286
+ elif not isinstance(size, int):
1287
+ raise TypeError("The size option must be an integer")
1288
+ if size > 0:
1289
+
1290
+ def chunks():
1291
+ while True:
1292
+ buffer = read(size)
1293
+ yield buffer
1294
+ if not buffer or len(buffer) < size:
1295
+ break
1296
+
1297
+ else:
1298
+
1299
+ def chunks():
1300
+ yield read()
1301
+
1302
+ if not table or not isinstance(table, basestring):
1303
+ raise TypeError("Need a table to copy to")
1304
+ if table.lower().startswith('select '):
1305
+ raise ValueError("Must specify a table, not a query")
1306
+ else:
1307
+ table = '.'.join(map(
1308
+ self.connection._cnx.escape_identifier, table.split('.', 1)))
1309
+ operation = ['copy %s' % (table,)]
1310
+ options = []
1311
+ params = []
1312
+ if format is not None:
1313
+ if not isinstance(format, basestring):
1314
+ raise TypeError("The format option must be be a string")
1315
+ if format not in ('text', 'csv', 'binary'):
1316
+ raise ValueError("Invalid format")
1317
+ options.append('format %s' % (format,))
1318
+ if sep is not None:
1319
+ if not isinstance(sep, basestring):
1320
+ raise TypeError("The sep option must be a string")
1321
+ if format == 'binary':
1322
+ raise ValueError(
1323
+ "The sep option is not allowed with binary format")
1324
+ if len(sep) != 1:
1325
+ raise ValueError(
1326
+ "The sep option must be a single one-byte character")
1327
+ options.append('delimiter %s')
1328
+ params.append(sep)
1329
+ if null is not None:
1330
+ if not isinstance(null, basestring):
1331
+ raise TypeError("The null option must be a string")
1332
+ options.append('null %s')
1333
+ params.append(null)
1334
+ if columns:
1335
+ if not isinstance(columns, basestring):
1336
+ columns = ','.join(map(
1337
+ self.connection._cnx.escape_identifier, columns))
1338
+ operation.append('(%s)' % (columns,))
1339
+ operation.append("from stdin")
1340
+ if options:
1341
+ operation.append('(%s)' % (','.join(options),))
1342
+ operation = ' '.join(operation)
1343
+
1344
+ putdata = self._src.putdata
1345
+ self.execute(operation, params)
1346
+
1347
+ try:
1348
+ for chunk in chunks():
1349
+ putdata(chunk)
1350
+ except BaseException as error:
1351
+ self.rowcount = -1
1352
+ # the following call will re-raise the error
1353
+ putdata(error)
1354
+ else:
1355
+ self.rowcount = putdata(None)
1356
+
1357
+ # return the cursor object, so you can chain operations
1358
+ return self
1359
+
1360
+ # noinspection PyShadowingBuiltins
1361
+ def copy_to(self, stream, table,
1362
+ format=None, sep=None, null=None, decode=None, columns=None):
1363
+ """Copy data from the specified table to an output stream.
1364
+
1365
+ The output stream can be a file-like object with a write() method or
1366
+ it can also be None, in which case the method will return a generator
1367
+ yielding a row on each iteration.
1368
+
1369
+ Output will be returned as byte strings unless you set decode to true.
1370
+
1371
+ Note that you can also use a select query instead of the table name.
1372
+
1373
+ The format must be text, csv or binary. The sep option sets the
1374
+ column separator (delimiter) used in the non binary formats.
1375
+ The null option sets the textual representation of NULL in the output.
1376
+
1377
+ The copy operation can be restricted to a subset of columns. If no
1378
+ columns are specified, all of them will be copied.
1379
+ """
1380
+ binary_format = format == 'binary'
1381
+ if stream is not None:
1382
+ try:
1383
+ write = stream.write
1384
+ except AttributeError:
1385
+ raise TypeError("Need an output stream to copy to")
1386
+ if not table or not isinstance(table, basestring):
1387
+ raise TypeError("Need a table to copy to")
1388
+ if table.lower().startswith('select '):
1389
+ if columns:
1390
+ raise ValueError("Columns must be specified in the query")
1391
+ table = '(%s)' % (table,)
1392
+ else:
1393
+ table = '.'.join(map(
1394
+ self.connection._cnx.escape_identifier, table.split('.', 1)))
1395
+ operation = ['copy %s' % (table,)]
1396
+ options = []
1397
+ params = []
1398
+ if format is not None:
1399
+ if not isinstance(format, basestring):
1400
+ raise TypeError("The format option must be a string")
1401
+ if format not in ('text', 'csv', 'binary'):
1402
+ raise ValueError("Invalid format")
1403
+ options.append('format %s' % (format,))
1404
+ if sep is not None:
1405
+ if not isinstance(sep, basestring):
1406
+ raise TypeError("The sep option must be a string")
1407
+ if binary_format:
1408
+ raise ValueError(
1409
+ "The sep option is not allowed with binary format")
1410
+ if len(sep) != 1:
1411
+ raise ValueError(
1412
+ "The sep option must be a single one-byte character")
1413
+ options.append('delimiter %s')
1414
+ params.append(sep)
1415
+ if null is not None:
1416
+ if not isinstance(null, basestring):
1417
+ raise TypeError("The null option must be a string")
1418
+ options.append('null %s')
1419
+ params.append(null)
1420
+ if decode is None:
1421
+ if format == 'binary':
1422
+ decode = False
1423
+ else:
1424
+ decode = str is unicode
1425
+ else:
1426
+ if not isinstance(decode, (int, bool)):
1427
+ raise TypeError("The decode option must be a boolean")
1428
+ if decode and binary_format:
1429
+ raise ValueError(
1430
+ "The decode option is not allowed with binary format")
1431
+ if columns:
1432
+ if not isinstance(columns, basestring):
1433
+ columns = ','.join(map(
1434
+ self.connection._cnx.escape_identifier, columns))
1435
+ operation.append('(%s)' % (columns,))
1436
+
1437
+ operation.append("to stdout")
1438
+ if options:
1439
+ operation.append('(%s)' % (','.join(options),))
1440
+ operation = ' '.join(operation)
1441
+
1442
+ getdata = self._src.getdata
1443
+ self.execute(operation, params)
1444
+
1445
+ def copy():
1446
+ self.rowcount = 0
1447
+ while True:
1448
+ row = getdata(decode)
1449
+ if isinstance(row, int):
1450
+ if self.rowcount != row:
1451
+ self.rowcount = row
1452
+ break
1453
+ self.rowcount += 1
1454
+ yield row
1455
+
1456
+ if stream is None:
1457
+ # no input stream, return the generator
1458
+ return copy()
1459
+
1460
+ # write the rows to the file-like input stream
1461
+ for row in copy():
1462
+ # noinspection PyUnboundLocalVariable
1463
+ write(row)
1464
+
1465
+ # return the cursor object, so you can chain operations
1466
+ return self
1467
+
1468
+ def __next__(self):
1469
+ """Return the next row (support for the iteration protocol)."""
1470
+ res = self.fetchone()
1471
+ if res is None:
1472
+ raise StopIteration
1473
+ return res
1474
+
1475
+ # Note that since Python 2.6 the iterator protocol uses __next()__
1476
+ # instead of next(), we keep it only for backward compatibility of pgdb.
1477
+ next = __next__
1478
+
1479
+ @staticmethod
1480
+ def nextset():
1481
+ """Not supported."""
1482
+ raise NotSupportedError("The nextset() method is not supported")
1483
+
1484
+ @staticmethod
1485
+ def setinputsizes(sizes):
1486
+ """Not supported."""
1487
+ pass # unsupported, but silently passed
1488
+
1489
+ @staticmethod
1490
+ def setoutputsize(size, column=0):
1491
+ """Not supported."""
1492
+ pass # unsupported, but silently passed
1493
+
1494
+ @staticmethod
1495
+ def row_factory(row):
1496
+ """Process rows before they are returned.
1497
+
1498
+ You can overwrite this statically with a custom row factory, or
1499
+ you can build a row factory dynamically with build_row_factory().
1500
+
1501
+ For example, you can create a Cursor class that returns rows as
1502
+ Python dictionaries like this:
1503
+
1504
+ class DictCursor(pgdb.Cursor):
1505
+
1506
+ def row_factory(self, row):
1507
+ return {desc[0]: value
1508
+ for desc, value in zip(self.description, row)}
1509
+
1510
+ cur = DictCursor(con) # get one DictCursor instance or
1511
+ con.cursor_type = DictCursor # always use DictCursor instances
1512
+ """
1513
+ raise NotImplementedError
1514
+
1515
+ def build_row_factory(self):
1516
+ """Build a row factory based on the current description.
1517
+
1518
+ This implementation builds a row factory for creating named tuples.
1519
+ You can overwrite this method if you want to dynamically create
1520
+ different row factories whenever the column description changes.
1521
+ """
1522
+ names = self.colnames
1523
+ if names:
1524
+ return _row_factory(tuple(names))
1525
+
1526
+
1527
+ CursorDescription = namedtuple('CursorDescription', (
1528
+ 'name', 'type_code', 'display_size', 'internal_size',
1529
+ 'precision', 'scale', 'null_ok'))
1530
+
1531
+
1532
+ # *** Connection Objects ***
1533
+
1534
+ class Connection(object):
1535
+ """Connection object."""
1536
+
1537
+ # expose the exceptions as attributes on the connection object
1538
+ Error = Error
1539
+ Warning = Warning
1540
+ InterfaceError = InterfaceError
1541
+ DatabaseError = DatabaseError
1542
+ InternalError = InternalError
1543
+ OperationalError = OperationalError
1544
+ ProgrammingError = ProgrammingError
1545
+ IntegrityError = IntegrityError
1546
+ DataError = DataError
1547
+ NotSupportedError = NotSupportedError
1548
+
1549
+ def __init__(self, cnx):
1550
+ """Create a database connection object."""
1551
+ self._cnx = cnx # connection
1552
+ self._tnx = False # transaction state
1553
+ self.type_cache = TypeCache(cnx)
1554
+ self.cursor_type = Cursor
1555
+ self.autocommit = False
1556
+ try:
1557
+ self._cnx.source()
1558
+ except Exception:
1559
+ raise _op_error("Invalid connection")
1560
+
1561
+ def __enter__(self):
1562
+ """Enter the runtime context for the connection object.
1563
+
1564
+ The runtime context can be used for running transactions.
1565
+
1566
+ This also starts a transaction in autocommit mode.
1567
+ """
1568
+ if self.autocommit:
1569
+ try:
1570
+ self._cnx.source().execute("BEGIN")
1571
+ except DatabaseError:
1572
+ raise # database provides error message
1573
+ except Exception:
1574
+ raise _op_error("Can't start transaction")
1575
+ else:
1576
+ self._tnx = True
1577
+ return self
1578
+
1579
+ def __exit__(self, et, ev, tb):
1580
+ """Exit the runtime context for the connection object.
1581
+
1582
+ This does not close the connection, but it ends a transaction.
1583
+ """
1584
+ if et is None and ev is None and tb is None:
1585
+ self.commit()
1586
+ else:
1587
+ self.rollback()
1588
+
1589
+ def close(self):
1590
+ """Close the connection object."""
1591
+ if self._cnx:
1592
+ if self._tnx:
1593
+ try:
1594
+ self.rollback()
1595
+ except DatabaseError:
1596
+ pass
1597
+ self._cnx.close()
1598
+ self._cnx = None
1599
+ else:
1600
+ raise _op_error("Connection has been closed")
1601
+
1602
+ @property
1603
+ def closed(self):
1604
+ """Check whether the connection has been closed or is broken."""
1605
+ try:
1606
+ return not self._cnx or self._cnx.status != 1
1607
+ except TypeError:
1608
+ return True
1609
+
1610
+ def commit(self):
1611
+ """Commit any pending transaction to the database."""
1612
+ if self._cnx:
1613
+ if self._tnx:
1614
+ self._tnx = False
1615
+ try:
1616
+ self._cnx.source().execute("COMMIT")
1617
+ except DatabaseError:
1618
+ raise # database provides error message
1619
+ except Exception:
1620
+ raise _op_error("Can't commit transaction")
1621
+ else:
1622
+ raise _op_error("Connection has been closed")
1623
+
1624
+ def rollback(self):
1625
+ """Roll back to the start of any pending transaction."""
1626
+ if self._cnx:
1627
+ if self._tnx:
1628
+ self._tnx = False
1629
+ try:
1630
+ self._cnx.source().execute("ROLLBACK")
1631
+ except DatabaseError:
1632
+ raise # database provides error message
1633
+ except Exception:
1634
+ raise _op_error("Can't rollback transaction")
1635
+ else:
1636
+ raise _op_error("Connection has been closed")
1637
+
1638
+ def cursor(self):
1639
+ """Return a new cursor object using the connection."""
1640
+ if self._cnx:
1641
+ try:
1642
+ return self.cursor_type(self)
1643
+ except Exception:
1644
+ raise _op_error("Invalid connection")
1645
+ else:
1646
+ raise _op_error("Connection has been closed")
1647
+
1648
+ if shortcutmethods: # otherwise do not implement and document this
1649
+
1650
+ def execute(self, operation, params=None):
1651
+ """Shortcut method to run an operation on an implicit cursor."""
1652
+ cursor = self.cursor()
1653
+ cursor.execute(operation, params)
1654
+ return cursor
1655
+
1656
+ def executemany(self, operation, param_seq):
1657
+ """Shortcut method to run an operation against a sequence."""
1658
+ cursor = self.cursor()
1659
+ cursor.executemany(operation, param_seq)
1660
+ return cursor
1661
+
1662
+
1663
+ # *** Module Interface ***
1664
+
1665
+ _connect = connect
1666
+
1667
+
1668
+ def connect(dsn=None,
1669
+ user=None, password=None,
1670
+ host=None, database=None, **kwargs):
1671
+ """Connect to a database."""
1672
+ # first get params from DSN
1673
+ dbport = -1
1674
+ dbhost = ""
1675
+ dbname = ""
1676
+ dbuser = ""
1677
+ dbpasswd = ""
1678
+ dbopt = ""
1679
+ try:
1680
+ params = dsn.split(":")
1681
+ dbhost = params[0]
1682
+ dbname = params[1]
1683
+ dbuser = params[2]
1684
+ dbpasswd = params[3]
1685
+ dbopt = params[4]
1686
+ except (AttributeError, IndexError, TypeError):
1687
+ pass
1688
+
1689
+ # override if necessary
1690
+ if user is not None:
1691
+ dbuser = user
1692
+ if password is not None:
1693
+ dbpasswd = password
1694
+ if database is not None:
1695
+ dbname = database
1696
+ if host is not None:
1697
+ try:
1698
+ params = host.split(":")
1699
+ dbhost = params[0]
1700
+ dbport = int(params[1])
1701
+ except (AttributeError, IndexError, TypeError, ValueError):
1702
+ pass
1703
+
1704
+ # empty host is localhost
1705
+ if dbhost == "":
1706
+ dbhost = None
1707
+ if dbuser == "":
1708
+ dbuser = None
1709
+
1710
+ # pass keyword arguments as connection info string
1711
+ if kwargs:
1712
+ kwargs = list(kwargs.items())
1713
+ if '=' in dbname:
1714
+ dbname = [dbname]
1715
+ else:
1716
+ kwargs.insert(0, ('dbname', dbname))
1717
+ dbname = []
1718
+ for kw, value in kwargs:
1719
+ value = str(value)
1720
+ if not value or ' ' in value:
1721
+ value = "'%s'" % (value.replace(
1722
+ '\\', '\\\\').replace("'", "\\'"))
1723
+ dbname.append('%s=%s' % (kw, value))
1724
+ dbname = ' '.join(dbname)
1725
+ # open the connection
1726
+ # noinspection PyArgumentList
1727
+ cnx = _connect(dbname, dbhost, dbport, dbopt, dbuser, dbpasswd)
1728
+ return Connection(cnx)
1729
+
1730
+
1731
+ # *** Types Handling ***
1732
+
1733
+ class Type(frozenset):
1734
+ """Type class for a couple of PostgreSQL data types.
1735
+
1736
+ PostgreSQL is object-oriented: types are dynamic.
1737
+ We must thus use type names as internal type codes.
1738
+ """
1739
+
1740
+ def __new__(cls, values):
1741
+ if isinstance(values, basestring):
1742
+ values = values.split()
1743
+ return super(Type, cls).__new__(cls, values)
1744
+
1745
+ def __eq__(self, other):
1746
+ if isinstance(other, basestring):
1747
+ if other.startswith('_'):
1748
+ other = other[1:]
1749
+ return other in self
1750
+ else:
1751
+ return super(Type, self).__eq__(other)
1752
+
1753
+ def __ne__(self, other):
1754
+ if isinstance(other, basestring):
1755
+ if other.startswith('_'):
1756
+ other = other[1:]
1757
+ return other not in self
1758
+ else:
1759
+ return super(Type, self).__ne__(other)
1760
+
1761
+
1762
+ class ArrayType:
1763
+ """Type class for PostgreSQL array types."""
1764
+
1765
+ def __eq__(self, other):
1766
+ if isinstance(other, basestring):
1767
+ return other.startswith('_')
1768
+ else:
1769
+ return isinstance(other, ArrayType)
1770
+
1771
+ def __ne__(self, other):
1772
+ if isinstance(other, basestring):
1773
+ return not other.startswith('_')
1774
+ else:
1775
+ return not isinstance(other, ArrayType)
1776
+
1777
+
1778
+ class RecordType:
1779
+ """Type class for PostgreSQL record types."""
1780
+
1781
+ def __eq__(self, other):
1782
+ if isinstance(other, TypeCode):
1783
+ # noinspection PyUnresolvedReferences
1784
+ return other.type == 'c'
1785
+ elif isinstance(other, basestring):
1786
+ return other == 'record'
1787
+ else:
1788
+ return isinstance(other, RecordType)
1789
+
1790
+ def __ne__(self, other):
1791
+ if isinstance(other, TypeCode):
1792
+ # noinspection PyUnresolvedReferences
1793
+ return other.type != 'c'
1794
+ elif isinstance(other, basestring):
1795
+ return other != 'record'
1796
+ else:
1797
+ return not isinstance(other, RecordType)
1798
+
1799
+
1800
+ # Mandatory type objects defined by DB-API 2 specs:
1801
+
1802
+ STRING = Type('char bpchar name text varchar')
1803
+ BINARY = Type('bytea')
1804
+ NUMBER = Type('int2 int4 serial int8 float4 float8 numeric money')
1805
+ DATETIME = Type('date time timetz timestamp timestamptz interval'
1806
+ ' abstime reltime') # these are very old
1807
+ ROWID = Type('oid')
1808
+
1809
+
1810
+ # Additional type objects (more specific):
1811
+
1812
+ BOOL = Type('bool')
1813
+ SMALLINT = Type('int2')
1814
+ INTEGER = Type('int2 int4 int8 serial')
1815
+ LONG = Type('int8')
1816
+ FLOAT = Type('float4 float8')
1817
+ NUMERIC = Type('numeric')
1818
+ MONEY = Type('money')
1819
+ DATE = Type('date')
1820
+ TIME = Type('time timetz')
1821
+ TIMESTAMP = Type('timestamp timestamptz')
1822
+ INTERVAL = Type('interval')
1823
+ UUID = Type('uuid')
1824
+ HSTORE = Type('hstore')
1825
+ JSON = Type('json jsonb')
1826
+
1827
+ # Type object for arrays (also equate to their base types):
1828
+
1829
+ ARRAY = ArrayType()
1830
+
1831
+ # Type object for records (encompassing all composite types):
1832
+
1833
+ RECORD = RecordType()
1834
+
1835
+
1836
+ # Mandatory type helpers defined by DB-API 2 specs:
1837
+
1838
+ def Date(year, month, day):
1839
+ """Construct an object holding a date value."""
1840
+ return date(year, month, day)
1841
+
1842
+
1843
+ def Time(hour, minute=0, second=0, microsecond=0, tzinfo=None):
1844
+ """Construct an object holding a time value."""
1845
+ return time(hour, minute, second, microsecond, tzinfo)
1846
+
1847
+
1848
+ def Timestamp(year, month, day, hour=0, minute=0, second=0, microsecond=0,
1849
+ tzinfo=None):
1850
+ """Construct an object holding a time stamp value."""
1851
+ return datetime(year, month, day, hour, minute, second, microsecond,
1852
+ tzinfo)
1853
+
1854
+
1855
+ def DateFromTicks(ticks):
1856
+ """Construct an object holding a date value from the given ticks value."""
1857
+ return Date(*localtime(ticks)[:3])
1858
+
1859
+
1860
+ def TimeFromTicks(ticks):
1861
+ """Construct an object holding a time value from the given ticks value."""
1862
+ return Time(*localtime(ticks)[3:6])
1863
+
1864
+
1865
+ def TimestampFromTicks(ticks):
1866
+ """Construct an object holding a time stamp from the given ticks value."""
1867
+ return Timestamp(*localtime(ticks)[:6])
1868
+
1869
+
1870
+ class Binary(bytes):
1871
+ """Construct an object capable of holding a binary (long) string value."""
1872
+
1873
+
1874
+ # Additional type helpers for PyGreSQL:
1875
+
1876
+ def Interval(days, hours=0, minutes=0, seconds=0, microseconds=0):
1877
+ """Construct an object holding a time interval value."""
1878
+ return timedelta(days, hours=hours, minutes=minutes, seconds=seconds,
1879
+ microseconds=microseconds)
1880
+
1881
+
1882
+ Uuid = Uuid # Construct an object holding a UUID value
1883
+
1884
+
1885
+ class Hstore(dict):
1886
+ """Wrapper class for marking hstore values."""
1887
+
1888
+ _re_quote = regex('^[Nn][Uu][Ll][Ll]$|[ ,=>]')
1889
+ _re_escape = regex(r'(["\\])')
1890
+
1891
+ @classmethod
1892
+ def _quote(cls, s):
1893
+ if s is None:
1894
+ return 'NULL'
1895
+ if not isinstance(s, basestring):
1896
+ s = str(s)
1897
+ if not s:
1898
+ return '""'
1899
+ quote = cls._re_quote.search(s)
1900
+ s = cls._re_escape.sub(r'\\\1', s)
1901
+ if quote:
1902
+ s = '"%s"' % (s,)
1903
+ return s
1904
+
1905
+ def __str__(self):
1906
+ q = self._quote
1907
+ return ','.join('%s=>%s' % (q(k), q(v)) for k, v in self.items())
1908
+
1909
+
1910
+ class Json:
1911
+ """Construct a wrapper for holding an object serializable to JSON."""
1912
+
1913
+ def __init__(self, obj, encode=None):
1914
+ self.obj = obj
1915
+ self.encode = encode or jsonencode
1916
+
1917
+ def __str__(self):
1918
+ obj = self.obj
1919
+ if isinstance(obj, basestring):
1920
+ return obj
1921
+ return self.encode(obj)
1922
+
1923
+
1924
+ class Literal:
1925
+ """Construct a wrapper for holding a literal SQL string."""
1926
+
1927
+ def __init__(self, sql):
1928
+ self.sql = sql
1929
+
1930
+ def __str__(self):
1931
+ return self.sql
1932
+
1933
+ __pg_repr__ = __str__
1934
+
1935
+
1936
+ # If run as script, print some information:
1937
+
1938
+ if __name__ == '__main__':
1939
+ print('PyGreSQL version', version)
1940
+ print('')
1941
+ print(__doc__)