README.rst 78 KB

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