API Reference¶
Complete API reference for all pycopg classes and methods.
Config¶
Configuration for database connections.
from pycopg import Config
Constructor¶
Config(
host: str = "localhost",
port: int = 5432,
database: str = "postgres",
user: str = "postgres",
password: str = "",
sslmode: Optional[str] = None,
options: dict = {}
)
Class Methods¶
Method |
Description |
|---|---|
|
Create Config from PostgreSQL URL |
|
Create Config from environment variables |
from_env Parameters¶
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
Path to .env file |
|
|
|
Whether to load .env file. Set |
Properties¶
Property |
Type |
Description |
|---|---|---|
|
|
psycopg-compatible DSN string |
|
|
SQLAlchemy-compatible URL |
|
|
Statement timeout in milliseconds (None = no limit) |
Methods¶
Method |
Description |
|---|---|
|
Return dict for psycopg.connect() |
|
Create new Config with different database |
Database¶
Synchronous database interface.
from pycopg import Database
Constructor¶
Database(config: Config)
Class Methods¶
Method |
Description |
|---|---|
|
Create from PostgreSQL URL |
|
Create from environment |
|
Create a new database and connect to it |
|
Create database using env credentials |
Query Methods¶
Method |
Parameters |
Returns |
Description |
|---|---|---|---|
|
|
|
Execute SQL, return results |
|
|
|
Execute for multiple params |
|
|
|
Fetch single row |
|
|
|
Fetch single value |
|
|
|
Fetch all rows as list of dicts |
CRUD Methods (v0.9.0)¶
Flat helpers on Database for common single-table operations. All column names are validated;
values are bound as %s. Full sync/async parity on AsyncDatabase.
delete_where, update_where, exists, count, paginate, paginate_page (v1.1.0), and
paginate_keyset (v1.1.0) additionally accept keyword-only where_sql: str | None = None +
where_params: Sequence | None = None — a raw-SQL escape hatch for predicates the where dict
cannot express (e.g. where_sql="age > %s AND status = ANY(%s)"). where and where_sql are
mutually exclusive; the fragment is passed through verbatim (never identifier-validated —
the caller owns the SQL text), only where_params are bound as %s.
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Pagination (v1.1.0)¶
Two additional pagination methods return a typed Page envelope instead of a plain
list[dict]. paginate() itself is unchanged (frozen list[dict]).
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
paginate_page is the offset-pagination sibling of paginate(). paginate_keyset is stable,
index-friendly seek pagination via a PostgreSQL row-value comparison
((c1, c2) > (%s, %s)) instead of OFFSET — order_by is mandatory (append a unique column
such as the primary key as a tiebreaker), forward-only for this release. order_by columns
should be NOT NULL — the row-value comparison follows SQL NULL semantics, so rows with a
NULL key are silently skipped by the seek predicate. Feed Page.next_cursor back as the next
call’s after= to page forward, processing each page’s rows before advancing the cursor:
page = db.paginate_keyset("events", 50, order_by=["created_at", "id"])
while True:
for row in page.rows:
... # process
if not page.has_next:
break
page = db.paginate_keyset(
"events", 50, order_by=["created_at", "id"], after=page.next_cursor
)
Page (frozen dataclass)¶
Field |
Type |
Description |
|---|---|---|
|
|
The page of rows, already trimmed to |
|
|
Full filtered |
|
|
Always computed cheaply via a |
|
|
For |
Page is exported from pycopg (from pycopg import Page), mirroring the RunResult
dataclass (see etl.md).
CRUD Methods (v1.2.0)¶
The predicate-read siblings of delete_where/update_where/exists/count, plus a
single-row insert. Full sync/async parity on AsyncDatabase.
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
select_where reuses the _build_select_sql builder shared with paginate (so order_by/
limit/offset are near-free) and, like count, treats an empty predicate as legal — with no
where/where_sql, all rows are returned (D-03), unlike the destructive-guard helpers
(delete_where/update_where/exists). find is a real, concrete, delegating twin of
select_where (D-02) — not a @deprecated_alias or module-level alias — provided as a
shorter, familiar name for the same read.
get/find_one force a server-side LIMIT 1 and return the first matching row (or None)
without raising on multiple matches (D-04); they expose columns=/order_by= but
deliberately omit limit=/offset=, since exposing them would contradict the forced
LIMIT 1 (D-05). find_one is get’s real, concrete, delegating twin, same rule as find.
insert is the singular twin of insert_many/upsert — a single-row RETURNING * insert.
on_conflict is a raw passthrough string (e.g. "DO NOTHING", "DO UPDATE SET ...")
mirroring insert_many’s shape (D-06), not upsert’s conflict/update-column computation.
Returns the inserted row as a dict; under on_conflict="DO NOTHING" with a pre-existing
conflicting row, no row is returned and insert returns None (D-07).
rows = db.select_where("users", {"active": True}, order_by="created_at DESC", limit=10)
user = db.get("users", {"email": "alice@example.com"})
new_row = db.insert("users", {"email": "bob@example.com", "active": True})
Context Managers¶
Method |
Parameters |
Yields |
Description |
|---|---|---|---|
|
|
|
Connection context |
|
|
|
Cursor with dict rows |
Schema Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
- |
|
|
|
|
|
|
- |
|
|
- |
Table Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- |
|
|
- |
Introspection Methods (v0.9.0)¶
Available on db.schema.* and async_db.schema.*.
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
describe’s into= selector (v1.1.0, D-11/D-12) defaults to "dict" — byte-identical to the
frozen v0.9.0 flat dict (C-03). into="dataclass" wraps the same four sub-values in a typed
TableDescription (no reshape); into="dataframe" returns the columns section as a
one-row-per-column pandas.DataFrame (nullable integer columns are promoted to float64 with
NaN, a pandas dtype-inference artifact — not data loss). An unrecognized into value raises
ValueError.
TableDescription (frozen dataclass)¶
Field |
Type |
Description |
|---|---|---|
|
|
Exact output of |
|
|
Exact output of |
|
|
Exact output of |
|
|
Exact output of |
TableDescription is exported from pycopg (from pycopg import TableDescription), mirroring
the RunResult/Page dataclass precedent (see etl.md).
Introspection Methods (v1.1.0)¶
Available on db.schema.* and async_db.schema.*. information_schema.views/columns
exclude materialized views per the SQL standard, so these two methods use dedicated
pg_catalog queries to close that gap (D-13/D-14). materialized_view_columns returns
the same 8-key shape as table_info; matview columns never carry NOT NULL constraints or
defaults, so is_nullable is always 'YES' and column_default is always None —
faithful to what a materialized view actually is, not a bug.
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
Introspection Methods (v1.2.0)¶
Available on db.schema.* and async_db.schema.*.
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
column_exists mirrors table_exists mechanically (D-08): table/column/schema are
bound as %s values against information_schema.columns, never interpolated as SQL
identifiers.
table_size returns the raw pg_total_relation_size byte count (heap + indexes + TOAST) —
no pretty formatting. It checks table_exists first and raises TableNotFoundError on a
missing table rather than leaking a raw psycopg UndefinedTable or silently returning 0
(D-09). This is a different accessor with different semantics than db.maint.table_size
(see “Size/Stats Methods” below), which returns a human-readable/pretty size
(pretty=True by default) with no existence guard — the two are intentionally not
deduplicated.
Extension Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
- |
|
|
|
|
|
|
- |
|
|
- |
Index Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
|
Constraint Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
- |
|
|
|
DataFrame Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
|
|
|
- |
|
|
|
PostGIS Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
|
Spatial Helpers (db.spatial.*)¶
Accessed via db.spatial.<method>(...). The accessor is initialized lazily on first
access and raises ExtensionNotAvailableError if PostGIS is not installed. All helpers accept
one of four geometry input forms: point=(x, y), wkt="...", geojson={...},
ref=(table, col). The into= parameter controls output: "rows" returns
list[dict] (default); "gdf" returns a GeoDataFrame. Scalar helpers (area,
perimeter, distance, centroid, length, is_valid, is_valid_reason) only
support into="rows".
Method |
Key Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
TimescaleDB Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
- |
|
|
- |
|
- |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Role Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
|
|
|
|
|
|
- |
|
|
- |
|
|
- |
|
|
- |
|
|
- |
|
|
|
|
|
|
Backup Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
|
|
|
|
Database Admin Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
|
|
- |
|
Size/Stats Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
Maintenance Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
|
- |
|
|
- |
|
|
|
AsyncDatabase¶
Asynchronous database interface with full parity to Database.
from pycopg import AsyncDatabase
Full Async Parity (v0.3.0): AsyncDatabase provides all the same methods as Database with async/await. All methods listed in the Database section above (query, schema, table, DataFrame, PostGIS, TimescaleDB, role, backup, admin, maintenance, and size methods) are available asynchronously.
Async-Only Methods¶
These methods are only available on AsyncDatabase and have no sync equivalent:
Method |
Parameters |
Returns |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- |
Async Context Managers¶
Method |
Parameters |
Yields |
|---|---|---|
|
|
|
|
|
|
|
- |
|
PooledDatabase¶
Synchronous connection pool.
from pycopg import PooledDatabase
Constructor¶
PooledDatabase(
config: Config,
min_size: int = 2,
max_size: int = 10,
max_idle: float = 300.0,
max_lifetime: float = 3600.0,
timeout: float = 30.0,
num_workers: int = 3,
)
Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
- |
|
|
|
|
|
|
|
|
|
- |
|
- |
- |
|
|
- |
|
- |
- |
Properties¶
Property |
Type |
Description |
|---|---|---|
|
|
Pool statistics |
AsyncPooledDatabase¶
Asynchronous connection pool.
from pycopg import AsyncPooledDatabase
Constructor¶
Same as PooledDatabase.
Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
- |
|
|
- |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- |
|
|
|
- |
|
- |
|
|
- |
|
Migrator¶
SQL migration manager.
from pycopg import Migrator
Constructor¶
Migrator(
db: Database,
migrations_dir: Union[str, Path],
table: str = "schema_migrations",
)
Methods¶
Method |
Parameters |
Returns |
|---|---|---|
|
- |
|
|
- |
|
|
- |
|
|
|
|
|
|
|
|
|
|
Exceptions¶
from pycopg import (
PycopgError, # Base exception
ConnectionError, # Connection failed
ConfigurationError, # Bad config
ExtensionNotAvailableError, # Missing extension
TableNotFoundError, # Table doesn't exist
InvalidIdentifierError, # SQL injection attempt
MigrationError, # Migration failed
)