pg8000


Namepg8000 JSON
Version 1.31.2 PyPI version JSON
download
home_pageNone
SummaryPostgreSQL interface library
upload_time2024-04-28 16:57:47
maintainerNone
docs_urlNone
authorThe Contributors
requires_python>=3.8
licenseBSD 3-Clause License
keywords dbapi postgresql
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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/). It is tested on Python versions
3.8+, on CPython and PyPy, and PostgreSQL versions 12+. 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.

All bug reports, feature requests and contributions are welcome at
[http://github.com/tlocke/pg8000/](http://github.com/tlocke/pg8000/).

[![Workflow Status Badge](https://github.com/tlocke/pg8000/workflows/pg8000/badge.svg)](https://github.com/tlocke/pg8000/actions)

## 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://github.com/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()

```


## 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 Style

pg8000 supports all the DB-API parameter styles. Here's an example of using the
'numeric' parameter style:

```python
>>> import pg8000.dbapi
>>>
>>> pg8000.dbapi.paramstyle = "numeric"
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = con.cursor()
>>>
>>> cursor.execute("SELECT array_prepend(:1, CAST(:2 AS int[]))", (500, [1, 2, 3, 4],))
>>> cursor.fetchone()
[[500, 1, 2, 3, 4]]
>>> pg8000.dbapi.paramstyle = "format"
>>>
>>> con.close()

```


### Autocommit

Following the DB-API specification, autocommit is off by default. It can be turned on by
using the autocommit property of the connection:

```python
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> con.autocommit = True
>>>
>>> cur = con.cursor()
>>> cur.execute("vacuum")
>>> conn.autocommit = False
>>> cur.close()
>>>
>>> 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.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>> cur.execute("SET CLIENT_ENCODING TO 'UTF8'")
>>> cur.execute("SHOW CLIENT_ENCODING")
>>> cur.fetchone()
['UTF8']
>>> cur.close()
>>>
>>> con.close()

```


### JSON

JSON is sent to the server serialized, and returned de-serialized. Here's an example:

```python
>>> import json
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>> val = ['Apollo 11 Cave', True, 26.003]
>>> cur.execute("SELECT cast(%s as json)", (json.dumps(val),))
>>> cur.fetchone()
[['Apollo 11 Cave', True, 26.003]]
>>> cur.close()
>>>
>>> con.close()

```

JSON queries can be have parameters:

```python
>>> import pg8000.dbapi
>>>
>>> with pg8000.dbapi.connect("postgres", password="cpsnow") as con:
...     cur = con.cursor()
...     cur.execute(""" SELECT CAST('{"a":1, "b":2}' AS jsonb) @> %s """, ({"b": 2},))
...     for row in cur.fetchall():
...         print(row)
[True]

```


### Retrieve Column Names From Results

Use the columns names retrieved from a query:

```python
>>> import pg8000
>>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> c = conn.cursor()
>>> c.execute("create temporary table quark (id serial, name text)")
>>> c.executemany("INSERT INTO quark (name) VALUES (%s)", (("Up",), ("Down",)))
>>> #
>>> # Now retrieve the results
>>> #
>>> c.execute("select * from quark")
>>> rows = c.fetchall()
>>> keys = [k[0] for k in c.description]
>>> results = [dict(zip(keys, row)) for row in rows]
>>> assert results == [{'id': 1, 'name': 'Up'}, {'id': 2, 'name': 'Down'}]
>>>
>>> conn.close()

```


### COPY from and to a file

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:

```python
>>> from io import StringIO
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>> #
>>> # COPY from a stream to a table
>>> #
>>> stream_in = StringIO('1\telectron\n2\tmuon\n3\ttau\n')
>>> cur = con.cursor()
>>> cur.execute("create temporary table lepton (id serial, name text)")
>>> cur.execute("COPY lepton FROM stdin", stream=stream_in)
>>> #
>>> # Now COPY from a table to a stream
>>> #
>>> stream_out = StringIO()
>>> cur.execute("copy lepton to stdout", stream=stream_out)
>>> stream_out.getvalue()
'1\telectron\n2\tmuon\n3\ttau\n'
>>>
>>> con.close()

```


### 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.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>> cur.execute("START TRANSACTION")
>>> cur.execute(
...    "DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)")
>>> cur.execute("FETCH FORWARD 5 FROM c")
>>> cur.fetchall()
([1], [2], [3], [4], [5])
>>> cur.execute("MOVE FORWARD 50 FROM c")
>>> cur.execute("FETCH BACKWARD 10 FROM c")
>>> cur.fetchall()
([54], [53], [52], [51], [50], [49], [48], [47], [46], [45])
>>> cur.execute("CLOSE c")
>>> cur.execute("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.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>>
>>> # Create a BLOB and get its oid
>>> data = b'hello'
>>> cur = con.cursor()
>>> cur.execute("SELECT lo_from_bytea(0, %s)", [data])
>>> oid = cur.fetchone()[0]
>>>
>>> # Create a table and store the oid of the BLOB
>>> cur.execute("CREATE TEMPORARY TABLE image (raster oid)")
>>> cur.execute("INSERT INTO image (raster) VALUES (%s)", [oid])
>>>
>>> # Retrieve the data using the oid
>>> cur.execute("SELECT lo_get(%s)", [oid])
>>> cur.fetchall()
([b'hello'],)
>>>
>>> # Add some data to the end of the BLOB
>>> more_data = b' all'
>>> offset = len(data)
>>> cur.execute("SELECT lo_put(%s, %s, %s)", [oid, offset, more_data])
>>> cur.execute("SELECT lo_get(%s)", [oid])
>>> cur.fetchall()
([b'hello all'],)
>>>
>>> # Download a part of the data
>>> cur.execute("SELECT lo_get(%s, 6, 3)", [oid])
>>> cur.fetchall()
([b'all'],)
>>>
>>> con.close()

```


### Parameter Limit

The protocol that PostgreSQL uses limits the number of parameters to 6,5535. The following will give
an error:

```python
>>> import pg8000.dbapi
>>>
>>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = conn.cursor()
>>> SIZE = 100000
>>> cursor.execute(
...    f"SELECT 1 WHERE 1 IN ({','.join(['%s'] * SIZE)})",
...    [1] * SIZE,
... )
Traceback (most recent call last):
struct.error: 'H' format requires 0 <= number <= 65535

```

One way of working round this problem is to use the [unnest
](https://www.postgresql.org/docs/current/functions-array.html) function:

```python
>>> import pg8000.dbapi
>>>
>>> conn = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cursor = conn.cursor()
>>> SIZE = 100000
>>> cursor.execute(
...    "SELECT 1 WHERE 1 IN (SELECT unnest(CAST(%s AS int[])))",
...    [[1] * SIZE],
... )
>>> conn.close()

```


## Type Mapping

The following table shows the default mapping between Python types and PostgreSQL types,
and vice versa.

If pg8000 doesn't recognize a type that it receives from PostgreSQL, it will return it
as a ``str`` type. This is how pg8000 handles PostgreSQL ``enum`` and XML types. It's
possible to change the default mapping using adapters (see the examples).

| Python Type           | PostgreSQL Type | Notes                                   |
|-----------------------|-----------------|-----------------------------------------|
| bool                  | bool            |                                         |
| int                   | int4            |                                         |
| str                   | text            |                                         |
| float                 | float8          |                                         |
| decimal.Decimal       | numeric         |                                         |
| bytes                 | bytea           |                                         |
| datetime.datetime (without tzinfo) | timestamp without timezone | +/-infinity PostgreSQL values are represented as Python `str` values. If a `timestamp` is too big for `datetime.datetime` then a `str` is used. |
| datetime.datetime (with tzinfo) | timestamp with timezone | +/-infinity PostgreSQL values are represented as Python `str` values. If a `timestamptz` is too big for `datetime.datetime` then a `str` is used. |
| datetime.date | date | +/-infinity PostgreSQL values are represented as Python `str` values. If a `date` is too big for a `datetime.date` then a `str` is used. |
| datetime.time         | time without time zone |                                  |
| datetime.timedelta | interval | If an ``interval`` is too big for `datetime.timedelta` then a `PGInterval`  is used. |
| None                  | NULL            |                                         |
| uuid.UUID             | uuid            |                                         |
| ipaddress.IPv4Address | inet            |                                         |
| ipaddress.IPv6Address | inet            |                                         |
| ipaddress.IPv4Network | inet            |                                         |
| ipaddress.IPv6Network | inet            |                                         |
| int                   | xid             |                                         |
| list of int           | INT4[]          |                                         |
| list of float         | FLOAT8[]        |                                         |
| list of bool          | BOOL[]          |                                         |
| list of str           | TEXT[]          |                                         |
| int                   | int2vector      | Only from PostgreSQL to Python          |
| JSON                  | json, jsonb     | The Python JSON is provided as a Python serialized string. Results returned as de-serialized JSON. |
| pg8000.Range | range | PostgreSQL multirange types are | represented in Python as a list of  range types. |
| tuple                 | composite type  | Only from Python to PostgreSQL          |


## Theory Of Operation

> A concept is tolerated inside the microkernel only if moving it outside the kernel,
> i.e., permitting competing implementations, would prevent the implementation of the
> system's required functionality.
>
> -- Jochen Liedtke, Liedtke's minimality principle

pg8000 is designed to be used with one thread per connection.

pg8000 communicates with the database using the [PostgreSQL Frontend/Backend Protocol
](https://www.postgresql.org/docs/current/protocol.html) (FEBE). If a query has no
parameters, pg8000 uses the 'simple query protocol'. If a query does have parameters,
pg8000 uses the 'extended query protocol' with unnamed prepared statements. The steps
for a query with parameters are:

1. Query comes in.

2. Send a PARSE message to the server to create an unnamed prepared statement.

3. Send a BIND message to run against the unnamed prepared statement, resulting in an
   unnamed portal on the server.

4. Send an EXECUTE message to read all the results from the portal.

It's also possible to use named prepared statements. In which case the prepared
statement persists on the server, and represented in pg8000 using a
`PreparedStatement` object. This means that the PARSE step gets executed once up
front, and then only the BIND and EXECUTE steps are repeated subsequently.

There are a lot of PostgreSQL data types, but few primitive data types in Python. By
default, pg8000 doesn't send PostgreSQL data type information in the PARSE step, in
which case PostgreSQL assumes the types implied by the SQL statement. In some cases
PostgreSQL can't work out a parameter type and so an [explicit cast
](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS)
can be used in the SQL.

In the FEBE protocol, each query parameter can be sent to the server either as binary
or text according to the format code. In pg8000 the parameters are always sent as text.

Occasionally, the network connection between pg8000 and the server may go down. If
pg8000 encounters a network problem it'll raise an `InterfaceError` with the message
`network error` and with the original exception set as the [cause
](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement).


## Native API Docs

### pg8000.native.Error

Generic exception that is the base exception of the other error exceptions.


### pg8000.native.InterfaceError

For errors that originate within pg8000.


### pg8000.native.DatabaseError

For errors that originate from the server.

### 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)

Creates a connection to a PostgreSQL database.

- *user* - The username to connect to the PostgreSQL server with. If your server character encoding is not `ascii` or `utf8`, then you need to provide `user` as bytes, eg. `'my_name'.encode('EUC-JP')`.
- *host* - The hostname of the PostgreSQL server to connect with. Providing this parameter is necessary for TCP/IP connections. One of either `host` or `unix_sock` must be provided. The default is `localhost`.
- *database* - The name of the database instance to connect with. If `None` then the PostgreSQL server will assume the database name is the same as the username. If your server character encoding is not `ascii` or `utf8`, then you need to provide `database` as bytes, eg. `'my_db'.encode('EUC-JP')`.
- *port* - The TCP/IP port of the PostgreSQL server instance.  This parameter defaults to `5432`, the registered common port of PostgreSQL TCP/IP servers.
- *password* - The user password to connect to the server with. This parameter is optional; if omitted and the database server requests password-based authentication, the connection will fail to open. If this parameter is provided but not requested by the server, no error will occur. If your server character encoding is not `ascii` or `utf8`, then you need to provide `password` as bytes, eg.  `'my_password'.encode('EUC-JP')`.
- *source_address* - The source IP address which initiates the connection to the PostgreSQL server. The default is `None` which means that the operating system will choose the source address.
- *unix_sock* - The path to the UNIX socket to access the database through, for example, `'/tmp/.s.PGSQL.5432'`. One of either `host` or `unix_sock` must be provided.
- *ssl_context* - This governs SSL encryption for TCP/IP sockets. It can have four values:
  - `None`, the default, meaning that an attempt will be made to connect over SSL, but if this is rejected by the server then pg8000 will fall back to using a plain socket.
  - `True`, means use SSL with an `ssl.SSLContext` with the minimum of checks.
  - `False`, means to not attempt to create an SSL socket.
  - An instance of `ssl.SSLContext` which will be used to create the SSL connection.
- *timeout* - This is the time in seconds before the connection to the server will time out. The default is `None` which means no timeout.
- *tcp_keepalive* - If `True` then use [TCP keepalive](https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive). The default is `True`.
- *application_name* - Sets the [application\_name](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 provide values as bytes, eg.  `'my_application_name'.encode('EUC-JP')`. The default is `None` which means that the server will set the application name.
- *replication* - Used to run in [streaming replication mode](https://www.postgresql.org/docs/current/protocol-replication.html). If your server character encoding is not `ascii` or `utf8`, then you need to provide values as bytes, eg. `'database'.encode('EUC-JP')`.
- *sock*  - A socket-like object to use for the connection. For example, `sock` could be a plain `socket.socket`, or it could represent an SSH tunnel or perhaps an `ssl.SSLSocket` to an SSL proxy. If an `ssl.SSLContext` is provided, then it will be used to attempt to create an SSL socket from the provided socket. 

### pg8000.native.Connection.notifications

A deque of server-side
[notifications](https://www.postgresql.org/docs/current/sql-notify.html) received by
this database connection (via the `LISTEN` / `NOTIFY` PostgreSQL commands). Each list
item is a three-element tuple containing the PostgreSQL backend PID that issued the
notify, the channel and the payload.


### pg8000.native.Connection.notices

A deque of server-side notices received by this database connection.


### pg8000.native.Connection.parameter\_statuses

A `dict` of server-side parameter statuses received by this database connection.


### pg8000.native.Connection.run(sql, stream=None, types=None, \*\*kwargs)

Executes an sql statement, and returns the results as a `list`. For example:

```
con.run("SELECT * FROM cities where population > :pop", pop=10000)
```

- *sql* - The SQL statement to execute. Parameter placeholders appear as a `:` followed by the parameter name.
- *stream* - For use with the PostgreSQL [COPY](http://www.postgresql.org/docs/current/static/sql-copy.html) command. The nature of the parameter depends on whether the SQL command is `COPY FROM` or `COPY TO`.
  - `COPY FROM` - The stream parameter must be a readable file-like object or an iterable. If it's an
    iterable then the items can be ``str`` or binary.
  - `COPY TO` - The stream parameter must be a writable file-like object.
- *types* - A dictionary of oids. A key corresponds to a parameter. 
- *kwargs* - The parameters of the SQL statement.


### pg8000.native.Connection.row\_count

This read-only attribute contains the number of rows that the last `run()` method
produced (for query statements like ``SELECT``) or affected (for modification statements
like `UPDATE`.

The value is -1 if:

- No `run()` method has been performed yet.
- There was no rowcount associated with the last `run()`.


### pg8000.native.Connection.columns

A list of column metadata. Each item in the list is a dictionary with the following
keys:

- name
- table\_oid
- column\_attrnum
- type\_oid
- type\_size
- type\_modifier
- format


### pg8000.native.Connection.close()

Closes the database connection.


### pg8000.native.Connection.register\_out\_adapter(typ, out\_func)

Register a type adapter for types going out from pg8000 to the server.

- *typ* - The Python class that the adapter is for.
- *out_func* - A function that takes the Python object and returns its string representation in the format that the server requires.


### pg8000.native.Connection.register\_in\_adapter(oid, in\_func)

Register a type adapter for types coming in from the server to pg8000.

- *oid* - The PostgreSQL type identifier found in the [pg\_type system catalog](https://www.postgresql.org/docs/current/catalog-pg-type.html).
- *in_func*  - A function that takes the PostgreSQL string representation and returns a corresponding
  Python object.


### pg8000.native.Connection.prepare(sql)

Returns a `PreparedStatement` object which represents a [prepared statement
](https://www.postgresql.org/docs/current/sql-prepare.html) on the server. It can
subsequently be repeatedly executed.

- *sql* - The SQL statement to prepare. Parameter placeholders appear as a `:` followed by the parameter name.


### pg8000.native.PreparedStatement

A prepared statement object is returned by the `pg8000.native.Connection.prepare()`
method of a connection. It has the following methods:


#### pg8000.native.PreparedStatement.run(\*\*kwargs)

Executes the prepared statement, and returns the results as a `tuple`.

- *kwargs* - The parameters of the prepared statement.


#### pg8000.native.PreparedStatement.close()

Closes the prepared statement, releasing the prepared statement held on the server.


### pg8000.native.identifier(ident)

Correctly quotes and escapes a string to be used as an [SQL identifier
](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).
- *ident* - The `str` to be used as an SQL identifier.


### pg8000.native.literal(value)

Correctly quotes and escapes a value to be used as an [SQL literal
](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS).
- *value* - The value to be used as an SQL literal.


## DB-API 2 Docs

### Properties

#### pg8000.dbapi.apilevel

The DBAPI level supported, currently "2.0".


#### pg8000.dbapi.threadsafety

Integer constant stating the level of thread safety the DBAPI interface supports. For
pg8000, the threadsafety value is 1, meaning that threads may share the module but not
connections.


#### pg8000.dbapi.paramstyle

String property stating the type of parameter marker formatting expected by
the interface.  This value defaults to "format", in which parameters are
marked in this format: "WHERE name=%s".

As an extension to the DBAPI specification, this value is not constant; it can be
changed to any of the following values:

- *qmark* - Question mark style, eg. `WHERE name=?`
- *numeric* - Numeric positional style, eg. `WHERE name=:1`
- *named* - Named style, eg. `WHERE name=:paramname`
- *format* - printf format codes, eg. `WHERE name=%s`
- *pyformat* - Python format codes, eg. `WHERE name=%(paramname)s`


#### pg8000.dbapi.STRING

String type oid.


#### pg8000.dbapi.BINARY


#### pg8000.dbapi.NUMBER

Numeric type oid.


#### pg8000.dbapi.DATETIME

Timestamp type oid


#### pg8000.dbapi.ROWID

ROWID type oid


### 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)

Creates a connection to a PostgreSQL database.

- *user*  - The username to connect to the PostgreSQL server with. If your server character encoding is not `ascii` or `utf8`, then you need to provide `user` as bytes, eg. `'my_name'.encode('EUC-JP')`.
- *host* - The hostname of the PostgreSQL server to connect with. Providing this parameter is necessary for TCP/IP connections. One of either `host` or `unix_sock` must be provided. The default is `localhost`.
- *database* - The name of the database instance to connect with. If `None` then the PostgreSQL server will assume the database name is the same as the username. If your server character encoding is not `ascii` or `utf8`, then you need to provide `database` as bytes, eg. `'my_db'.encode('EUC-JP')`.
- *port* - The TCP/IP port of the PostgreSQL server instance.  This parameter defaults to `5432`, the registered common port of PostgreSQL TCP/IP servers.
- *password* - The user password to connect to the server with. This parameter is optional; if omitted and the database server requests password-based authentication, the connection will fail to open. If this parameter is provided but not requested by the server, no error will occur. If your server character encoding is not `ascii` or `utf8`, then you need to provide `password` as bytes, eg.  `'my_password'.encode('EUC-JP')`.
- *source_address* - The source IP address which initiates the connection to the PostgreSQL server. The default is `None` which means that the operating system will choose the source address.
- *unix_sock* - The path to the UNIX socket to access the database through, for example, `'/tmp/.s.PGSQL.5432'`. One of either `host` or `unix_sock` must be provided.
- *ssl_context* - This governs SSL encryption for TCP/IP sockets. It can have four values:
  - `None`, the default, meaning that an attempt will be made to connect over SSL, but if this is rejected by the server then pg8000 will fall back to using a plain socket.
  - `True`, means use SSL with an `ssl.SSLContext` with the minimum of checks.
  - `False`, means to not attempt to create an SSL socket.
  - An instance of `ssl.SSLContext` which will be used to create the SSL connection.
- *timeout* - This is the time in seconds before the connection to the server will time out. The default is `None` which means no timeout.
- *tcp_keepalive* - If `True` then use [TCP keepalive](https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive). The default is `True`.
- *application_name* - Sets the [application\_name](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 provide values as bytes, eg. `'my_application_name'.encode('EUC-JP')`. The default is `None` which means that the server will set the application name.
- *replication* - Used to run in [streaming replication mode](https://www.postgresql.org/docs/current/protocol-replication.html). If your server character encoding is not `ascii` or `utf8`, then you need to provide values as bytes, eg. `'database'.encode('EUC-JP')`.
- *sock* - A socket-like object to use for the connection. For example, `sock` could be a plain `socket.socket`, or it could represent an SSH tunnel or perhaps an `ssl.SSLSocket` to an SSL proxy. If an `ssl.SSLContext` is provided, then it will be used to attempt to create an SSL socket from the provided socket. 


#### pg8000.dbapi.Date(year, month, day)

Construct an object holding a date value.

This property is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.

Returns: `datetime.date`


#### pg8000.dbapi.Time(hour, minute, second)

Construct an object holding a time value.

Returns: `datetime.time`


#### pg8000.dbapi.Timestamp(year, month, day, hour, minute, second)

Construct an object holding a timestamp value.

Returns: `datetime.datetime`


#### pg8000.dbapi.DateFromTicks(ticks)

Construct an object holding a date value from the given ticks value (number of seconds
since the epoch).

Returns: `datetime.datetime`


#### pg8000.dbapi.TimeFromTicks(ticks)

Construct an object holding a time value from the given ticks value (number of seconds
since the epoch).

Returns: `datetime.time`


#### pg8000.dbapi.TimestampFromTicks(ticks)

Construct an object holding a timestamp value from the given ticks value (number of
seconds since the epoch).

Returns: `datetime.datetime`


#### pg8000.dbapi.Binary(value)

Construct an object holding binary data.

Returns: `bytes`


### Generic Exceptions

Pg8000 uses the standard DBAPI 2.0 exception tree as "generic" exceptions. Generally,
more specific exception types are raised; these specific exception types are derived
from the generic exceptions.

#### pg8000.dbapi.Warning

Generic exception raised for important database warnings like data truncations. This
exception is not currently used by pg8000.


#### pg8000.dbapi.Error

Generic exception that is the base exception of all other error exceptions.


#### pg8000.dbapi.InterfaceError

Generic exception raised for errors that are related to the database interface rather
than the database itself. For example, if the interface attempts to use an SSL
connection but the server refuses, an InterfaceError will be raised.


#### pg8000.dbapi.DatabaseError

Generic exception raised for errors that are related to the database. This exception is
currently never raised by pg8000.


#### pg8000.dbapi.DataError

Generic exception raised for errors that are due to problems with the processed data.
This exception is not currently raised by pg8000.


#### pg8000.dbapi.OperationalError

Generic exception raised for errors that are related to the database's operation and not
necessarily under the control of the programmer. This exception is currently never
raised by pg8000.


#### pg8000.dbapi.IntegrityError

Generic exception raised when the relational integrity of the database is affected. This
exception is not currently raised by pg8000.


#### pg8000.dbapi.InternalError

Generic exception raised when the database encounters an internal error. This is
currently only raised when unexpected state occurs in the pg8000 interface itself, and
is typically the result of a interface bug.


#### pg8000.dbapi.ProgrammingError

Generic exception raised for programming errors. For example, this exception is raised
if more parameter fields are in a query string than there are available parameters.


#### pg8000.dbapi.NotSupportedError

Generic exception raised in case a method or database API was used which is not
supported by the database.


### Classes


#### pg8000.dbapi.Connection

A connection object is returned by the `pg8000.dbapi.connect()` function. It represents a
single physical connection to a PostgreSQL database.


#### pg8000.dbapi.Connection.autocommit

Following the DB-API specification, autocommit is off by default. It can be turned on by
setting this boolean pg8000-specific autocommit property to ``True``.


#### pg8000.dbapi.Connection.close()

Closes the database connection.


#### pg8000.dbapi.Connection.cursor()

Creates a `pg8000.dbapi.Cursor` object bound to this connection.


#### pg8000.dbapi.Connection.rollback()

Rolls back the current database transaction.


#### pg8000.dbapi.Connection.tpc_begin(xid)

Begins a TPC transaction with the given transaction ID xid. This method should be
called outside of a transaction (i.e. nothing may have executed since the last
`commit()`  or `rollback()`. Furthermore, it is an error to call `commit()` or
`rollback()` within the TPC transaction. A `ProgrammingError` is raised, if the
application calls `commit()` or `rollback()` during an active TPC transaction.


#### pg8000.dbapi.Connection.tpc_commit(xid=None)

When called with no arguments, `tpc_commit()` commits a TPC transaction previously
prepared with `tpc_prepare()`. If `tpc_commit()` is called prior to
`tpc_prepare()`, a single phase commit is performed. A transaction manager may choose
to do this if only a single resource is participating in the global transaction.

When called with a transaction ID `xid`, the database commits the given transaction.
If an invalid transaction ID is provided, a `ProgrammingError` will be raised. This
form should be called outside of a transaction, and is intended for use in recovery.

On return, the TPC transaction is ended.


#### pg8000.dbapi.Connection.tpc_prepare()

Performs the first phase of a transaction started with `.tpc_begin()`. A
`ProgrammingError` is be raised if this method is called outside of a TPC transaction.

After calling `tpc_prepare()`, no statements can be executed until `tpc_commit()` or
`tpc_rollback()` have been called.


#### pg8000.dbapi.Connection.tpc_recover()

Returns a list of pending transaction IDs suitable for use with `tpc_commit(xid)` or
`tpc_rollback(xid)`.


#### pg8000.dbapi.Connection.tpc_rollback(xid=None)

When called with no arguments, `tpc_rollback()` rolls back a TPC transaction. It may
be called before or after `tpc_prepare()`.

When called with a transaction ID xid, it rolls back the given transaction. If an
invalid transaction ID is provided, a `ProgrammingError` is raised. This form should
be called outside of a transaction, and is intended for use in recovery.

On return, the TPC transaction is ended.


#### pg8000.dbapi.Connection.xid(format_id, global_transaction_id, branch_qualifier)

Create a Transaction IDs (only global_transaction_id is used in pg) format_id and
branch_qualifier are not used in postgres global_transaction_id may be any string
identifier supported by postgres returns a tuple (format_id, global_transaction_id,
branch_qualifier)


#### pg8000.dbapi.Cursor

A cursor object is returned by the `pg8000.dbapi.Connection.cursor()` method of a
connection. It has the following attributes and methods:

##### pg8000.dbapi.Cursor.arraysize

This read/write attribute specifies the number of rows to fetch at a time with
`pg8000.dbapi.Cursor.fetchmany()`.  It defaults to 1.


##### pg8000.dbapi.Cursor.connection

This read-only attribute contains a reference to the connection object (an instance of
`pg8000.dbapi.Connection`) on which the cursor was created.


##### pg8000.dbapi.Cursor.rowcount

This read-only attribute contains the number of rows that the last `execute()` or
`executemany()` method produced (for query statements like `SELECT`) or affected
(for modification statements like `UPDATE`.

The value is -1 if:

- No `execute()` or `executemany()` method has been performed yet on the cursor.
- There was no rowcount associated with the last `execute()`.
- At least one of the statements executed as part of an `executemany()` had no row
  count associated with it.


##### pg8000.dbapi.Cursor.description

This read-only attribute is a sequence of 7-item sequences. Each value contains
information describing one result column. The 7 items returned for each column are
(name, type_code, display_size, internal_size, precision, scale, null_ok). Only the
first two values are provided by the current implementation.


##### pg8000.dbapi.Cursor.close()

Closes the cursor.


##### pg8000.dbapi.Cursor.execute(operation, args=None, stream=None)

Executes a database operation. Parameters may be provided as a sequence, or as a
mapping, depending upon the value of `pg8000.dbapi.paramstyle`. Returns the cursor,
which may be iterated over.

- *operation* - The SQL statement to execute.
- *args* - If `pg8000.dbapi.paramstyle` is `qmark`, `numeric`, or `format`, this argument should be an array of parameters to bind into the statement. If `pg8000.dbapi.paramstyle` is `named`, the argument should be a `dict` mapping of parameters. If `pg8000.dbapi.paramstyle` is `pyformat`, the argument value may be either an array or a mapping.
- *stream* - This is a pg8000 extension for use with the PostgreSQL [COPY](http://www.postgresql.org/docs/current/static/sql-copy.html) command. For a `COPY FROM` the parameter must be a readable file-like object, and for `COPY TO` it must be writable.


##### pg8000.dbapi.Cursor.executemany(operation, param_sets)

Prepare a database operation, and then execute it against all parameter sequences or
mappings provided.

- *operation* - The SQL statement to execute.
- *parameter_sets* - A sequence of parameters to execute the statement with. The values in the sequence should be sequences or mappings of parameters, the same as the args argument of the `pg8000.dbapi.Cursor.execute()` method.


##### pg8000.dbapi.Cursor.callproc(procname, parameters=None)

Call a stored database procedure with the given name and optional parameters.

- *procname* - The name of the procedure to call.
- *parameters* - A list of parameters.


##### pg8000.dbapi.Cursor.fetchall()

Fetches all remaining rows of a query result.

Returns: A sequence, each entry of which is a sequence of field values making up a row.


##### pg8000.dbapi.Cursor.fetchmany(size=None)

Fetches the next set of rows of a query result.

- *size* - The number of rows to fetch when called.  If not provided, the `pg8000.dbapi.Cursor.arraysize` attribute value is used instead.

Returns: A sequence, each entry of which is a sequence of field values making up a row.
If no more rows are available, an empty sequence will be returned.


##### pg8000.dbapi.Cursor.fetchone()

Fetch the next row of a query result set.

Returns: A row as a sequence of field values, or `None` if no more rows are available.


##### pg8000.dbapi.Cursor.setinputsizes(\*sizes)

Used to set the parameter types of the next query. This is useful if it's difficult for
pg8000 to work out the types from the parameters themselves (eg. for parameters of type
None).

- *sizes* - Positional parameters that are either the Python type of the parameter to be sent, or the PostgreSQL oid. Common oids are available as constants such as `pg8000.STRING`, `pg8000.INTEGER`, `pg8000.TIME` etc.


##### pg8000.dbapi.Cursor.setoutputsize(size, column=None)

Not implemented by pg8000.


#### pg8000.dbapi.Interval

An Interval represents a measurement of time.  In PostgreSQL, an interval is defined in
the measure of months, days, and microseconds; as such, the pg8000 interval type
represents the same information.

Note that values of the `pg8000.dbapi.Interval.microseconds`,
`pg8000.dbapi.Interval.days`, and `pg8000.dbapi.Interval.months` properties are
independently measured and cannot be converted to each other. A month may be 28, 29, 30,
or 31 days, and a day may occasionally be lengthened slightly by a leap second.


## Design Decisions

For the `Range` type, the constructor follows the [PostgreSQL range constructor functions
](https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-CONSTRUCT)
which makes [[closed, open)](https://fhur.me/posts/always-use-closed-open-intervals)
the easiest to express:

```python
>>> from pg8000.types import Range
>>>
>>> pg_range = Range(2, 6)

```


## Tests

- Install [tox](http://testrun.org/tox/latest/): `pip install tox`

- Enable the PostgreSQL hstore extension by running the SQL command:
  `create extension hstore;`

- Add a line to `pg_hba.conf` for the various authentication options:

```
host    pg8000_md5           all        127.0.0.1/32            md5
host    pg8000_gss           all        127.0.0.1/32            gss
host    pg8000_password      all        127.0.0.1/32            password
host    pg8000_scram_sha_256 all        127.0.0.1/32            scram-sha-256
host    all                  all        127.0.0.1/32            trust
```

- Set password encryption to `scram-sha-256` in `postgresql.conf`:
  `password_encryption = 'scram-sha-256'`

- Set the password for the postgres user: `ALTER USER postgresql WITH PASSWORD 'pw';`

- Run `tox` from the `pg8000` directory: `tox`

This will run the tests against the Python version of the virtual environment, on the
machine, and the installed PostgreSQL version listening on port 5432, or the `PGPORT`
environment variable if set.

Benchmarks are run as part of the test suite at `tests/test_benchmarks.py`.


## Doing A Release Of pg8000

Run `tox` to make sure all tests pass, then update the release notes, then do:


```
git tag -a x.y.z -m "version x.y.z"
rm -r dist
python -m build
twine upload dist/*
```


## Release Notes

### Version 1.31.2, 2024-04-28

- Fix bug where `parameter_statuses` fails for non-ascii encoding.
- Add support for Python 3.12


### Version 1.31.1, 2024-04-01

- Move to src style layout, and also for packaging use Hatch rather than setuptools. This means that if the source distribution has a directory added to it (as is needed for packaging for OS distributions) the package can still be built.


### Version 1.31.0, 2024-03-31

- Now the `ssl_context` connection parameter can have one of four values:
  - None - The default, meaning it'll try and connect over SSL but fall back to a plain socket if not.
  - True - Will try and connect over SSL and fail if not.
  - False - It'll not try to connect over SSL.
  - SSLContext object - It'll use this object to connect over SSL.


### Version 1.30.5, 2024-02-22

- Fix bug that now means the number of parameters cam be as high as an unsigned 16 bit
  integer will go.


### Version 1.30.4, 2024-01-03

- Add support for more range and multirange types.
- Make the `Connection.parameter_statuses` property a `dict` rather than a `dequeue`.


### Version 1.30.3, 2023-10-31

- Fix problem with PG date overflowing Python types. Now we return the `str` we got from the
  server if we can't parse it. 


### Version 1.30.2, 2023-09-17

- Bug fix where dollar-quoted string constants weren't supported.


### Version 1.30.1, 2023-07-29

- There was a problem uploading the previous version (1.30.0) to PyPI because the markup of the README.rst was invalid. There's now a step in the automated tests to check for this.


### Version 1.30.0, 2023-07-27

- Remove support for Python 3.7
- Add a `sock` keyword parameter for creating a connection from a pre-configured socket.


### Version 1.29.8, 2023-06-16

- Ranges don't work with legacy API.


### Version 1.29.7, 2023-06-16

- Add support for PostgreSQL `range` and `multirange` types. Previously pg8000 would just return them as strings, but now they're returned as `Range` and lists of `Range`.
- The PostgreSQL `record` type is now returned as a `tuple` of strings, whereas before it was returned as one string.


### Version 1.29.6, 2023-05-29

- Fixed two bugs with composite types. Nulls should be represented by an empty string, and in an array of composite types, the elements should be surrounded by double quotes.


### Version 1.29.5, 2023-05-09

- Fixed bug where pg8000 didn't handle the case when the number of bytes received from a socket was fewer than requested. This was being interpreted as a network error, but in fact we just needed to wait until more bytes were available.
- When using the `PGInterval` type, if a response from the server contained the period `millennium`, it wasn't recognised. This was caused by a spelling mistake where we had `millenium` rather than `millennium`.
- Added support for sending PostgreSQL composite types. If a value is sent as a `tuple`, pg8000 will send it to the server as a `(` delimited composite string.


### Version 1.29.4, 2022-12-14

- Fixed bug in `pg8000.dbapi` in the `setinputsizes()` method where if a `size` was a recognized Python type, the method failed.


### Version 1.29.3, 2022-10-26

- Upgrade the SCRAM library to version 1.4.3. This adds support for the case where the client supports channel binding but the server doesn't.


### Version 1.29.2, 2022-10-09

- Fixed a bug where in a literal array, items such as `\n` and `\r` weren't escaped properly before being sent to the server.
- Fixed a bug where if the PostgreSQL server has a half-hour time zone set, values of type `timestamp with time zone` failed. This has been fixed by using the `parse` function of the `dateutil` package if the `datetime` parser fails.


### Version 1.29.1, 2022-05-23

- In trying to determine if there's been a failed commit, check for `ROLLBACK TO SAVEPOINT`.


### Version 1.29.0, 2022-05-21

- Implement a workaround for the [silent failed commit](https://github.com/tlocke/pg8000/issues/36) bug.
- Previously if an empty string was sent as the query an exception would be raised, but that isn't done now.


### Version 1.28.3, 2022-05-18

- Put back `__version__` attributes that were inadvertently removed.


### Version 1.28.2, 2022-05-17

- Use a build system that's compliant with PEP517.


### Version 1.28.1, 2022-05-17

- If when doing a `COPY FROM` the `stream` parameter is an iterator of `str`, pg8000 used to silently append a newline to the end. That no longer happens.


### Version 1.28.0, 2022-05-17

- When using the `COPY FROM` SQL statement, allow the `stream` parameter to be an iterable.


### Version 1.27.1, 2022-05-16

- The `seconds` attribute of `PGInterval` is now always a `float`, to cope with fractional seconds.
- Updated the `interval` parsers for `iso_8601` and `sql_standard` to take account of fractional seconds.


### Version 1.27.0, 2022-05-16

- It used to be that by default, if pg8000 received an `interval` type from the server and it was too big to fit into a `datetime.timedelta` then an exception would be raised. Now if an interval is too big for `datetime.timedelta` a `PGInterval` is returned.
- pg8000 now supports all the output formats for an `interval` (`postgres`, `postgres_verbose`, `iso_8601` and `sql_standard`).


### Version 1.26.1, 2022-04-23

- Make sure all tests are run by the GitHub Actions tests on commit.
- Remove support for Python 3.6
- Remove support for PostgreSQL 9.6


### Version 1.26.0, 2022-04-18

- When connecting, raise an `InterfaceError('network error')` rather than let the underlying `struct.error` float up.
- Make licence text the same as that used by the OSI. Previously the licence wording differed slightly from the BSD 3 Clause licence at https://opensource.org/licenses/BSD-3-Clause. This meant that automated tools didn't pick it up as being Open Source. The changes are believed to not alter the meaning of the license at all.


### Version 1.25.0, 2022-04-17

- Fix more cases where a `ResourceWarning` would be raise because of a socket that had been left open.
- We now have a single `InterfaceError` with the message 'network error' for all network errors, with the underlying exception held in the `cause` of the exception.


### Version 1.24.2, 2022-04-15

- To prevent a `ResourceWarning` close socket if a connection can't be created.


### Version 1.24.1, 2022-03-02

- Return pg +/-infinity dates as `str`. Previously +/-infinity pg values would cause an error when returned, but now we return +/-infinity as strings.


### Version 1.24.0, 2022-02-06

- Add SQL escape functions identifier() and literal() to the native API. For use when a query can't be parameterised and the SQL string has to be created using untrusted values.


### Version 1.23.0, 2021-11-13

- If a query has no parameters, then the query will no longer be parsed. Although there are performance benefits for doing this, the main reason is to avoid query rewriting, which can introduce errors.


### Version 1.22.1, 2021-11-10

- Fix bug in PGInterval type where `str()` failed for a millennia value.


### Version 1.22.0, 2021-10-13

- Rather than specifying the oids in the `Parse` step of the Postgres protocol, pg8000 now omits them, and so Postgres will use the oids it determines from the query. This makes the pg8000 code simpler and also it should also make the nuances of type matching more straightforward.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pg8000",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "dbapi, postgresql",
    "author": "The Contributors",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/0f/d7/0554640cbe3e193184796bedb6de23f797c03958425176faf0e694c06eb0/pg8000-1.31.2.tar.gz",
    "platform": null,
    "description": "# pg8000\n\npg8000 is a pure-[Python](https://www.python.org/)\n[PostgreSQL](http://www.postgresql.org/) driver that complies with\n[DB-API 2.0](http://www.python.org/dev/peps/pep-0249/). It is tested on Python versions\n3.8+, on CPython and PyPy, and PostgreSQL versions 12+. pg8000's name comes from the\nbelief that it is probably about the 8000th PostgreSQL interface for Python. pg8000 is\ndistributed under the BSD 3-clause license.\n\nAll bug reports, feature requests and contributions are welcome at\n[http://github.com/tlocke/pg8000/](http://github.com/tlocke/pg8000/).\n\n[![Workflow Status Badge](https://github.com/tlocke/pg8000/workflows/pg8000/badge.svg)](https://github.com/tlocke/pg8000/actions)\n\n## Installation\n\nTo install pg8000 using `pip` type: `pip install pg8000`\n\n\n## Native API Interactive Examples\n\npg8000 comes with two APIs, the native pg8000 API and the DB-API 2.0 standard\nAPI. These are the examples for the native API, and the DB-API 2.0 examples\nfollow in the next section.\n\n\n### Basic Example\n\nImport pg8000, connect to the database, create a table, add some rows and then\nquery the table:\n\n```python\n>>> import pg8000.native\n>>>\n>>> # Connect to the database with user name postgres\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> # Create a temporary table\n>>>\n>>> con.run(\"CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)\")\n>>>\n>>> # Populate the table\n>>>\n>>> for title in (\"Ender's Game\", \"The Magus\"):\n...     con.run(\"INSERT INTO book (title) VALUES (:title)\", title=title)\n>>>\n>>> # Print all the rows in the table\n>>>\n>>> for row in con.run(\"SELECT * FROM book\"):\n...     print(row)\n[1, \"Ender's Game\"]\n[2, 'The Magus']\n>>>\n>>> con.close()\n\n```\n\n\n### Transactions\n\nHere's how to run groups of SQL statements in a\n[transaction](https://www.postgresql.org/docs/current/tutorial-transactions.html>):\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"START TRANSACTION\")\n>>>\n>>> # Create a temporary table\n>>> con.run(\"CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)\")\n>>>\n>>> for title in (\"Ender's Game\", \"The Magus\", \"Phineas Finn\"):\n...     con.run(\"INSERT INTO book (title) VALUES (:title)\", title=title)\n>>> con.run(\"COMMIT\")\n>>> for row in con.run(\"SELECT * FROM book\"):\n...     print(row)\n[1, \"Ender's Game\"]\n[2, 'The Magus']\n[3, 'Phineas Finn']\n>>>\n>>> con.close()\n\n```\n\nrolling back a transaction:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> # Create a temporary table\n>>> con.run(\"CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)\")\n>>>\n>>> for title in (\"Ender's Game\", \"The Magus\", \"Phineas Finn\"):\n...     con.run(\"INSERT INTO book (title) VALUES (:title)\", title=title)\n>>>\n>>> con.run(\"START TRANSACTION\")\n>>> con.run(\"DELETE FROM book WHERE title = :title\", title=\"Phineas Finn\") \n>>> con.run(\"ROLLBACK\")\n>>> for row in con.run(\"SELECT * FROM book\"):\n...     print(row)\n[1, \"Ender's Game\"]\n[2, 'The Magus']\n[3, 'Phineas Finn']\n>>>\n>>> con.close()\n\n```\n\nNB. There is [a longstanding bug](https://github.com/tlocke/pg8000/issues/36>) in the\nPostgreSQL server whereby if a `COMMIT` is issued against a failed transaction, the\ntransaction is silently rolled back, rather than an error being returned. pg8000\nattempts to detect when this has happened and raise an `InterfaceError`.\n\n\n### Query Using Functions\n\nAnother query, using some PostgreSQL functions:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')\")\n[['2021 AD']]\n>>>\n>>> con.close()\n\n```\n\n\n### Interval Type\n\nA query that returns the PostgreSQL interval type:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> import datetime\n>>>\n>>> ts = datetime.date(1980, 4, 27)\n>>> con.run(\"SELECT timestamp '2013-12-01 16:06' - :ts\", ts=ts)\n[[datetime.timedelta(days=12271, seconds=57960)]]\n>>>\n>>> con.close()\n\n```\n\n\n### Point Type\n\nA round-trip with a\n[PostgreSQL point](https://www.postgresql.org/docs/current/datatype-geometric.html)\ntype:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT CAST(:pt as point)\", pt=(2.3,1))\n[[(2.3, 1.0)]]\n>>>\n>>> con.close()\n\n```\n\n\n### Client Encoding\n\nWhen communicating with the server, pg8000 uses the character set that the server asks\nit to use (the client encoding). By default the client encoding is the database's\ncharacter set (chosen when the database is created), but the client encoding can be\nchanged in a number of ways (eg. setting `CLIENT_ENCODING` in `postgresql.conf`).\nAnother way of changing the client encoding is by using an SQL command. For example:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SET CLIENT_ENCODING TO 'UTF8'\")\n>>> con.run(\"SHOW CLIENT_ENCODING\")\n[['UTF8']]\n>>>\n>>> con.close()\n\n```\n\n### JSON\n\n[JSON](https://www.postgresql.org/docs/current/datatype-json.html) always comes back\nfrom the server de-serialized. If the JSON you want to send is a ``dict`` then you can\njust do:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}\n>>> con.run(\"SELECT CAST(:apollo as jsonb)\", apollo=val)\n[[{'age': 26.003, 'name': 'Apollo 11 Cave', 'zebra': True}]]\n>>>\n>>> con.close()\n\n```\n\nJSON can always be sent in serialized form to the server:\n\n```python\n>>> import json\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>>\n>>> val = ['Apollo 11 Cave', True, 26.003]\n>>> con.run(\"SELECT CAST(:apollo as jsonb)\", apollo=json.dumps(val))\n[[['Apollo 11 Cave', True, 26.003]]]\n>>>\n>>> con.close()\n\n```\n\nJSON queries can be have parameters:\n\n```python\n>>> import pg8000.native\n>>>\n>>> with pg8000.native.Connection(\"postgres\", password=\"cpsnow\") as con:\n...     con.run(\"\"\" SELECT CAST('{\"a\":1, \"b\":2}' AS jsonb) @> :v \"\"\", v={\"b\": 2})\n[[True]]\n\n```\n\n\n### Retrieve Column Metadata From Results\n\nFind the column metadata returned from a query:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"create temporary table quark (id serial, name text)\")\n>>> for name in ('Up', 'Down'):\n...     con.run(\"INSERT INTO quark (name) VALUES (:name)\", name=name)\n>>> # Now execute the query\n>>>\n>>> con.run(\"SELECT * FROM quark\")\n[[1, 'Up'], [2, 'Down']]\n>>>\n>>> # and retrieve the metadata\n>>>\n>>> con.columns\n[{'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'}]\n>>>\n>>> # Show just the column names\n>>>\n>>> [c['name'] for c in con.columns]\n['id', 'name']\n>>>\n>>> con.close()\n\n```\n\n\n### Notices And Notifications\n\nPostgreSQL [notices\n](https://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html) are\nstored in a deque called `Connection.notices` and added using the `append()` method.\nSimilarly there are `Connection.notifications` for [notifications\n](https://www.postgresql.org/docs/current/static/sql-notify.html). Here's an example:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"LISTEN aliens_landed\")\n>>> con.run(\"NOTIFY aliens_landed\")\n>>> # A notification is a tuple containing (backend_pid, channel, payload)\n>>>\n>>> con.notifications[0]\n(..., 'aliens_landed', '')\n>>>\n>>> con.close()\n\n```\n\n\n### Parameter Statuses\n\n[Certain parameter values are reported by the server automatically at connection startup or whenever\ntheir values change\n](https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQPARAMETERSTATUS>) and\npg8000 stores the latest values in a dict called `Connection.parameter_statuses`. Here's\nan example where we set the `aplication_name` parameter and then read it from the\n`parameter_statuses`:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\n...     \"postgres\", password=\"cpsnow\", application_name='AGI')\n>>>\n>>> con.parameter_statuses['application_name']\n'AGI'\n>>>\n>>> con.close()\n\n```\n\n\n### LIMIT ALL\n\nYou might think that the following would work, but in fact it fails:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT 'silo 1' LIMIT :lim\", lim='ALL')\nTraceback (most recent call last):\npg8000.exceptions.DatabaseError: ...\n>>>\n>>> con.close()\n\n```\n\nInstead the [docs say](https://www.postgresql.org/docs/current/sql-select.html) that you\ncan send `null` as an alternative to `ALL`, which does work:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT 'silo 1' LIMIT :lim\", lim=None)\n[['silo 1']]\n>>>\n>>> con.close()\n\n```\n\n\n### IN and NOT IN\n\nYou might think that the following would work, but in fact the server doesn't like it:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT 'silo 1' WHERE 'a' IN :v\", v=['a', 'b'])\nTraceback (most recent call last):\npg8000.exceptions.DatabaseError: ...\n>>>\n>>> con.close()\n\n```\n\nthe most straightforward way to get around this problem is to rewrie the query using the [`ANY`](\nhttps://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-ANY-SOME)\nfunction:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT 'silo 1' WHERE 'a' = ANY(:v)\", v=['a', 'b'])\n[['silo 1']]\n>>> con.close()\n\n```\n\nHowever, using the array variant of `ANY` [may cause a performance problem](\nhttps://stackoverflow.com/questions/34627026/in-vs-any-operator-in-postgresql/34627688#34627688)\nand so you can use the [subquery variant of `IN`](\nhttps://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-IN)\nwith the [unnest\n](https://www.postgresql.org/docs/current/functions-array.html) function:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\n...     \"SELECT 'silo 1' WHERE 'a' IN (SELECT unnest(CAST(:v as varchar[])))\",\n...     v=['a', 'b'])\n[['silo 1']]\n>>> con.close()\n\n```\n\nand you can do the same for `NOT IN`.\n\n\n### Many SQL Statements Can't Be Parameterized\n\nIn PostgreSQL parameters can only be used for [data values, not identifiers\n](https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS).\nSometimes this might not work as expected, for example the following fails:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> channel = 'top_secret'\n>>>\n>>> con.run(\"LISTEN :channel\", channel=channel)\nTraceback (most recent call last):\npg8000.exceptions.DatabaseError: ...\n>>>\n>>> con.close()\n\n```\n\nIt fails because the PostgreSQL server doesn't allow this statement to have any\nparameters. There are many SQL statements that one might think would have parameters,\nbut don't. For these cases the SQL has to be created manually, being careful to use the\n`identifier()` and `literal()` functions to escape the values to avoid [SQL injection\nattacks](https://en.wikipedia.org/wiki/SQL_injection>):\n\n```python\n>>> from pg8000.native import Connection, identifier, literal\n>>>\n>>> con = Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> channel = 'top_secret'\n>>> payload = 'Aliens Landed!'\n>>> con.run(f\"LISTEN {identifier(channel)}\")\n>>> con.run(f\"NOTIFY {identifier(channel)}, {literal(payload)}\")\n>>>\n>>> con.notifications[0]\n(..., 'top_secret', 'Aliens Landed!')\n>>>\n>>> con.close()\n\n```\n\n\n### COPY FROM And TO A Stream\n\nThe SQL [COPY](https://www.postgresql.org/docs/current/sql-copy.html) statement can be\nused to copy from and to a file or file-like object. Here's an example using the CSV\nformat:\n\n```python\n>>> import pg8000.native\n>>> from io import StringIO\n>>> import csv\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> # Create a CSV file in memory\n>>>\n>>> stream_in = StringIO()\n>>> csv_writer = csv.writer(stream_in)\n>>> csv_writer.writerow([1, \"electron\"])\n12\n>>> csv_writer.writerow([2, \"muon\"])\n8\n>>> csv_writer.writerow([3, \"tau\"])\n7\n>>> stream_in.seek(0)\n0\n>>>\n>>> # Create a table and then copy the CSV into it\n>>>\n>>> con.run(\"CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)\")\n>>> con.run(\"COPY lepton FROM STDIN WITH (FORMAT CSV)\", stream=stream_in)\n>>>\n>>> # COPY from a table to a stream\n>>>\n>>> stream_out = StringIO()\n>>> con.run(\"COPY lepton TO STDOUT WITH (FORMAT CSV)\", stream=stream_out)\n>>> stream_out.seek(0)\n0\n>>> for row in csv.reader(stream_out):\n...     print(row)\n['1', 'electron']\n['2', 'muon']\n['3', 'tau']\n>>>\n>>> con.close()\n\n```\n\nIt's also possible to COPY FROM an iterable, which is useful if you're creating rows\nprogrammatically:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> # Generator function for creating rows\n>>> def row_gen():\n...     for i, name in ((1, \"electron\"), (2, \"muon\"), (3, \"tau\")):\n...         yield f\"{i},{name}\\n\"\n>>>\n>>> # Create a table and then copy the CSV into it\n>>>\n>>> con.run(\"CREATE TEMPORARY TABLE lepton (id SERIAL, name TEXT)\")\n>>> con.run(\"COPY lepton FROM STDIN WITH (FORMAT CSV)\", stream=row_gen())\n>>>\n>>> # COPY from a table to a stream\n>>>\n>>> stream_out = StringIO()\n>>> con.run(\"COPY lepton TO STDOUT WITH (FORMAT CSV)\", stream=stream_out)\n>>> stream_out.seek(0)\n0\n>>> for row in csv.reader(stream_out):\n...     print(row)\n['1', 'electron']\n['2', 'muon']\n['3', 'tau']\n>>>\n>>> con.close()\n\n```\n\n\n### Execute Multiple SQL Statements\n\nIf you want to execute a series of SQL statements (eg. an `.sql` file), you can run\nthem as expected:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> statements = \"SELECT 5; SELECT 'Erich Fromm';\"\n>>>\n>>> con.run(statements)\n[[5], ['Erich Fromm']]\n>>>\n>>> con.close()\n\n```\n\nThe only caveat is that when executing multiple statements you can't have any\nparameters.\n\n\n### Quoted Identifiers in SQL\n\nSay you had a column called `My Column`. Since it's case sensitive and contains a space,\nyou'd have to [surround it by double quotes\n](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIER).\nBut you can't do:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"select 'hello' as \"My Column\"\")\nTraceback (most recent call last):\nSyntaxError: invalid syntax...\n>>>\n>>> con.close()\n\n```\n\nsince Python uses double quotes to delimit string literals, so one solution is\nto use Python's [triple quotes\n](https://docs.python.org/3/tutorial/introduction.html#strings) to delimit the string\ninstead:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run('''SELECT 'hello' AS \"My Column\"''')\n[['hello']]\n>>>\n>>> con.close()\n\n```\n\nanother solution, that's especially useful if the identifier comes from an untrusted\nsource, is to use the `identifier()` function, which correctly quotes and escapes the\nidentifier as needed:\n\n```python\n>>> from pg8000.native import Connection, identifier\n>>>\n>>> con = Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> sql = f\"SELECT 'hello' as {identifier('My Column')}\"\n>>> print(sql)\nSELECT 'hello' as \"My Column\"\n>>>\n>>> con.run(sql)\n[['hello']]\n>>>\n>>> con.close()\n\n```\n\nthis approach guards against [SQL injection attacks\n](https://en.wikipedia.org/wiki/SQL_injection). One thing to note if you're using\nexplicit schemas (eg. `pg_catalog.pg_language`) is that the schema name and table name\nare both separate identifiers. So to escape them you'd do:\n\n```python\n>>> from pg8000.native import Connection, identifier\n>>>\n>>> con = Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> query = (\n...     f\"SELECT lanname FROM {identifier('pg_catalog')}.{identifier('pg_language')} \"\n...     f\"WHERE lanname = 'sql'\"\n... )\n>>> print(query)\nSELECT lanname FROM pg_catalog.pg_language WHERE lanname = 'sql'\n>>>\n>>> con.run(query)\n[['sql']]\n>>>\n>>> con.close()\n\n```\n\n\n### Custom adapter from a Python type to a PostgreSQL type\n\npg8000 has a mapping from Python types to PostgreSQL types for when it needs to send\nSQL parameters to the server. The default mapping that comes with pg8000 is designed to\nwork well in most cases, but you might want to add or replace the default mapping.\n\nA Python `datetime.timedelta` object is sent to the server as a PostgreSQL\n`interval` type,  which has the `oid` 1186. But let's say we wanted to create our\nown Python class to be sent as an `interval` type. Then we'd have to register an\nadapter:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> class MyInterval(str):\n...     pass\n>>>\n>>> def my_interval_out(my_interval):\n...     return my_interval  # Must return a str\n>>>\n>>> con.register_out_adapter(MyInterval, my_interval_out)\n>>> con.run(\"SELECT CAST(:interval as interval)\", interval=MyInterval(\"2 hours\"))\n[[datetime.timedelta(seconds=7200)]]\n>>>\n>>> con.close()\n\n```\n\nNote that it still came back as a `datetime.timedelta` object because we only changed\nthe mapping from Python to PostgreSQL. See below for an example of how to change the\nmapping from PostgreSQL to Python.\n\n\n### Custom adapter from a PostgreSQL type to a Python type\n\npg8000 has a mapping from PostgreSQL types to Python types for when it receives SQL\nresults from the server. The default mapping that comes with pg8000 is designed to work\nwell in most cases, but you might want to add or replace the default mapping.\n\nIf pg8000 receives PostgreSQL `interval` type, which has the `oid` 1186, it converts\nit into a Python `datetime.timedelta` object. But let's say we wanted to create our\nown Python class to be used instead of `datetime.timedelta`. Then we'd have to\nregister an adapter:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> class MyInterval(str):\n...     pass\n>>>\n>>> def my_interval_in(my_interval_str):  # The parameter is of type str\n...     return MyInterval(my_interval)\n>>>\n>>> con.register_in_adapter(1186, my_interval_in)\n>>> con.run(\"SELECT \\'2 years'\")\n[['2 years']]\n>>>\n>>> con.close()\n\n```\n\nNote that registering the 'in' adapter only afects the mapping from the PostgreSQL type\nto the Python type. See above for an example of how to change the mapping from\nPostgreSQL to Python.\n\n\n### Could Not Determine Data Type Of Parameter\n\nSometimes you'll get the `could not determine data type of parameter` error message from\nthe server:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT :v IS NULL\", v=None)\nTraceback (most recent call last):\npg8000.exceptions.DatabaseError: {'S': 'ERROR', 'V': 'ERROR', 'C': '42P18', 'M': 'could not determine data type of parameter $1', 'F': 'postgres.c', 'L': '...', 'R': '...'}\n>>>\n>>> con.close()\n\n```\n\nOne way of solving it is to put a `CAST` in the SQL:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT cast(:v as TIMESTAMP) IS NULL\", v=None)\n[[True]]\n>>>\n>>> con.close()\n\n```\n\nAnother way is to override the type that pg8000 sends along with each parameter:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> con.run(\"SELECT :v IS NULL\", v=None, types={'v': pg8000.native.TIMESTAMP})\n[[True]]\n>>>\n>>> con.close()\n\n```\n\n\n### Prepared Statements\n\n[Prepared statements](https://www.postgresql.org/docs/current/sql-prepare.html) can be\nuseful in improving performance when you have a statement that's executed repeatedly.\nHere's an example:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\"postgres\", password=\"cpsnow\")\n>>>\n>>> # Create the prepared statement\n>>> ps = con.prepare(\"SELECT cast(:v as varchar)\")\n>>>\n>>> # Execute the statement repeatedly\n>>> ps.run(v=\"speedy\")\n[['speedy']]\n>>> ps.run(v=\"rapid\")\n[['rapid']]\n>>> ps.run(v=\"swift\")\n[['swift']]\n>>>\n>>> # Close the prepared statement, releasing resources on the server\n>>> ps.close()\n>>>\n>>> con.close()\n\n```\n\n\n### Use Environment Variables As Connection Defaults\n\nYou might want to use the current user as the database username for example:\n\n```python\n>>> import pg8000.native\n>>> import getpass\n>>>\n>>> # Connect to the database with current user name\n>>> username = getpass.getuser()\n>>> connection = pg8000.native.Connection(username, password=\"cpsnow\")\n>>>\n>>> connection.run(\"SELECT 'pilau'\")\n[['pilau']]\n>>>\n>>> connection.close()\n\n```\n\nor perhaps you may want to use some of the same [environment variables that libpg uses\n](https://www.postgresql.org/docs/current/libpq-envars.html):\n\n```python\n>>> import pg8000.native\n>>> from os import environ\n>>>\n>>> username = environ.get('PGUSER', 'postgres')\n>>> password = environ.get('PGPASSWORD', 'cpsnow')\n>>> host = environ.get('PGHOST', 'localhost')\n>>> port = environ.get('PGPORT', '5432')\n>>> database = environ.get('PGDATABASE')\n>>>\n>>> connection = pg8000.native.Connection(\n...     username, password=password, host=host, port=port, database=database)\n>>>\n>>> connection.run(\"SELECT 'Mr Cairo'\")\n[['Mr Cairo']]\n>>>\n>>> connection.close()\n\n```\n\nIt might be asked, why doesn't pg8000 have this behaviour built in? The thinking\nfollows the second aphorism of [The Zen of Python\n](https://www.python.org/dev/peps/pep-0020/):\n\n> Explicit is better than implicit.\n\nSo we've taken the approach of only being able to set connection parameters using the\n`pg8000.native.Connection()` constructor.\n\n\n### Connect To PostgreSQL Over SSL\n\nBy default the `ssl_context` connection parameter has the value `None` which means pg8000 will\nattempt to connect to the server using SSL, and then fall back to a plain socket if the server\nrefuses SSL. If you want to *require* SSL (ie. to fail if it's not achieved) then you can set\n`ssl_context=True`:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection('postgres', password=\"cpsnow\", ssl_context=True)\n>>> con.run(\"SELECT 'The game is afoot!'\")\n[['The game is afoot!']]\n>>> con.close()\n\n```\n\nIf on the other hand you want to connect over SSL with custom settings, set the `ssl_context`\nparameter to an [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) object:\n\n```python\n>>> import pg8000.native\n>>> import ssl\n>>>\n>>> ssl_context = ssl.create_default_context()\n>>> ssl_context.check_hostname = False\n>>> ssl_context.verify_mode = ssl.CERT_NONE\n>>> con = pg8000.native.Connection(\n...     'postgres', password=\"cpsnow\", ssl_context=ssl_context)\n>>> con.run(\"SELECT 'Work is the curse of the drinking classes.'\")\n[['Work is the curse of the drinking classes.']]\n>>> con.close()\n\n```\n\nIt may be that your PostgreSQL server is behind an SSL proxy server in which case you\ncan give pg8000 the SSL socket with the `sock` parameter, and then set\n`ssl_context=False` which means that no attempt will be made to create an SSL connection\nto the server.\n\n\n### Server-Side Cursors\n\nYou can use the SQL commands [DECLARE\n](https://www.postgresql.org/docs/current/sql-declare.html),\n[FETCH](https://www.postgresql.org/docs/current/sql-fetch.html),\n[MOVE](https://www.postgresql.org/docs/current/sql-move.html) and\n[CLOSE](https://www.postgresql.org/docs/current/sql-close.html) to manipulate\nserver-side cursors. For example:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection('postgres', password=\"cpsnow\")\n>>> con.run(\"START TRANSACTION\")\n>>> con.run(\"DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)\")\n>>> con.run(\"FETCH FORWARD 5 FROM c\")\n[[1], [2], [3], [4], [5]]\n>>> con.run(\"MOVE FORWARD 50 FROM c\")\n>>> con.run(\"FETCH BACKWARD 10 FROM c\")\n[[54], [53], [52], [51], [50], [49], [48], [47], [46], [45]]\n>>> con.run(\"CLOSE c\")\n>>> con.run(\"ROLLBACK\")\n>>>\n>>> con.close()\n\n```\n\n\n### BLOBs (Binary Large Objects)\n\nThere's a set of [SQL functions\n](https://www.postgresql.org/docs/current/lo-funcs.html) for manipulating BLOBs.\nHere's an example:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection('postgres', password=\"cpsnow\")\n>>>\n>>> # Create a BLOB and get its oid\n>>> data = b'hello'\n>>> res = con.run(\"SELECT lo_from_bytea(0, :data)\", data=data)\n>>> oid = res[0][0]\n>>>\n>>> # Create a table and store the oid of the BLOB\n>>> con.run(\"CREATE TEMPORARY TABLE image (raster oid)\")\n>>>\n>>> con.run(\"INSERT INTO image (raster) VALUES (:oid)\", oid=oid)\n>>> # Retrieve the data using the oid\n>>> con.run(\"SELECT lo_get(:oid)\", oid=oid)\n[[b'hello']]\n>>>\n>>> # Add some data to the end of the BLOB\n>>> more_data = b' all'\n>>> offset = len(data)\n>>> con.run(\n...     \"SELECT lo_put(:oid, :offset, :data)\",\n...     oid=oid, offset=offset, data=more_data)\n[['']]\n>>> con.run(\"SELECT lo_get(:oid)\", oid=oid)\n[[b'hello all']]\n>>>\n>>> # Download a part of the data\n>>> con.run(\"SELECT lo_get(:oid, 6, 3)\", oid=oid)\n[[b'all']]\n>>>\n>>> con.close()\n\n```\n\n\n### Replication Protocol\n\nThe PostgreSQL [Replication Protocol\n](https://www.postgresql.org/docs/current/protocol-replication.html) is supported using\nthe `replication` keyword when creating a connection:\n\n```python\n>>> import pg8000.native\n>>>\n>>> con = pg8000.native.Connection(\n...    'postgres', password=\"cpsnow\", replication=\"database\")\n>>>\n>>> con.run(\"IDENTIFY_SYSTEM\")\n[['...', 1, '.../...', 'postgres']]\n>>>\n>>> con.close()\n\n```\n\n\n## DB-API 2 Interactive Examples\n\nThese examples stick to the DB-API 2.0 standard.\n\n\n### Basic Example\n\nImport pg8000, connect to the database, create a table, add some rows and then query the\ntable:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> conn = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = conn.cursor()\n>>> cursor.execute(\"CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)\")\n>>> cursor.execute(\n...     \"INSERT INTO book (title) VALUES (%s), (%s) RETURNING id, title\",\n...     (\"Ender's Game\", \"Speaker for the Dead\"))\n>>> results = cursor.fetchall()\n>>> for row in results:\n...     id, title = row\n...     print(\"id = %s, title = %s\" % (id, title))\nid = 1, title = Ender's Game\nid = 2, title = Speaker for the Dead\n>>> conn.commit()\n>>>\n>>> conn.close()\n\n```\n\n\n### Query Using Functions\n\nAnother query, using some PostgreSQL functions:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = con.cursor()\n>>>\n>>> cursor.execute(\"SELECT TO_CHAR(TIMESTAMP '2021-10-10', 'YYYY BC')\")\n>>> cursor.fetchone()\n['2021 AD']\n>>>\n>>> con.close()\n\n```\n\n\n### Interval Type\n\nA query that returns the PostgreSQL interval type:\n\n```python\n>>> import datetime\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = con.cursor()\n>>>\n>>> cursor.execute(\"SELECT timestamp '2013-12-01 16:06' - %s\",\n... (datetime.date(1980, 4, 27),))\n>>> cursor.fetchone()\n[datetime.timedelta(days=12271, seconds=57960)]\n>>>\n>>> con.close()\n\n```\n\n\n### Point Type\n\nA round-trip with a [PostgreSQL point\n](https://www.postgresql.org/docs/current/datatype-geometric.html) type:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = con.cursor()\n>>>\n>>> cursor.execute(\"SELECT cast(%s as point)\", ((2.3,1),))\n>>> cursor.fetchone()\n[(2.3, 1.0)]\n>>>\n>>> con.close()\n\n```\n\n\n### Numeric Parameter Style\n\npg8000 supports all the DB-API parameter styles. Here's an example of using the\n'numeric' parameter style:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> pg8000.dbapi.paramstyle = \"numeric\"\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = con.cursor()\n>>>\n>>> cursor.execute(\"SELECT array_prepend(:1, CAST(:2 AS int[]))\", (500, [1, 2, 3, 4],))\n>>> cursor.fetchone()\n[[500, 1, 2, 3, 4]]\n>>> pg8000.dbapi.paramstyle = \"format\"\n>>>\n>>> con.close()\n\n```\n\n\n### Autocommit\n\nFollowing the DB-API specification, autocommit is off by default. It can be turned on by\nusing the autocommit property of the connection:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> con.autocommit = True\n>>>\n>>> cur = con.cursor()\n>>> cur.execute(\"vacuum\")\n>>> conn.autocommit = False\n>>> cur.close()\n>>>\n>>> con.close()\n\n```\n\n\n### Client Encoding\n\nWhen communicating with the server, pg8000 uses the character set that the server asks\nit to use (the client encoding). By default the client encoding is the database's\ncharacter set (chosen when the database is created), but the client encoding can be\nchanged in a number of ways (eg. setting `CLIENT_ENCODING` in `postgresql.conf`).\nAnother way of changing the client encoding is by using an SQL command. For example:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cur = con.cursor()\n>>> cur.execute(\"SET CLIENT_ENCODING TO 'UTF8'\")\n>>> cur.execute(\"SHOW CLIENT_ENCODING\")\n>>> cur.fetchone()\n['UTF8']\n>>> cur.close()\n>>>\n>>> con.close()\n\n```\n\n\n### JSON\n\nJSON is sent to the server serialized, and returned de-serialized. Here's an example:\n\n```python\n>>> import json\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cur = con.cursor()\n>>> val = ['Apollo 11 Cave', True, 26.003]\n>>> cur.execute(\"SELECT cast(%s as json)\", (json.dumps(val),))\n>>> cur.fetchone()\n[['Apollo 11 Cave', True, 26.003]]\n>>> cur.close()\n>>>\n>>> con.close()\n\n```\n\nJSON queries can be have parameters:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> with pg8000.dbapi.connect(\"postgres\", password=\"cpsnow\") as con:\n...     cur = con.cursor()\n...     cur.execute(\"\"\" SELECT CAST('{\"a\":1, \"b\":2}' AS jsonb) @> %s \"\"\", ({\"b\": 2},))\n...     for row in cur.fetchall():\n...         print(row)\n[True]\n\n```\n\n\n### Retrieve Column Names From Results\n\nUse the columns names retrieved from a query:\n\n```python\n>>> import pg8000\n>>> conn = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> c = conn.cursor()\n>>> c.execute(\"create temporary table quark (id serial, name text)\")\n>>> c.executemany(\"INSERT INTO quark (name) VALUES (%s)\", ((\"Up\",), (\"Down\",)))\n>>> #\n>>> # Now retrieve the results\n>>> #\n>>> c.execute(\"select * from quark\")\n>>> rows = c.fetchall()\n>>> keys = [k[0] for k in c.description]\n>>> results = [dict(zip(keys, row)) for row in rows]\n>>> assert results == [{'id': 1, 'name': 'Up'}, {'id': 2, 'name': 'Down'}]\n>>>\n>>> conn.close()\n\n```\n\n\n### COPY from and to a file\n\nThe SQL [COPY](https://www.postgresql.org/docs/current/sql-copy.html) statement can\nbe used to copy from and to a file or file-like object:\n\n```python\n>>> from io import StringIO\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cur = con.cursor()\n>>> #\n>>> # COPY from a stream to a table\n>>> #\n>>> stream_in = StringIO('1\\telectron\\n2\\tmuon\\n3\\ttau\\n')\n>>> cur = con.cursor()\n>>> cur.execute(\"create temporary table lepton (id serial, name text)\")\n>>> cur.execute(\"COPY lepton FROM stdin\", stream=stream_in)\n>>> #\n>>> # Now COPY from a table to a stream\n>>> #\n>>> stream_out = StringIO()\n>>> cur.execute(\"copy lepton to stdout\", stream=stream_out)\n>>> stream_out.getvalue()\n'1\\telectron\\n2\\tmuon\\n3\\ttau\\n'\n>>>\n>>> con.close()\n\n```\n\n\n### Server-Side Cursors\n\nYou can use the SQL commands [DECLARE\n](https://www.postgresql.org/docs/current/sql-declare.html),\n[FETCH](https://www.postgresql.org/docs/current/sql-fetch.html),\n[MOVE](https://www.postgresql.org/docs/current/sql-move.html) and\n[CLOSE](https://www.postgresql.org/docs/current/sql-close.html) to manipulate\nserver-side cursors. For example:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cur = con.cursor()\n>>> cur.execute(\"START TRANSACTION\")\n>>> cur.execute(\n...    \"DECLARE c SCROLL CURSOR FOR SELECT * FROM generate_series(1, 100)\")\n>>> cur.execute(\"FETCH FORWARD 5 FROM c\")\n>>> cur.fetchall()\n([1], [2], [3], [4], [5])\n>>> cur.execute(\"MOVE FORWARD 50 FROM c\")\n>>> cur.execute(\"FETCH BACKWARD 10 FROM c\")\n>>> cur.fetchall()\n([54], [53], [52], [51], [50], [49], [48], [47], [46], [45])\n>>> cur.execute(\"CLOSE c\")\n>>> cur.execute(\"ROLLBACK\")\n>>>\n>>> con.close()\n\n```\n\n\n### BLOBs (Binary Large Objects)\n\nThere's a set of [SQL functions\n](https://www.postgresql.org/docs/current/lo-funcs.html) for manipulating BLOBs.\nHere's an example:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> con = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cur = con.cursor()\n>>>\n>>> # Create a BLOB and get its oid\n>>> data = b'hello'\n>>> cur = con.cursor()\n>>> cur.execute(\"SELECT lo_from_bytea(0, %s)\", [data])\n>>> oid = cur.fetchone()[0]\n>>>\n>>> # Create a table and store the oid of the BLOB\n>>> cur.execute(\"CREATE TEMPORARY TABLE image (raster oid)\")\n>>> cur.execute(\"INSERT INTO image (raster) VALUES (%s)\", [oid])\n>>>\n>>> # Retrieve the data using the oid\n>>> cur.execute(\"SELECT lo_get(%s)\", [oid])\n>>> cur.fetchall()\n([b'hello'],)\n>>>\n>>> # Add some data to the end of the BLOB\n>>> more_data = b' all'\n>>> offset = len(data)\n>>> cur.execute(\"SELECT lo_put(%s, %s, %s)\", [oid, offset, more_data])\n>>> cur.execute(\"SELECT lo_get(%s)\", [oid])\n>>> cur.fetchall()\n([b'hello all'],)\n>>>\n>>> # Download a part of the data\n>>> cur.execute(\"SELECT lo_get(%s, 6, 3)\", [oid])\n>>> cur.fetchall()\n([b'all'],)\n>>>\n>>> con.close()\n\n```\n\n\n### Parameter Limit\n\nThe protocol that PostgreSQL uses limits the number of parameters to 6,5535. The following will give\nan error:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> conn = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = conn.cursor()\n>>> SIZE = 100000\n>>> cursor.execute(\n...    f\"SELECT 1 WHERE 1 IN ({','.join(['%s'] * SIZE)})\",\n...    [1] * SIZE,\n... )\nTraceback (most recent call last):\nstruct.error: 'H' format requires 0 <= number <= 65535\n\n```\n\nOne way of working round this problem is to use the [unnest\n](https://www.postgresql.org/docs/current/functions-array.html) function:\n\n```python\n>>> import pg8000.dbapi\n>>>\n>>> conn = pg8000.dbapi.connect(user=\"postgres\", password=\"cpsnow\")\n>>> cursor = conn.cursor()\n>>> SIZE = 100000\n>>> cursor.execute(\n...    \"SELECT 1 WHERE 1 IN (SELECT unnest(CAST(%s AS int[])))\",\n...    [[1] * SIZE],\n... )\n>>> conn.close()\n\n```\n\n\n## Type Mapping\n\nThe following table shows the default mapping between Python types and PostgreSQL types,\nand vice versa.\n\nIf pg8000 doesn't recognize a type that it receives from PostgreSQL, it will return it\nas a ``str`` type. This is how pg8000 handles PostgreSQL ``enum`` and XML types. It's\npossible to change the default mapping using adapters (see the examples).\n\n| Python Type           | PostgreSQL Type | Notes                                   |\n|-----------------------|-----------------|-----------------------------------------|\n| bool                  | bool            |                                         |\n| int                   | int4            |                                         |\n| str                   | text            |                                         |\n| float                 | float8          |                                         |\n| decimal.Decimal       | numeric         |                                         |\n| bytes                 | bytea           |                                         |\n| datetime.datetime (without tzinfo) | timestamp without timezone | +/-infinity PostgreSQL values are represented as Python `str` values. If a `timestamp` is too big for `datetime.datetime` then a `str` is used. |\n| datetime.datetime (with tzinfo) | timestamp with timezone | +/-infinity PostgreSQL values are represented as Python `str` values. If a `timestamptz` is too big for `datetime.datetime` then a `str` is used. |\n| datetime.date | date | +/-infinity PostgreSQL values are represented as Python `str` values. If a `date` is too big for a `datetime.date` then a `str` is used. |\n| datetime.time         | time without time zone |                                  |\n| datetime.timedelta | interval | If an ``interval`` is too big for `datetime.timedelta` then a `PGInterval`  is used. |\n| None                  | NULL            |                                         |\n| uuid.UUID             | uuid            |                                         |\n| ipaddress.IPv4Address | inet            |                                         |\n| ipaddress.IPv6Address | inet            |                                         |\n| ipaddress.IPv4Network | inet            |                                         |\n| ipaddress.IPv6Network | inet            |                                         |\n| int                   | xid             |                                         |\n| list of int           | INT4[]          |                                         |\n| list of float         | FLOAT8[]        |                                         |\n| list of bool          | BOOL[]          |                                         |\n| list of str           | TEXT[]          |                                         |\n| int                   | int2vector      | Only from PostgreSQL to Python          |\n| JSON                  | json, jsonb     | The Python JSON is provided as a Python serialized string. Results returned as de-serialized JSON. |\n| pg8000.Range | range | PostgreSQL multirange types are | represented in Python as a list of  range types. |\n| tuple                 | composite type  | Only from Python to PostgreSQL          |\n\n\n## Theory Of Operation\n\n> A concept is tolerated inside the microkernel only if moving it outside the kernel,\n> i.e., permitting competing implementations, would prevent the implementation of the\n> system's required functionality.\n>\n> -- Jochen Liedtke, Liedtke's minimality principle\n\npg8000 is designed to be used with one thread per connection.\n\npg8000 communicates with the database using the [PostgreSQL Frontend/Backend Protocol\n](https://www.postgresql.org/docs/current/protocol.html) (FEBE). If a query has no\nparameters, pg8000 uses the 'simple query protocol'. If a query does have parameters,\npg8000 uses the 'extended query protocol' with unnamed prepared statements. The steps\nfor a query with parameters are:\n\n1. Query comes in.\n\n2. Send a PARSE message to the server to create an unnamed prepared statement.\n\n3. Send a BIND message to run against the unnamed prepared statement, resulting in an\n   unnamed portal on the server.\n\n4. Send an EXECUTE message to read all the results from the portal.\n\nIt's also possible to use named prepared statements. In which case the prepared\nstatement persists on the server, and represented in pg8000 using a\n`PreparedStatement` object. This means that the PARSE step gets executed once up\nfront, and then only the BIND and EXECUTE steps are repeated subsequently.\n\nThere are a lot of PostgreSQL data types, but few primitive data types in Python. By\ndefault, pg8000 doesn't send PostgreSQL data type information in the PARSE step, in\nwhich case PostgreSQL assumes the types implied by the SQL statement. In some cases\nPostgreSQL can't work out a parameter type and so an [explicit cast\n](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS)\ncan be used in the SQL.\n\nIn the FEBE protocol, each query parameter can be sent to the server either as binary\nor text according to the format code. In pg8000 the parameters are always sent as text.\n\nOccasionally, the network connection between pg8000 and the server may go down. If\npg8000 encounters a network problem it'll raise an `InterfaceError` with the message\n`network error` and with the original exception set as the [cause\n](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement).\n\n\n## Native API Docs\n\n### pg8000.native.Error\n\nGeneric exception that is the base exception of the other error exceptions.\n\n\n### pg8000.native.InterfaceError\n\nFor errors that originate within pg8000.\n\n\n### pg8000.native.DatabaseError\n\nFor errors that originate from the server.\n\n### 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)\n\nCreates a connection to a PostgreSQL database.\n\n- *user* - The username to connect to the PostgreSQL server with. If your server character encoding is not `ascii` or `utf8`, then you need to provide `user` as bytes, eg. `'my_name'.encode('EUC-JP')`.\n- *host* - The hostname of the PostgreSQL server to connect with. Providing this parameter is necessary for TCP/IP connections. One of either `host` or `unix_sock` must be provided. The default is `localhost`.\n- *database* - The name of the database instance to connect with. If `None` then the PostgreSQL server will assume the database name is the same as the username. If your server character encoding is not `ascii` or `utf8`, then you need to provide `database` as bytes, eg. `'my_db'.encode('EUC-JP')`.\n- *port* - The TCP/IP port of the PostgreSQL server instance.  This parameter defaults to `5432`, the registered common port of PostgreSQL TCP/IP servers.\n- *password* - The user password to connect to the server with. This parameter is optional; if omitted and the database server requests password-based authentication, the connection will fail to open. If this parameter is provided but not requested by the server, no error will occur. If your server character encoding is not `ascii` or `utf8`, then you need to provide `password` as bytes, eg.  `'my_password'.encode('EUC-JP')`.\n- *source_address* - The source IP address which initiates the connection to the PostgreSQL server. The default is `None` which means that the operating system will choose the source address.\n- *unix_sock* - The path to the UNIX socket to access the database through, for example, `'/tmp/.s.PGSQL.5432'`. One of either `host` or `unix_sock` must be provided.\n- *ssl_context* - This governs SSL encryption for TCP/IP sockets. It can have four values:\n  - `None`, the default, meaning that an attempt will be made to connect over SSL, but if this is rejected by the server then pg8000 will fall back to using a plain socket.\n  - `True`, means use SSL with an `ssl.SSLContext` with the minimum of checks.\n  - `False`, means to not attempt to create an SSL socket.\n  - An instance of `ssl.SSLContext` which will be used to create the SSL connection.\n- *timeout* - This is the time in seconds before the connection to the server will time out. The default is `None` which means no timeout.\n- *tcp_keepalive* - If `True` then use [TCP keepalive](https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive). The default is `True`.\n- *application_name* - Sets the [application\\_name](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 provide values as bytes, eg.  `'my_application_name'.encode('EUC-JP')`. The default is `None` which means that the server will set the application name.\n- *replication* - Used to run in [streaming replication mode](https://www.postgresql.org/docs/current/protocol-replication.html). If your server character encoding is not `ascii` or `utf8`, then you need to provide values as bytes, eg. `'database'.encode('EUC-JP')`.\n- *sock*  - A socket-like object to use for the connection. For example, `sock` could be a plain `socket.socket`, or it could represent an SSH tunnel or perhaps an `ssl.SSLSocket` to an SSL proxy. If an `ssl.SSLContext` is provided, then it will be used to attempt to create an SSL socket from the provided socket. \n\n### pg8000.native.Connection.notifications\n\nA deque of server-side\n[notifications](https://www.postgresql.org/docs/current/sql-notify.html) received by\nthis database connection (via the `LISTEN` / `NOTIFY` PostgreSQL commands). Each list\nitem is a three-element tuple containing the PostgreSQL backend PID that issued the\nnotify, the channel and the payload.\n\n\n### pg8000.native.Connection.notices\n\nA deque of server-side notices received by this database connection.\n\n\n### pg8000.native.Connection.parameter\\_statuses\n\nA `dict` of server-side parameter statuses received by this database connection.\n\n\n### pg8000.native.Connection.run(sql, stream=None, types=None, \\*\\*kwargs)\n\nExecutes an sql statement, and returns the results as a `list`. For example:\n\n```\ncon.run(\"SELECT * FROM cities where population > :pop\", pop=10000)\n```\n\n- *sql* - The SQL statement to execute. Parameter placeholders appear as a `:` followed by the parameter name.\n- *stream* - For use with the PostgreSQL [COPY](http://www.postgresql.org/docs/current/static/sql-copy.html) command. The nature of the parameter depends on whether the SQL command is `COPY FROM` or `COPY TO`.\n  - `COPY FROM` - The stream parameter must be a readable file-like object or an iterable. If it's an\n    iterable then the items can be ``str`` or binary.\n  - `COPY TO` - The stream parameter must be a writable file-like object.\n- *types* - A dictionary of oids. A key corresponds to a parameter. \n- *kwargs* - The parameters of the SQL statement.\n\n\n### pg8000.native.Connection.row\\_count\n\nThis read-only attribute contains the number of rows that the last `run()` method\nproduced (for query statements like ``SELECT``) or affected (for modification statements\nlike `UPDATE`.\n\nThe value is -1 if:\n\n- No `run()` method has been performed yet.\n- There was no rowcount associated with the last `run()`.\n\n\n### pg8000.native.Connection.columns\n\nA list of column metadata. Each item in the list is a dictionary with the following\nkeys:\n\n- name\n- table\\_oid\n- column\\_attrnum\n- type\\_oid\n- type\\_size\n- type\\_modifier\n- format\n\n\n### pg8000.native.Connection.close()\n\nCloses the database connection.\n\n\n### pg8000.native.Connection.register\\_out\\_adapter(typ, out\\_func)\n\nRegister a type adapter for types going out from pg8000 to the server.\n\n- *typ* - The Python class that the adapter is for.\n- *out_func* - A function that takes the Python object and returns its string representation in the format that the server requires.\n\n\n### pg8000.native.Connection.register\\_in\\_adapter(oid, in\\_func)\n\nRegister a type adapter for types coming in from the server to pg8000.\n\n- *oid* - The PostgreSQL type identifier found in the [pg\\_type system catalog](https://www.postgresql.org/docs/current/catalog-pg-type.html).\n- *in_func*  - A function that takes the PostgreSQL string representation and returns a corresponding\n  Python object.\n\n\n### pg8000.native.Connection.prepare(sql)\n\nReturns a `PreparedStatement` object which represents a [prepared statement\n](https://www.postgresql.org/docs/current/sql-prepare.html) on the server. It can\nsubsequently be repeatedly executed.\n\n- *sql* - The SQL statement to prepare. Parameter placeholders appear as a `:` followed by the parameter name.\n\n\n### pg8000.native.PreparedStatement\n\nA prepared statement object is returned by the `pg8000.native.Connection.prepare()`\nmethod of a connection. It has the following methods:\n\n\n#### pg8000.native.PreparedStatement.run(\\*\\*kwargs)\n\nExecutes the prepared statement, and returns the results as a `tuple`.\n\n- *kwargs* - The parameters of the prepared statement.\n\n\n#### pg8000.native.PreparedStatement.close()\n\nCloses the prepared statement, releasing the prepared statement held on the server.\n\n\n### pg8000.native.identifier(ident)\n\nCorrectly quotes and escapes a string to be used as an [SQL identifier\n](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).\n- *ident* - The `str` to be used as an SQL identifier.\n\n\n### pg8000.native.literal(value)\n\nCorrectly quotes and escapes a value to be used as an [SQL literal\n](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS).\n- *value* - The value to be used as an SQL literal.\n\n\n## DB-API 2 Docs\n\n### Properties\n\n#### pg8000.dbapi.apilevel\n\nThe DBAPI level supported, currently \"2.0\".\n\n\n#### pg8000.dbapi.threadsafety\n\nInteger constant stating the level of thread safety the DBAPI interface supports. For\npg8000, the threadsafety value is 1, meaning that threads may share the module but not\nconnections.\n\n\n#### pg8000.dbapi.paramstyle\n\nString property stating the type of parameter marker formatting expected by\nthe interface.  This value defaults to \"format\", in which parameters are\nmarked in this format: \"WHERE name=%s\".\n\nAs an extension to the DBAPI specification, this value is not constant; it can be\nchanged to any of the following values:\n\n- *qmark* - Question mark style, eg. `WHERE name=?`\n- *numeric* - Numeric positional style, eg. `WHERE name=:1`\n- *named* - Named style, eg. `WHERE name=:paramname`\n- *format* - printf format codes, eg. `WHERE name=%s`\n- *pyformat* - Python format codes, eg. `WHERE name=%(paramname)s`\n\n\n#### pg8000.dbapi.STRING\n\nString type oid.\n\n\n#### pg8000.dbapi.BINARY\n\n\n#### pg8000.dbapi.NUMBER\n\nNumeric type oid.\n\n\n#### pg8000.dbapi.DATETIME\n\nTimestamp type oid\n\n\n#### pg8000.dbapi.ROWID\n\nROWID type oid\n\n\n### Functions\n\n#### 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)\n\nCreates a connection to a PostgreSQL database.\n\n- *user*  - The username to connect to the PostgreSQL server with. If your server character encoding is not `ascii` or `utf8`, then you need to provide `user` as bytes, eg. `'my_name'.encode('EUC-JP')`.\n- *host* - The hostname of the PostgreSQL server to connect with. Providing this parameter is necessary for TCP/IP connections. One of either `host` or `unix_sock` must be provided. The default is `localhost`.\n- *database* - The name of the database instance to connect with. If `None` then the PostgreSQL server will assume the database name is the same as the username. If your server character encoding is not `ascii` or `utf8`, then you need to provide `database` as bytes, eg. `'my_db'.encode('EUC-JP')`.\n- *port* - The TCP/IP port of the PostgreSQL server instance.  This parameter defaults to `5432`, the registered common port of PostgreSQL TCP/IP servers.\n- *password* - The user password to connect to the server with. This parameter is optional; if omitted and the database server requests password-based authentication, the connection will fail to open. If this parameter is provided but not requested by the server, no error will occur. If your server character encoding is not `ascii` or `utf8`, then you need to provide `password` as bytes, eg.  `'my_password'.encode('EUC-JP')`.\n- *source_address* - The source IP address which initiates the connection to the PostgreSQL server. The default is `None` which means that the operating system will choose the source address.\n- *unix_sock* - The path to the UNIX socket to access the database through, for example, `'/tmp/.s.PGSQL.5432'`. One of either `host` or `unix_sock` must be provided.\n- *ssl_context* - This governs SSL encryption for TCP/IP sockets. It can have four values:\n  - `None`, the default, meaning that an attempt will be made to connect over SSL, but if this is rejected by the server then pg8000 will fall back to using a plain socket.\n  - `True`, means use SSL with an `ssl.SSLContext` with the minimum of checks.\n  - `False`, means to not attempt to create an SSL socket.\n  - An instance of `ssl.SSLContext` which will be used to create the SSL connection.\n- *timeout* - This is the time in seconds before the connection to the server will time out. The default is `None` which means no timeout.\n- *tcp_keepalive* - If `True` then use [TCP keepalive](https://en.wikipedia.org/wiki/Keepalive#TCP_keepalive). The default is `True`.\n- *application_name* - Sets the [application\\_name](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 provide values as bytes, eg. `'my_application_name'.encode('EUC-JP')`. The default is `None` which means that the server will set the application name.\n- *replication* - Used to run in [streaming replication mode](https://www.postgresql.org/docs/current/protocol-replication.html). If your server character encoding is not `ascii` or `utf8`, then you need to provide values as bytes, eg. `'database'.encode('EUC-JP')`.\n- *sock* - A socket-like object to use for the connection. For example, `sock` could be a plain `socket.socket`, or it could represent an SSH tunnel or perhaps an `ssl.SSLSocket` to an SSL proxy. If an `ssl.SSLContext` is provided, then it will be used to attempt to create an SSL socket from the provided socket. \n\n\n#### pg8000.dbapi.Date(year, month, day)\n\nConstruct an object holding a date value.\n\nThis property is part of the `DBAPI 2.0 specification\n<http://www.python.org/dev/peps/pep-0249/>`_.\n\nReturns: `datetime.date`\n\n\n#### pg8000.dbapi.Time(hour, minute, second)\n\nConstruct an object holding a time value.\n\nReturns: `datetime.time`\n\n\n#### pg8000.dbapi.Timestamp(year, month, day, hour, minute, second)\n\nConstruct an object holding a timestamp value.\n\nReturns: `datetime.datetime`\n\n\n#### pg8000.dbapi.DateFromTicks(ticks)\n\nConstruct an object holding a date value from the given ticks value (number of seconds\nsince the epoch).\n\nReturns: `datetime.datetime`\n\n\n#### pg8000.dbapi.TimeFromTicks(ticks)\n\nConstruct an object holding a time value from the given ticks value (number of seconds\nsince the epoch).\n\nReturns: `datetime.time`\n\n\n#### pg8000.dbapi.TimestampFromTicks(ticks)\n\nConstruct an object holding a timestamp value from the given ticks value (number of\nseconds since the epoch).\n\nReturns: `datetime.datetime`\n\n\n#### pg8000.dbapi.Binary(value)\n\nConstruct an object holding binary data.\n\nReturns: `bytes`\n\n\n### Generic Exceptions\n\nPg8000 uses the standard DBAPI 2.0 exception tree as \"generic\" exceptions. Generally,\nmore specific exception types are raised; these specific exception types are derived\nfrom the generic exceptions.\n\n#### pg8000.dbapi.Warning\n\nGeneric exception raised for important database warnings like data truncations. This\nexception is not currently used by pg8000.\n\n\n#### pg8000.dbapi.Error\n\nGeneric exception that is the base exception of all other error exceptions.\n\n\n#### pg8000.dbapi.InterfaceError\n\nGeneric exception raised for errors that are related to the database interface rather\nthan the database itself. For example, if the interface attempts to use an SSL\nconnection but the server refuses, an InterfaceError will be raised.\n\n\n#### pg8000.dbapi.DatabaseError\n\nGeneric exception raised for errors that are related to the database. This exception is\ncurrently never raised by pg8000.\n\n\n#### pg8000.dbapi.DataError\n\nGeneric exception raised for errors that are due to problems with the processed data.\nThis exception is not currently raised by pg8000.\n\n\n#### pg8000.dbapi.OperationalError\n\nGeneric exception raised for errors that are related to the database's operation and not\nnecessarily under the control of the programmer. This exception is currently never\nraised by pg8000.\n\n\n#### pg8000.dbapi.IntegrityError\n\nGeneric exception raised when the relational integrity of the database is affected. This\nexception is not currently raised by pg8000.\n\n\n#### pg8000.dbapi.InternalError\n\nGeneric exception raised when the database encounters an internal error. This is\ncurrently only raised when unexpected state occurs in the pg8000 interface itself, and\nis typically the result of a interface bug.\n\n\n#### pg8000.dbapi.ProgrammingError\n\nGeneric exception raised for programming errors. For example, this exception is raised\nif more parameter fields are in a query string than there are available parameters.\n\n\n#### pg8000.dbapi.NotSupportedError\n\nGeneric exception raised in case a method or database API was used which is not\nsupported by the database.\n\n\n### Classes\n\n\n#### pg8000.dbapi.Connection\n\nA connection object is returned by the `pg8000.dbapi.connect()` function. It represents a\nsingle physical connection to a PostgreSQL database.\n\n\n#### pg8000.dbapi.Connection.autocommit\n\nFollowing the DB-API specification, autocommit is off by default. It can be turned on by\nsetting this boolean pg8000-specific autocommit property to ``True``.\n\n\n#### pg8000.dbapi.Connection.close()\n\nCloses the database connection.\n\n\n#### pg8000.dbapi.Connection.cursor()\n\nCreates a `pg8000.dbapi.Cursor` object bound to this connection.\n\n\n#### pg8000.dbapi.Connection.rollback()\n\nRolls back the current database transaction.\n\n\n#### pg8000.dbapi.Connection.tpc_begin(xid)\n\nBegins a TPC transaction with the given transaction ID xid. This method should be\ncalled outside of a transaction (i.e. nothing may have executed since the last\n`commit()`  or `rollback()`. Furthermore, it is an error to call `commit()` or\n`rollback()` within the TPC transaction. A `ProgrammingError` is raised, if the\napplication calls `commit()` or `rollback()` during an active TPC transaction.\n\n\n#### pg8000.dbapi.Connection.tpc_commit(xid=None)\n\nWhen called with no arguments, `tpc_commit()` commits a TPC transaction previously\nprepared with `tpc_prepare()`. If `tpc_commit()` is called prior to\n`tpc_prepare()`, a single phase commit is performed. A transaction manager may choose\nto do this if only a single resource is participating in the global transaction.\n\nWhen called with a transaction ID `xid`, the database commits the given transaction.\nIf an invalid transaction ID is provided, a `ProgrammingError` will be raised. This\nform should be called outside of a transaction, and is intended for use in recovery.\n\nOn return, the TPC transaction is ended.\n\n\n#### pg8000.dbapi.Connection.tpc_prepare()\n\nPerforms the first phase of a transaction started with `.tpc_begin()`. A\n`ProgrammingError` is be raised if this method is called outside of a TPC transaction.\n\nAfter calling `tpc_prepare()`, no statements can be executed until `tpc_commit()` or\n`tpc_rollback()` have been called.\n\n\n#### pg8000.dbapi.Connection.tpc_recover()\n\nReturns a list of pending transaction IDs suitable for use with `tpc_commit(xid)` or\n`tpc_rollback(xid)`.\n\n\n#### pg8000.dbapi.Connection.tpc_rollback(xid=None)\n\nWhen called with no arguments, `tpc_rollback()` rolls back a TPC transaction. It may\nbe called before or after `tpc_prepare()`.\n\nWhen called with a transaction ID xid, it rolls back the given transaction. If an\ninvalid transaction ID is provided, a `ProgrammingError` is raised. This form should\nbe called outside of a transaction, and is intended for use in recovery.\n\nOn return, the TPC transaction is ended.\n\n\n#### pg8000.dbapi.Connection.xid(format_id, global_transaction_id, branch_qualifier)\n\nCreate a Transaction IDs (only global_transaction_id is used in pg) format_id and\nbranch_qualifier are not used in postgres global_transaction_id may be any string\nidentifier supported by postgres returns a tuple (format_id, global_transaction_id,\nbranch_qualifier)\n\n\n#### pg8000.dbapi.Cursor\n\nA cursor object is returned by the `pg8000.dbapi.Connection.cursor()` method of a\nconnection. It has the following attributes and methods:\n\n##### pg8000.dbapi.Cursor.arraysize\n\nThis read/write attribute specifies the number of rows to fetch at a time with\n`pg8000.dbapi.Cursor.fetchmany()`.  It defaults to 1.\n\n\n##### pg8000.dbapi.Cursor.connection\n\nThis read-only attribute contains a reference to the connection object (an instance of\n`pg8000.dbapi.Connection`) on which the cursor was created.\n\n\n##### pg8000.dbapi.Cursor.rowcount\n\nThis read-only attribute contains the number of rows that the last `execute()` or\n`executemany()` method produced (for query statements like `SELECT`) or affected\n(for modification statements like `UPDATE`.\n\nThe value is -1 if:\n\n- No `execute()` or `executemany()` method has been performed yet on the cursor.\n- There was no rowcount associated with the last `execute()`.\n- At least one of the statements executed as part of an `executemany()` had no row\n  count associated with it.\n\n\n##### pg8000.dbapi.Cursor.description\n\nThis read-only attribute is a sequence of 7-item sequences. Each value contains\ninformation describing one result column. The 7 items returned for each column are\n(name, type_code, display_size, internal_size, precision, scale, null_ok). Only the\nfirst two values are provided by the current implementation.\n\n\n##### pg8000.dbapi.Cursor.close()\n\nCloses the cursor.\n\n\n##### pg8000.dbapi.Cursor.execute(operation, args=None, stream=None)\n\nExecutes a database operation. Parameters may be provided as a sequence, or as a\nmapping, depending upon the value of `pg8000.dbapi.paramstyle`. Returns the cursor,\nwhich may be iterated over.\n\n- *operation* - The SQL statement to execute.\n- *args* - If `pg8000.dbapi.paramstyle` is `qmark`, `numeric`, or `format`, this argument should be an array of parameters to bind into the statement. If `pg8000.dbapi.paramstyle` is `named`, the argument should be a `dict` mapping of parameters. If `pg8000.dbapi.paramstyle` is `pyformat`, the argument value may be either an array or a mapping.\n- *stream* - This is a pg8000 extension for use with the PostgreSQL [COPY](http://www.postgresql.org/docs/current/static/sql-copy.html) command. For a `COPY FROM` the parameter must be a readable file-like object, and for `COPY TO` it must be writable.\n\n\n##### pg8000.dbapi.Cursor.executemany(operation, param_sets)\n\nPrepare a database operation, and then execute it against all parameter sequences or\nmappings provided.\n\n- *operation* - The SQL statement to execute.\n- *parameter_sets* - A sequence of parameters to execute the statement with. The values in the sequence should be sequences or mappings of parameters, the same as the args argument of the `pg8000.dbapi.Cursor.execute()` method.\n\n\n##### pg8000.dbapi.Cursor.callproc(procname, parameters=None)\n\nCall a stored database procedure with the given name and optional parameters.\n\n- *procname* - The name of the procedure to call.\n- *parameters* - A list of parameters.\n\n\n##### pg8000.dbapi.Cursor.fetchall()\n\nFetches all remaining rows of a query result.\n\nReturns: A sequence, each entry of which is a sequence of field values making up a row.\n\n\n##### pg8000.dbapi.Cursor.fetchmany(size=None)\n\nFetches the next set of rows of a query result.\n\n- *size* - The number of rows to fetch when called.  If not provided, the `pg8000.dbapi.Cursor.arraysize` attribute value is used instead.\n\nReturns: A sequence, each entry of which is a sequence of field values making up a row.\nIf no more rows are available, an empty sequence will be returned.\n\n\n##### pg8000.dbapi.Cursor.fetchone()\n\nFetch the next row of a query result set.\n\nReturns: A row as a sequence of field values, or `None` if no more rows are available.\n\n\n##### pg8000.dbapi.Cursor.setinputsizes(\\*sizes)\n\nUsed to set the parameter types of the next query. This is useful if it's difficult for\npg8000 to work out the types from the parameters themselves (eg. for parameters of type\nNone).\n\n- *sizes* - Positional parameters that are either the Python type of the parameter to be sent, or the PostgreSQL oid. Common oids are available as constants such as `pg8000.STRING`, `pg8000.INTEGER`, `pg8000.TIME` etc.\n\n\n##### pg8000.dbapi.Cursor.setoutputsize(size, column=None)\n\nNot implemented by pg8000.\n\n\n#### pg8000.dbapi.Interval\n\nAn Interval represents a measurement of time.  In PostgreSQL, an interval is defined in\nthe measure of months, days, and microseconds; as such, the pg8000 interval type\nrepresents the same information.\n\nNote that values of the `pg8000.dbapi.Interval.microseconds`,\n`pg8000.dbapi.Interval.days`, and `pg8000.dbapi.Interval.months` properties are\nindependently measured and cannot be converted to each other. A month may be 28, 29, 30,\nor 31 days, and a day may occasionally be lengthened slightly by a leap second.\n\n\n## Design Decisions\n\nFor the `Range` type, the constructor follows the [PostgreSQL range constructor functions\n](https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-CONSTRUCT)\nwhich makes [[closed, open)](https://fhur.me/posts/always-use-closed-open-intervals)\nthe easiest to express:\n\n```python\n>>> from pg8000.types import Range\n>>>\n>>> pg_range = Range(2, 6)\n\n```\n\n\n## Tests\n\n- Install [tox](http://testrun.org/tox/latest/): `pip install tox`\n\n- Enable the PostgreSQL hstore extension by running the SQL command:\n  `create extension hstore;`\n\n- Add a line to `pg_hba.conf` for the various authentication options:\n\n```\nhost    pg8000_md5           all        127.0.0.1/32            md5\nhost    pg8000_gss           all        127.0.0.1/32            gss\nhost    pg8000_password      all        127.0.0.1/32            password\nhost    pg8000_scram_sha_256 all        127.0.0.1/32            scram-sha-256\nhost    all                  all        127.0.0.1/32            trust\n```\n\n- Set password encryption to `scram-sha-256` in `postgresql.conf`:\n  `password_encryption = 'scram-sha-256'`\n\n- Set the password for the postgres user: `ALTER USER postgresql WITH PASSWORD 'pw';`\n\n- Run `tox` from the `pg8000` directory: `tox`\n\nThis will run the tests against the Python version of the virtual environment, on the\nmachine, and the installed PostgreSQL version listening on port 5432, or the `PGPORT`\nenvironment variable if set.\n\nBenchmarks are run as part of the test suite at `tests/test_benchmarks.py`.\n\n\n## Doing A Release Of pg8000\n\nRun `tox` to make sure all tests pass, then update the release notes, then do:\n\n\n```\ngit tag -a x.y.z -m \"version x.y.z\"\nrm -r dist\npython -m build\ntwine upload dist/*\n```\n\n\n## Release Notes\n\n### Version 1.31.2, 2024-04-28\n\n- Fix bug where `parameter_statuses` fails for non-ascii encoding.\n- Add support for Python 3.12\n\n\n### Version 1.31.1, 2024-04-01\n\n- Move to src style layout, and also for packaging use Hatch rather than setuptools. This means that if the source distribution has a directory added to it (as is needed for packaging for OS distributions) the package can still be built.\n\n\n### Version 1.31.0, 2024-03-31\n\n- Now the `ssl_context` connection parameter can have one of four values:\n  - None - The default, meaning it'll try and connect over SSL but fall back to a plain socket if not.\n  - True - Will try and connect over SSL and fail if not.\n  - False - It'll not try to connect over SSL.\n  - SSLContext object - It'll use this object to connect over SSL.\n\n\n### Version 1.30.5, 2024-02-22\n\n- Fix bug that now means the number of parameters cam be as high as an unsigned 16 bit\n  integer will go.\n\n\n### Version 1.30.4, 2024-01-03\n\n- Add support for more range and multirange types.\n- Make the `Connection.parameter_statuses` property a `dict` rather than a `dequeue`.\n\n\n### Version 1.30.3, 2023-10-31\n\n- Fix problem with PG date overflowing Python types. Now we return the `str` we got from the\n  server if we can't parse it. \n\n\n### Version 1.30.2, 2023-09-17\n\n- Bug fix where dollar-quoted string constants weren't supported.\n\n\n### Version 1.30.1, 2023-07-29\n\n- There was a problem uploading the previous version (1.30.0) to PyPI because the markup of the README.rst was invalid. There's now a step in the automated tests to check for this.\n\n\n### Version 1.30.0, 2023-07-27\n\n- Remove support for Python 3.7\n- Add a `sock` keyword parameter for creating a connection from a pre-configured socket.\n\n\n### Version 1.29.8, 2023-06-16\n\n- Ranges don't work with legacy API.\n\n\n### Version 1.29.7, 2023-06-16\n\n- Add support for PostgreSQL `range` and `multirange` types. Previously pg8000 would just return them as strings, but now they're returned as `Range` and lists of `Range`.\n- The PostgreSQL `record` type is now returned as a `tuple` of strings, whereas before it was returned as one string.\n\n\n### Version 1.29.6, 2023-05-29\n\n- Fixed two bugs with composite types. Nulls should be represented by an empty string, and in an array of composite types, the elements should be surrounded by double quotes.\n\n\n### Version 1.29.5, 2023-05-09\n\n- Fixed bug where pg8000 didn't handle the case when the number of bytes received from a socket was fewer than requested. This was being interpreted as a network error, but in fact we just needed to wait until more bytes were available.\n- When using the `PGInterval` type, if a response from the server contained the period `millennium`, it wasn't recognised. This was caused by a spelling mistake where we had `millenium` rather than `millennium`.\n- Added support for sending PostgreSQL composite types. If a value is sent as a `tuple`, pg8000 will send it to the server as a `(` delimited composite string.\n\n\n### Version 1.29.4, 2022-12-14\n\n- Fixed bug in `pg8000.dbapi` in the `setinputsizes()` method where if a `size` was a recognized Python type, the method failed.\n\n\n### Version 1.29.3, 2022-10-26\n\n- Upgrade the SCRAM library to version 1.4.3. This adds support for the case where the client supports channel binding but the server doesn't.\n\n\n### Version 1.29.2, 2022-10-09\n\n- Fixed a bug where in a literal array, items such as `\\n` and `\\r` weren't escaped properly before being sent to the server.\n- Fixed a bug where if the PostgreSQL server has a half-hour time zone set, values of type `timestamp with time zone` failed. This has been fixed by using the `parse` function of the `dateutil` package if the `datetime` parser fails.\n\n\n### Version 1.29.1, 2022-05-23\n\n- In trying to determine if there's been a failed commit, check for `ROLLBACK TO SAVEPOINT`.\n\n\n### Version 1.29.0, 2022-05-21\n\n- Implement a workaround for the [silent failed commit](https://github.com/tlocke/pg8000/issues/36) bug.\n- Previously if an empty string was sent as the query an exception would be raised, but that isn't done now.\n\n\n### Version 1.28.3, 2022-05-18\n\n- Put back `__version__` attributes that were inadvertently removed.\n\n\n### Version 1.28.2, 2022-05-17\n\n- Use a build system that's compliant with PEP517.\n\n\n### Version 1.28.1, 2022-05-17\n\n- If when doing a `COPY FROM` the `stream` parameter is an iterator of `str`, pg8000 used to silently append a newline to the end. That no longer happens.\n\n\n### Version 1.28.0, 2022-05-17\n\n- When using the `COPY FROM` SQL statement, allow the `stream` parameter to be an iterable.\n\n\n### Version 1.27.1, 2022-05-16\n\n- The `seconds` attribute of `PGInterval` is now always a `float`, to cope with fractional seconds.\n- Updated the `interval` parsers for `iso_8601` and `sql_standard` to take account of fractional seconds.\n\n\n### Version 1.27.0, 2022-05-16\n\n- It used to be that by default, if pg8000 received an `interval` type from the server and it was too big to fit into a `datetime.timedelta` then an exception would be raised. Now if an interval is too big for `datetime.timedelta` a `PGInterval` is returned.\n- pg8000 now supports all the output formats for an `interval` (`postgres`, `postgres_verbose`, `iso_8601` and `sql_standard`).\n\n\n### Version 1.26.1, 2022-04-23\n\n- Make sure all tests are run by the GitHub Actions tests on commit.\n- Remove support for Python 3.6\n- Remove support for PostgreSQL 9.6\n\n\n### Version 1.26.0, 2022-04-18\n\n- When connecting, raise an `InterfaceError('network error')` rather than let the underlying `struct.error` float up.\n- Make licence text the same as that used by the OSI. Previously the licence wording differed slightly from the BSD 3 Clause licence at https://opensource.org/licenses/BSD-3-Clause. This meant that automated tools didn't pick it up as being Open Source. The changes are believed to not alter the meaning of the license at all.\n\n\n### Version 1.25.0, 2022-04-17\n\n- Fix more cases where a `ResourceWarning` would be raise because of a socket that had been left open.\n- We now have a single `InterfaceError` with the message 'network error' for all network errors, with the underlying exception held in the `cause` of the exception.\n\n\n### Version 1.24.2, 2022-04-15\n\n- To prevent a `ResourceWarning` close socket if a connection can't be created.\n\n\n### Version 1.24.1, 2022-03-02\n\n- Return pg +/-infinity dates as `str`. Previously +/-infinity pg values would cause an error when returned, but now we return +/-infinity as strings.\n\n\n### Version 1.24.0, 2022-02-06\n\n- Add SQL escape functions identifier() and literal() to the native API. For use when a query can't be parameterised and the SQL string has to be created using untrusted values.\n\n\n### Version 1.23.0, 2021-11-13\n\n- If a query has no parameters, then the query will no longer be parsed. Although there are performance benefits for doing this, the main reason is to avoid query rewriting, which can introduce errors.\n\n\n### Version 1.22.1, 2021-11-10\n\n- Fix bug in PGInterval type where `str()` failed for a millennia value.\n\n\n### Version 1.22.0, 2021-10-13\n\n- Rather than specifying the oids in the `Parse` step of the Postgres protocol, pg8000 now omits them, and so Postgres will use the oids it determines from the query. This makes the pg8000 code simpler and also it should also make the nuances of type matching more straightforward.\n",
    "bugtrack_url": null,
    "license": "BSD 3-Clause License",
    "summary": "PostgreSQL interface library",
    "version": "1.31.2",
    "project_urls": {
        "Homepage": "https://github.com/tlocke/pg8000"
    },
    "split_keywords": [
        "dbapi",
        " postgresql"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "09a02b30d52017c4ced8fc107386666ea7573954eb708bf66121f0229df05d41",
                "md5": "6785e25d1cf8df0fb15a5451290c2561",
                "sha256": "436c771ede71af4d4c22ba867a30add0bc5c942d7ab27fadbb6934a487ecc8f6"
            },
            "downloads": -1,
            "filename": "pg8000-1.31.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6785e25d1cf8df0fb15a5451290c2561",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 54494,
            "upload_time": "2024-04-28T16:57:44",
            "upload_time_iso_8601": "2024-04-28T16:57:44.431968Z",
            "url": "https://files.pythonhosted.org/packages/09/a0/2b30d52017c4ced8fc107386666ea7573954eb708bf66121f0229df05d41/pg8000-1.31.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0fd70554640cbe3e193184796bedb6de23f797c03958425176faf0e694c06eb0",
                "md5": "d133eebc067dbe2318a861f1589cafee",
                "sha256": "1ea46cf09d8eca07fe7eaadefd7951e37bee7fabe675df164f1a572ffb300876"
            },
            "downloads": -1,
            "filename": "pg8000-1.31.2.tar.gz",
            "has_sig": false,
            "md5_digest": "d133eebc067dbe2318a861f1589cafee",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 113513,
            "upload_time": "2024-04-28T16:57:47",
            "upload_time_iso_8601": "2024-04-28T16:57:47.611102Z",
            "url": "https://files.pythonhosted.org/packages/0f/d7/0554640cbe3e193184796bedb6de23f797c03958425176faf0e694c06eb0/pg8000-1.31.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-28 16:57:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tlocke",
    "github_project": "pg8000",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pg8000"
}
        
Elapsed time: 0.24369s