extras.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. """Miscellaneous goodies for psycopg2
  2. This module is a generic place used to hold little helper functions
  3. and classes until a better place in the distribution is found.
  4. """
  5. # psycopg/extras.py - miscellaneous extra goodies for psycopg
  6. #
  7. # Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org>
  8. # Copyright (C) 2020-2021 The Psycopg Team
  9. #
  10. # psycopg2 is free software: you can redistribute it and/or modify it
  11. # under the terms of the GNU Lesser General Public License as published
  12. # by the Free Software Foundation, either version 3 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # In addition, as a special exception, the copyright holders give
  16. # permission to link this program with the OpenSSL library (or with
  17. # modified versions of OpenSSL that use the same license as OpenSSL),
  18. # and distribute linked combinations including the two.
  19. #
  20. # You must obey the GNU Lesser General Public License in all respects for
  21. # all of the code used other than OpenSSL.
  22. #
  23. # psycopg2 is distributed in the hope that it will be useful, but WITHOUT
  24. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  25. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  26. # License for more details.
  27. import os as _os
  28. import time as _time
  29. import re as _re
  30. from collections import namedtuple, OrderedDict
  31. import logging as _logging
  32. import psycopg2
  33. from psycopg2 import extensions as _ext
  34. from .extensions import cursor as _cursor
  35. from .extensions import connection as _connection
  36. from .extensions import adapt as _A, quote_ident
  37. from functools import lru_cache
  38. from psycopg2._psycopg import ( # noqa
  39. REPLICATION_PHYSICAL, REPLICATION_LOGICAL,
  40. ReplicationConnection as _replicationConnection,
  41. ReplicationCursor as _replicationCursor,
  42. ReplicationMessage)
  43. # expose the json adaptation stuff into the module
  44. from psycopg2._json import ( # noqa
  45. json, Json, register_json, register_default_json, register_default_jsonb)
  46. # Expose range-related objects
  47. from psycopg2._range import ( # noqa
  48. Range, NumericRange, DateRange, DateTimeRange, DateTimeTZRange,
  49. register_range, RangeAdapter, RangeCaster)
  50. # Expose ipaddress-related objects
  51. from psycopg2._ipaddress import register_ipaddress # noqa
  52. class DictCursorBase(_cursor):
  53. """Base class for all dict-like cursors."""
  54. def __init__(self, *args, **kwargs):
  55. if 'row_factory' in kwargs:
  56. row_factory = kwargs['row_factory']
  57. del kwargs['row_factory']
  58. else:
  59. raise NotImplementedError(
  60. "DictCursorBase can't be instantiated without a row factory.")
  61. super().__init__(*args, **kwargs)
  62. self._query_executed = False
  63. self._prefetch = False
  64. self.row_factory = row_factory
  65. def fetchone(self):
  66. if self._prefetch:
  67. res = super().fetchone()
  68. if self._query_executed:
  69. self._build_index()
  70. if not self._prefetch:
  71. res = super().fetchone()
  72. return res
  73. def fetchmany(self, size=None):
  74. if self._prefetch:
  75. res = super().fetchmany(size)
  76. if self._query_executed:
  77. self._build_index()
  78. if not self._prefetch:
  79. res = super().fetchmany(size)
  80. return res
  81. def fetchall(self):
  82. if self._prefetch:
  83. res = super().fetchall()
  84. if self._query_executed:
  85. self._build_index()
  86. if not self._prefetch:
  87. res = super().fetchall()
  88. return res
  89. def __iter__(self):
  90. try:
  91. if self._prefetch:
  92. res = super().__iter__()
  93. first = next(res)
  94. if self._query_executed:
  95. self._build_index()
  96. if not self._prefetch:
  97. res = super().__iter__()
  98. first = next(res)
  99. yield first
  100. while True:
  101. yield next(res)
  102. except StopIteration:
  103. return
  104. class DictConnection(_connection):
  105. """A connection that uses `DictCursor` automatically."""
  106. def cursor(self, *args, **kwargs):
  107. kwargs.setdefault('cursor_factory', self.cursor_factory or DictCursor)
  108. return super().cursor(*args, **kwargs)
  109. class DictCursor(DictCursorBase):
  110. """A cursor that keeps a list of column name -> index mappings__.
  111. .. __: https://docs.python.org/glossary.html#term-mapping
  112. """
  113. def __init__(self, *args, **kwargs):
  114. kwargs['row_factory'] = DictRow
  115. super().__init__(*args, **kwargs)
  116. self._prefetch = True
  117. def execute(self, query, vars=None):
  118. self.index = OrderedDict()
  119. self._query_executed = True
  120. return super().execute(query, vars)
  121. def callproc(self, procname, vars=None):
  122. self.index = OrderedDict()
  123. self._query_executed = True
  124. return super().callproc(procname, vars)
  125. def _build_index(self):
  126. if self._query_executed and self.description:
  127. for i in range(len(self.description)):
  128. self.index[self.description[i][0]] = i
  129. self._query_executed = False
  130. class DictRow(list):
  131. """A row object that allow by-column-name access to data."""
  132. __slots__ = ('_index',)
  133. def __init__(self, cursor):
  134. self._index = cursor.index
  135. self[:] = [None] * len(cursor.description)
  136. def __getitem__(self, x):
  137. if not isinstance(x, (int, slice)):
  138. x = self._index[x]
  139. return super().__getitem__(x)
  140. def __setitem__(self, x, v):
  141. if not isinstance(x, (int, slice)):
  142. x = self._index[x]
  143. super().__setitem__(x, v)
  144. def items(self):
  145. g = super().__getitem__
  146. return ((n, g(self._index[n])) for n in self._index)
  147. def keys(self):
  148. return iter(self._index)
  149. def values(self):
  150. g = super().__getitem__
  151. return (g(self._index[n]) for n in self._index)
  152. def get(self, x, default=None):
  153. try:
  154. return self[x]
  155. except Exception:
  156. return default
  157. def copy(self):
  158. return OrderedDict(self.items())
  159. def __contains__(self, x):
  160. return x in self._index
  161. def __reduce__(self):
  162. # this is apparently useless, but it fixes #1073
  163. return super().__reduce__()
  164. def __getstate__(self):
  165. return self[:], self._index.copy()
  166. def __setstate__(self, data):
  167. self[:] = data[0]
  168. self._index = data[1]
  169. class RealDictConnection(_connection):
  170. """A connection that uses `RealDictCursor` automatically."""
  171. def cursor(self, *args, **kwargs):
  172. kwargs.setdefault('cursor_factory', self.cursor_factory or RealDictCursor)
  173. return super().cursor(*args, **kwargs)
  174. class RealDictCursor(DictCursorBase):
  175. """A cursor that uses a real dict as the base type for rows.
  176. Note that this cursor is extremely specialized and does not allow
  177. the normal access (using integer indices) to fetched data. If you need
  178. to access database rows both as a dictionary and a list, then use
  179. the generic `DictCursor` instead of `!RealDictCursor`.
  180. """
  181. def __init__(self, *args, **kwargs):
  182. kwargs['row_factory'] = RealDictRow
  183. super().__init__(*args, **kwargs)
  184. def execute(self, query, vars=None):
  185. self.column_mapping = []
  186. self._query_executed = True
  187. return super().execute(query, vars)
  188. def callproc(self, procname, vars=None):
  189. self.column_mapping = []
  190. self._query_executed = True
  191. return super().callproc(procname, vars)
  192. def _build_index(self):
  193. if self._query_executed and self.description:
  194. self.column_mapping = [d[0] for d in self.description]
  195. self._query_executed = False
  196. class RealDictRow(OrderedDict):
  197. """A `!dict` subclass representing a data record."""
  198. def __init__(self, *args, **kwargs):
  199. if args and isinstance(args[0], _cursor):
  200. cursor = args[0]
  201. args = args[1:]
  202. else:
  203. cursor = None
  204. super().__init__(*args, **kwargs)
  205. if cursor is not None:
  206. # Required for named cursors
  207. if cursor.description and not cursor.column_mapping:
  208. cursor._build_index()
  209. # Store the cols mapping in the dict itself until the row is fully
  210. # populated, so we don't need to add attributes to the class
  211. # (hence keeping its maintenance, special pickle support, etc.)
  212. self[RealDictRow] = cursor.column_mapping
  213. def __setitem__(self, key, value):
  214. if RealDictRow in self:
  215. # We are in the row building phase
  216. mapping = self[RealDictRow]
  217. super().__setitem__(mapping[key], value)
  218. if key == len(mapping) - 1:
  219. # Row building finished
  220. del self[RealDictRow]
  221. return
  222. super().__setitem__(key, value)
  223. class NamedTupleConnection(_connection):
  224. """A connection that uses `NamedTupleCursor` automatically."""
  225. def cursor(self, *args, **kwargs):
  226. kwargs.setdefault('cursor_factory', self.cursor_factory or NamedTupleCursor)
  227. return super().cursor(*args, **kwargs)
  228. class NamedTupleCursor(_cursor):
  229. """A cursor that generates results as `~collections.namedtuple`.
  230. `!fetch*()` methods will return named tuples instead of regular tuples, so
  231. their elements can be accessed both as regular numeric items as well as
  232. attributes.
  233. >>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  234. >>> rec = nt_cur.fetchone()
  235. >>> rec
  236. Record(id=1, num=100, data="abc'def")
  237. >>> rec[1]
  238. 100
  239. >>> rec.data
  240. "abc'def"
  241. """
  242. Record = None
  243. MAX_CACHE = 1024
  244. def execute(self, query, vars=None):
  245. self.Record = None
  246. return super().execute(query, vars)
  247. def executemany(self, query, vars):
  248. self.Record = None
  249. return super().executemany(query, vars)
  250. def callproc(self, procname, vars=None):
  251. self.Record = None
  252. return super().callproc(procname, vars)
  253. def fetchone(self):
  254. t = super().fetchone()
  255. if t is not None:
  256. nt = self.Record
  257. if nt is None:
  258. nt = self.Record = self._make_nt()
  259. return nt._make(t)
  260. def fetchmany(self, size=None):
  261. ts = super().fetchmany(size)
  262. nt = self.Record
  263. if nt is None:
  264. nt = self.Record = self._make_nt()
  265. return list(map(nt._make, ts))
  266. def fetchall(self):
  267. ts = super().fetchall()
  268. nt = self.Record
  269. if nt is None:
  270. nt = self.Record = self._make_nt()
  271. return list(map(nt._make, ts))
  272. def __iter__(self):
  273. try:
  274. it = super().__iter__()
  275. t = next(it)
  276. nt = self.Record
  277. if nt is None:
  278. nt = self.Record = self._make_nt()
  279. yield nt._make(t)
  280. while True:
  281. yield nt._make(next(it))
  282. except StopIteration:
  283. return
  284. # ascii except alnum and underscore
  285. _re_clean = _re.compile(
  286. '[' + _re.escape(' !"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~') + ']')
  287. def _make_nt(self):
  288. key = tuple(d[0] for d in self.description) if self.description else ()
  289. return self._cached_make_nt(key)
  290. @classmethod
  291. def _do_make_nt(cls, key):
  292. fields = []
  293. for s in key:
  294. s = cls._re_clean.sub('_', s)
  295. # Python identifier cannot start with numbers, namedtuple fields
  296. # cannot start with underscore. So...
  297. if s[0] == '_' or '0' <= s[0] <= '9':
  298. s = 'f' + s
  299. fields.append(s)
  300. nt = namedtuple("Record", fields)
  301. return nt
  302. @lru_cache(512)
  303. def _cached_make_nt(cls, key):
  304. return cls._do_make_nt(key)
  305. # Exposed for testability, and if someone wants to monkeypatch to tweak
  306. # the cache size.
  307. NamedTupleCursor._cached_make_nt = classmethod(_cached_make_nt)
  308. class LoggingConnection(_connection):
  309. """A connection that logs all queries to a file or logger__ object.
  310. .. __: https://docs.python.org/library/logging.html
  311. """
  312. def initialize(self, logobj):
  313. """Initialize the connection to log to `!logobj`.
  314. The `!logobj` parameter can be an open file object or a Logger/LoggerAdapter
  315. instance from the standard logging module.
  316. """
  317. self._logobj = logobj
  318. if _logging and isinstance(
  319. logobj, (_logging.Logger, _logging.LoggerAdapter)):
  320. self.log = self._logtologger
  321. else:
  322. self.log = self._logtofile
  323. def filter(self, msg, curs):
  324. """Filter the query before logging it.
  325. This is the method to overwrite to filter unwanted queries out of the
  326. log or to add some extra data to the output. The default implementation
  327. just does nothing.
  328. """
  329. return msg
  330. def _logtofile(self, msg, curs):
  331. msg = self.filter(msg, curs)
  332. if msg:
  333. if isinstance(msg, bytes):
  334. msg = msg.decode(_ext.encodings[self.encoding], 'replace')
  335. self._logobj.write(msg + _os.linesep)
  336. def _logtologger(self, msg, curs):
  337. msg = self.filter(msg, curs)
  338. if msg:
  339. self._logobj.debug(msg)
  340. def _check(self):
  341. if not hasattr(self, '_logobj'):
  342. raise self.ProgrammingError(
  343. "LoggingConnection object has not been initialize()d")
  344. def cursor(self, *args, **kwargs):
  345. self._check()
  346. kwargs.setdefault('cursor_factory', self.cursor_factory or LoggingCursor)
  347. return super().cursor(*args, **kwargs)
  348. class LoggingCursor(_cursor):
  349. """A cursor that logs queries using its connection logging facilities."""
  350. def execute(self, query, vars=None):
  351. try:
  352. return super().execute(query, vars)
  353. finally:
  354. self.connection.log(self.query, self)
  355. def callproc(self, procname, vars=None):
  356. try:
  357. return super().callproc(procname, vars)
  358. finally:
  359. self.connection.log(self.query, self)
  360. class MinTimeLoggingConnection(LoggingConnection):
  361. """A connection that logs queries based on execution time.
  362. This is just an example of how to sub-class `LoggingConnection` to
  363. provide some extra filtering for the logged queries. Both the
  364. `initialize()` and `filter()` methods are overwritten to make sure
  365. that only queries executing for more than ``mintime`` ms are logged.
  366. Note that this connection uses the specialized cursor
  367. `MinTimeLoggingCursor`.
  368. """
  369. def initialize(self, logobj, mintime=0):
  370. LoggingConnection.initialize(self, logobj)
  371. self._mintime = mintime
  372. def filter(self, msg, curs):
  373. t = (_time.time() - curs.timestamp) * 1000
  374. if t > self._mintime:
  375. if isinstance(msg, bytes):
  376. msg = msg.decode(_ext.encodings[self.encoding], 'replace')
  377. return f"{msg}{_os.linesep} (execution time: {t} ms)"
  378. def cursor(self, *args, **kwargs):
  379. kwargs.setdefault('cursor_factory',
  380. self.cursor_factory or MinTimeLoggingCursor)
  381. return LoggingConnection.cursor(self, *args, **kwargs)
  382. class MinTimeLoggingCursor(LoggingCursor):
  383. """The cursor sub-class companion to `MinTimeLoggingConnection`."""
  384. def execute(self, query, vars=None):
  385. self.timestamp = _time.time()
  386. return LoggingCursor.execute(self, query, vars)
  387. def callproc(self, procname, vars=None):
  388. self.timestamp = _time.time()
  389. return LoggingCursor.callproc(self, procname, vars)
  390. class LogicalReplicationConnection(_replicationConnection):
  391. def __init__(self, *args, **kwargs):
  392. kwargs['replication_type'] = REPLICATION_LOGICAL
  393. super().__init__(*args, **kwargs)
  394. class PhysicalReplicationConnection(_replicationConnection):
  395. def __init__(self, *args, **kwargs):
  396. kwargs['replication_type'] = REPLICATION_PHYSICAL
  397. super().__init__(*args, **kwargs)
  398. class StopReplication(Exception):
  399. """
  400. Exception used to break out of the endless loop in
  401. `~ReplicationCursor.consume_stream()`.
  402. Subclass of `~exceptions.Exception`. Intentionally *not* inherited from
  403. `~psycopg2.Error` as occurrence of this exception does not indicate an
  404. error.
  405. """
  406. pass
  407. class ReplicationCursor(_replicationCursor):
  408. """A cursor used for communication on replication connections."""
  409. def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None):
  410. """Create streaming replication slot."""
  411. command = f"CREATE_REPLICATION_SLOT {quote_ident(slot_name, self)} "
  412. if slot_type is None:
  413. slot_type = self.connection.replication_type
  414. if slot_type == REPLICATION_LOGICAL:
  415. if output_plugin is None:
  416. raise psycopg2.ProgrammingError(
  417. "output plugin name is required to create "
  418. "logical replication slot")
  419. command += f"LOGICAL {quote_ident(output_plugin, self)}"
  420. elif slot_type == REPLICATION_PHYSICAL:
  421. if output_plugin is not None:
  422. raise psycopg2.ProgrammingError(
  423. "cannot specify output plugin name when creating "
  424. "physical replication slot")
  425. command += "PHYSICAL"
  426. else:
  427. raise psycopg2.ProgrammingError(
  428. f"unrecognized replication type: {repr(slot_type)}")
  429. self.execute(command)
  430. def drop_replication_slot(self, slot_name):
  431. """Drop streaming replication slot."""
  432. command = f"DROP_REPLICATION_SLOT {quote_ident(slot_name, self)}"
  433. self.execute(command)
  434. def start_replication(
  435. self, slot_name=None, slot_type=None, start_lsn=0,
  436. timeline=0, options=None, decode=False, status_interval=10):
  437. """Start replication stream."""
  438. command = "START_REPLICATION "
  439. if slot_type is None:
  440. slot_type = self.connection.replication_type
  441. if slot_type == REPLICATION_LOGICAL:
  442. if slot_name:
  443. command += f"SLOT {quote_ident(slot_name, self)} "
  444. else:
  445. raise psycopg2.ProgrammingError(
  446. "slot name is required for logical replication")
  447. command += "LOGICAL "
  448. elif slot_type == REPLICATION_PHYSICAL:
  449. if slot_name:
  450. command += f"SLOT {quote_ident(slot_name, self)} "
  451. # don't add "PHYSICAL", before 9.4 it was just START_REPLICATION XXX/XXX
  452. else:
  453. raise psycopg2.ProgrammingError(
  454. f"unrecognized replication type: {repr(slot_type)}")
  455. if type(start_lsn) is str:
  456. lsn = start_lsn.split('/')
  457. lsn = f"{int(lsn[0], 16):X}/{int(lsn[1], 16):08X}"
  458. else:
  459. lsn = f"{start_lsn >> 32 & 4294967295:X}/{start_lsn & 4294967295:08X}"
  460. command += lsn
  461. if timeline != 0:
  462. if slot_type == REPLICATION_LOGICAL:
  463. raise psycopg2.ProgrammingError(
  464. "cannot specify timeline for logical replication")
  465. command += f" TIMELINE {timeline}"
  466. if options:
  467. if slot_type == REPLICATION_PHYSICAL:
  468. raise psycopg2.ProgrammingError(
  469. "cannot specify output plugin options for physical replication")
  470. command += " ("
  471. for k, v in options.items():
  472. if not command.endswith('('):
  473. command += ", "
  474. command += f"{quote_ident(k, self)} {_A(str(v))}"
  475. command += ")"
  476. self.start_replication_expert(
  477. command, decode=decode, status_interval=status_interval)
  478. # allows replication cursors to be used in select.select() directly
  479. def fileno(self):
  480. return self.connection.fileno()
  481. # a dbtype and adapter for Python UUID type
  482. class UUID_adapter:
  483. """Adapt Python's uuid.UUID__ type to PostgreSQL's uuid__.
  484. .. __: https://docs.python.org/library/uuid.html
  485. .. __: https://www.postgresql.org/docs/current/static/datatype-uuid.html
  486. """
  487. def __init__(self, uuid):
  488. self._uuid = uuid
  489. def __conform__(self, proto):
  490. if proto is _ext.ISQLQuote:
  491. return self
  492. def getquoted(self):
  493. return (f"'{self._uuid}'::uuid").encode('utf8')
  494. def __str__(self):
  495. return f"'{self._uuid}'::uuid"
  496. def register_uuid(oids=None, conn_or_curs=None):
  497. """Create the UUID type and an uuid.UUID adapter.
  498. :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence
  499. with oids of the type and the array. If not specified, use PostgreSQL
  500. standard oids.
  501. :param conn_or_curs: where to register the typecaster. If not specified,
  502. register it globally.
  503. """
  504. import uuid
  505. if not oids:
  506. oid1 = 2950
  507. oid2 = 2951
  508. elif isinstance(oids, (list, tuple)):
  509. oid1, oid2 = oids
  510. else:
  511. oid1 = oids
  512. oid2 = 2951
  513. _ext.UUID = _ext.new_type((oid1, ), "UUID",
  514. lambda data, cursor: data and uuid.UUID(data) or None)
  515. _ext.UUIDARRAY = _ext.new_array_type((oid2,), "UUID[]", _ext.UUID)
  516. _ext.register_type(_ext.UUID, conn_or_curs)
  517. _ext.register_type(_ext.UUIDARRAY, conn_or_curs)
  518. _ext.register_adapter(uuid.UUID, UUID_adapter)
  519. return _ext.UUID
  520. # a type, dbtype and adapter for PostgreSQL inet type
  521. class Inet:
  522. """Wrap a string to allow for correct SQL-quoting of inet values.
  523. Note that this adapter does NOT check the passed value to make
  524. sure it really is an inet-compatible address but DOES call adapt()
  525. on it to make sure it is impossible to execute an SQL-injection
  526. by passing an evil value to the initializer.
  527. """
  528. def __init__(self, addr):
  529. self.addr = addr
  530. def __repr__(self):
  531. return f"{self.__class__.__name__}({self.addr!r})"
  532. def prepare(self, conn):
  533. self._conn = conn
  534. def getquoted(self):
  535. obj = _A(self.addr)
  536. if hasattr(obj, 'prepare'):
  537. obj.prepare(self._conn)
  538. return obj.getquoted() + b"::inet"
  539. def __conform__(self, proto):
  540. if proto is _ext.ISQLQuote:
  541. return self
  542. def __str__(self):
  543. return str(self.addr)
  544. def register_inet(oid=None, conn_or_curs=None):
  545. """Create the INET type and an Inet adapter.
  546. :param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence
  547. with oids of the type and the array. If not specified, use PostgreSQL
  548. standard oids.
  549. :param conn_or_curs: where to register the typecaster. If not specified,
  550. register it globally.
  551. """
  552. import warnings
  553. warnings.warn(
  554. "the inet adapter is deprecated, it's not very useful",
  555. DeprecationWarning)
  556. if not oid:
  557. oid1 = 869
  558. oid2 = 1041
  559. elif isinstance(oid, (list, tuple)):
  560. oid1, oid2 = oid
  561. else:
  562. oid1 = oid
  563. oid2 = 1041
  564. _ext.INET = _ext.new_type((oid1, ), "INET",
  565. lambda data, cursor: data and Inet(data) or None)
  566. _ext.INETARRAY = _ext.new_array_type((oid2, ), "INETARRAY", _ext.INET)
  567. _ext.register_type(_ext.INET, conn_or_curs)
  568. _ext.register_type(_ext.INETARRAY, conn_or_curs)
  569. return _ext.INET
  570. def wait_select(conn):
  571. """Wait until a connection or cursor has data available.
  572. The function is an example of a wait callback to be registered with
  573. `~psycopg2.extensions.set_wait_callback()`. This function uses
  574. :py:func:`~select.select()` to wait for data to become available, and
  575. therefore is able to handle/receive SIGINT/KeyboardInterrupt.
  576. """
  577. import select
  578. from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
  579. while True:
  580. try:
  581. state = conn.poll()
  582. if state == POLL_OK:
  583. break
  584. elif state == POLL_READ:
  585. select.select([conn.fileno()], [], [])
  586. elif state == POLL_WRITE:
  587. select.select([], [conn.fileno()], [])
  588. else:
  589. raise conn.OperationalError(f"bad state from poll: {state}")
  590. except KeyboardInterrupt:
  591. conn.cancel()
  592. # the loop will be broken by a server error
  593. continue
  594. def _solve_conn_curs(conn_or_curs):
  595. """Return the connection and a DBAPI cursor from a connection or cursor."""
  596. if conn_or_curs is None:
  597. raise psycopg2.ProgrammingError("no connection or cursor provided")
  598. if hasattr(conn_or_curs, 'execute'):
  599. conn = conn_or_curs.connection
  600. curs = conn.cursor(cursor_factory=_cursor)
  601. else:
  602. conn = conn_or_curs
  603. curs = conn.cursor(cursor_factory=_cursor)
  604. return conn, curs
  605. class HstoreAdapter:
  606. """Adapt a Python dict to the hstore syntax."""
  607. def __init__(self, wrapped):
  608. self.wrapped = wrapped
  609. def prepare(self, conn):
  610. self.conn = conn
  611. # use an old-style getquoted implementation if required
  612. if conn.info.server_version < 90000:
  613. self.getquoted = self._getquoted_8
  614. def _getquoted_8(self):
  615. """Use the operators available in PG pre-9.0."""
  616. if not self.wrapped:
  617. return b"''::hstore"
  618. adapt = _ext.adapt
  619. rv = []
  620. for k, v in self.wrapped.items():
  621. k = adapt(k)
  622. k.prepare(self.conn)
  623. k = k.getquoted()
  624. if v is not None:
  625. v = adapt(v)
  626. v.prepare(self.conn)
  627. v = v.getquoted()
  628. else:
  629. v = b'NULL'
  630. # XXX this b'ing is painfully inefficient!
  631. rv.append(b"(" + k + b" => " + v + b")")
  632. return b"(" + b'||'.join(rv) + b")"
  633. def _getquoted_9(self):
  634. """Use the hstore(text[], text[]) function."""
  635. if not self.wrapped:
  636. return b"''::hstore"
  637. k = _ext.adapt(list(self.wrapped.keys()))
  638. k.prepare(self.conn)
  639. v = _ext.adapt(list(self.wrapped.values()))
  640. v.prepare(self.conn)
  641. return b"hstore(" + k.getquoted() + b", " + v.getquoted() + b")"
  642. getquoted = _getquoted_9
  643. _re_hstore = _re.compile(r"""
  644. # hstore key:
  645. # a string of normal or escaped chars
  646. "((?: [^"\\] | \\. )*)"
  647. \s*=>\s* # hstore value
  648. (?:
  649. NULL # the value can be null - not catched
  650. # or a quoted string like the key
  651. | "((?: [^"\\] | \\. )*)"
  652. )
  653. (?:\s*,\s*|$) # pairs separated by comma or end of string.
  654. """, _re.VERBOSE)
  655. @classmethod
  656. def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")):
  657. """Parse an hstore representation in a Python string.
  658. The hstore is represented as something like::
  659. "a"=>"1", "b"=>"2"
  660. with backslash-escaped strings.
  661. """
  662. if s is None:
  663. return None
  664. rv = {}
  665. start = 0
  666. for m in self._re_hstore.finditer(s):
  667. if m is None or m.start() != start:
  668. raise psycopg2.InterfaceError(
  669. f"error parsing hstore pair at char {start}")
  670. k = _bsdec.sub(r'\1', m.group(1))
  671. v = m.group(2)
  672. if v is not None:
  673. v = _bsdec.sub(r'\1', v)
  674. rv[k] = v
  675. start = m.end()
  676. if start < len(s):
  677. raise psycopg2.InterfaceError(
  678. f"error parsing hstore: unparsed data after char {start}")
  679. return rv
  680. @classmethod
  681. def parse_unicode(self, s, cur):
  682. """Parse an hstore returning unicode keys and values."""
  683. if s is None:
  684. return None
  685. s = s.decode(_ext.encodings[cur.connection.encoding])
  686. return self.parse(s, cur)
  687. @classmethod
  688. def get_oids(self, conn_or_curs):
  689. """Return the lists of OID of the hstore and hstore[] types.
  690. """
  691. conn, curs = _solve_conn_curs(conn_or_curs)
  692. # Store the transaction status of the connection to revert it after use
  693. conn_status = conn.status
  694. # column typarray not available before PG 8.3
  695. typarray = conn.info.server_version >= 80300 and "typarray" or "NULL"
  696. rv0, rv1 = [], []
  697. # get the oid for the hstore
  698. curs.execute(f"""SELECT t.oid, {typarray}
  699. FROM pg_type t JOIN pg_namespace ns
  700. ON typnamespace = ns.oid
  701. WHERE typname = 'hstore';
  702. """)
  703. for oids in curs:
  704. rv0.append(oids[0])
  705. rv1.append(oids[1])
  706. # revert the status of the connection as before the command
  707. if (conn_status != _ext.STATUS_IN_TRANSACTION
  708. and not conn.autocommit):
  709. conn.rollback()
  710. return tuple(rv0), tuple(rv1)
  711. def register_hstore(conn_or_curs, globally=False, unicode=False,
  712. oid=None, array_oid=None):
  713. r"""Register adapter and typecaster for `!dict`\-\ |hstore| conversions.
  714. :param conn_or_curs: a connection or cursor: the typecaster will be
  715. registered only on this object unless *globally* is set to `!True`
  716. :param globally: register the adapter globally, not only on *conn_or_curs*
  717. :param unicode: if `!True`, keys and values returned from the database
  718. will be `!unicode` instead of `!str`. The option is not available on
  719. Python 3
  720. :param oid: the OID of the |hstore| type if known. If not, it will be
  721. queried on *conn_or_curs*.
  722. :param array_oid: the OID of the |hstore| array type if known. If not, it
  723. will be queried on *conn_or_curs*.
  724. The connection or cursor passed to the function will be used to query the
  725. database and look for the OID of the |hstore| type (which may be different
  726. across databases). If querying is not desirable (e.g. with
  727. :ref:`asynchronous connections <async-support>`) you may specify it in the
  728. *oid* parameter, which can be found using a query such as :sql:`SELECT
  729. 'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid*
  730. using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`.
  731. Note that, when passing a dictionary from Python to the database, both
  732. strings and unicode keys and values are supported. Dictionaries returned
  733. from the database have keys/values according to the *unicode* parameter.
  734. The |hstore| contrib module must be already installed in the database
  735. (executing the ``hstore.sql`` script in your ``contrib`` directory).
  736. Raise `~psycopg2.ProgrammingError` if the type is not found.
  737. """
  738. if oid is None:
  739. oid = HstoreAdapter.get_oids(conn_or_curs)
  740. if oid is None or not oid[0]:
  741. raise psycopg2.ProgrammingError(
  742. "hstore type not found in the database. "
  743. "please install it from your 'contrib/hstore.sql' file")
  744. else:
  745. array_oid = oid[1]
  746. oid = oid[0]
  747. if isinstance(oid, int):
  748. oid = (oid,)
  749. if array_oid is not None:
  750. if isinstance(array_oid, int):
  751. array_oid = (array_oid,)
  752. else:
  753. array_oid = tuple([x for x in array_oid if x])
  754. # create and register the typecaster
  755. HSTORE = _ext.new_type(oid, "HSTORE", HstoreAdapter.parse)
  756. _ext.register_type(HSTORE, not globally and conn_or_curs or None)
  757. _ext.register_adapter(dict, HstoreAdapter)
  758. if array_oid:
  759. HSTOREARRAY = _ext.new_array_type(array_oid, "HSTOREARRAY", HSTORE)
  760. _ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None)
  761. class CompositeCaster:
  762. """Helps conversion of a PostgreSQL composite type into a Python object.
  763. The class is usually created by the `register_composite()` function.
  764. You may want to create and register manually instances of the class if
  765. querying the database at registration time is not desirable (such as when
  766. using an :ref:`asynchronous connections <async-support>`).
  767. """
  768. def __init__(self, name, oid, attrs, array_oid=None, schema=None):
  769. self.name = name
  770. self.schema = schema
  771. self.oid = oid
  772. self.array_oid = array_oid
  773. self.attnames = [a[0] for a in attrs]
  774. self.atttypes = [a[1] for a in attrs]
  775. self._create_type(name, self.attnames)
  776. self.typecaster = _ext.new_type((oid,), name, self.parse)
  777. if array_oid:
  778. self.array_typecaster = _ext.new_array_type(
  779. (array_oid,), f"{name}ARRAY", self.typecaster)
  780. else:
  781. self.array_typecaster = None
  782. def parse(self, s, curs):
  783. if s is None:
  784. return None
  785. tokens = self.tokenize(s)
  786. if len(tokens) != len(self.atttypes):
  787. raise psycopg2.DataError(
  788. "expecting %d components for the type %s, %d found instead" %
  789. (len(self.atttypes), self.name, len(tokens)))
  790. values = [curs.cast(oid, token)
  791. for oid, token in zip(self.atttypes, tokens)]
  792. return self.make(values)
  793. def make(self, values):
  794. """Return a new Python object representing the data being casted.
  795. *values* is the list of attributes, already casted into their Python
  796. representation.
  797. You can subclass this method to :ref:`customize the composite cast
  798. <custom-composite>`.
  799. """
  800. return self._ctor(values)
  801. _re_tokenize = _re.compile(r"""
  802. \(? ([,)]) # an empty token, representing NULL
  803. | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string
  804. | \(? ([^",)]+) [,)] # or an unquoted string
  805. """, _re.VERBOSE)
  806. _re_undouble = _re.compile(r'(["\\])\1')
  807. @classmethod
  808. def tokenize(self, s):
  809. rv = []
  810. for m in self._re_tokenize.finditer(s):
  811. if m is None:
  812. raise psycopg2.InterfaceError(f"can't parse type: {s!r}")
  813. if m.group(1) is not None:
  814. rv.append(None)
  815. elif m.group(2) is not None:
  816. rv.append(self._re_undouble.sub(r"\1", m.group(2)))
  817. else:
  818. rv.append(m.group(3))
  819. return rv
  820. def _create_type(self, name, attnames):
  821. self.type = namedtuple(name, attnames)
  822. self._ctor = self.type._make
  823. @classmethod
  824. def _from_db(self, name, conn_or_curs):
  825. """Return a `CompositeCaster` instance for the type *name*.
  826. Raise `ProgrammingError` if the type is not found.
  827. """
  828. conn, curs = _solve_conn_curs(conn_or_curs)
  829. # Store the transaction status of the connection to revert it after use
  830. conn_status = conn.status
  831. # Use the correct schema
  832. if '.' in name:
  833. schema, tname = name.split('.', 1)
  834. else:
  835. tname = name
  836. schema = 'public'
  837. # column typarray not available before PG 8.3
  838. typarray = conn.info.server_version >= 80300 and "typarray" or "NULL"
  839. # get the type oid and attributes
  840. curs.execute("""\
  841. SELECT t.oid, %s, attname, atttypid
  842. FROM pg_type t
  843. JOIN pg_namespace ns ON typnamespace = ns.oid
  844. JOIN pg_attribute a ON attrelid = typrelid
  845. WHERE typname = %%s AND nspname = %%s
  846. AND attnum > 0 AND NOT attisdropped
  847. ORDER BY attnum;
  848. """ % typarray, (tname, schema))
  849. recs = curs.fetchall()
  850. # revert the status of the connection as before the command
  851. if (conn_status != _ext.STATUS_IN_TRANSACTION
  852. and not conn.autocommit):
  853. conn.rollback()
  854. if not recs:
  855. raise psycopg2.ProgrammingError(
  856. f"PostgreSQL type '{name}' not found")
  857. type_oid = recs[0][0]
  858. array_oid = recs[0][1]
  859. type_attrs = [(r[2], r[3]) for r in recs]
  860. return self(tname, type_oid, type_attrs,
  861. array_oid=array_oid, schema=schema)
  862. def register_composite(name, conn_or_curs, globally=False, factory=None):
  863. """Register a typecaster to convert a composite type into a tuple.
  864. :param name: the name of a PostgreSQL composite type, e.g. created using
  865. the |CREATE TYPE|_ command
  866. :param conn_or_curs: a connection or cursor used to find the type oid and
  867. components; the typecaster is registered in a scope limited to this
  868. object, unless *globally* is set to `!True`
  869. :param globally: if `!False` (default) register the typecaster only on
  870. *conn_or_curs*, otherwise register it globally
  871. :param factory: if specified it should be a `CompositeCaster` subclass: use
  872. it to :ref:`customize how to cast composite types <custom-composite>`
  873. :return: the registered `CompositeCaster` or *factory* instance
  874. responsible for the conversion
  875. """
  876. if factory is None:
  877. factory = CompositeCaster
  878. caster = factory._from_db(name, conn_or_curs)
  879. _ext.register_type(caster.typecaster, not globally and conn_or_curs or None)
  880. if caster.array_typecaster is not None:
  881. _ext.register_type(
  882. caster.array_typecaster, not globally and conn_or_curs or None)
  883. return caster
  884. def _paginate(seq, page_size):
  885. """Consume an iterable and return it in chunks.
  886. Every chunk is at most `page_size`. Never return an empty chunk.
  887. """
  888. page = []
  889. it = iter(seq)
  890. while True:
  891. try:
  892. for i in range(page_size):
  893. page.append(next(it))
  894. yield page
  895. page = []
  896. except StopIteration:
  897. if page:
  898. yield page
  899. return
  900. def execute_batch(cur, sql, argslist, page_size=100):
  901. r"""Execute groups of statements in fewer server roundtrips.
  902. Execute *sql* several times, against all parameters set (sequences or
  903. mappings) found in *argslist*.
  904. The function is semantically similar to
  905. .. parsed-literal::
  906. *cur*\.\ `~cursor.executemany`\ (\ *sql*\ , *argslist*\ )
  907. but has a different implementation: Psycopg will join the statements into
  908. fewer multi-statement commands, each one containing at most *page_size*
  909. statements, resulting in a reduced number of server roundtrips.
  910. After the execution of the function the `cursor.rowcount` property will
  911. **not** contain a total result.
  912. """
  913. for page in _paginate(argslist, page_size=page_size):
  914. sqls = [cur.mogrify(sql, args) for args in page]
  915. cur.execute(b";".join(sqls))
  916. def execute_values(cur, sql, argslist, template=None, page_size=100, fetch=False):
  917. '''Execute a statement using :sql:`VALUES` with a sequence of parameters.
  918. :param cur: the cursor to use to execute the query.
  919. :param sql: the query to execute. It must contain a single ``%s``
  920. placeholder, which will be replaced by a `VALUES list`__.
  921. Example: ``"INSERT INTO mytable (id, f1, f2) VALUES %s"``.
  922. :param argslist: sequence of sequences or dictionaries with the arguments
  923. to send to the query. The type and content must be consistent with
  924. *template*.
  925. :param template: the snippet to merge to every item in *argslist* to
  926. compose the query.
  927. - If the *argslist* items are sequences it should contain positional
  928. placeholders (e.g. ``"(%s, %s, %s)"``, or ``"(%s, %s, 42)``" if there
  929. are constants value...).
  930. - If the *argslist* items are mappings it should contain named
  931. placeholders (e.g. ``"(%(id)s, %(f1)s, 42)"``).
  932. If not specified, assume the arguments are sequence and use a simple
  933. positional template (i.e. ``(%s, %s, ...)``), with the number of
  934. placeholders sniffed by the first element in *argslist*.
  935. :param page_size: maximum number of *argslist* items to include in every
  936. statement. If there are more items the function will execute more than
  937. one statement.
  938. :param fetch: if `!True` return the query results into a list (like in a
  939. `~cursor.fetchall()`). Useful for queries with :sql:`RETURNING`
  940. clause.
  941. .. __: https://www.postgresql.org/docs/current/static/queries-values.html
  942. After the execution of the function the `cursor.rowcount` property will
  943. **not** contain a total result.
  944. While :sql:`INSERT` is an obvious candidate for this function it is
  945. possible to use it with other statements, for example::
  946. >>> cur.execute(
  947. ... "create table test (id int primary key, v1 int, v2 int)")
  948. >>> execute_values(cur,
  949. ... "INSERT INTO test (id, v1, v2) VALUES %s",
  950. ... [(1, 2, 3), (4, 5, 6), (7, 8, 9)])
  951. >>> execute_values(cur,
  952. ... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1)
  953. ... WHERE test.id = data.id""",
  954. ... [(1, 20), (4, 50)])
  955. >>> cur.execute("select * from test order by id")
  956. >>> cur.fetchall()
  957. [(1, 20, 3), (4, 50, 6), (7, 8, 9)])
  958. '''
  959. from psycopg2.sql import Composable
  960. if isinstance(sql, Composable):
  961. sql = sql.as_string(cur)
  962. # we can't just use sql % vals because vals is bytes: if sql is bytes
  963. # there will be some decoding error because of stupid codec used, and Py3
  964. # doesn't implement % on bytes.
  965. if not isinstance(sql, bytes):
  966. sql = sql.encode(_ext.encodings[cur.connection.encoding])
  967. pre, post = _split_sql(sql)
  968. result = [] if fetch else None
  969. for page in _paginate(argslist, page_size=page_size):
  970. if template is None:
  971. template = b'(' + b','.join([b'%s'] * len(page[0])) + b')'
  972. parts = pre[:]
  973. for args in page:
  974. parts.append(cur.mogrify(template, args))
  975. parts.append(b',')
  976. parts[-1:] = post
  977. cur.execute(b''.join(parts))
  978. if fetch:
  979. result.extend(cur.fetchall())
  980. return result
  981. def _split_sql(sql):
  982. """Split *sql* on a single ``%s`` placeholder.
  983. Split on the %s, perform %% replacement and return pre, post lists of
  984. snippets.
  985. """
  986. curr = pre = []
  987. post = []
  988. tokens = _re.split(br'(%.)', sql)
  989. for token in tokens:
  990. if len(token) != 2 or token[:1] != b'%':
  991. curr.append(token)
  992. continue
  993. if token[1:] == b's':
  994. if curr is pre:
  995. curr = post
  996. else:
  997. raise ValueError(
  998. "the query contains more than one '%s' placeholder")
  999. elif token[1:] == b'%':
  1000. curr.append(b'%')
  1001. else:
  1002. raise ValueError("unsupported format character: '%s'"
  1003. % token[1:].decode('ascii', 'replace'))
  1004. if curr is pre:
  1005. raise ValueError("the query doesn't contain any '%s' placeholder")
  1006. return pre, post