METADATA 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474
  1. Metadata-Version: 2.1
  2. Name: pg8000
  3. Version: 1.30.3
  4. Summary: PostgreSQL interface library
  5. License: BSD 3-Clause License
  6. Project-URL: Homepage, https://github.com/tlocke/pg8000
  7. Keywords: postgresql,dbapi
  8. Classifier: Development Status :: 5 - Production/Stable
  9. Classifier: Intended Audience :: Developers
  10. Classifier: License :: OSI Approved :: BSD License
  11. Classifier: Programming Language :: Python
  12. Classifier: Programming Language :: Python :: 3
  13. Classifier: Programming Language :: Python :: 3.8
  14. Classifier: Programming Language :: Python :: 3.9
  15. Classifier: Programming Language :: Python :: 3.10
  16. Classifier: Programming Language :: Python :: 3.11
  17. Classifier: Programming Language :: Python :: Implementation
  18. Classifier: Programming Language :: Python :: Implementation :: CPython
  19. Classifier: Programming Language :: Python :: Implementation :: PyPy
  20. Classifier: Operating System :: OS Independent
  21. Classifier: Topic :: Database :: Front-Ends
  22. Classifier: Topic :: Software Development :: Libraries :: Python Modules
  23. Requires-Python: >=3.8
  24. Description-Content-Type: text/x-rst
  25. License-File: LICENSE
  26. Requires-Dist: scramp >=1.4.4
  27. Requires-Dist: python-dateutil >=2.8.2
  28. ======
  29. pg8000
  30. ======
  31. .. |ssl.SSLContext| replace:: ``ssl.SSLContext``
  32. .. _ssl.SSLContext: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
  33. .. |ssl.create_default_context()| replace:: ``ssl.create_default_context()``
  34. .. _ssl.create_default_context(): https://docs.python.org/3/library/ssl.html#ssl.create_default_context
  35. pg8000 is a pure-`Python <https://www.python.org/>`_
  36. `PostgreSQL <http://www.postgresql.org/>`_ driver that complies with
  37. `DB-API 2.0 <http://www.python.org/dev/peps/pep-0249/>`_. It is tested on Python
  38. versions 3.8+, on CPython and PyPy, and PostgreSQL versions 11+. pg8000's name comes
  39. from the belief that it is probably about the 8000th PostgreSQL interface for Python.
  40. pg8000 is distributed under the BSD 3-clause license.
  41. All bug reports, feature requests and contributions are welcome at
  42. `http://github.com/tlocke/pg8000/ <http://github.com/tlocke/pg8000/>`_.
  43. .. image:: https://github.com/tlocke/pg8000/workflows/pg8000/badge.svg
  44. :alt: Build Status
  45. .. contents:: Table of Contents
  46. :depth: 2
  47. :local:
  48. Installation
  49. ------------
  50. To install pg8000 using `pip` type:
  51. `pip install pg8000`
  52. Native API Interactive Examples
  53. -------------------------------
  54. pg8000 comes with two APIs, the native pg8000 API and the DB-API 2.0 standard
  55. API. These are the examples for the native API, and the DB-API 2.0 examples
  56. follow in the next section.
  57. Basic Example
  58. `````````````
  59. Import pg8000, connect to the database, create a table, add some rows and then
  60. query the table:
  61. >>> import pg8000.native
  62. >>>
  63. >>> # Connect to the database with user name postgres
  64. >>>
  65. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  66. >>>
  67. >>> # Create a temporary table
  68. >>>
  69. >>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
  70. >>>
  71. >>> # Populate the table
  72. >>>
  73. >>> for title in ("Ender's Game", "The Magus"):
  74. ... con.run("INSERT INTO book (title) VALUES (:title)", title=title)
  75. >>>
  76. >>> # Print all the rows in the table
  77. >>>
  78. >>> for row in con.run("SELECT * FROM book"):
  79. ... print(row)
  80. [1, "Ender's Game"]
  81. [2, 'The Magus']
  82. >>>
  83. >>> con.close()
  84. Transactions
  85. ````````````
  86. Here's how to run groups of SQL statements in a
  87. `transaction <https://www.postgresql.org/docs/current/tutorial-transactions.html>`_:
  88. >>> import pg8000.native
  89. >>>
  90. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  91. >>>
  92. >>> con.run("START TRANSACTION")
  93. >>>
  94. >>> # Create a temporary table
  95. >>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
  96. >>>
  97. >>> for title in ("Ender's Game", "The Magus", "Phineas Finn"):
  98. ... con.run("INSERT INTO book (title) VALUES (:title)", title=title)
  99. >>> con.run("COMMIT")
  100. >>> for row in con.run("SELECT * FROM book"):
  101. ... print(row)
  102. [1, "Ender's Game"]
  103. [2, 'The Magus']
  104. [3, 'Phineas Finn']
  105. >>>
  106. >>> con.close()
  107. rolling back a transaction:
  108. >>> import pg8000.native
  109. >>>
  110. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  111. >>>
  112. >>> # Create a temporary table
  113. >>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
  114. >>>
  115. >>> for title in ("Ender's Game", "The Magus", "Phineas Finn"):
  116. ... con.run("INSERT INTO book (title) VALUES (:title)", title=title)
  117. >>>
  118. >>> con.run("START TRANSACTION")
  119. >>> con.run("DELETE FROM book WHERE title = :title", title="Phineas Finn")
  120. >>> con.run("ROLLBACK")
  121. >>> for row in con.run("SELECT * FROM book"):
  122. ... print(row)
  123. [1, "Ender's Game"]
  124. [2, 'The Magus']
  125. [3, 'Phineas Finn']
  126. >>>
  127. >>> con.close()
  128. NB. There is `a longstanding bug <https://github.com/tlocke/pg8000/issues/36>`_
  129. in the PostgreSQL server whereby if a `COMMIT` is issued against a failed
  130. transaction, the transaction is silently rolled back, rather than an error being
  131. returned. pg8000 attempts to detect when this has happened and raise an
  132. `InterfaceError`.
  133. Query Using Functions
  134. `````````````````````
  135. Another query, using some PostgreSQL functions:
  136. >>> import pg8000.native
  137. >>>
  138. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  139. >>>
  140. >>> con.run("SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')")
  141. [['2021 AD']]
  142. >>>
  143. >>> con.close()
  144. Interval Type
  145. `````````````
  146. A query that returns the PostgreSQL interval type:
  147. >>> import pg8000.native
  148. >>>
  149. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  150. >>>
  151. >>> import datetime
  152. >>>
  153. >>> ts = datetime.date(1980, 4, 27)
  154. >>> con.run("SELECT timestamp '2013-12-01 16:06' - :ts", ts=ts)
  155. [[datetime.timedelta(days=12271, seconds=57960)]]
  156. >>>
  157. >>> con.close()
  158. Point Type
  159. ``````````
  160. A round-trip with a
  161. `PostgreSQL point <https://www.postgresql.org/docs/current/datatype-geometric.html>`_
  162. type:
  163. >>> import pg8000.native
  164. >>>
  165. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  166. >>>
  167. >>> con.run("SELECT CAST(:pt as point)", pt=(2.3,1))
  168. [[(2.3, 1.0)]]
  169. >>>
  170. >>> con.close()
  171. Client Encoding
  172. ```````````````
  173. When communicating with the server, pg8000 uses the character set that the server asks
  174. it to use (the client encoding). By default the client encoding is the database's
  175. character set (chosen when the database is created), but the client encoding can be
  176. changed in a number of ways (eg. setting ``CLIENT_ENCODING`` in ``postgresql.conf``).
  177. Another way of changing the client encoding is by using an SQL command. For example:
  178. >>> import pg8000.native
  179. >>>
  180. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  181. >>>
  182. >>> con.run("SET CLIENT_ENCODING TO 'UTF8'")
  183. >>> con.run("SHOW CLIENT_ENCODING")
  184. [['UTF8']]
  185. >>>
  186. >>> con.close()
  187. JSON
  188. ````
  189. `JSON <https://www.postgresql.org/docs/current/datatype-json.html>`_ always comes back
  190. from the server de-serialized. If the JSON you want to send is a ``dict`` then you can
  191. just do:
  192. >>> import pg8000.native
  193. >>>
  194. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  195. >>>
  196. >>> val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}
  197. >>> con.run("SELECT CAST(:apollo as jsonb)", apollo=val)
  198. [[{'age': 26.003, 'name': 'Apollo 11 Cave', 'zebra': True}]]
  199. >>>
  200. >>> con.close()
  201. JSON can always be sent in serialized form to the server:
  202. >>> import json
  203. >>> import pg8000.native
  204. >>>
  205. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  206. >>>
  207. >>>
  208. >>> val = ['Apollo 11 Cave', True, 26.003]
  209. >>> con.run("SELECT CAST(:apollo as jsonb)", apollo=json.dumps(val))
  210. [[['Apollo 11 Cave', True, 26.003]]]
  211. >>>
  212. >>> con.close()
  213. JSON queries can be have parameters:
  214. >>> import pg8000.native
  215. >>>
  216. >>> with pg8000.native.Connection("postgres", password="cpsnow") as con:
  217. ... con.run(""" SELECT CAST('{"a":1, "b":2}' AS jsonb) @> :v """, v={"b": 2})
  218. [[True]]
  219. Retrieve Column Metadata From Results
  220. `````````````````````````````````````
  221. Find the column metadata returned from a query:
  222. >>> import pg8000.native
  223. >>>
  224. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  225. >>>
  226. >>> con.run("create temporary table quark (id serial, name text)")
  227. >>> for name in ('Up', 'Down'):
  228. ... con.run("INSERT INTO quark (name) VALUES (:name)", name=name)
  229. >>> # Now execute the query
  230. >>>
  231. >>> con.run("SELECT * FROM quark")
  232. [[1, 'Up'], [2, 'Down']]
  233. >>>
  234. >>> # and retrieve the metadata
  235. >>>
  236. >>> con.columns
  237. [{'table_oid': ..., 'column_attrnum': 1, 'type_oid': 23, 'type_size': 4, 'type_modifier': -1, 'format': 0, 'name': 'id'}, {'table_oid': ..., 'column_attrnum': 2, 'type_oid': 25, 'type_size': -1, 'type_modifier': -1, 'format': 0, 'name': 'name'}]
  238. >>>
  239. >>> # Show just the column names
  240. >>>
  241. >>> [c['name'] for c in con.columns]
  242. ['id', 'name']
  243. >>>
  244. >>> con.close()
  245. Notices And Notifications
  246. `````````````````````````
  247. PostgreSQL `notices
  248. <https://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html>`_ are
  249. stored in a deque called ``Connection.notices`` and added using the ``append()``
  250. method. Similarly there are ``Connection.notifications`` for `notifications
  251. <https://www.postgresql.org/docs/current/static/sql-notify.html>`_ and
  252. ``Connection.parameter_statuses`` for changes to the server configuration. Here's an
  253. example:
  254. >>> import pg8000.native
  255. >>>
  256. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  257. >>>
  258. >>> con.run("LISTEN aliens_landed")
  259. >>> con.run("NOTIFY aliens_landed")
  260. >>> # A notification is a tuple containing (backend_pid, channel, payload)
  261. >>>
  262. >>> con.notifications[0]
  263. (..., 'aliens_landed', '')
  264. >>>
  265. >>> con.close()
  266. LIMIT ALL
  267. `````````
  268. You might think that the following would work, but in fact it fails:
  269. >>> import pg8000.native
  270. >>>
  271. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  272. >>>
  273. >>> con.run("SELECT 'silo 1' LIMIT :lim", lim='ALL')
  274. Traceback (most recent call last):
  275. pg8000.exceptions.DatabaseError: ...
  276. >>>
  277. >>> con.close()
  278. Instead the `docs say <https://www.postgresql.org/docs/current/sql-select.html>`_ that
  279. you can send ``null`` as an alternative to ``ALL``, which does work:
  280. >>> import pg8000.native
  281. >>>
  282. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  283. >>>
  284. >>> con.run("SELECT 'silo 1' LIMIT :lim", lim=None)
  285. [['silo 1']]
  286. >>>
  287. >>> con.close()
  288. IN and NOT IN
  289. `````````````
  290. You might think that the following would work, but in fact the server doesn't like it:
  291. >>> import pg8000.native
  292. >>>
  293. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  294. >>>
  295. >>> con.run("SELECT 'silo 1' WHERE 'a' IN :v", v=['a', 'b'])
  296. Traceback (most recent call last):
  297. pg8000.exceptions.DatabaseError: ...
  298. >>>
  299. >>> con.close()
  300. instead you can write it using the `unnest
  301. <https://www.postgresql.org/docs/current/functions-array.html>`_ function:
  302. >>> import pg8000.native
  303. >>>
  304. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  305. >>>
  306. >>> con.run(
  307. ... "SELECT 'silo 1' WHERE 'a' IN (SELECT unnest(CAST(:v as varchar[])))",
  308. ... v=['a', 'b'])
  309. [['silo 1']]
  310. >>> con.close()
  311. and you can do the same for ``NOT IN``.
  312. Many SQL Statements Can't Be Parameterized
  313. ``````````````````````````````````````````
  314. In PostgreSQL parameters can only be used for `data values, not identifiers
  315. <https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS>`_.
  316. Sometimes this might not work as expected, for example the following fails:
  317. >>> import pg8000.native
  318. >>>
  319. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  320. >>>
  321. >>> channel = 'top_secret'
  322. >>>
  323. >>> con.run("LISTEN :channel", channel=channel)
  324. Traceback (most recent call last):
  325. pg8000.exceptions.DatabaseError: ...
  326. >>>
  327. >>> con.close()
  328. It fails because the PostgreSQL server doesn't allow this statement to have any
  329. parameters. There are many SQL statements that one might think would have parameters,
  330. but don't. For these cases the SQL has to be created manually, being careful to use the
  331. ``identifier()`` and ``literal()`` functions to escape the values to avoid `SQL
  332. injection attacks <https://en.wikipedia.org/wiki/SQL_injection>`_:
  333. >>> from pg8000.native import Connection, identifier, literal
  334. >>>
  335. >>> con = Connection("postgres", password="cpsnow")
  336. >>>
  337. >>> channel = 'top_secret'
  338. >>> payload = 'Aliens Landed!'
  339. >>> con.run(f"LISTEN {identifier(channel)}")
  340. >>> con.run(f"NOTIFY {identifier(channel)}, {literal(payload)}")
  341. >>>
  342. >>> con.notifications[0]
  343. (..., 'top_secret', 'Aliens Landed!')
  344. >>>
  345. >>> con.close()
  346. COPY FROM And TO A Stream
  347. `````````````````````````
  348. The SQL `COPY <https://www.postgresql.org/docs/current/sql-copy.html>`_ statement can be
  349. used to copy from and to a file or file-like object. Here' an example using the CSV
  350. format:
  351. >>> import pg8000.native
  352. >>> from io import StringIO
  353. >>> import csv
  354. >>>
  355. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  356. >>>
  357. >>> # Create a CSV file in memory
  358. >>>
  359. >>> stream_in = StringIO()
  360. >>> csv_writer = csv.writer(stream_in)
  361. >>> csv_writer.writerow([1, "electron"])
  362. 12
  363. >>> csv_writer.writerow([2, "muon"])
  364. 8
  365. >>> csv_writer.writerow([3, "tau"])
  366. 7
  367. >>> stream_in.seek(0)
  368. 0
  369. >>>
  370. >>> # Create a table and then copy the CSV into it
  371. >>>
  372. >>> con.run("CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)")
  373. >>> con.run("COPY lepton FROM STDIN WITH (FORMAT CSV)", stream=stream_in)
  374. >>>
  375. >>> # COPY from a table to a stream
  376. >>>
  377. >>> stream_out = StringIO()
  378. >>> con.run("COPY lepton TO STDOUT WITH (FORMAT CSV)", stream=stream_out)
  379. >>> stream_out.seek(0)
  380. 0
  381. >>> for row in csv.reader(stream_out):
  382. ... print(row)
  383. ['1', 'electron']
  384. ['2', 'muon']
  385. ['3', 'tau']
  386. >>>
  387. >>> con.close()
  388. It's also possible to COPY FROM an iterable, which is useful if you're creating rows
  389. programmatically:
  390. >>> import pg8000.native
  391. >>>
  392. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  393. >>>
  394. >>> # Generator function for creating rows
  395. >>> def row_gen():
  396. ... for i, name in ((1, "electron"), (2, "muon"), (3, "tau")):
  397. ... yield f"{i},{name}\n"
  398. >>>
  399. >>> # Create a table and then copy the CSV into it
  400. >>>
  401. >>> con.run("CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)")
  402. >>> con.run("COPY lepton FROM STDIN WITH (FORMAT CSV)", stream=row_gen())
  403. >>>
  404. >>> # COPY from a table to a stream
  405. >>>
  406. >>> stream_out = StringIO()
  407. >>> con.run("COPY lepton TO STDOUT WITH (FORMAT CSV)", stream=stream_out)
  408. >>> stream_out.seek(0)
  409. 0
  410. >>> for row in csv.reader(stream_out):
  411. ... print(row)
  412. ['1', 'electron']
  413. ['2', 'muon']
  414. ['3', 'tau']
  415. >>>
  416. >>> con.close()
  417. Execute Multiple SQL Statements
  418. ```````````````````````````````
  419. If you want to execute a series of SQL statements (eg. an ``.sql`` file), you can run
  420. them as expected:
  421. >>> import pg8000.native
  422. >>>
  423. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  424. >>>
  425. >>> statements = "SELECT 5; SELECT 'Erich Fromm';"
  426. >>>
  427. >>> con.run(statements)
  428. [[5], ['Erich Fromm']]
  429. >>>
  430. >>> con.close()
  431. The only caveat is that when executing multiple statements you can't have any
  432. parameters.
  433. Quoted Identifiers in SQL
  434. `````````````````````````
  435. Say you had a column called ``My Column``. Since it's case sensitive and contains a
  436. space, you'd have to `surround it by double quotes
  437. <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIER>`_.
  438. But you can't do:
  439. >>> import pg8000.native
  440. >>>
  441. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  442. >>>
  443. >>> con.run("select 'hello' as "My Column"")
  444. Traceback (most recent call last):
  445. SyntaxError: invalid syntax...
  446. >>>
  447. >>> con.close()
  448. since Python uses double quotes to delimit string literals, so one solution is
  449. to use Python's `triple quotes
  450. <https://docs.python.org/3/tutorial/introduction.html#strings>`_ to delimit the string
  451. instead:
  452. >>> import pg8000.native
  453. >>>
  454. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  455. >>>
  456. >>> con.run('''SELECT 'hello' AS "My Column"''')
  457. [['hello']]
  458. >>>
  459. >>> con.close()
  460. another solution, that's especially useful if the identifier comes from an untrusted
  461. source, is to use the ``identifier()`` function, which correctly quotes and escapes the
  462. identifier as needed:
  463. >>> from pg8000.native import Connection, identifier
  464. >>>
  465. >>> con = Connection("postgres", password="cpsnow")
  466. >>>
  467. >>> sql = f"SELECT 'hello' as {identifier('My Column')}"
  468. >>> print(sql)
  469. SELECT 'hello' as "My Column"
  470. >>>
  471. >>> con.run(sql)
  472. [['hello']]
  473. >>>
  474. >>> con.close()
  475. this approach guards against `SQL injection attacks
  476. <https://en.wikipedia.org/wiki/SQL_injection>`_. One thing to note if you're using
  477. explicit schemas (eg. ``pg_catalog.pg_language``) is that the schema name and table name
  478. are both separate identifiers. So to escape them you'd do:
  479. >>> from pg8000.native import Connection, identifier
  480. >>>
  481. >>> con = Connection("postgres", password="cpsnow")
  482. >>>
  483. >>> query = (
  484. ... f"SELECT lanname FROM {identifier('pg_catalog')}.{identifier('pg_language')} "
  485. ... f"WHERE lanname = 'sql'"
  486. ... )
  487. >>> print(query)
  488. SELECT lanname FROM pg_catalog.pg_language WHERE lanname = 'sql'
  489. >>>
  490. >>> con.run(query)
  491. [['sql']]
  492. >>>
  493. >>> con.close()
  494. Custom adapter from a Python type to a PostgreSQL type
  495. ``````````````````````````````````````````````````````
  496. pg8000 has a mapping from Python types to PostgreSQL types for when it needs to send
  497. SQL parameters to the server. The default mapping that comes with pg8000 is designed to
  498. work well in most cases, but you might want to add or replace the default mapping.
  499. A Python ``datetime.timedelta`` object is sent to the server as a PostgreSQL
  500. ``interval`` type, which has the ``oid`` 1186. But let's say we wanted to create our
  501. own Python class to be sent as an ``interval`` type. Then we'd have to register an
  502. adapter:
  503. >>> import pg8000.native
  504. >>>
  505. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  506. >>>
  507. >>> class MyInterval(str):
  508. ... pass
  509. >>>
  510. >>> def my_interval_out(my_interval):
  511. ... return my_interval # Must return a str
  512. >>>
  513. >>> con.register_out_adapter(MyInterval, my_interval_out)
  514. >>> con.run("SELECT CAST(:interval as interval)", interval=MyInterval("2 hours"))
  515. [[datetime.timedelta(seconds=7200)]]
  516. >>>
  517. >>> con.close()
  518. Note that it still came back as a ``datetime.timedelta`` object because we only changed
  519. the mapping from Python to PostgreSQL. See below for an example of how to change the
  520. mapping from PostgreSQL to Python.
  521. Custom adapter from a PostgreSQL type to a Python type
  522. ``````````````````````````````````````````````````````
  523. pg8000 has a mapping from PostgreSQL types to Python types for when it receives SQL
  524. results from the server. The default mapping that comes with pg8000 is designed to work
  525. well in most cases, but you might want to add or replace the default mapping.
  526. If pg8000 receives PostgreSQL ``interval`` type, which has the ``oid`` 1186, it converts
  527. it into a Python ``datetime.timedelta`` object. But let's say we wanted to create our
  528. own Python class to be used instead of ``datetime.timedelta``. Then we'd have to
  529. register an adapter:
  530. >>> import pg8000.native
  531. >>>
  532. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  533. >>>
  534. >>> class MyInterval(str):
  535. ... pass
  536. >>>
  537. >>> def my_interval_in(my_interval_str): # The parameter is of type str
  538. ... return MyInterval(my_interval)
  539. >>>
  540. >>> con.register_in_adapter(1186, my_interval_in)
  541. >>> con.run("SELECT \'2 years'")
  542. [['2 years']]
  543. >>>
  544. >>> con.close()
  545. Note that registering the 'in' adapter only afects the mapping from the PostgreSQL type
  546. to the Python type. See above for an example of how to change the mapping from
  547. PostgreSQL to Python.
  548. Could Not Determine Data Type Of Parameter
  549. ``````````````````````````````````````````
  550. Sometimes you'll get the 'could not determine data type of parameter' error message from
  551. the server:
  552. >>> import pg8000.native
  553. >>>
  554. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  555. >>>
  556. >>> con.run("SELECT :v IS NULL", v=None)
  557. Traceback (most recent call last):
  558. pg8000.exceptions.DatabaseError: {'S': 'ERROR', 'V': 'ERROR', 'C': '42P18', 'M': 'could not determine data type of parameter $1', 'F': 'postgres.c', 'L': '...', 'R': 'exec_parse_message'}
  559. >>>
  560. >>> con.close()
  561. One way of solving it is to put a ``CAST`` in the SQL:
  562. >>> import pg8000.native
  563. >>>
  564. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  565. >>>
  566. >>> con.run("SELECT cast(:v as TIMESTAMP) IS NULL", v=None)
  567. [[True]]
  568. >>>
  569. >>> con.close()
  570. Another way is to override the type that pg8000 sends along with each parameter:
  571. >>> import pg8000.native
  572. >>>
  573. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  574. >>>
  575. >>> con.run("SELECT :v IS NULL", v=None, types={'v': pg8000.native.TIMESTAMP})
  576. [[True]]
  577. >>>
  578. >>> con.close()
  579. Prepared Statements
  580. ```````````````````
  581. `Prepared statements <https://www.postgresql.org/docs/current/sql-prepare.html>`_
  582. can be useful in improving performance when you have a statement that's executed
  583. repeatedly. Here's an example:
  584. >>> import pg8000.native
  585. >>>
  586. >>> con = pg8000.native.Connection("postgres", password="cpsnow")
  587. >>>
  588. >>> # Create the prepared statement
  589. >>> ps = con.prepare("SELECT cast(:v as varchar)")
  590. >>>
  591. >>> # Execute the statement repeatedly
  592. >>> ps.run(v="speedy")
  593. [['speedy']]
  594. >>> ps.run(v="rapid")
  595. [['rapid']]
  596. >>> ps.run(v="swift")
  597. [['swift']]
  598. >>>
  599. >>> # Close the prepared statement, releasing resources on the server
  600. >>> ps.close()
  601. >>>
  602. >>> con.close()
  603. Use Environment Variables As Connection Defaults
  604. ````````````````````````````````````````````````
  605. You might want to use the current user as the database username for example:
  606. >>> import pg8000.native
  607. >>> import getpass
  608. >>>
  609. >>> # Connect to the database with current user name
  610. >>> username = getpass.getuser()
  611. >>> connection = pg8000.native.Connection(username, password="cpsnow")
  612. >>>
  613. >>> connection.run("SELECT 'pilau'")
  614. [['pilau']]
  615. >>>
  616. >>> connection.close()
  617. or perhaps you may want to use some of the same `environment variables that libpg uses
  618. <https://www.postgresql.org/docs/current/libpq-envars.html>`_:
  619. >>> import pg8000.native
  620. >>> from os import environ
  621. >>>
  622. >>> username = environ.get('PGUSER', 'postgres')
  623. >>> password = environ.get('PGPASSWORD', 'cpsnow')
  624. >>> host = environ.get('PGHOST', 'localhost')
  625. >>> port = environ.get('PGPORT', '5432')
  626. >>> database = environ.get('PGDATABASE')
  627. >>>
  628. >>> connection = pg8000.native.Connection(
  629. ... username, password=password, host=host, port=port, database=database)
  630. >>>
  631. >>> connection.run("SELECT 'Mr Cairo'")
  632. [['Mr Cairo']]
  633. >>>
  634. >>> connection.close()
  635. It might be asked, why doesn't pg8000 have this behaviour built in? The thinking
  636. follows the second aphorism of `The Zen of Python
  637. <https://www.python.org/dev/peps/pep-0020/>`_:
  638. Explicit is better than implicit.
  639. So we've taken the approach of only being able to set connection parameters using the
  640. ``pg8000.native.Connection()`` constructor.
  641. Connect To PostgreSQL Over SSL
  642. ``````````````````````````````
  643. To connect to the server using SSL defaults do::
  644. import pg8000.native
  645. connection = pg8000.native.Connection('postgres', password="cpsnow", ssl_context=True)
  646. connection.run("SELECT 'The game is afoot!'")
  647. To connect over SSL with custom settings, set the ``ssl_context`` parameter to an
  648. |ssl.SSLContext|_ object:
  649. ::
  650. import pg8000.native
  651. import ssl
  652. ssl_context = ssl.create_default_context()
  653. ssl_context.verify_mode = ssl.CERT_REQUIRED
  654. ssl_context.load_verify_locations('root.pem')
  655. connection = pg8000.native.Connection(
  656. 'postgres', password="cpsnow", ssl_context=ssl_context)
  657. It may be that your PostgreSQL server is behind an SSL proxy server in which case you
  658. can set a pg8000-specific attribute ``ssl.SSLContext.request_ssl = False`` which tells
  659. pg8000 to connect using an SSL socket, but not to request SSL from the PostgreSQL
  660. server:
  661. ::
  662. import pg8000.native
  663. import ssl
  664. ssl_context = ssl.create_default_context()
  665. ssl_context.request_ssl = False
  666. connection = pg8000.native.Connection(
  667. 'postgres', password="cpsnow", ssl_context=ssl_context)
  668. Server-Side Cursors
  669. ```````````````````
  670. You can use the SQL commands `DECLARE
  671. <https://www.postgresql.org/docs/current/sql-declare.html>`_,
  672. `FETCH <https://www.postgresql.org/docs/current/sql-fetch.html>`_,
  673. `MOVE <https://www.postgresql.org/docs/current/sql-move.html>`_ and
  674. `CLOSE <https://www.postgresql.org/docs/current/sql-close.html>`_ to manipulate
  675. server-side cursors. For example:
  676. >>> import pg8000.native
  677. >>>
  678. >>> con = pg8000.native.Connection('postgres', password="cpsnow")
  679. >>> con.run("START TRANSACTION")
  680. >>> con.run("DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)")
  681. >>> con.run("FETCH FORWARD 5 FROM c")
  682. [[1], [2], [3], [4], [5]]
  683. >>> con.run("MOVE FORWARD 50 FROM c")
  684. >>> con.run("FETCH BACKWARD 10 FROM c")
  685. [[54], [53], [52], [51], [50], [49], [48], [47], [46], [45]]
  686. >>> con.run("CLOSE c")
  687. >>> con.run("ROLLBACK")
  688. >>>
  689. >>> con.close()
  690. BLOBs (Binary Large Objects)
  691. ````````````````````````````
  692. There's a set of `SQL functions
  693. <https://www.postgresql.org/docs/current/lo-funcs.html>`_ for manipulating BLOBs.
  694. Here's an example:
  695. >>> import pg8000.native
  696. >>>
  697. >>> con = pg8000.native.Connection('postgres', password="cpsnow")
  698. >>>
  699. >>> # Create a BLOB and get its oid
  700. >>> data = b'hello'
  701. >>> res = con.run("SELECT lo_from_bytea(0, :data)", data=data)
  702. >>> oid = res[0][0]
  703. >>>
  704. >>> # Create a table and store the oid of the BLOB
  705. >>> con.run("CREATE TEMPORARY TABLE image (raster oid)")
  706. >>>
  707. >>> con.run("INSERT INTO image (raster) VALUES (:oid)", oid=oid)
  708. >>> # Retrieve the data using the oid
  709. >>> con.run("SELECT lo_get(:oid)", oid=oid)
  710. [[b'hello']]
  711. >>>
  712. >>> # Add some data to the end of the BLOB
  713. >>> more_data = b' all'
  714. >>> offset = len(data)
  715. >>> con.run(
  716. ... "SELECT lo_put(:oid, :offset, :data)",
  717. ... oid=oid, offset=offset, data=more_data)
  718. [['']]
  719. >>> con.run("SELECT lo_get(:oid)", oid=oid)
  720. [[b'hello all']]
  721. >>>
  722. >>> # Download a part of the data
  723. >>> con.run("SELECT lo_get(:oid, 6, 3)", oid=oid)
  724. [[b'all']]
  725. >>>
  726. >>> con.close()
  727. Replication Protocol
  728. ````````````````````
  729. The PostgreSQL `Replication Protocol
  730. <https://www.postgresql.org/docs/current/protocol-replication.html>`_ is supported using
  731. the ``replication`` keyword when creating a connection:
  732. >>> import pg8000.native
  733. >>>
  734. >>> con = pg8000.native.Connection(
  735. ... 'postgres', password="cpsnow", replication="database")
  736. >>>
  737. >>> con.run("IDENTIFY_SYSTEM")
  738. [['...', 1, '0/...', 'postgres']]
  739. >>>
  740. >>> con.close()
  741. DB-API 2 Interactive Examples
  742. -----------------------------
  743. These examples stick to the DB-API 2.0 standard.
  744. Basic Example
  745. `````````````
  746. Import pg8000, connect to the database, create a table, add some rows and then query the
  747. table:
  748. >>> import pg8000.dbapi
  749. >>>
  750. >>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  751. >>> cursor = conn.cursor()
  752. >>> cursor.execute("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
  753. >>> cursor.execute(
  754. ... "INSERT INTO book (title) VALUES (%s), (%s) RETURNING id, title",
  755. ... ("Ender's Game", "Speaker for the Dead"))
  756. >>> results = cursor.fetchall()
  757. >>> for row in results:
  758. ... id, title = row
  759. ... print("id = %s, title = %s" % (id, title))
  760. id = 1, title = Ender's Game
  761. id = 2, title = Speaker for the Dead
  762. >>> conn.commit()
  763. >>>
  764. >>> conn.close()
  765. Query Using Functions
  766. `````````````````````
  767. Another query, using some PostgreSQL functions:
  768. >>> import pg8000.dbapi
  769. >>>
  770. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  771. >>> cursor = con.cursor()
  772. >>>
  773. >>> cursor.execute("SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')")
  774. >>> cursor.fetchone()
  775. ['2021 AD']
  776. >>>
  777. >>> con.close()
  778. Interval Type
  779. `````````````
  780. A query that returns the PostgreSQL interval type:
  781. >>> import datetime
  782. >>> import pg8000.dbapi
  783. >>>
  784. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  785. >>> cursor = con.cursor()
  786. >>>
  787. >>> cursor.execute("SELECT timestamp '2013-12-01 16:06' - %s",
  788. ... (datetime.date(1980, 4, 27),))
  789. >>> cursor.fetchone()
  790. [datetime.timedelta(days=12271, seconds=57960)]
  791. >>>
  792. >>> con.close()
  793. Point Type
  794. ``````````
  795. A round-trip with a `PostgreSQL point
  796. <https://www.postgresql.org/docs/current/datatype-geometric.html>`_ type:
  797. >>> import pg8000.dbapi
  798. >>>
  799. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  800. >>> cursor = con.cursor()
  801. >>>
  802. >>> cursor.execute("SELECT cast(%s as point)", ((2.3,1),))
  803. >>> cursor.fetchone()
  804. [(2.3, 1.0)]
  805. >>>
  806. >>> con.close()
  807. Numeric Parameter Style
  808. ```````````````````````
  809. pg8000 supports all the DB-API parameter styles. Here's an example of using the
  810. 'numeric' parameter style:
  811. >>> import pg8000.dbapi
  812. >>>
  813. >>> pg8000.dbapi.paramstyle = "numeric"
  814. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  815. >>> cursor = con.cursor()
  816. >>>
  817. >>> cursor.execute("SELECT array_prepend(:1, CAST(:2 AS int[]))", (500, [1, 2, 3, 4],))
  818. >>> cursor.fetchone()
  819. [[500, 1, 2, 3, 4]]
  820. >>> pg8000.dbapi.paramstyle = "format"
  821. >>>
  822. >>> con.close()
  823. Autocommit
  824. ``````````
  825. Following the DB-API specification, autocommit is off by default. It can be turned on by
  826. using the autocommit property of the connection:
  827. >>> import pg8000.dbapi
  828. >>>
  829. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  830. >>> con.autocommit = True
  831. >>>
  832. >>> cur = con.cursor()
  833. >>> cur.execute("vacuum")
  834. >>> conn.autocommit = False
  835. >>> cur.close()
  836. >>>
  837. >>> con.close()
  838. Client Encoding
  839. ```````````````
  840. When communicating with the server, pg8000 uses the character set that the server asks
  841. it to use (the client encoding). By default the client encoding is the database's
  842. character set (chosen when the database is created), but the client encoding can be
  843. changed in a number of ways (eg. setting ``CLIENT_ENCODING`` in ``postgresql.conf``).
  844. Another way of changing the client encoding is by using an SQL command. For example:
  845. >>> import pg8000.dbapi
  846. >>>
  847. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  848. >>> cur = con.cursor()
  849. >>> cur.execute("SET CLIENT_ENCODING TO 'UTF8'")
  850. >>> cur.execute("SHOW CLIENT_ENCODING")
  851. >>> cur.fetchone()
  852. ['UTF8']
  853. >>> cur.close()
  854. >>>
  855. >>> con.close()
  856. JSON
  857. ````
  858. JSON is sent to the server serialized, and returned de-serialized. Here's an example:
  859. >>> import json
  860. >>> import pg8000.dbapi
  861. >>>
  862. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  863. >>> cur = con.cursor()
  864. >>> val = ['Apollo 11 Cave', True, 26.003]
  865. >>> cur.execute("SELECT cast(%s as json)", (json.dumps(val),))
  866. >>> cur.fetchone()
  867. [['Apollo 11 Cave', True, 26.003]]
  868. >>> cur.close()
  869. >>>
  870. >>> con.close()
  871. JSON queries can be have parameters:
  872. >>> import pg8000.dbapi
  873. >>>
  874. >>> with pg8000.dbapi.connect("postgres", password="cpsnow") as con:
  875. ... cur = con.cursor()
  876. ... cur.execute(""" SELECT CAST('{"a":1, "b":2}' AS jsonb) @> %s """, ({"b": 2},))
  877. ... for row in cur.fetchall():
  878. ... print(row)
  879. [True]
  880. Retrieve Column Names From Results
  881. ``````````````````````````````````
  882. Use the columns names retrieved from a query:
  883. >>> import pg8000
  884. >>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  885. >>> c = conn.cursor()
  886. >>> c.execute("create temporary table quark (id serial, name text)")
  887. >>> c.executemany("INSERT INTO quark (name) VALUES (%s)", (("Up",), ("Down",)))
  888. >>> #
  889. >>> # Now retrieve the results
  890. >>> #
  891. >>> c.execute("select * from quark")
  892. >>> rows = c.fetchall()
  893. >>> keys = [k[0] for k in c.description]
  894. >>> results = [dict(zip(keys, row)) for row in rows]
  895. >>> assert results == [{'id': 1, 'name': 'Up'}, {'id': 2, 'name': 'Down'}]
  896. >>>
  897. >>> conn.close()
  898. COPY from and to a file
  899. ```````````````````````
  900. The SQL `COPY <https://www.postgresql.org/docs/current/sql-copy.html>`__ statement can
  901. be used to copy from and to a file or file-like object:
  902. >>> from io import StringIO
  903. >>> import pg8000.dbapi
  904. >>>
  905. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  906. >>> cur = con.cursor()
  907. >>> #
  908. >>> # COPY from a stream to a table
  909. >>> #
  910. >>> stream_in = StringIO('1\telectron\n2\tmuon\n3\ttau\n')
  911. >>> cur = con.cursor()
  912. >>> cur.execute("create temporary table lepton (id serial, name text)")
  913. >>> cur.execute("COPY lepton FROM stdin", stream=stream_in)
  914. >>> #
  915. >>> # Now COPY from a table to a stream
  916. >>> #
  917. >>> stream_out = StringIO()
  918. >>> cur.execute("copy lepton to stdout", stream=stream_out)
  919. >>> stream_out.getvalue()
  920. '1\telectron\n2\tmuon\n3\ttau\n'
  921. >>>
  922. >>> con.close()
  923. Server-Side Cursors
  924. ```````````````````
  925. You can use the SQL commands `DECLARE
  926. <https://www.postgresql.org/docs/current/sql-declare.html>`_,
  927. `FETCH <https://www.postgresql.org/docs/current/sql-fetch.html>`_,
  928. `MOVE <https://www.postgresql.org/docs/current/sql-move.html>`_ and
  929. `CLOSE <https://www.postgresql.org/docs/current/sql-close.html>`_ to manipulate
  930. server-side cursors. For example:
  931. >>> import pg8000.dbapi
  932. >>>
  933. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  934. >>> cur = con.cursor()
  935. >>> cur.execute("START TRANSACTION")
  936. >>> cur.execute(
  937. ... "DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)")
  938. >>> cur.execute("FETCH FORWARD 5 FROM c")
  939. >>> cur.fetchall()
  940. ([1], [2], [3], [4], [5])
  941. >>> cur.execute("MOVE FORWARD 50 FROM c")
  942. >>> cur.execute("FETCH BACKWARD 10 FROM c")
  943. >>> cur.fetchall()
  944. ([54], [53], [52], [51], [50], [49], [48], [47], [46], [45])
  945. >>> cur.execute("CLOSE c")
  946. >>> cur.execute("ROLLBACK")
  947. >>>
  948. >>> con.close()
  949. BLOBs (Binary Large Objects)
  950. ````````````````````````````
  951. There's a set of `SQL functions
  952. <https://www.postgresql.org/docs/current/lo-funcs.html>`_ for manipulating BLOBs.
  953. Here's an example:
  954. >>> import pg8000.dbapi
  955. >>>
  956. >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
  957. >>> cur = con.cursor()
  958. >>>
  959. >>> # Create a BLOB and get its oid
  960. >>> data = b'hello'
  961. >>> cur = con.cursor()
  962. >>> cur.execute("SELECT lo_from_bytea(0, %s)", [data])
  963. >>> oid = cur.fetchone()[0]
  964. >>>
  965. >>> # Create a table and store the oid of the BLOB
  966. >>> cur.execute("CREATE TEMPORARY TABLE image (raster oid)")
  967. >>> cur.execute("INSERT INTO image (raster) VALUES (%s)", [oid])
  968. >>>
  969. >>> # Retrieve the data using the oid
  970. >>> cur.execute("SELECT lo_get(%s)", [oid])
  971. >>> cur.fetchall()
  972. ([b'hello'],)
  973. >>>
  974. >>> # Add some data to the end of the BLOB
  975. >>> more_data = b' all'
  976. >>> offset = len(data)
  977. >>> cur.execute("SELECT lo_put(%s, %s, %s)", [oid, offset, more_data])
  978. >>> cur.execute("SELECT lo_get(%s)", [oid])
  979. >>> cur.fetchall()
  980. ([b'hello all'],)
  981. >>>
  982. >>> # Download a part of the data
  983. >>> cur.execute("SELECT lo_get(%s, 6, 3)", [oid])
  984. >>> cur.fetchall()
  985. ([b'all'],)
  986. >>>
  987. >>> con.close()
  988. Type Mapping
  989. ------------
  990. The following table shows the default mapping between Python types and PostgreSQL types,
  991. and vice versa.
  992. If pg8000 doesn't recognize a type that it receives from PostgreSQL, it will return it
  993. as a ``str`` type. This is how pg8000 handles PostgreSQL ``enum`` and XML types. It's
  994. possible to change the default mapping using adapters (see the examples).
  995. .. table:: Python to PostgreSQL Type Mapping
  996. +-----------------------+-----------------+-----------------------------------------+
  997. | Python Type | PostgreSQL Type | Notes |
  998. +=======================+=================+=========================================+
  999. | bool | bool | |
  1000. +-----------------------+-----------------+-----------------------------------------+
  1001. | int | int4 | |
  1002. +-----------------------+-----------------+-----------------------------------------+
  1003. | str | text | |
  1004. +-----------------------+-----------------+-----------------------------------------+
  1005. | float | float8 | |
  1006. +-----------------------+-----------------+-----------------------------------------+
  1007. | decimal.Decimal | numeric | |
  1008. +-----------------------+-----------------+-----------------------------------------+
  1009. | bytes | bytea | |
  1010. +-----------------------+-----------------+-----------------------------------------+
  1011. | datetime.datetime | timestamp | +/-infinity PostgreSQL values are |
  1012. | (without tzinfo) | without | represented as Python ``str`` values. |
  1013. | | timezone | If a ``timestamp`` is too big for |
  1014. | | | ``datetime.datetime`` then a ``str`` is |
  1015. | | | used. |
  1016. +-----------------------+-----------------+-----------------------------------------+
  1017. | datetime.datetime | timestamp with | +/-infinity PostgreSQL values are |
  1018. | (with tzinfo) | timezone | represented as Python ``str`` values. |
  1019. | | | If a ``timestamptz`` is too big for |
  1020. | | | ``datetime.datetime`` then a ``str`` is |
  1021. | | | used. |
  1022. +-----------------------+-----------------+-----------------------------------------+
  1023. | datetime.date | date | +/-infinity PostgreSQL values are |
  1024. | | | represented as Python ``str`` values. |
  1025. | | | If a ``date`` is too big for a |
  1026. | | | ``datetime.date`` then a ``str`` is |
  1027. | | | used. |
  1028. +-----------------------+-----------------+-----------------------------------------+
  1029. | datetime.time | time without | |
  1030. | | time zone | |
  1031. +-----------------------+-----------------+-----------------------------------------+
  1032. | datetime.timedelta | interval | If an ``interval`` is too big for |
  1033. | | | ``datetime.timedelta`` then a |
  1034. | | | ``PGInterval`` is used. |
  1035. +-----------------------+-----------------+-----------------------------------------+
  1036. | None | NULL | |
  1037. +-----------------------+-----------------+-----------------------------------------+
  1038. | uuid.UUID | uuid | |
  1039. +-----------------------+-----------------+-----------------------------------------+
  1040. | ipaddress.IPv4Address | inet | |
  1041. +-----------------------+-----------------+-----------------------------------------+
  1042. | ipaddress.IPv6Address | inet | |
  1043. +-----------------------+-----------------+-----------------------------------------+
  1044. | ipaddress.IPv4Network | inet | |
  1045. +-----------------------+-----------------+-----------------------------------------+
  1046. | ipaddress.IPv6Network | inet | |
  1047. +-----------------------+-----------------+-----------------------------------------+
  1048. | int | xid | |
  1049. +-----------------------+-----------------+-----------------------------------------+
  1050. | list of int | INT4[] | |
  1051. +-----------------------+-----------------+-----------------------------------------+
  1052. | list of float | FLOAT8[] | |
  1053. +-----------------------+-----------------+-----------------------------------------+
  1054. | list of bool | BOOL[] | |
  1055. +-----------------------+-----------------+-----------------------------------------+
  1056. | list of str | TEXT[] | |
  1057. +-----------------------+-----------------+-----------------------------------------+
  1058. | int | int2vector | Only from PostgreSQL to Python |
  1059. +-----------------------+-----------------+-----------------------------------------+
  1060. | JSON | json, jsonb | The Python JSON is provided as a Python |
  1061. | | | serialized string. Results returned as |
  1062. | | | de-serialized JSON. |
  1063. +-----------------------+-----------------+-----------------------------------------+
  1064. | pg8000.Range | \*range | PostgreSQL multirange types are |
  1065. | | | represented in Python as a list of |
  1066. | | | range types. |
  1067. +-----------------------+-----------------+-----------------------------------------+
  1068. | tuple | composite type | Only from Python to PostgreSQL |
  1069. +-----------------------+-----------------+-----------------------------------------+
  1070. Theory Of Operation
  1071. -------------------
  1072. A concept is tolerated inside the microkernel only if moving it outside the kernel,
  1073. i.e., permitting competing implementations, would prevent the implementation of the
  1074. system's required functionality.
  1075. -- Jochen Liedtke, Liedtke's minimality principle
  1076. pg8000 is designed to be used with one thread per connection.
  1077. Pg8000 communicates with the database using the `PostgreSQL Frontend/Backend Protocol
  1078. <https://www.postgresql.org/docs/current/protocol.html>`_ (FEBE). If a query has no
  1079. parameters, pg8000 uses the 'simple query protocol'. If a query does have parameters,
  1080. pg8000 uses the 'extended query protocol' with unnamed prepared statements. The steps
  1081. for a query with parameters are:
  1082. 1. Query comes in.
  1083. #. Send a PARSE message to the server to create an unnamed prepared statement.
  1084. #. Send a BIND message to run against the unnamed prepared statement, resulting in an
  1085. unnamed portal on the server.
  1086. #. Send an EXECUTE message to read all the results from the portal.
  1087. It's also possible to use named prepared statements. In which case the prepared
  1088. statement persists on the server, and represented in pg8000 using a
  1089. ``PreparedStatement`` object. This means that the PARSE step gets executed once up
  1090. front, and then only the BIND and EXECUTE steps are repeated subsequently.
  1091. There are a lot of PostgreSQL data types, but few primitive data types in Python. By
  1092. default, pg8000 doesn't send PostgreSQL data type information in the PARSE step, in
  1093. which case PostgreSQL assumes the types implied by the SQL statement. In some cases
  1094. PostgreSQL can't work out a parameter type and so an `explicit cast
  1095. <https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS>`_
  1096. can be used in the SQL.
  1097. In the FEBE protocol, each query parameter can be sent to the server either as binary
  1098. or text according to the format code. In pg8000 the parameters are always sent as text.
  1099. Occasionally, the network connection between pg8000 and the server may go down. If
  1100. pg8000 encounters a network problem it'll raise an ``InterfaceError`` with the message
  1101. ``network error`` and with the original exception set as the `cause
  1102. <https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement>`_.
  1103. Native API Docs
  1104. ---------------
  1105. pg8000.native.Error
  1106. ```````````````````
  1107. Generic exception that is the base exception of the other error exceptions.
  1108. pg8000.native.InterfaceError
  1109. ````````````````````````````
  1110. For errors that originate within pg8000.
  1111. pg8000.native.DatabaseError
  1112. ```````````````````````````
  1113. For errors that originate from the server.
  1114. pg8000.native.Connection(user, host='localhost', database=None, port=5432, password=None, source_address=None, unix_sock=None, ssl_context=None, timeout=None, tcp_keepalive=True, application_name=None, replication=None, sock=None)
  1115. ``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
  1116. Creates a connection to a PostgreSQL database.
  1117. user
  1118. The username to connect to the PostgreSQL server with. If your server character
  1119. encoding is not ``ascii`` or ``utf8``, then you need to provide ``user`` as bytes,
  1120. eg. ``'my_name'.encode('EUC-JP')``.
  1121. host
  1122. The hostname of the PostgreSQL server to connect with. Providing this parameter is
  1123. necessary for TCP/IP connections. One of either ``host`` or ``unix_sock`` must be
  1124. provided. The default is ``localhost``.
  1125. database
  1126. The name of the database instance to connect with. If ``None`` then the PostgreSQL
  1127. server will assume the database name is the same as the username. If your server
  1128. character encoding is not ``ascii`` or ``utf8``, then you need to provide ``database``
  1129. as bytes, eg. ``'my_db'.encode('EUC-JP')``.
  1130. port
  1131. The TCP/IP port of the PostgreSQL server instance. This parameter defaults to
  1132. ``5432``, the registered common port of PostgreSQL TCP/IP servers.
  1133. password
  1134. The user password to connect to the server with. This parameter is optional; if
  1135. omitted and the database server requests password-based authentication, the connection
  1136. will fail to open. If this parameter is provided but not
  1137. requested by the server, no error will occur.
  1138. If your server character encoding is not ``ascii`` or ``utf8``, then you need to
  1139. provide ``password`` as bytes, eg. ``'my_password'.encode('EUC-JP')``.
  1140. source_address
  1141. The source IP address which initiates the connection to the PostgreSQL server. The
  1142. default is ``None`` which means that the operating system will choose the source
  1143. address.
  1144. unix_sock
  1145. The path to the UNIX socket to access the database through, for example,
  1146. ``'/tmp/.s.PGSQL.5432'``. One of either ``host`` or ``unix_sock`` must be provided.
  1147. ssl_context
  1148. This governs SSL encryption for TCP/IP sockets. It can have three values:
  1149. - ``None``, meaning no SSL (the default)
  1150. - ``True``, means use SSL with an |ssl.SSLContext|_ created using
  1151. |ssl.create_default_context()|_
  1152. - An instance of |ssl.SSLContext|_ which will be used to create the SSL connection.
  1153. If your PostgreSQL server is behind an SSL proxy, you can set the pg8000-specific
  1154. attribute ``ssl.SSLContext.request_ssl = False``, which tells pg8000 to use an SSL
  1155. socket, but not to request SSL from the PostgreSQL server. Note that this means you
  1156. can't use SCRAM authentication with channel binding.
  1157. timeout
  1158. This is the time in seconds before the connection to the server will time out. The
  1159. default is ``None`` which means no timeout.
  1160. tcp_keepalive
  1161. If ``True`` then use `TCP keepalive
  1162. <https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive>`_. The default is ``True``.
  1163. application_name
  1164. Sets the `application_name
  1165. <https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-APPLICATION-NAME>`_.
  1166. If your server character encoding is not ``ascii`` or ``utf8``, then you need to
  1167. provide values as bytes, eg. ``'my_application_name'.encode('EUC-JP')``. The default
  1168. is ``None`` which means that the server will set the application name.
  1169. replication
  1170. Used to run in `streaming replication mode
  1171. <https://www.postgresql.org/docs/current/protocol-replication.html>`_. If your server
  1172. character encoding is not ``ascii`` or ``utf8``, then you need to provide values as
  1173. bytes, eg. ``'database'.encode('EUC-JP')``.
  1174. sock
  1175. A socket-like object to use for the connection. For example, ``sock`` could be a plain
  1176. ``socket.socket``, or it could represent an SSH tunnel or perhaps an
  1177. ``ssl.SSLSocket`` to an SSL proxy. If an |ssl.SSLContext| is provided, then it will be
  1178. used to attempt to create an SSL socket from the provided socket.
  1179. pg8000.native.Connection.notifications
  1180. ``````````````````````````````````````
  1181. A deque of server-side `notifications
  1182. <https://www.postgresql.org/docs/current/sql-notify.html>`__ received by this database
  1183. connection (via the ``LISTEN`` / ``NOTIFY`` PostgreSQL commands). Each list item is a
  1184. three-element tuple containing the PostgreSQL backend PID that issued the notify, the
  1185. channel and the payload.
  1186. pg8000.native.Connection.notices
  1187. ````````````````````````````````
  1188. A deque of server-side notices received by this database connection.
  1189. pg8000.native.Connection.parameter_statuses
  1190. ```````````````````````````````````````````
  1191. A deque of server-side parameter statuses received by this database connection.
  1192. pg8000.native.Connection.run(sql, stream=None, types=None, \*\*kwargs)
  1193. ``````````````````````````````````````````````````````````````````````
  1194. Executes an sql statement, and returns the results as a ``list``. For example::
  1195. con.run("SELECT * FROM cities where population > :pop", pop=10000)
  1196. sql
  1197. The SQL statement to execute. Parameter placeholders appear as a ``:`` followed by the
  1198. parameter name.
  1199. stream
  1200. For use with the PostgreSQL `COPY
  1201. <http://www.postgresql.org/docs/current/static/sql-copy.html>`__ command. The nature
  1202. of the parameter depends on whether the SQL command is ``COPY FROM`` or ``COPY TO``.
  1203. ``COPY FROM``
  1204. The stream parameter must be a readable file-like object or an iterable. If it's an
  1205. iterable then the items can be ``str`` or binary.
  1206. ``COPY TO``
  1207. The stream parameter must be a writable file-like object.
  1208. types
  1209. A dictionary of oids. A key corresponds to a parameter.
  1210. kwargs
  1211. The parameters of the SQL statement.
  1212. pg8000.native.Connection.row_count
  1213. ``````````````````````````````````
  1214. This read-only attribute contains the number of rows that the last ``run()`` method
  1215. produced (for query statements like ``SELECT``) or affected (for modification statements
  1216. like ``UPDATE``.
  1217. The value is -1 if:
  1218. - No ``run()`` method has been performed yet.
  1219. - There was no rowcount associated with the last ``run()``.
  1220. pg8000.native.Connection.columns
  1221. ````````````````````````````````
  1222. A list of column metadata. Each item in the list is a dictionary with the following
  1223. keys:
  1224. - name
  1225. - table_oid
  1226. - column_attrnum
  1227. - type_oid
  1228. - type_size
  1229. - type_modifier
  1230. - format
  1231. pg8000.native.Connection.close()
  1232. ````````````````````````````````
  1233. Closes the database connection.
  1234. pg8000.native.Connection.register_out_adapter(typ, out_func)
  1235. ````````````````````````````````````````````````````````````
  1236. Register a type adapter for types going out from pg8000 to the server.
  1237. typ
  1238. The Python class that the adapter is for.
  1239. out_func
  1240. A function that takes the Python object and returns its string representation
  1241. in the format that the server requires.
  1242. pg8000.native.Connection.register_in_adapter(oid, in_func)
  1243. ``````````````````````````````````````````````````````````
  1244. Register a type adapter for types coming in from the server to pg8000.
  1245. oid
  1246. The PostgreSQL type identifier found in the `pg_type system catalog
  1247. <https://www.postgresql.org/docs/current/catalog-pg-type.html>`_.
  1248. in_func
  1249. A function that takes the PostgreSQL string representation and returns a corresponding
  1250. Python object.
  1251. pg8000.native.Connection.prepare(sql)
  1252. `````````````````````````````````````
  1253. Returns a ``PreparedStatement`` object which represents a `prepared statement
  1254. <https://www.postgresql.org/docs/current/sql-prepare.html>`_ on the server. It can
  1255. subsequently be repeatedly executed.
  1256. sql
  1257. The SQL statement to prepare. Parameter placeholders appear as a ``:`` followed by the
  1258. parameter name.
  1259. pg8000.native.PreparedStatement
  1260. ```````````````````````````````
  1261. A prepared statement object is returned by the ``pg8000.native.Connection.prepare()``
  1262. method of a connection. It has the following methods:
  1263. pg8000.native.PreparedStatement.run(\*\*kwargs)
  1264. ```````````````````````````````````````````````
  1265. Executes the prepared statement, and returns the results as a ``tuple``.
  1266. kwargs
  1267. The parameters of the prepared statement.
  1268. pg8000.native.PreparedStatement.close()
  1269. ```````````````````````````````````````
  1270. Closes the prepared statement, releasing the prepared statement held on the server.
  1271. pg8000.native.identifier(ident)
  1272. ```````````````````````````````
  1273. Correctly quotes and escapes a string to be used as an `SQL identifier
  1274. <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS>`_.
  1275. ident
  1276. The ``str`` to be used as an SQL identifier.
  1277. pg8000.native.literal(value)
  1278. ````````````````````````````
  1279. Correctly quotes and escapes a value to be used as an `SQL literal
  1280. <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS>`_.
  1281. value
  1282. The value to be used as an SQL literal.
  1283. DB-API 2 Docs
  1284. -------------
  1285. Properties
  1286. ``````````
  1287. pg8000.dbapi.apilevel
  1288. :::::::::::::::::::::
  1289. The DBAPI level supported, currently "2.0".
  1290. pg8000.dbapi.threadsafety
  1291. :::::::::::::::::::::::::
  1292. Integer constant stating the level of thread safety the DBAPI interface supports. For
  1293. pg8000, the threadsafety value is 1, meaning that threads may share the module but not
  1294. connections.
  1295. pg8000.dbapi.paramstyle
  1296. :::::::::::::::::::::::
  1297. String property stating the type of parameter marker formatting expected by
  1298. the interface. This value defaults to "format", in which parameters are
  1299. marked in this format: "WHERE name=%s".
  1300. As an extension to the DBAPI specification, this value is not constant; it can be
  1301. changed to any of the following values:
  1302. qmark
  1303. Question mark style, eg. ``WHERE name=?``
  1304. numeric
  1305. Numeric positional style, eg. ``WHERE name=:1``
  1306. named
  1307. Named style, eg. ``WHERE name=:paramname``
  1308. format
  1309. printf format codes, eg. ``WHERE name=%s``
  1310. pyformat
  1311. Python format codes, eg. ``WHERE name=%(paramname)s``
  1312. pg8000.dbapi.STRING
  1313. :::::::::::::::::::
  1314. String type oid.
  1315. pg8000.dbapi.BINARY
  1316. :::::::::::::::::::
  1317. pg8000.dbapi.NUMBER
  1318. :::::::::::::::::::
  1319. Numeric type oid.
  1320. pg8000.dbapi.DATETIME
  1321. :::::::::::::::::::::
  1322. Timestamp type oid
  1323. pg8000.dbapi.ROWID
  1324. ::::::::::::::::::
  1325. ROWID type oid
  1326. Functions
  1327. `````````
  1328. pg8000.dbapi.connect(user, host='localhost', database=None, port=5432, password=None, source_address=None, unix_sock=None, ssl_context=None, timeout=None, tcp_keepalive=True, application_name=None, replication=None, sock=None)
  1329. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  1330. Creates a connection to a PostgreSQL database.
  1331. user
  1332. The username to connect to the PostgreSQL server with. If your server character
  1333. encoding is not ``ascii`` or ``utf8``, then you need to provide ``user`` as bytes,
  1334. eg. ``'my_name'.encode('EUC-JP')``.
  1335. host
  1336. The hostname of the PostgreSQL server to connect with. Providing this parameter is
  1337. necessary for TCP/IP connections. One of either ``host`` or ``unix_sock`` must be
  1338. provided. The default is ``localhost``.
  1339. database
  1340. The name of the database instance to connect with. If ``None`` then the PostgreSQL
  1341. server will assume the database name is the same as the username. If your server
  1342. character encoding is not ``ascii`` or ``utf8``, then you need to provide ``database``
  1343. as bytes, eg. ``'my_db'.encode('EUC-JP')``.
  1344. port
  1345. The TCP/IP port of the PostgreSQL server instance. This parameter defaults to
  1346. ``5432``, the registered common port of PostgreSQL TCP/IP servers.
  1347. password
  1348. The user password to connect to the server with. This parameter is optional; if
  1349. omitted and the database server requests password-based authentication, the
  1350. connection will fail to open. If this parameter is provided but not requested by the
  1351. server, no error will occur.
  1352. If your server character encoding is not ``ascii`` or ``utf8``, then you need to
  1353. provide ``password`` as bytes, eg. ``'my_password'.encode('EUC-JP')``.
  1354. source_address
  1355. The source IP address which initiates the connection to the PostgreSQL server. The
  1356. default is ``None`` which means that the operating system will choose the source
  1357. address.
  1358. unix_sock
  1359. The path to the UNIX socket to access the database through, for example,
  1360. ``'/tmp/.s.PGSQL.5432'``. One of either ``host`` or ``unix_sock`` must be provided.
  1361. ssl_context
  1362. This governs SSL encryption for TCP/IP sockets. It can have three values:
  1363. - ``None``, meaning no SSL (the default)
  1364. - ``True``, means use SSL with an |ssl.SSLContext|_ created using
  1365. |ssl.create_default_context()|_.
  1366. - An instance of |ssl.SSLContext|_ which will be used to create the SSL connection.
  1367. If your PostgreSQL server is behind an SSL proxy, you can set the pg8000-specific
  1368. attribute ``ssl.SSLContext.request_ssl = False``, which tells pg8000 to use an SSL
  1369. socket, but not to request SSL from the PostgreSQL server. Note that this means you
  1370. can't use SCRAM authentication with channel binding.
  1371. timeout
  1372. This is the time in seconds before the connection to the server will time out. The
  1373. default is ``None`` which means no timeout.
  1374. tcp_keepalive
  1375. If ``True`` then use `TCP keepalive
  1376. <https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive>`_. The default is ``True``.
  1377. application_name
  1378. Sets the `application_name
  1379. <https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-APPLICATION-NAME>`_. If your server character encoding is not ``ascii`` or ``utf8``, then you need to
  1380. provide values as bytes, eg. ``'my_application_name'.encode('EUC-JP')``. The default
  1381. is ``None`` which means that the server will set the application name.
  1382. replication
  1383. Used to run in `streaming replication mode
  1384. <https://www.postgresql.org/docs/current/protocol-replication.html>`_. If your server
  1385. character encoding is not ``ascii`` or ``utf8``, then you need to provide values as
  1386. bytes, eg. ``'database'.encode('EUC-JP')``.
  1387. sock
  1388. A socket-like object to use for the connection. For example, ``sock`` could be a plain
  1389. ``socket.socket``, or it could represent an SSH tunnel or perhaps an
  1390. ``ssl.SSLSocket`` to an SSL proxy. If an |ssl.SSLContext| is provided, then it will be
  1391. used to attempt to create an SSL socket from the provided socket.
  1392. pg8000.dbapi.Date(year, month, day)
  1393. Construct an object holding a date value.
  1394. This property is part of the `DBAPI 2.0 specification
  1395. <http://www.python.org/dev/peps/pep-0249/>`_.
  1396. Returns: `datetime.date`
  1397. pg8000.dbapi.Time(hour, minute, second)
  1398. :::::::::::::::::::::::::::::::::::::::
  1399. Construct an object holding a time value.
  1400. Returns: ``datetime.time``
  1401. pg8000.dbapi.Timestamp(year, month, day, hour, minute, second)
  1402. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  1403. Construct an object holding a timestamp value.
  1404. Returns: ``datetime.datetime``
  1405. pg8000.dbapi.DateFromTicks(ticks)
  1406. :::::::::::::::::::::::::::::::::
  1407. Construct an object holding a date value from the given ticks value (number of seconds
  1408. since the epoch).
  1409. Returns: ``datetime.datetime``
  1410. pg8000.dbapi.TimeFromTicks(ticks)
  1411. :::::::::::::::::::::::::::::::::
  1412. Construct an object holding a time value from the given ticks value (number of seconds
  1413. since the epoch).
  1414. Returns: ``datetime.time``
  1415. pg8000.dbapi.TimestampFromTicks(ticks)
  1416. ::::::::::::::::::::::::::::::::::::::
  1417. Construct an object holding a timestamp value from the given ticks value (number of
  1418. seconds since the epoch).
  1419. Returns: ``datetime.datetime``
  1420. pg8000.dbapi.Binary(value)
  1421. ::::::::::::::::::::::::::
  1422. Construct an object holding binary data.
  1423. Returns: ``bytes``.
  1424. Generic Exceptions
  1425. ``````````````````
  1426. Pg8000 uses the standard DBAPI 2.0 exception tree as "generic" exceptions. Generally,
  1427. more specific exception types are raised; these specific exception types are derived
  1428. from the generic exceptions.
  1429. pg8000.dbapi.Warning
  1430. ::::::::::::::::::::
  1431. Generic exception raised for important database warnings like data truncations. This
  1432. exception is not currently used by pg8000.
  1433. pg8000.dbapi.Error
  1434. ::::::::::::::::::
  1435. Generic exception that is the base exception of all other error exceptions.
  1436. pg8000.dbapi.InterfaceError
  1437. :::::::::::::::::::::::::::
  1438. Generic exception raised for errors that are related to the database interface rather
  1439. than the database itself. For example, if the interface attempts to use an SSL
  1440. connection but the server refuses, an InterfaceError will be raised.
  1441. pg8000.dbapi.DatabaseError
  1442. ::::::::::::::::::::::::::
  1443. Generic exception raised for errors that are related to the database. This exception is
  1444. currently never raised by pg8000.
  1445. pg8000.dbapi.DataError
  1446. ::::::::::::::::::::::
  1447. Generic exception raised for errors that are due to problems with the processed data.
  1448. This exception is not currently raised by pg8000.
  1449. pg8000.dbapi.OperationalError
  1450. :::::::::::::::::::::::::::::
  1451. Generic exception raised for errors that are related to the database's operation and not
  1452. necessarily under the control of the programmer. This exception is currently never
  1453. raised by pg8000.
  1454. pg8000.dbapi.IntegrityError
  1455. :::::::::::::::::::::::::::
  1456. Generic exception raised when the relational integrity of the database is affected. This
  1457. exception is not currently raised by pg8000.
  1458. pg8000.dbapi.InternalError
  1459. ::::::::::::::::::::::::::
  1460. Generic exception raised when the database encounters an internal error. This is
  1461. currently only raised when unexpected state occurs in the pg8000 interface itself, and
  1462. is typically the result of a interface bug.
  1463. pg8000.dbapi.ProgrammingError
  1464. :::::::::::::::::::::::::::::
  1465. Generic exception raised for programming errors. For example, this exception is raised
  1466. if more parameter fields are in a query string than there are available parameters.
  1467. pg8000.dbapi.NotSupportedError
  1468. ::::::::::::::::::::::::::::::
  1469. Generic exception raised in case a method or database API was used which is not
  1470. supported by the database.
  1471. Classes
  1472. ```````
  1473. pg8000.dbapi.Connection
  1474. :::::::::::::::::::::::
  1475. A connection object is returned by the ``pg8000.connect()`` function. It represents a
  1476. single physical connection to a PostgreSQL database.
  1477. pg8000.dbapi.Connection.autocommit
  1478. ::::::::::::::::::::::::::::::::::
  1479. Following the DB-API specification, autocommit is off by default. It can be turned on by
  1480. setting this boolean pg8000-specific autocommit property to ``True``.
  1481. pg8000.dbapi.Connection.close()
  1482. :::::::::::::::::::::::::::::::
  1483. Closes the database connection.
  1484. pg8000.dbapi.Connection.cursor()
  1485. ::::::::::::::::::::::::::::::::
  1486. Creates a ``pg8000.dbapi.Cursor`` object bound to this connection.
  1487. pg8000.dbapi.Connection.rollback()
  1488. ::::::::::::::::::::::::::::::::::
  1489. Rolls back the current database transaction.
  1490. pg8000.dbapi.Connection.tpc_begin(xid)
  1491. ::::::::::::::::::::::::::::::::::::::
  1492. Begins a TPC transaction with the given transaction ID xid. This method should be
  1493. called outside of a transaction (i.e. nothing may have executed since the last
  1494. ``commit()`` or ``rollback()``. Furthermore, it is an error to call ``commit()`` or
  1495. ``rollback()`` within the TPC transaction. A ``ProgrammingError`` is raised, if the
  1496. application calls ``commit()`` or ``rollback()`` during an active TPC transaction.
  1497. pg8000.dbapi.Connection.tpc_commit(xid=None)
  1498. ::::::::::::::::::::::::::::::::::::::::::::
  1499. When called with no arguments, ``tpc_commit()`` commits a TPC transaction previously
  1500. prepared with ``tpc_prepare()``. If ``tpc_commit()`` is called prior to
  1501. ``tpc_prepare()``, a single phase commit is performed. A transaction manager may choose
  1502. to do this if only a single resource is participating in the global transaction.
  1503. When called with a transaction ID ``xid``, the database commits the given transaction.
  1504. If an invalid transaction ID is provided, a ``ProgrammingError`` will be raised. This
  1505. form should be called outside of a transaction, and is intended for use in recovery.
  1506. On return, the TPC transaction is ended.
  1507. pg8000.dbapi.Connection.tpc_prepare()
  1508. :::::::::::::::::::::::::::::::::::::
  1509. Performs the first phase of a transaction started with ``.tpc_begin()``. A
  1510. ``ProgrammingError`` is be raised if this method is called outside of a TPC transaction.
  1511. After calling ``tpc_prepare()``, no statements can be executed until ``tpc_commit()`` or
  1512. ``tpc_rollback()`` have been called.
  1513. pg8000.dbapi.Connection.tpc_recover()
  1514. :::::::::::::::::::::::::::::::::::::
  1515. Returns a list of pending transaction IDs suitable for use with ``tpc_commit(xid)`` or
  1516. ``tpc_rollback(xid)``.
  1517. pg8000.dbapi.Connection.tpc_rollback(xid=None)
  1518. ::::::::::::::::::::::::::::::::::::::::::::::
  1519. When called with no arguments, ``tpc_rollback()`` rolls back a TPC transaction. It may
  1520. be called before or after ``tpc_prepare()``.
  1521. When called with a transaction ID xid, it rolls back the given transaction. If an
  1522. invalid transaction ID is provided, a ``ProgrammingError`` is raised. This form should
  1523. be called outside of a transaction, and is intended for use in recovery.
  1524. On return, the TPC transaction is ended.
  1525. pg8000.dbapi.Connection.xid(format_id, global_transaction_id, branch_qualifier)
  1526. :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  1527. Create a Transaction IDs (only global_transaction_id is used in pg) format_id and
  1528. branch_qualifier are not used in postgres global_transaction_id may be any string
  1529. identifier supported by postgres returns a tuple (format_id, global_transaction_id,
  1530. branch_qualifier)
  1531. pg8000.dbapi.Cursor
  1532. :::::::::::::::::::
  1533. A cursor object is returned by the ``pg8000.dbapi.Connection.cursor()`` method of a
  1534. connection. It has the following attributes and methods:
  1535. pg8000.dbapi.Cursor.arraysize
  1536. '''''''''''''''''''''''''''''
  1537. This read/write attribute specifies the number of rows to fetch at a time with
  1538. ``pg8000.dbapi.Cursor.fetchmany()``. It defaults to 1.
  1539. pg8000.dbapi.Cursor.connection
  1540. ''''''''''''''''''''''''''''''
  1541. This read-only attribute contains a reference to the connection object (an instance of
  1542. ``pg8000.dbapi.Connection``) on which the cursor was created.
  1543. pg8000.dbapi.Cursor.rowcount
  1544. ''''''''''''''''''''''''''''
  1545. This read-only attribute contains the number of rows that the last ``execute()`` or
  1546. ``executemany()`` method produced (for query statements like ``SELECT``) or affected
  1547. (for modification statements like ``UPDATE``.
  1548. The value is -1 if:
  1549. - No ``execute()`` or ``executemany()`` method has been performed yet on the cursor.
  1550. - There was no rowcount associated with the last ``execute()``.
  1551. - At least one of the statements executed as part of an ``executemany()`` had no row
  1552. count associated with it.
  1553. pg8000.dbapi.Cursor.description
  1554. '''''''''''''''''''''''''''''''
  1555. This read-only attribute is a sequence of 7-item sequences. Each value contains
  1556. information describing one result column. The 7 items returned for each column are
  1557. (name, type_code, display_size, internal_size, precision, scale, null_ok). Only the
  1558. first two values are provided by the current implementation.
  1559. pg8000.dbapi.Cursor.close()
  1560. '''''''''''''''''''''''''''
  1561. Closes the cursor.
  1562. pg8000.dbapi.Cursor.execute(operation, args=None, stream=None)
  1563. ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  1564. Executes a database operation. Parameters may be provided as a sequence, or as a
  1565. mapping, depending upon the value of ``pg8000.dbapi.paramstyle``. Returns the cursor,
  1566. which may be iterated over.
  1567. operation
  1568. The SQL statement to execute.
  1569. args
  1570. If ``pg8000.dbapi.paramstyle`` is ``qmark``, ``numeric``, or ``format``, this
  1571. argument should be an array of parameters to bind into the statement. If
  1572. ``pg8000.dbapi.paramstyle`` is ``named``, the argument should be a ``dict`` mapping of
  1573. parameters. If ``pg8000.dbapi.paramstyle`` is ``pyformat``, the argument value may be
  1574. either an array or a mapping.
  1575. stream
  1576. This is a pg8000 extension for use with the PostgreSQL `COPY
  1577. <http://www.postgresql.org/docs/current/static/sql-copy.html>`__ command. For a
  1578. ``COPY FROM`` the parameter must be a readable file-like object, and for ``COPY TO``
  1579. it must be writable.
  1580. pg8000.dbapi.Cursor.executemany(operation, param_sets)
  1581. ''''''''''''''''''''''''''''''''''''''''''''''''''''''
  1582. Prepare a database operation, and then execute it against all parameter sequences or
  1583. mappings provided.
  1584. operation
  1585. The SQL statement to execute.
  1586. parameter_sets
  1587. A sequence of parameters to execute the statement with. The values in the sequence
  1588. should be sequences or mappings of parameters, the same as the args argument of the
  1589. ``pg8000.dbapi.Cursor.execute()`` method.
  1590. pg8000.dbapi.Cursor.callproc(procname, parameters=None)
  1591. '''''''''''''''''''''''''''''''''''''''''''''''''''''''
  1592. Call a stored database procedure with the given name and optional parameters.
  1593. procname
  1594. The name of the procedure to call.
  1595. parameters
  1596. A list of parameters.
  1597. pg8000.dbapi.Cursor.fetchall()
  1598. ''''''''''''''''''''''''''''''
  1599. Fetches all remaining rows of a query result.
  1600. Returns: A sequence, each entry of which is a sequence of field values making up a row.
  1601. pg8000.dbapi.Cursor.fetchmany(size=None)
  1602. ''''''''''''''''''''''''''''''''''''''''
  1603. Fetches the next set of rows of a query result.
  1604. size
  1605. The number of rows to fetch when called. If not provided, the
  1606. ``pg8000.dbapi.Cursor.arraysize`` attribute value is used instead.
  1607. Returns: A sequence, each entry of which is a sequence of field values making up a row.
  1608. If no more rows are available, an empty sequence will be returned.
  1609. pg8000.dbapi.Cursor.fetchone()
  1610. ''''''''''''''''''''''''''''''
  1611. Fetch the next row of a query result set.
  1612. Returns: A row as a sequence of field values, or ``None`` if no more rows are available.
  1613. pg8000.dbapi.Cursor.setinputsizes(\*sizes)
  1614. ''''''''''''''''''''''''''''''''''''''''''
  1615. Used to set the parameter types of the next query. This is useful if it's difficult for
  1616. pg8000 to work out the types from the parameters themselves (eg. for parameters of type
  1617. None).
  1618. sizes
  1619. Positional parameters that are either the Python type of the parameter to be sent, or
  1620. the PostgreSQL oid. Common oids are available as constants such as ``pg8000.STRING``,
  1621. ``pg8000.INTEGER``, ``pg8000.TIME`` etc.
  1622. pg8000.dbapi.Cursor.setoutputsize(size, column=None)
  1623. ''''''''''''''''''''''''''''''''''''''''''''''''''''
  1624. Not implemented by pg8000.
  1625. pg8000.dbapi.Interval
  1626. '''''''''''''''''''''
  1627. An Interval represents a measurement of time. In PostgreSQL, an interval is defined in
  1628. the measure of months, days, and microseconds; as such, the pg8000 interval type
  1629. represents the same information.
  1630. Note that values of the ``pg8000.dbapi.Interval.microseconds``,
  1631. ``pg8000.dbapi.Interval.days``, and ``pg8000.dbapi.Interval.months`` properties are
  1632. independently measured and cannot be converted to each other. A month may be 28, 29, 30,
  1633. or 31 days, and a day may occasionally be lengthened slightly by a leap second.
  1634. Design Decisions
  1635. ----------------
  1636. For the ``Range`` type, the constructor follows the `PostgreSQL range constructor functions <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-CONSTRUCT>`_
  1637. which makes `[closed, open) <https://fhur.me/posts/always-use-closed-open-intervals>`_
  1638. the easiest to express:
  1639. >>> from pg8000.types import Range
  1640. >>>
  1641. >>> pg_range = Range(2, 6)
  1642. Tests
  1643. -----
  1644. - Install `tox <http://testrun.org/tox/latest/>`_: ``pip install tox``
  1645. - Enable the PostgreSQL hstore extension by running the SQL command:
  1646. ``create extension hstore;``
  1647. - Add a line to ``pg_hba.conf`` for the various authentication options:
  1648. ::
  1649. host pg8000_md5 all 127.0.0.1/32 md5
  1650. host pg8000_gss all 127.0.0.1/32 gss
  1651. host pg8000_password all 127.0.0.1/32 password
  1652. host pg8000_scram_sha_256 all 127.0.0.1/32 scram-sha-256
  1653. host all all 127.0.0.1/32 trust
  1654. - Set password encryption to ``scram-sha-256`` in ``postgresql.conf``:
  1655. ``password_encryption = 'scram-sha-256'``
  1656. - Set the password for the postgres user: ``ALTER USER postgresql WITH PASSWORD 'pw';``
  1657. - Run ``tox`` from the ``pg8000`` directory: ``tox``
  1658. This will run the tests against the Python version of the virtual environment, on the
  1659. machine, and the installed PostgreSQL version listening on port 5432, or the ``PGPORT``
  1660. environment variable if set.
  1661. Benchmarks are run as part of the test suite at ``tests/test_benchmarks.py``.
  1662. README.rst
  1663. ----------
  1664. This file is written in the `reStructuredText
  1665. <https://docutils.sourceforge.io/docs/user/rst/quickref.html>`_ format. To generate an
  1666. HTML page from it, do:
  1667. - Activate the virtual environment: ``source venv/bin/activate``
  1668. - Install ``Sphinx``: ``pip install Sphinx``
  1669. - Run ``rst2html.py``: ``rst2html.py README.rst README.html``
  1670. Doing A Release Of pg8000
  1671. -------------------------
  1672. Run ``tox`` to make sure all tests pass, then update the release notes, then do:
  1673. ::
  1674. git tag -a x.y.z -m "version x.y.z"
  1675. rm -r dist
  1676. python -m build
  1677. twine upload dist/*
  1678. Release Notes
  1679. -------------
  1680. Version 1.30.3, 2023-10-31
  1681. ``````````````````````````
  1682. - Fix problem with PG date overflowing Python types. Now we return the ``str`` we got from the
  1683. server if we can't parse it.
  1684. Version 1.30.2, 2023-09-17
  1685. ``````````````````````````
  1686. - Bug fix where dollar-quoted string constants weren't supported.
  1687. Version 1.30.1, 2023-07-29
  1688. ``````````````````````````
  1689. - There was a problem uploading the previous version (1.30.0) to PyPI because the
  1690. markup of the README.rst was invalid. There's now a step in the automated tests to
  1691. check for this.
  1692. Version 1.30.0, 2023-07-27
  1693. ``````````````````````````
  1694. - Remove support for Python 3.7
  1695. - Add a ``sock`` keyword parameter for creating a connection from a pre-configured
  1696. socket.
  1697. Version 1.29.8, 2023-06-16
  1698. ``````````````````````````
  1699. - Ranges don't work with legacy API.
  1700. Version 1.29.7, 2023-06-16
  1701. ``````````````````````````
  1702. - Add support for PostgreSQL ``range`` and ``multirange`` types. Previously pg8000
  1703. would just return them as strings, but now they're returned as ``Range`` and lists of
  1704. ``Range``.
  1705. - The PostgreSQL ``record`` type is now returned as a ``tuple`` of strings, whereas
  1706. before it was returned as one string.
  1707. Version 1.29.6, 2023-05-29
  1708. ``````````````````````````
  1709. - Fixed two bugs with composite types. Nulls should be represented by an empty string,
  1710. and in an array of composite types, the elements should be surrounded by double
  1711. quotes.
  1712. Version 1.29.5, 2023-05-09
  1713. ``````````````````````````
  1714. - Fixed bug where pg8000 didn't handle the case when the number of bytes received from
  1715. a socket was fewer than requested. This was being interpreted as a network error, but
  1716. in fact we just needed to wait until more bytes were available.
  1717. - When using the ``PGInterval`` type, if a response from the server contained the period
  1718. ``millennium``, it wasn't recognised. This was caused by a spelling mistake where we
  1719. had ``millenium`` rather than ``millennium``.
  1720. - Added support for sending PostgreSQL composite types. If a value is sent as a
  1721. ``tuple``, pg8000 will send it to the server as a ``(`` delimited composite string.
  1722. Version 1.29.4, 2022-12-14
  1723. ``````````````````````````
  1724. - Fixed bug in ``pg8000.dbapi`` in the ``setinputsizes()`` method where if a ``size``
  1725. was a recognized Python type, the method failed.
  1726. Version 1.29.3, 2022-10-26
  1727. ``````````````````````````
  1728. - Upgrade the SCRAM library to version 1.4.3. This adds support for the case where the
  1729. client supports channel binding but the server doesn't.
  1730. Version 1.29.2, 2022-10-09
  1731. ``````````````````````````
  1732. - Fixed a bug where in a literal array, items such as ``\n`` and ``\r`` weren't
  1733. escaped properly before being sent to the server.
  1734. - Fixed a bug where if the PostgreSQL server has a half-hour time zone set, values of
  1735. type ``timestamp with time zone`` failed. This has been fixed by using the ``parse``
  1736. function of the ``dateutil`` package if the ``datetime`` parser fails.
  1737. Version 1.29.1, 2022-05-23
  1738. ``````````````````````````
  1739. - In trying to determine if there's been a failed commit, check for ``ROLLBACK TO
  1740. SAVEPOINT``.
  1741. Version 1.29.0, 2022-05-21
  1742. ``````````````````````````
  1743. - Implement a workaround for the `silent failed commit
  1744. <https://github.com/tlocke/pg8000/issues/36>`_ bug.
  1745. - Previously if an empty string was sent as the query an exception would be raised, but
  1746. that isn't done now.
  1747. Version 1.28.3, 2022-05-18
  1748. ``````````````````````````
  1749. - Put back ``__version__`` attributes that were inadvertently removed.
  1750. Version 1.28.2, 2022-05-17
  1751. ``````````````````````````
  1752. - Use a build system that's compliant with PEP517.
  1753. Version 1.28.1, 2022-05-17
  1754. ``````````````````````````
  1755. - If when doing a ``COPY FROM`` the ``stream`` parameter is an iterator of ``str``,
  1756. pg8000 used to silently append a newline to the end. That no longer happens.
  1757. Version 1.28.0, 2022-05-17
  1758. ``````````````````````````
  1759. - When using the ``COPY FROM`` SQL statement, allow the ``stream`` parameter to be an
  1760. iterable.
  1761. Version 1.27.1, 2022-05-16
  1762. ``````````````````````````
  1763. - The ``seconds`` attribute of ``PGInterval`` is now always a ``float``, to cope with
  1764. fractional seconds.
  1765. - Updated the ``interval`` parsers for ``iso_8601`` and ``sql_standard`` to take
  1766. account of fractional seconds.
  1767. Version 1.27.0, 2022-05-16
  1768. ``````````````````````````
  1769. - It used to be that by default, if pg8000 received an ``interval`` type from the server
  1770. and it was too big to fit into a ``datetime.timedelta`` then an exception would be
  1771. raised. Now if an interval is too big for ``datetime.timedelta`` a ``PGInterval`` is
  1772. returned.
  1773. * pg8000 now supports all the output formats for an ``interval`` (``postgres``,
  1774. ``postgres_verbose``, ``iso_8601`` and ``sql_standard``).
  1775. Version 1.26.1, 2022-04-23
  1776. ``````````````````````````
  1777. - Make sure all tests are run by the GitHub Actions tests on commit.
  1778. - Remove support for Python 3.6
  1779. - Remove support for PostgreSQL 9.6
  1780. Version 1.26.0, 2022-04-18
  1781. ``````````````````````````
  1782. - When connecting, raise an ``InterfaceError('network error')`` rather than let the
  1783. underlying ``struct.error`` float up.
  1784. - Make licence text the same as that used by the OSI. Previously the licence wording
  1785. differed slightly from the BSD 3 Clause licence at
  1786. https://opensource.org/licenses/BSD-3-Clause. This meant that automated tools didn't
  1787. pick it up as being Open Source. The changes are believed to not alter the meaning of the license at all.
  1788. Version 1.25.0, 2022-04-17
  1789. ``````````````````````````
  1790. - Fix more cases where a ``ResourceWarning`` would be raise because of a socket that had
  1791. been left open.
  1792. - We now have a single ``InterfaceError`` with the message 'network error' for all
  1793. network errors, with the underlying exception held in the ``cause`` of the exception.
  1794. Version 1.24.2, 2022-04-15
  1795. ``````````````````````````
  1796. - To prevent a ``ResourceWarning`` close socket if a connection can't be created.
  1797. Version 1.24.1, 2022-03-02
  1798. ``````````````````````````
  1799. - Return pg +/-infinity dates as ``str``. Previously +/-infinity pg values would cause
  1800. an error when returned, but now we return +/-infinity as strings.
  1801. Version 1.24.0, 2022-02-06
  1802. ``````````````````````````
  1803. - Add SQL escape functions identifier() and literal() to the native API. For use when a
  1804. query can't be parameterised and the SQL string has to be created using untrusted
  1805. values.
  1806. Version 1.23.0, 2021-11-13
  1807. ``````````````````````````
  1808. - If a query has no parameters, then the query will no longer be parsed. Although there
  1809. are performance benefits for doing this, the main reason is to avoid query rewriting,
  1810. which can introduce errors.
  1811. Version 1.22.1, 2021-11-10
  1812. ``````````````````````````
  1813. - Fix bug in PGInterval type where ``str()`` failed for a millennia value.
  1814. Version 1.22.0, 2021-10-13
  1815. ``````````````````````````
  1816. - Rather than specifying the oids in the ``Parse`` step of the Postgres protocol, pg8000
  1817. now omits them, and so Postgres will use the oids it determines from the query. This
  1818. makes the pg8000 code simpler and also it should also make the nuances of type
  1819. matching more straightforward.