extensions.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """psycopg extensions to the DBAPI-2.0
  2. This module holds all the extensions to the DBAPI-2.0 provided by psycopg.
  3. - `connection` -- the new-type inheritable connection class
  4. - `cursor` -- the new-type inheritable cursor class
  5. - `lobject` -- the new-type inheritable large object class
  6. - `adapt()` -- exposes the PEP-246_ compatible adapting mechanism used
  7. by psycopg to adapt Python types to PostgreSQL ones
  8. .. _PEP-246: https://www.python.org/dev/peps/pep-0246/
  9. """
  10. # psycopg/extensions.py - DBAPI-2.0 extensions specific to psycopg
  11. #
  12. # Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org>
  13. # Copyright (C) 2020-2021 The Psycopg Team
  14. #
  15. # psycopg2 is free software: you can redistribute it and/or modify it
  16. # under the terms of the GNU Lesser General Public License as published
  17. # by the Free Software Foundation, either version 3 of the License, or
  18. # (at your option) any later version.
  19. #
  20. # In addition, as a special exception, the copyright holders give
  21. # permission to link this program with the OpenSSL library (or with
  22. # modified versions of OpenSSL that use the same license as OpenSSL),
  23. # and distribute linked combinations including the two.
  24. #
  25. # You must obey the GNU Lesser General Public License in all respects for
  26. # all of the code used other than OpenSSL.
  27. #
  28. # psycopg2 is distributed in the hope that it will be useful, but WITHOUT
  29. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  30. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  31. # License for more details.
  32. import re as _re
  33. from psycopg2._psycopg import ( # noqa
  34. BINARYARRAY, BOOLEAN, BOOLEANARRAY, BYTES, BYTESARRAY, DATE, DATEARRAY,
  35. DATETIMEARRAY, DECIMAL, DECIMALARRAY, FLOAT, FLOATARRAY, INTEGER,
  36. INTEGERARRAY, INTERVAL, INTERVALARRAY, LONGINTEGER, LONGINTEGERARRAY,
  37. ROWIDARRAY, STRINGARRAY, TIME, TIMEARRAY, UNICODE, UNICODEARRAY,
  38. AsIs, Binary, Boolean, Float, Int, QuotedString, )
  39. from psycopg2._psycopg import ( # noqa
  40. PYDATE, PYDATETIME, PYDATETIMETZ, PYINTERVAL, PYTIME, PYDATEARRAY,
  41. PYDATETIMEARRAY, PYDATETIMETZARRAY, PYINTERVALARRAY, PYTIMEARRAY,
  42. DateFromPy, TimeFromPy, TimestampFromPy, IntervalFromPy, )
  43. from psycopg2._psycopg import ( # noqa
  44. adapt, adapters, encodings, connection, cursor,
  45. lobject, Xid, libpq_version, parse_dsn, quote_ident,
  46. string_types, binary_types, new_type, new_array_type, register_type,
  47. ISQLQuote, Notify, Diagnostics, Column, ConnectionInfo,
  48. QueryCanceledError, TransactionRollbackError,
  49. set_wait_callback, get_wait_callback, encrypt_password, )
  50. """Isolation level values."""
  51. ISOLATION_LEVEL_AUTOCOMMIT = 0
  52. ISOLATION_LEVEL_READ_UNCOMMITTED = 4
  53. ISOLATION_LEVEL_READ_COMMITTED = 1
  54. ISOLATION_LEVEL_REPEATABLE_READ = 2
  55. ISOLATION_LEVEL_SERIALIZABLE = 3
  56. ISOLATION_LEVEL_DEFAULT = None
  57. """psycopg connection status values."""
  58. STATUS_SETUP = 0
  59. STATUS_READY = 1
  60. STATUS_BEGIN = 2
  61. STATUS_SYNC = 3 # currently unused
  62. STATUS_ASYNC = 4 # currently unused
  63. STATUS_PREPARED = 5
  64. # This is a useful mnemonic to check if the connection is in a transaction
  65. STATUS_IN_TRANSACTION = STATUS_BEGIN
  66. """psycopg asynchronous connection polling values"""
  67. POLL_OK = 0
  68. POLL_READ = 1
  69. POLL_WRITE = 2
  70. POLL_ERROR = 3
  71. """Backend transaction status values."""
  72. TRANSACTION_STATUS_IDLE = 0
  73. TRANSACTION_STATUS_ACTIVE = 1
  74. TRANSACTION_STATUS_INTRANS = 2
  75. TRANSACTION_STATUS_INERROR = 3
  76. TRANSACTION_STATUS_UNKNOWN = 4
  77. def register_adapter(typ, callable):
  78. """Register 'callable' as an ISQLQuote adapter for type 'typ'."""
  79. adapters[(typ, ISQLQuote)] = callable
  80. # The SQL_IN class is the official adapter for tuples starting from 2.0.6.
  81. class SQL_IN:
  82. """Adapt any iterable to an SQL quotable object."""
  83. def __init__(self, seq):
  84. self._seq = seq
  85. self._conn = None
  86. def prepare(self, conn):
  87. self._conn = conn
  88. def getquoted(self):
  89. # this is the important line: note how every object in the
  90. # list is adapted and then how getquoted() is called on it
  91. pobjs = [adapt(o) for o in self._seq]
  92. if self._conn is not None:
  93. for obj in pobjs:
  94. if hasattr(obj, 'prepare'):
  95. obj.prepare(self._conn)
  96. qobjs = [o.getquoted() for o in pobjs]
  97. return b'(' + b', '.join(qobjs) + b')'
  98. def __str__(self):
  99. return str(self.getquoted())
  100. class NoneAdapter:
  101. """Adapt None to NULL.
  102. This adapter is not used normally as a fast path in mogrify uses NULL,
  103. but it makes easier to adapt composite types.
  104. """
  105. def __init__(self, obj):
  106. pass
  107. def getquoted(self, _null=b"NULL"):
  108. return _null
  109. def make_dsn(dsn=None, **kwargs):
  110. """Convert a set of keywords into a connection strings."""
  111. if dsn is None and not kwargs:
  112. return ''
  113. # If no kwarg is specified don't mung the dsn, but verify it
  114. if not kwargs:
  115. parse_dsn(dsn)
  116. return dsn
  117. # Override the dsn with the parameters
  118. if 'database' in kwargs:
  119. if 'dbname' in kwargs:
  120. raise TypeError(
  121. "you can't specify both 'database' and 'dbname' arguments")
  122. kwargs['dbname'] = kwargs.pop('database')
  123. # Drop the None arguments
  124. kwargs = {k: v for (k, v) in kwargs.items() if v is not None}
  125. if dsn is not None:
  126. tmp = parse_dsn(dsn)
  127. tmp.update(kwargs)
  128. kwargs = tmp
  129. dsn = " ".join(["{}={}".format(k, _param_escape(str(v)))
  130. for (k, v) in kwargs.items()])
  131. # verify that the returned dsn is valid
  132. parse_dsn(dsn)
  133. return dsn
  134. def _param_escape(s,
  135. re_escape=_re.compile(r"([\\'])"),
  136. re_space=_re.compile(r'\s')):
  137. """
  138. Apply the escaping rule required by PQconnectdb
  139. """
  140. if not s:
  141. return "''"
  142. s = re_escape.sub(r'\\\1', s)
  143. if re_space.search(s):
  144. s = "'" + s + "'"
  145. return s
  146. # Create default json typecasters for PostgreSQL 9.2 oids
  147. from psycopg2._json import register_default_json, register_default_jsonb # noqa
  148. try:
  149. JSON, JSONARRAY = register_default_json()
  150. JSONB, JSONBARRAY = register_default_jsonb()
  151. except ImportError:
  152. pass
  153. del register_default_json, register_default_jsonb
  154. # Create default Range typecasters
  155. from psycopg2. _range import Range # noqa
  156. del Range
  157. # Add the "cleaned" version of the encodings to the key.
  158. # When the encoding is set its name is cleaned up from - and _ and turned
  159. # uppercase, so an encoding not respecting these rules wouldn't be found in the
  160. # encodings keys and would raise an exception with the unicode typecaster
  161. for k, v in list(encodings.items()):
  162. k = k.replace('_', '').replace('-', '').upper()
  163. encodings[k] = v
  164. del k, v