pg8000 1.31.5
PostgreSQL interface library
License: BSD 3-Clause License
Requires Python: >=3.9
Keywords: dbapi, postgresql

# pg8000

pg8000 is a pure-[Python](https://www.python.org/)
[PostgreSQL](http://www.postgresql.org/) driver that complies with
[DB-API 2.0](http://www.python.org/dev/peps/pep-0249/). pg8000's name comes from the
belief that it is probably about the 8000th PostgreSQL interface for Python. pg8000 is
distributed under the BSD 3-clause license.

<!-- mtoc-start -->

* [Installation](#installation)
* [Native API Interactive Examples](#native-api-interactive-examples)
  * [Basic Example](#basic-example)
  * [Transactions](#transactions)
  * [Query Using Functions](#query-using-functions)
  * [Interval Type](#interval-type)
  * [Point Type](#point-type)
  * [Client Encoding](#client-encoding)
  * [JSON](#json)
  * [Retrieve Column Metadata From Results](#retrieve-column-metadata-from-results)
  * [Notices And Notifications](#notices-and-notifications)
  * [Parameter Statuses](#parameter-statuses)
  * [LIMIT ALL](#limit-all)
  * [IN and NOT IN](#in-and-not-in)
  * [Many SQL Statements Can't Be Parameterized](#many-sql-statements-cant-be-parameterized)
  * [COPY FROM And TO A Stream](#copy-from-and-to-a-stream)
  * [Execute Multiple SQL Statements](#execute-multiple-sql-statements)
  * [Quoted Identifiers in SQL](#quoted-identifiers-in-sql)
  * [Custom adapter from a Python type to a PostgreSQL type](#custom-adapter-from-a-python-type-to-a-postgresql-type)
  * [Custom adapter from a PostgreSQL type to a Python type](#custom-adapter-from-a-postgresql-type-to-a-python-type)
  * [Could Not Determine Data Type Of Parameter](#could-not-determine-data-type-of-parameter)
  * [Prepared Statements](#prepared-statements)
  * [Use Environment Variables As Connection Defaults](#use-environment-variables-as-connection-defaults)
  * [Connect To PostgreSQL Over SSL](#connect-to-postgresql-over-ssl)
  * [Server-Side Cursors](#server-side-cursors)
  * [BLOBs (Binary Large Objects)](#blobs-binary-large-objects)
  * [Replication Protocol](#replication-protocol)
  * [Extra Startup Parameters](#extra-startup-parameters)
  * [PostgreSQL-Style Parameter Placeholders](#postgresql-style-parameter-placeholders)
* [DB-API 2 Interactive Examples](#db-api-2-interactive-examples)
  * [Basic Example](#basic-example-1)
  * [Query Using Functions](#query-using-functions-1)
  * [Interval Type](#interval-type-1)
  * [Point Type](#point-type-1)
  * [Numeric Parameter Style](#numeric-parameter-style)
  * [Autocommit](#autocommit)
  * [Client Encoding](#client-encoding-1)
  * [JSON](#json-1)
  * [Retrieve Column Names From Results](#retrieve-column-names-from-results)
  * [COPY from and to a file](#copy-from-and-to-a-file)
  * [Server-Side Cursors](#server-side-cursors-1)
  * [BLOBs (Binary Large Objects)](#blobs-binary-large-objects-1)
  * [Parameter Limit](#parameter-limit)
* [Type Mapping](#type-mapping)
* [Theory Of Operation](#theory-of-operation)
* [Native API Docs](#native-api-docs)
  * [pg8000.native.Error](#pg8000nativeerror)
  * [pg8000.native.InterfaceError](#pg8000nativeinterfaceerror)
  * [pg8000.native.DatabaseError](#pg8000nativedatabaseerror)
  * [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)](#pg8000nativeconnectionuser-hostlocalhost-databasenone-port5432-passwordnone-source_addressnone-unix_socknone-ssl_contextnone-timeoutnone-tcp_keepalivetrue-application_namenone-replicationnone-socknone)
  * [pg8000.native.Connection.notifications](#pg8000nativeconnectionnotifications)
  * [pg8000.native.Connection.notices](#pg8000nativeconnectionnotices)
  * [pg8000.native.Connection.parameter\_statuses](#pg8000nativeconnectionparameter_statuses)
  * [pg8000.native.Connection.run(sql, stream=None, types=None, \*\*kwargs)](#pg8000nativeconnectionrunsql-streamnone-typesnone-kwargs)
  * [pg8000.native.Connection.row\_count](#pg8000nativeconnectionrow_count)
  * [pg8000.native.Connection.columns](#pg8000nativeconnectioncolumns)
  * [pg8000.native.Connection.close()](#pg8000nativeconnectionclose)
  * [pg8000.native.Connection.register\_out\_adapter(typ, out\_func)](#pg8000nativeconnectionregister_out_adaptertyp-out_func)
  * [pg8000.native.Connection.register\_in\_adapter(oid, in\_func)](#pg8000nativeconnectionregister_in_adapteroid-in_func)
  * [pg8000.native.Connection.prepare(sql)](#pg8000nativeconnectionpreparesql)
  * [pg8000.native.PreparedStatement](#pg8000nativepreparedstatement)
    * [pg8000.native.PreparedStatement.run(\*\*kwargs)](#pg8000nativepreparedstatementrunkwargs)
    * [pg8000.native.PreparedStatement.close()](#pg8000nativepreparedstatementclose)
  * [pg8000.native.identifier(ident)](#pg8000nativeidentifierident)
  * [pg8000.native.literal(value)](#pg8000nativeliteralvalue)
* [DB-API 2 Docs](#db-api-2-docs)
  * [Properties](#properties)
    * [pg8000.dbapi.apilevel](#pg8000dbapiapilevel)
    * [pg8000.dbapi.threadsafety](#pg8000dbapithreadsafety)
    * [pg8000.dbapi.paramstyle](#pg8000dbapiparamstyle)
    * [pg8000.dbapi.STRING](#pg8000dbapistring)
    * [pg8000.dbapi.BINARY](#pg8000dbapibinary)
    * [pg8000.dbapi.NUMBER](#pg8000dbapinumber)
    * [pg8000.dbapi.DATETIME](#pg8000dbapidatetime)
    * [pg8000.dbapi.ROWID](#pg8000dbapirowid)
  * [Functions](#functions)
    * [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, applicationa_name=None, replication=None, sock=None)](#pg8000dbapiconnectuser-hostlocalhost-databasenone-port5432-passwordnone-source_addressnone-unix_socknone-ssl_contextnone-timeoutnone-tcp_keepalivetrue-applicationa_namenone-replicationnone-socknone)
    * [pg8000.dbapi.Date(year, month, day)](#pg8000dbapidateyear-month-day)
    * [pg8000.dbapi.Time(hour, minute, second)](#pg8000dbapitimehour-minute-second)
    * [pg8000.dbapi.Timestamp(year, month, day, hour, minute, second)](#pg8000dbapitimestampyear-month-day-hour-minute-second)
    * [pg8000.dbapi.DateFromTicks(ticks)](#pg8000dbapidatefromticksticks)
    * [pg8000.dbapi.TimeFromTicks(ticks)](#pg8000dbapitimefromticksticks)
    * [pg8000.dbapi.TimestampFromTicks(ticks)](#pg8000dbapitimestampfromticksticks)
    * [pg8000.dbapi.Binary(value)](#pg8000dbapibinaryvalue)
  * [Generic Exceptions](#generic-exceptions)
    * [pg8000.dbapi.Warning](#pg8000dbapiwarning)
    * [pg8000.dbapi.Error](#pg8000dbapierror)
    * [pg8000.dbapi.InterfaceError](#pg8000dbapiinterfaceerror)
    * [pg8000.dbapi.DatabaseError](#pg8000dbapidatabaseerror)
    * [pg8000.dbapi.DataError](#pg8000dbapidataerror)
    * [pg8000.dbapi.OperationalError](#pg8000dbapioperationalerror)
    * [pg8000.dbapi.IntegrityError](#pg8000dbapiintegrityerror)
    * [pg8000.dbapi.InternalError](#pg8000dbapiinternalerror)
    * [pg8000.dbapi.ProgrammingError](#pg8000dbapiprogrammingerror)
    * [pg8000.dbapi.NotSupportedError](#pg8000dbapinotsupportederror)
  * [Classes](#classes)
    * [pg8000.dbapi.Connection](#pg8000dbapiconnection)
    * [pg8000.dbapi.Connection.autocommit](#pg8000dbapiconnectionautocommit)
    * [pg8000.dbapi.Connection.close()](#pg8000dbapiconnectionclose)
    * [pg8000.dbapi.Connection.cursor()](#pg8000dbapiconnectioncursor)
    * [pg8000.dbapi.Connection.rollback()](#pg8000dbapiconnectionrollback)
    * [pg8000.dbapi.Connection.tpc\_begin(xid)](#pg8000dbapiconnectiontpc_beginxid)
    * [pg8000.dbapi.Connection.tpc_commit(xid=None)](#pg8000dbapiconnectiontpc_commitxidnone)
    * [pg8000.dbapi.Connection.tpc_prepare()](#pg8000dbapiconnectiontpc_prepare)
    * [pg8000.dbapi.Connection.tpc_recover()](#pg8000dbapiconnectiontpc_recover)
    * [pg8000.dbapi.Connection.tpc_rollback(xid=None)](#pg8000dbapiconnectiontpc_rollbackxidnone)
    * [pg8000.dbapi.Connection.xid(format_id, global_transaction_id, branch_qualifier)](#pg8000dbapiconnectionxidformat_id-global_transaction_id-branch_qualifier)
    * [pg8000.dbapi.Cursor](#pg8000dbapicursor)
      * [pg8000.dbapi.Cursor.arraysize](#pg8000dbapicursorarraysize)
      * [pg8000.dbapi.Cursor.connection](#pg8000dbapicursorconnection)
      * [pg8000.dbapi.Cursor.rowcount](#pg8000dbapicursorrowcount)
      * [pg8000.dbapi.Cursor.description](#pg8000dbapicursordescription)
      * [pg8000.dbapi.Cursor.close()](#pg8000dbapicursorclose)
      * [pg8000.dbapi.Cursor.execute(operation, args=None, stream=None)](#pg8000dbapicursorexecuteoperation-argsnone-streamnone)
      * [pg8000.dbapi.Cursor.executemany(operation, param_sets)](#pg8000dbapicursorexecutemanyoperation-param_sets)
      * [pg8000.dbapi.Cursor.callproc(procname, parameters=None)](#pg8000dbapicursorcallprocprocname-parametersnone)
      * [pg8000.dbapi.Cursor.fetchall()](#pg8000dbapicursorfetchall)
      * [pg8000.dbapi.Cursor.fetchmany(size=None)](#pg8000dbapicursorfetchmanysizenone)
      * [pg8000.dbapi.Cursor.fetchone()](#pg8000dbapicursorfetchone)
      * [pg8000.dbapi.Cursor.setinputsizes(\*sizes)](#pg8000dbapicursorsetinputsizessizes)
      * [pg8000.dbapi.Cursor.setoutputsize(size, column=None)](#pg8000dbapicursorsetoutputsizesize-columnnone)
    * [pg8000.dbapi.Interval](#pg8000dbapiinterval)
* [Design Decisions](#design-decisions)
* [Tests](#tests)
* [Doing A Release Of pg8000](#doing-a-release-of-pg8000)
* [Release Notes](#release-notes)
  * [Version 1.31.5, 2025-09-14](#version-1315-2025-09-14)
  * [Version 1.31.4, 2025-07-20](#version-1314-2025-07-20)
  * [Version 1.31.3, 2025-07-19](#version-1313-2025-07-19)
  * [Version 1.31.2, 2024-04-28](#version-1312-2024-04-28)
  * [Version 1.31.1, 2024-04-01](#version-1311-2024-04-01)
  * [Version 1.31.0, 2024-03-31](#version-1310-2024-03-31)
  * [Version 1.30.5, 2024-02-22](#version-1305-2024-02-22)
  * [Version 1.30.4, 2024-01-03](#version-1304-2024-01-03)
  * [Version 1.30.3, 2023-10-31](#version-1303-2023-10-31)
  * [Version 1.30.2, 2023-09-17](#version-1302-2023-09-17)
  * [Version 1.30.1, 2023-07-29](#version-1301-2023-07-29)
  * [Version 1.30.0, 2023-07-27](#version-1300-2023-07-27)
  * [Version 1.29.8, 2023-06-16](#version-1298-2023-06-16)
  * [Version 1.29.7, 2023-06-16](#version-1297-2023-06-16)
  * [Version 1.29.6, 2023-05-29](#version-1296-2023-05-29)
  * [Version 1.29.5, 2023-05-09](#version-1295-2023-05-09)
  * [Version 1.29.4, 2022-12-14](#version-1294-2022-12-14)
  * [Version 1.29.3, 2022-10-26](#version-1293-2022-10-26)
  * [Version 1.29.2, 2022-10-09](#version-1292-2022-10-09)
  * [Version 1.29.1, 2022-05-23](#version-1291-2022-05-23)
  * [Version 1.29.0, 2022-05-21](#version-1290-2022-05-21)
  * [Version 1.28.3, 2022-05-18](#version-1283-2022-05-18)
  * [Version 1.28.2, 2022-05-17](#version-1282-2022-05-17)
  * [Version 1.28.1, 2022-05-17](#version-1281-2022-05-17)
  * [Version 1.28.0, 2022-05-17](#version-1280-2022-05-17)
  * [Version 1.27.1, 2022-05-16](#version-1271-2022-05-16)
  * [Version 1.27.0, 2022-05-16](#version-1270-2022-05-16)
  * [Version 1.26.1, 2022-04-23](#version-1261-2022-04-23)
  * [Version 1.26.0, 2022-04-18](#version-1260-2022-04-18)
  * [Version 1.25.0, 2022-04-17](#version-1250-2022-04-17)
  * [Version 1.24.2, 2022-04-15](#version-1242-2022-04-15)
  * [Version 1.24.1, 2022-03-02](#version-1241-2022-03-02)
  * [Version 1.24.0, 2022-02-06](#version-1240-2022-02-06)
  * [Version 1.23.0, 2021-11-13](#version-1230-2021-11-13)
  * [Version 1.22.1, 2021-11-10](#version-1221-2021-11-10)
  * [Version 1.22.0, 2021-10-13](#version-1220-2021-10-13)

<!-- mtoc-end -->

## Installation

To install pg8000 using `pip` type: `pip install pg8000`


## Native API Interactive Examples

pg8000 comes with two APIs, the native pg8000 API and the DB-API 2.0 standard
API. These are the examples for the native API, and the DB-API 2.0 examples
follow in the next section.


### Basic Example

Import pg8000, connect to the database, create a table, add some rows and then
query the table:

```python
>>> import pg8000.native
>>>
>>> # Connect to the database with user name postgres
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> # Create a temporary table
>>>
>>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
>>>
>>> # Populate the table
>>>
>>> for title in ("Ender's Game", "The Magus"):
...     con.run("INSERT INTO book (title) VALUES (:title)", title=title)
>>>
>>> # Print all the rows in the table
>>>
>>> for row in con.run("SELECT * FROM book"):
...     print(row)
[1, "Ender's Game"]
[2, 'The Magus']
>>>
>>> con.close()

```


### Transactions

Here's how to run groups of SQL statements in a
[transaction](https://www.postgresql.org/docs/current/tutorial-transactions.html>):

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("START TRANSACTION")
>>>
>>> # Create a temporary table
>>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
>>>
>>> for title in ("Ender's Game", "The Magus", "Phineas Finn"):
...     con.run("INSERT INTO book (title) VALUES (:title)", title=title)
>>> con.run("COMMIT")
>>> for row in con.run("SELECT * FROM book"):
...     print(row)
[1, "Ender's Game"]
[2, 'The Magus']
[3, 'Phineas Finn']
>>>
>>> con.close()

```

rolling back a transaction:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> # Create a temporary table
>>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
>>>
>>> for title in ("Ender's Game", "The Magus", "Phineas Finn"):
...     con.run("INSERT INTO book (title) VALUES (:title)", title=title)
>>>
>>> con.run("START TRANSACTION")
>>> con.run("DELETE FROM book WHERE title = :title", title="Phineas Finn") 
>>> con.run("ROLLBACK")
>>> for row in con.run("SELECT * FROM book"):
...     print(row)
[1, "Ender's Game"]
[2, 'The Magus']
[3, 'Phineas Finn']
>>>
>>> con.close()

```

NB. There is [a longstanding bug](https://codeberg.org/tlocke/pg8000/issues/36) in the
PostgreSQL server whereby if a `COMMIT` is issued against a failed transaction, the
transaction is silently rolled back, rather than an error being returned. pg8000
attempts to detect when this has happened and raise an `InterfaceError`.


### Query Using Functions

Another query, using some PostgreSQL functions:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')")
[['2021 AD']]
>>>
>>> con.close()

```


### Interval Type

A query that returns the PostgreSQL interval type:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> import datetime
>>>
>>> ts = datetime.date(1980, 4, 27)
>>> con.run("SELECT timestamp '2013-12-01 16:06' - :ts", ts=ts)
[[datetime.timedelta(days=12271, seconds=57960)]]
>>>
>>> con.close()

```


### Point Type

A round-trip with a
[PostgreSQL point](https://www.postgresql.org/docs/current/datatype-geometric.html)
type:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT CAST(:pt as point)", pt=(2.3,1))
[[(2.3, 1.0)]]
>>>
>>> con.close()

```


### Client Encoding

When communicating with the server, pg8000 uses the character set that the server asks
it to use (the client encoding). By default the client encoding is the database's
character set (chosen when the database is created), but the client encoding can be
changed in a number of ways (eg. setting `CLIENT_ENCODING` in `postgresql.conf`).
Another way of changing the client encoding is by using an SQL command. For example:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SET CLIENT_ENCODING TO 'UTF8'")
>>> con.run("SHOW CLIENT_ENCODING")
[['UTF8']]
>>>
>>> con.close()

```

### JSON

[JSON](https://www.postgresql.org/docs/current/datatype-json.html) always comes back
from the server de-serialized. If the JSON you want to send is a ``dict`` then you can
just do:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}
>>> con.run("SELECT CAST(:apollo as jsonb)", apollo=val)
[[{'age': 26.003, 'name': 'Apollo 11 Cave', 'zebra': True}]]
>>>
>>> con.close()

```

JSON can always be sent in serialized form to the server:

```python
>>> import json
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>>
>>> val = ['Apollo 11 Cave', True, 26.003]
>>> con.run("SELECT CAST(:apollo as jsonb)", apollo=json.dumps(val))
[[['Apollo 11 Cave', True, 26.003]]]
>>>
>>> con.close()

```

JSON queries can be have parameters:

```python
>>> import pg8000.native
>>>
>>> with pg8000.native.Connection("postgres", password="cpsnow") as con:
...     con.run(""" SELECT CAST('{"a":1, "b":2}' AS jsonb) @> :v """, v={"b": 2})
[[True]]

```


### Retrieve Column Metadata From Results

Find the column metadata returned from a query:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("create temporary table quark (id serial, name text)")
>>> for name in ('Up', 'Down'):
...     con.run("INSERT INTO quark (name) VALUES (:name)", name=name)
>>> # Now execute the query
>>>
>>> con.run("SELECT * FROM quark")
[[1, 'Up'], [2, 'Down']]
>>>
>>> # and retrieve the metadata
>>>
>>> con.columns
[{'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'}]
>>>
>>> # Show just the column names
>>>
>>> [c['name'] for c in con.columns]
['id', 'name']
>>>
>>> con.close()

```


### Notices And Notifications

PostgreSQL [notices
](https://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html) are
stored in a deque called `Connection.notices` and added using the `append()` method.
Similarly there are `Connection.notifications` for [notifications
](https://www.postgresql.org/docs/current/static/sql-notify.html). Here's an example:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("LISTEN aliens_landed")
>>> con.run("NOTIFY aliens_landed")
>>> # A notification is a tuple containing (backend_pid, channel, payload)
>>>
>>> con.notifications[0]
(..., 'aliens_landed', '')
>>>
>>> con.close()

```


### Parameter Statuses

[Certain parameter values are reported by the server automatically at connection startup or whenever
their values change
](https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQPARAMETERSTATUS>) and
pg8000 stores the latest values in a dict called `Connection.parameter_statuses`. Here's
an example where we set the `aplication_name` parameter and then read it from the
`parameter_statuses`:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection(
...     "postgres", password="cpsnow", application_name='AGI')
>>>
>>> con.parameter_statuses['application_name']
'AGI'
>>>
>>> con.close()

```


### LIMIT ALL

You might think that the following would work, but in fact it fails:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT 'silo 1' LIMIT :lim", lim='ALL')
Traceback (most recent call last):
pg8000.exceptions.DatabaseError: ...
>>>
>>> con.close()

```

Instead the [docs say](https://www.postgresql.org/docs/current/sql-select.html) that you
can send `null` as an alternative to `ALL`, which does work:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT 'silo 1' LIMIT :lim", lim=None)
[['silo 1']]
>>>
>>> con.close()

```


### IN and NOT IN

You might think that the following would work, but in fact the server doesn't like it:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT 'silo 1' WHERE 'a' IN :v", v=['a', 'b'])
Traceback (most recent call last):
pg8000.exceptions.DatabaseError: ...
>>>
>>> con.close()

```

the most straightforward way to get around this problem is to rewrie the query using the [`ANY`](
https://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-ANY-SOME)
function:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT 'silo 1' WHERE 'a' = ANY(:v)", v=['a', 'b'])
[['silo 1']]
>>> con.close()

```

However, using the array variant of `ANY` [may cause a performance problem](
https://stackoverflow.com/questions/34627026/in-vs-any-operator-in-postgresql/34627688#34627688)
and so you can use the [subquery variant of `IN`](
https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-IN)
with the [unnest
](https://www.postgresql.org/docs/current/functions-array.html) function:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run(
...     "SELECT 'silo 1' WHERE 'a' IN (SELECT unnest(CAST(:v as varchar[])))",
...     v=['a', 'b'])
[['silo 1']]
>>> con.close()

```

and you can do the same for `NOT IN`.


### Many SQL Statements Can't Be Parameterized

In PostgreSQL parameters can only be used for [data values, not identifiers
](https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS).
Sometimes this might not work as expected, for example the following fails:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> channel = 'top_secret'
>>>
>>> con.run("LISTEN :channel", channel=channel)
Traceback (most recent call last):
pg8000.exceptions.DatabaseError: ...
>>>
>>> con.close()

```

It fails because the PostgreSQL server doesn't allow this statement to have any
parameters. There are many SQL statements that one might think would have parameters,
but don't. For these cases the SQL has to be created manually, being careful to use the
`identifier()` and `literal()` functions to escape the values to avoid [SQL injection
attacks](https://en.wikipedia.org/wiki/SQL_injection>):

```python
>>> from pg8000.native import Connection, identifier, literal
>>>
>>> con = Connection("postgres", password="cpsnow")
>>>
>>> channel = 'top_secret'
>>> payload = 'Aliens Landed!'
>>> con.run(f"LISTEN {identifier(channel)}")
>>> con.run(f"NOTIFY {identifier(channel)}, {literal(payload)}")
>>>
>>> con.notifications[0]
(..., 'top_secret', 'Aliens Landed!')
>>>
>>> con.close()

```


### COPY FROM And TO A Stream

The SQL [COPY](https://www.postgresql.org/docs/current/sql-copy.html) statement can be
used to copy from and to a file or file-like object. Here's an example using the CSV
format:

```python
>>> import pg8000.native
>>> from io import StringIO
>>> import csv
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> # Create a CSV file in memory
>>>
>>> stream_in = StringIO()
>>> csv_writer = csv.writer(stream_in)
>>> csv_writer.writerow([1, "electron"])
12
>>> csv_writer.writerow([2, "muon"])
8
>>> csv_writer.writerow([3, "tau"])
7
>>> stream_in.seek(0)
0
>>>
>>> # Create a table and then copy the CSV into it
>>>
>>> con.run("CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)")
>>> con.run("COPY lepton FROM STDIN WITH (FORMAT CSV)", stream=stream_in)
>>>
>>> # COPY from a table to a stream
>>>
>>> stream_out = StringIO()
>>> con.run("COPY lepton TO STDOUT WITH (FORMAT CSV)", stream=stream_out)
>>> stream_out.seek(0)
0
>>> for row in csv.reader(stream_out):
...     print(row)
['1', 'electron']
['2', 'muon']
['3', 'tau']
>>>
>>> con.close()

```

It's also possible to COPY FROM an iterable, which is useful if you're creating rows
programmatically:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> # Generator function for creating rows
>>> def row_gen():
...     for i, name in ((1, "electron"), (2, "muon"), (3, "tau")):
...         yield f"{i},{name}\n"
>>>
>>> # Create a table and then copy the CSV into it
>>>
>>> con.run("CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)")
>>> con.run("COPY lepton FROM STDIN WITH (FORMAT CSV)", stream=row_gen())
>>>
>>> # COPY from a table to a stream
>>>
>>> stream_out = StringIO()
>>> con.run("COPY lepton TO STDOUT WITH (FORMAT CSV)", stream=stream_out)
>>> stream_out.seek(0)
0
>>> for row in csv.reader(stream_out):
...     print(row)
['1', 'electron']
['2', 'muon']
['3', 'tau']
>>>
>>> con.close()

```


### Execute Multiple SQL Statements

If you want to execute a series of SQL statements (eg. an `.sql` file), you can run
them as expected:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> statements = "SELECT 5; SELECT 'Erich Fromm';"
>>>
>>> con.run(statements)
[[5], ['Erich Fromm']]
>>>
>>> con.close()

```

The only caveat is that when executing multiple statements you can't have any
parameters.


### Quoted Identifiers in SQL

Say you had a column called `My Column`. Since it's case sensitive and contains a space,
you'd have to [surround it by double quotes
](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIER).
But you can't do:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("select 'hello' as "My Column"")
Traceback (most recent call last):
SyntaxError: invalid syntax...
>>>
>>> con.close()

```

since Python uses double quotes to delimit string literals, so one solution is
to use Python's [triple quotes
](https://docs.python.org/3/tutorial/introduction.html#strings) to delimit the string
instead:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run('''SELECT 'hello' AS "My Column"''')
[['hello']]
>>>
>>> con.close()

```

another solution, that's especially useful if the identifier comes from an untrusted
source, is to use the `identifier()` function, which correctly quotes and escapes the
identifier as needed:

```python
>>> from pg8000.native import Connection, identifier
>>>
>>> con = Connection("postgres", password="cpsnow")
>>>
>>> sql = f"SELECT 'hello' as {identifier('My Column')}"
>>> print(sql)
SELECT 'hello' as "My Column"
>>>
>>> con.run(sql)
[['hello']]
>>>
>>> con.close()

```

this approach guards against [SQL injection attacks
](https://en.wikipedia.org/wiki/SQL_injection). One thing to note if you're using
explicit schemas (eg. `pg_catalog.pg_language`) is that the schema name and table name
are both separate identifiers. So to escape them you'd do:

```python
>>> from pg8000.native import Connection, identifier
>>>
>>> con = Connection("postgres", password="cpsnow")
>>>
>>> query = (
...     f"SELECT lanname FROM {identifier('pg_catalog')}.{identifier('pg_language')} "
...     f"WHERE lanname = 'sql'"
... )
>>> print(query)
SELECT lanname FROM "pg_catalog"."pg_language" WHERE lanname = 'sql'
>>>
>>> con.run(query)
[['sql']]
>>>
>>> con.close()

```


### Custom adapter from a Python type to a PostgreSQL type

pg8000 has a mapping from Python types to PostgreSQL types for when it needs to send
SQL parameters to the server. The default mapping that comes with pg8000 is designed to
work well in most cases, but you might want to add or replace the default mapping.

A Python `datetime.timedelta` object is sent to the server as a PostgreSQL
`interval` type,  which has the `oid` 1186. But let's say we wanted to create our
own Python class to be sent as an `interval` type. Then we'd have to register an
adapter:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> class MyInterval(str):
...     pass
>>>
>>> def my_interval_out(my_interval):
...     return my_interval  # Must return a str
>>>
>>> con.register_out_adapter(MyInterval, my_interval_out)
>>> con.run("SELECT CAST(:interval as interval)", interval=MyInterval("2 hours"))
[[datetime.timedelta(seconds=7200)]]
>>>
>>> con.close()

```

Note that it still came back as a `datetime.timedelta` object because we only changed
the mapping from Python to PostgreSQL. See below for an example of how to change the
mapping from PostgreSQL to Python.


### Custom adapter from a PostgreSQL type to a Python type

pg8000 has a mapping from PostgreSQL types to Python types for when it receives SQL
results from the server. The default mapping that comes with pg8000 is designed to work
well in most cases, but you might want to add or replace the default mapping.

If pg8000 receives PostgreSQL `interval` type, which has the `oid` 1186, it converts
it into a Python `datetime.timedelta` object. But let's say we wanted to create our
own Python class to be used instead of `datetime.timedelta`. Then we'd have to
register an adapter:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> class MyInterval(str):
...     pass
>>>
>>> def my_interval_in(my_interval_str):  # The parameter is of type str
...     return MyInterval(my_interval)
>>>
>>> con.register_in_adapter(1186, my_interval_in)
>>> con.run("SELECT \'2 years'")
[['2 years']]
>>>
>>> con.close()

```

Note that registering the 'in' adapter only afects the mapping from the PostgreSQL type
to the Python type. See above for an example of how to change the mapping from
PostgreSQL to Python.


### Could Not Determine Data Type Of Parameter

Sometimes you'll get the `could not determine data type of parameter` error message from
the server:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT :v IS NULL", v=None)
Traceback (most recent call last):
pg8000.exceptions.DatabaseError: {'S': 'ERROR', 'V': 'ERROR', 'C': '42P18', 'M': 'could not determine data type of parameter $1', 'F': 'postgres.c', 'L': '...', 'R': '...'}
>>>
>>> con.close()

```

One way of solving it is to put a `CAST` in the SQL:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT cast(:v as TIMESTAMP) IS NULL", v=None)
[[True]]
>>>
>>> con.close()

```

Another way is to override the type that pg8000 sends along with each parameter:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> con.run("SELECT :v IS NULL", v=None, types={'v': pg8000.native.TIMESTAMP})
[[True]]
>>>
>>> con.close()

```


### Prepared Statements

[Prepared statements](https://www.postgresql.org/docs/current/sql-prepare.html) can be
useful in improving performance when you have a statement that's executed repeatedly.
Here's an example:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection("postgres", password="cpsnow")
>>>
>>> # Create the prepared statement
>>> ps = con.prepare("SELECT cast(:v as varchar)")
>>>
>>> # Execute the statement repeatedly
>>> ps.run(v="speedy")
[['speedy']]
>>> ps.run(v="rapid")
[['rapid']]
>>> ps.run(v="swift")
[['swift']]
>>>
>>> # Close the prepared statement, releasing resources on the server
>>> ps.close()
>>>
>>> con.close()

```


### Use Environment Variables As Connection Defaults

You might want to use the current user as the database username for example:

```python
>>> import pg8000.native
>>> import getpass
>>>
>>> # Connect to the database with current user name
>>> username = getpass.getuser()
>>> connection = pg8000.native.Connection(username, password="cpsnow")
>>>
>>> connection.run("SELECT 'pilau'")
[['pilau']]
>>>
>>> connection.close()

```

or perhaps you may want to use some of the same [environment variables that libpg uses
](https://www.postgresql.org/docs/current/libpq-envars.html):

```python
>>> import pg8000.native
>>> from os import environ
>>>
>>> username = environ.get('PGUSER', 'postgres')
>>> password = environ.get('PGPASSWORD', 'cpsnow')
>>> host = environ.get('PGHOST', 'localhost')
>>> port = environ.get('PGPORT', '5432')
>>> database = environ.get('PGDATABASE')
>>>
>>> connection = pg8000.native.Connection(
...     username, password=password, host=host, port=port, database=database)
>>>
>>> connection.run("SELECT 'Mr Cairo'")
[['Mr Cairo']]
>>>
>>> connection.close()

```

It might be asked, why doesn't pg8000 have this behaviour built in? The thinking
follows the second aphorism of [The Zen of Python
](https://www.python.org/dev/peps/pep-0020/):

> Explicit is better than implicit.

So we've taken the approach of only being able to set connection parameters using the
`pg8000.native.Connection()` constructor.


### Connect To PostgreSQL Over SSL

By default the `ssl_context` connection parameter has the value `None` which means pg8000 will
attempt to connect to the server using SSL, and then fall back to a plain socket if the server
refuses SSL. If you want to *require* SSL (ie. to fail if it's not achieved) then you can set
`ssl_context=True`:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection('postgres', password="cpsnow", ssl_context=True)
>>> con.run("SELECT 'The game is afoot!'")
[['The game is afoot!']]
>>> con.close()

```

If on the other hand you want to connect over SSL with custom settings, set the `ssl_context`
parameter to an [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) object:

```python
>>> import pg8000.native
>>> import ssl
>>>
>>> ssl_context = ssl.create_default_context()
>>> ssl_context.check_hostname = False
>>> ssl_context.verify_mode = ssl.CERT_NONE
>>> con = pg8000.native.Connection(
...     'postgres', password="cpsnow", ssl_context=ssl_context)
>>> con.run("SELECT 'Work is the curse of the drinking classes.'")
[['Work is the curse of the drinking classes.']]
>>> con.close()

```

It may be that your PostgreSQL server is behind an SSL proxy server in which case you
can give pg8000 the SSL socket with the `sock` parameter, and then set
`ssl_context=False` which means that no attempt will be made to create an SSL connection
to the server.


### Server-Side Cursors

You can use the SQL commands [DECLARE
](https://www.postgresql.org/docs/current/sql-declare.html),
[FETCH](https://www.postgresql.org/docs/current/sql-fetch.html),
[MOVE](https://www.postgresql.org/docs/current/sql-move.html) and
[CLOSE](https://www.postgresql.org/docs/current/sql-close.html) to manipulate
server-side cursors. For example:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection('postgres', password="cpsnow")
>>> con.run("START TRANSACTION")
>>> con.run("DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)")
>>> con.run("FETCH FORWARD 5 FROM c")
[[1], [2], [3], [4], [5]]
>>> con.run("MOVE FORWARD 50 FROM c")
>>> con.run("FETCH BACKWARD 10 FROM c")
[[54], [53], [52], [51], [50], [49], [48], [47], [46], [45]]
>>> con.run("CLOSE c")
>>> con.run("ROLLBACK")
>>>
>>> con.close()

```


### BLOBs (Binary Large Objects)

There's a set of [SQL functions
](https://www.postgresql.org/docs/current/lo-funcs.html) for manipulating BLOBs.
Here's an example:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection('postgres', password="cpsnow")
>>>
>>> # Create a BLOB and get its oid
>>> data = b'hello'
>>> res = con.run("SELECT lo_from_bytea(0, :data)", data=data)
>>> oid = res[0][0]
>>>
>>> # Create a table and store the oid of the BLOB
>>> con.run("CREATE TEMPORARY TABLE image (raster oid)")
>>>
>>> con.run("INSERT INTO image (raster) VALUES (:oid)", oid=oid)
>>> # Retrieve the data using the oid
>>> con.run("SELECT lo_get(:oid)", oid=oid)
[[b'hello']]
>>>
>>> # Add some data to the end of the BLOB
>>> more_data = b' all'
>>> offset = len(data)
>>> con.run(
...     "SELECT lo_put(:oid, :offset, :data)",
...     oid=oid, offset=offset, data=more_data)
[['']]
>>> con.run("SELECT lo_get(:oid)", oid=oid)
[[b'hello all']]
>>>
>>> # Download a part of the data
>>> con.run("SELECT lo_get(:oid, 6, 3)", oid=oid)
[[b'all']]
>>>
>>> con.close()

```


### Replication Protocol

The PostgreSQL [Replication Protocol
](https://www.postgresql.org/docs/current/protocol-replication.html) is supported using
the `replication` keyword when creating a connection:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection(
...    'postgres', password="cpsnow", replication="database")
>>>
>>> con.run("IDENTIFY_SYSTEM")
[['...', 1, '.../...', 'postgres']]
>>>
>>> con.close()

```

### Extra Startup Parameters

The standard startup parameters `user`, `database` and `replication` are set with their
own parameters in the `Connection()` constructor. However, as the
[docs](https://www.postgresql.org/docs/current/protocol-message-formats.html) say:

> In addition to the above, other parameters may be listed. Parameter names beginning
> with \_pq\_. are reserved for use as protocol extensions, while others are treated as
> run-time parameters to be set at backend start time. Such settings will be applied
> during backend start (after parsing the command-line arguments if any) and will act as
> session defaults.

these additional parameters can be specified using the `startup_params` parameter of the
`Connection()` constructor:

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection(
...    'postgres', password="cpsnow", startup_params={'IntervalStyle': 'sql_standard'})
>>>
>>> con.run("SHOW IntervalStyle")
[['sql_standard']]
>>>
>>> con.close()

```

### PostgreSQL-Style Parameter Placeholders

```python
>>> import pg8000.native
>>>
>>> con = pg8000.native.Connection('postgres', password="cpsnow")
>>>
>>> con.run("SELECT $1", title='A Time Of Hope')
[['A Time Of Hope']]
>>>
>>> con.close()

```


## DB-API 2 Interactive Examples

These examples stick to the DB-API 2.0 standard.


### Basic Example

Import pg8000, connect to the database, create a table, add some rows and then query the
table:

```python
>>> import pg8000.dbapi
>>>
>>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = conn.cursor()
>>> cursor.execute("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
>>> cursor.execute(
...     "INSERT INTO book (title) VALUES (%s), (%s) RETURNING id, title",
...     ("Ender's Game", "Speaker for the Dead"))
>>> results = cursor.fetchall()
>>> for row in results:
...     id, title = row
...     print("id = %s, title = %s" % (id, title))
id = 1, title = Ender's Game
id = 2, title = Speaker for the Dead
>>> conn.commit()
>>>
>>> conn.close()

```


### Query Using Functions

Another query, using some PostgreSQL functions:

```python
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = con.cursor()
>>>
>>> cursor.execute("SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')")
>>> cursor.fetchone()
['2021 AD']
>>>
>>> con.close()

```


### Interval Type

A query that returns the PostgreSQL interval type:

```python
>>> import datetime
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = con.cursor()
>>>
>>> cursor.execute("SELECT timestamp '2013-12-01 16:06' - %s",
... (datetime.date(1980, 4, 27),))
>>> cursor.fetchone()
[datetime.timedelta(days=12271, seconds=57960)]
>>>
>>> con.close()

```


### Point Type

A round-trip with a [PostgreSQL point
](https://www.postgresql.org/docs/current/datatype-geometric.html) type:

```python
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = con.cursor()
>>>
>>> cursor.execute("SELECT cast(%s as point)", ((2.3,1),))
>>> cursor.fetchone()
[(2.3, 1.0)]
>>>
>>> con.close()

```


### Numeric Parameter S