Guide 10 · Relational and Document Databases

asyncpg and psycopg3, Deep Dive

Two PostgreSQL drivers, one asynchronous and one standard, and when the difference in speed is worth it.

Complete 17 notebooks 17 written

Before this guide: sqlite3, Deep Dive.

The notebooks

Open in Colab runs a notebook in your browser, and Read shows it on GitHub without running it. Every notebook runs on its own, and the answers to its exercises are in a separate notebook, linked as Solutions.

1A Server of Your OwnThe second writer your SQLite file refused, and PostgreSQL running in your session in about two minutesOpen in ColabReadSolutions
2Connecting and Executingexecute and fetchall, dict_row instead of tuples, and what the with block actually commitsOpen in ColabReadSolutions
3Transactions and ErrorsInFailedSqlTransaction, and the savepoint that saves the rest of the batchOpen in ColabReadSolutions
4Placeholders and Identifiers%s against the f-string, executemany, and sql.Identifier for what no placeholder can carryOpen in ColabReadSolutions
5Types and AdaptationEvery value becomes bytes on the wire, and three of your Python objects have no rule for itOpen in ColabReadSolutions
6JSONBWrap the dict in Jsonb, query with @>, and read EXPLAIN before and after a GIN indexOpen in ColabReadSolutions
7Server-Side Cursorsexecute has already pulled every row into memory before fetchall runs, and a named cursor is how you stop itOpen in ColabReadSolutions
8COPYBulk loading in both drivers, out as well as in, and the row with one column too manyOpen in ColabReadSolutions
9Pipeline ModeRound trips removed, and the PipelineAborted raised at a statement that was fineOpen in ColabReadSolutions
10AsyncConnectionawait psycopg, and the two tasks that share one connection and take turnsOpen in ColabReadSolutions
11asyncpg$1 rather than %s, and every statement in autocommit until you open a transactionOpen in ColabReadSolutions
12Prepared StatementsAnd the ALTER TABLE that invalidates a statement the server is still holdingOpen in ColabReadSolutions
13Connection Poolspsycopg_pool, create_pool, and why a pool sized to the database's cores beats one sized to your trafficOpen in ColabReadSolutions
14Connecting to a Hosted ServerA DSN out of the environment, sslmode against asyncpg's ssl argument, and the connection limit a managed server enforcesOpen in ColabReadSolutions
15LISTEN and NOTIFYA push from the database, and the notification that never arrives without autocommitOpen in ColabReadSolutions
16Which DriverWhere async wins, where it does not, and the missing await that fakes a winOpen in ColabReadSolutions
17An Event StoreCOPY in, JSONB out, a pool in front, and one wake-up for a thousand rowsOpen in ColabReadSolutions