postgres
4.1.1 · 11 Nov 2026Unlicense38.9M / weekRepositoryHomepagenpmAtom feed
36 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.
- 4.x · latest line
4.1.1
11 Nov 2026A statement
sql.beginsends after its ownCOMMITorROLLBACKis rejected (#1320). A statement the callback did not await, sent between the transaction'sCOMMITorROLLBACKand the release of its connection, ran outside the transaction, and after a rollback its write was kept. It now rejects withUNSAFE_TRANSACTION, as a statement after the transaction has ended does.A command after a select in a multi-statement simple query has no columns (#1321). In
sql.unsafe('select …; rollback')theROLLBACKresult had the columns of theSELECTbefore it.A query queued behind one with an untyped string or boolean parameter resolves on Cloudflare Hyperdrive (#1319). Such a query is described first, and 4.1.0 sent its Bind, Execute and Sync together with the next query, which never resolved through Hyperdrive. On Cloudflare Workers the next query now waits until the described one is done, as in 3.4.9. Other runtimes still pipeline it.
Fixed
A statement
sql.beginsends after its ownCOMMITorROLLBACKis rejected (#1320). A statement the callback did not await, sent between the transaction'sCOMMITorROLLBACKand the release of its connection, ran outside the transaction, and after a rollback its write was kept. It now rejects withUNSAFE_TRANSACTION, as a statement after the transaction has ended does.A command after a select in a multi-statement simple query has no columns (#1321). In
sql.unsafe('select …; rollback')theROLLBACKresult had the columns of theSELECTbefore it.A query queued behind one with an untyped string or boolean parameter resolves on Cloudflare Hyperdrive (#1319). Such a query is described first, and 4.1.0 sent its Bind, Execute and Sync together with the next query, which never resolved through Hyperdrive. On Cloudflare Workers the next query now waits until the described one is done, as in 3.4.9. Other runtimes still pipeline it.
.cursor()yields the rows ofSHOW,EXPLAINand other commands without a row count. Their last batch was only passed on when the command tag had a count, so a cursor over them yielded nothing.PGSSLMODEis kept when a url hassslrootcert,sslcertorsslkey. Such a url without ansslmodeusedrequireeven ifPGSSLMODEwas set, soPGSSLMODE=verify-fulldropped the host name check andPGSSLMODE=disableused TLS.A connection error without a
stackrejects the waiting queries (#1312). Adding the calling line to such an error threw, so the queries waiting for a connection never settled and the pool stopped retrying. On Bun a DNS error such asEAI_AGAINhas nostack, so a query to a host that doesn't resolve hung forever.A canceled
sql.batchno longer keeps the process alive forcancel_timeout(#1317, #1318). The timer that waits for the cancel to be answered was left running after the batch rejected, so the process stayed up for 5 seconds aftersql.end().A JSON key ending with
_no longer makestoCamelandtoPascalthrow (#1313). Withtransform: postgres.camel, such a key made the whole query throw. The trailing_is now kept, soa_staysa_, and an empty key stays empty instead of becomingundefined.
4.1.0
5 Nov 2026Summary· from the note as AI read it
Upgrade: this release fixes a security issue.
New
query_timeout(#1278). Seconds a query may take, waiting for a connection and running together, before it is canceled and rejects withQUERY_TIMEOUT. Off by default. Unlikestatement_timeoutit also ends a query whose server or network has gone silent, which TCP alone takes many minutes to notice. Transaction control queries andforEachare limited too; cursors, streams andsql.listenare not.cancel_timeout, 5 seconds by default: how long a canceled query may take to end before its connection is closed.sql.batch([queries])sends queries in one round trip with a single Sync: outside a transaction they commit or roll back together, and the batch rejects with the failing query's position inerror.index.jsonon a transform (#1169). The built-in transforms rename the keys of JSON values in results but send JSON values as they are.json: falseleaves JSON values as they are both ways, andjson: truerenames their keys when sending too, with the transform'scolumn.to. Without it nothing changes.eager_types:truereads array types and domains when the pool starts instead of when a query first meets one.sql.identifier(...parts)(#1292). An identifier from its parts, each quoted as it is and joined with., for a name that contains a dot, whichsql(name)reads as a separator:sql.identifier('acme.inc', 'users')gives"acme.inc"."users". Thetransformis not applied. With no parts it throwsNO_PARTS.Node.js 18 is supported again:
enginesis>=18and CI runs it. Nothing in Postgres.js needs 20;using,await usingand tracing are used where the runtime has them. Loading it withrequirestill needs Node.js 20.19 or 22.12.sql`...`.parsers(parsers)(#1294). A query's own parsers, for its rows only: by type,{ [oid]: parse }, on top of the instance'stypes, or a function that gets each column and returns the parser for it,nullfor the server's text. A library that knows how to decode some queries' columns can decode them once, inside the row reader, while every other query on the instance and its pool keeps the instance's parsers. Such a query receives every column as text, sobyteaand the integer arrays otherwise read in binary reach its parsers as text. A query without.parsers()reads its rows as before.
Fixed
sql.listenkeeps its connection after the lastunlisten()(#1298). The connection was closed so the process could exit (#1022), which made every followinglisten()connect again: about 3.5 ms instead of 0.1 ms perlisten. It now stays open without keeping the process alive once nothing is listened.PGSSLMODEis read (#1307). It was ignored, soPGSSLMODE=verify-fullconnected in plain text without an error. This may change how existing setups connect:requirenow uses TLS and fails against a server without it, andverify-caandverify-fullcheck the certificate against Node's CAs, not~/.postgresql/root.crtorPGSSLROOTCERT. A url or anssloption still comes first.An insert helper after a quoted schema and an unquoted table builds the insert (#1304). In
insert into ${ sql('s') }.t ${ sql(row) }orinsert into "s".t, the quoted schema and the table were read as two words, so the row was taken for a list of identifiers and threwx.replace is not a function.sql.listenkeeps reconnecting when its first reconnect fails (#1285, #1286). After the listen connection closed, it was reopened once, and if that attempt failed, as it does while a restarting server still refuses connections, nothing tried again, soonlistenwas never called and notifications were lost. A failed reconnect is now retried afterbackoff, until it succeeds, the channel is unlistened or the pool ends.A canceled query whose server never answers no longer waits forever.
.cancel(),.signal()and nowquery_timeoutsend a cancel request and waited for the server to end the query, so a server or network gone silent left both the query and the promise.cancel()returns pending until TCP gave up. This applies to every cancel, also withoutquery_timeout: when the server doesn't answer withincancel_timeout, the connection is closed and the pool connects again. Whether the queries on it ran is unknown, so they reject withCONNECTION_DESTROYED(a timed out one withQUERY_TIMEOUT) whosecauseisCANCEL_UNANSWERED, not with57014. The cancel request's own connection is limited bycancel_timeouttoo, and a cancel is no longer sent for a query whose result has already arrived, where it could only hit the query after it. A cancel request whose own connection fails, as over TLS to a server gone silent, no longer crashes the process with an unhandled rejection. A query that times out while it waits behind another one on its connection is canceled only after it has had its ownquery_timeoutonce its turn comes, instead of the moment its turn comes, when it had usually finished and the cancel stopped the next query; if the server sends nothing forcancel_timeoutwhile it waits, the connection is closed. A query waiting for types to be read rejects withQUERY_TIMEOUTwithout closing its connection, and the read of array types and domains is limited byquery_timeouttoo.sslrootcert,sslcertandsslkeyin a url are used (#1308). They were sent to the server as startup parameters, so?sslrootcert=systemfailed withunrecognized configuration parameter. Files are read intoca,certandkey. As in libpq, a root certificate withrequireorverify-cachecks the CA but not the host name, andverify-fullchecks both, as doesssl: true. A file without ansslmodemeansrequire.A transaction the server ends rejects with the server's error (#1283, #1284). When a
transaction_timeout(25P04), anidle_in_transaction_session_timeout(25P03) orpg_terminate_backend(57P01) ended the session,sql.beginrejected withCONNECTION_CLOSED, so a timeout or a termination looked the same as a network drop; it now rejects with the FATAL error the server sent before closing, as a query in flight already did, and a later query on that connection rejects withCONNECTION_CLOSEDthat has it ascause. A server restart or failover ends sessions with57P01, so code that retries a transaction onCONNECTION_CLOSEDshould retry on that code too. A FATAL in answer toCOMMITrejects withCONNECTION_CLOSEDthat has it ascause, as the outcome is unknown, as it is when the connection is lost duringCOMMIT.A server certificate is verified against an IP host (#1309). With
ssl: 'verify-full'orssl: trueand an IP as the host, a connection upgraded to TLS checked the certificate againstlocalhost, so a certificate forlocalhostfrom a trusted CA passed for any IP and a correct certificate for the IP failed. Direct TLS was not affected.A savepoint or nested
beginrejects when its transaction's connection is lost (#1281, #1282). One whose callback was still running when the connection went resolved with the callback's result after the transaction had already rejected; it now rejects with the transaction's error.A connection closed while the pool reads its array and domain types counts as a failed connection attempt (#1279). Reconnecting follows
backoffand waiting queries reject onceconnect_timeouthas passed, instead of reconnecting as fast as the server accepts for as long as it keeps closing. Withconnect_timeoutset to 0, null or false the pool now keeps trying for as long as it takes, as the option says, also after a refused or closed startup, which used to reject the waiting queries at once.A query failed by a
FATALerror gives that error to the queries pipelined behind it as well, instead ofCONNECTION_CLOSED.A FATAL error with the severity only in the
Sfield is recognised as one. The non-localizedVfield is optional in the protocol: PostgreSQL sends it since 9.6, and a pooler that builds its own errors, such as PgBouncer, may send only the localizedS. Such an error was not seen as FATAL, so the query, asql.beginand the queries pipelined behind it rejected withCONNECTION_CLOSEDwithout acauseinstead of with the error.error.severitynow falls back toseverity_localwhenVis missing.Each query on a connection that closes gets its own error. They shared one error object, so every query pipelined on the connection reported the first one's
queryandparameters.A cached prepared statement no longer keeps the query that prepared it (#1287). Each connection's entry for a prepared statement kept that query's values and rows for as long as the statement stayed cached, up to 1,000 statements per connection, so an app with many distinct statements grew by their results until every cache was full: about 1.1 GB with 10 connections and 50-row results. They are let go once the query settles. On 4.0.0,
prepare: falseavoids it.Destroying a
copy ... to stdoutstream frees the connection (#1306). Afterdestroy(), breaking out offor awaitor a failedpipeline, the connection stayed paused for good and the queries behind it never ran. The rest of the copy is now read and dropped, so the connection is free once the server has sent it. The query is not canceled, so in a transaction the next query still succeeds.
Performance
An
sslobject with acabuilds its TLS context once (#1280). The connections made with it share one context instead of each parsing the wholecalist again, so with a provider's CA bundle a new connection takes about half the time and CPU, and a burst of them no longer blocks the event loop. Replacing one of the object's values, as with a renewedcert, builds a new context for the connections after it.A new statement whose untyped values are all numbers or
nullis prepared, described and run in one round trip, as one whose parameter types are all known is, since those values are written the same for any type the server picks; one with other values only the server can type is still described first, once per connection.Array types and domains are read when a query first meets a type the pool does not know (an oid from 16384 up), instead of when the pool starts: a pool that only uses built-in types never sends that query, and a new pool's first query costs no more than any other. The connection that met the type waits for it, read on another connection. With custom types given by name they are still read at startup, as their oids are needed before the first query. Leases and values typed as a type the pool hasn't read yet still wait for it. A read whose connection fails is retried after
backoff, and onceconnect_timeouthas passed the connections waiting for it are closed and their queries reject, as for a failed startup.eager_types: truereads them when the pool starts, as before.timestamptz, andtimestampanddateread as UTC, are decoded straight from the bytes when they use the built-in parsers, with the text parser for anything else (BC,infinity, years before 1000); about 20% more rows per second for rows with timestamps.byteaand arrays ofint2,int4,int8andboolare fetched in binary once a prepared statement's columns are known on the connection, when they use the built-in parsers: the values are the same as from the text, about 4.5 times faster to read forbyteaand 3 times for anint4. A custom parser for the type or its elements, andraw(), still get the text.A connection that becomes ready while others are still opening no longer takes the queries meant for those; 50 connections opened at once each run one of 50 queries.
4.0.0
29 Oct 2026Summary· from the note as AI read it
Upgrade: this release fixes a security issue.
- Security
A NUL character in a connection parameter can no longer add parameters (also in v3). A
database,userorconnectionvalue such as'db\0user\0postgres'was sent as further startup parameters, so an app that put untrusted input there, as with a database per tenant, could be made to log in as another user where that user needs no password, or withreplicationoroptionsset. A NUL in any protocol string, also in query text and identifiers, now rejects withNUL_CHARACTER. - Security
A column named
__proto__is an own property (also in v3). It became the prototype of the row, so a JSON value in it, for instance from a column alias built from user input, made the row inherit its properties (row.isAdmin), in query results and insql.subscriberows alike.
v4 rewrites everything below the public API: the pool, the connection, the protocol, startup and the socket layer. Queries, helpers, transactions, cursors, COPY, listen, subscribe, large objects and the options work as in 3.4.9, apart from the changes below.
Security
- Security
A NUL character in a connection parameter can no longer add parameters (also in v3). A
database,userorconnectionvalue such as'db\0user\0postgres'was sent as further startup parameters, so an app that put untrusted input there, as with a database per tenant, could be made to log in as another user where that user needs no password, or withreplicationoroptionsset. A NUL in any protocol string, also in query text and identifiers, now rejects withNUL_CHARACTER. - Security
A column named
__proto__is an own property (also in v3). It became the prototype of the row, so a JSON value in it, for instance from a column alias built from user input, made the row inherit its properties (row.isAdmin), in query results and insql.subscriberows alike.
Upgrading from v3
The README has an upgrade guide, with a query that shows whether the change in parameter types concerns you.
The server decides the type of every parameter (
infer: falseby default) (#392). v3 typed aDateastimestamptz, a boolean, aBuffer, abigintand arrays of these from JavaScript; v4 sends them without a type and writes each value for the type the server asks for, as libpq does.timestamptzcolumns, values written to a column of their own type, strings, numbers and anything cast work as before. Outside UTC, aDatewritten to or compared with atimestampordatecolumn is taken as UTC instead of the session's local time, and atimestampis read as UTC, so it comes back as the instant that was written whatever the time zone. ADatewhere the query doesn't decide its type, such as indate_trunc('day', ${ date }), needs a cast (${ date }::timestamptz).infer: truekeeps v3's behaviour.Runtimes. Node.js 20 or later, Bun, and Cloudflare Workers; Deno through its Node.js compatibility. The CommonJS and Deno builds are gone: Postgres.js is an ES module, which
requirecan load on Node.js 20.19 and 22.12 and later (require('postgres').default).sql.array()is removed. Pass the array as it is, with a cast where the query doesn't decide its type:${ ids }::int. Callingsql.array()throwsARRAY_REMOVED.A transaction the server rolled back rejects. When the server answers COMMIT with ROLLBACK,
sql.beginrejects withTRANSACTION_ROLLED_BACK; v3 took it as a commit.A released connection stays released. A query on a reserved
sqlafterrelease(), or on a transaction'ssqlafter it has committed or rolled back, rejects; v3 ran it on whatever connection it then had. Releasing a reserved connection while its ownBEGINis still open closes it instead of returning an open transaction to the pool.An unsafe
beginoutsidesql.begin, a reserved connection ormax: 1rejects withUNSAFE_TRANSACTIONand is rolled back. A query that looks like it may open a transaction runs alone on its connection, so nothing else lands in it, and any query that leaves its connection in a transaction is rolled back and rejected. v3 rejectedBEGINbut left the transaction open. A script that opens and closes its own transaction in one query, such as a migration file withBEGINandCOMMIT, runs; v3 ran it and still rejected it.A query that cannot be built or serialized inside a transaction aborts the transaction, in
sql.begin(#1236, #1238) or one opened by hand on a reserved connection, just as a server error would: the queries after it fail with25P02and a laterCOMMITanswersROLLBACK. v3 skipped the query and let the rest commit.Domains that exist when the pool starts are read and written as their base type, so a domain over
intcomes back as an array of numbers; v3 returned the text.A connection refused for too many connections (
53300) is retried withbackoffuntilconnect_timeouthas passed, and the waiting queries reject with that error only then. Such a refusal is often momentary: connections opened at the same time against a connection limit can all be refused while the server counts them. v3 rejected the queries of the refused connection at once.No host matching
target_session_attrsrejects withCONNECTION_DESTROYEDinstead of retrying forever.An unknown authentication type rejects with
AUTH_TYPE_NOT_IMPLEMENTEDinstead of waiting for the connect timeout.A replication error with no
onerroris logged. When thesql.subscribestream fails and none of its subscriptions has anonerror, the error goes toconsole.errorbefore the stream reconnects; v3 dropped it. Passonerrorto handle or silence it.infinitytimestamps areInfinityand-Infinity, both ways, instead of an invalidDate.TypeScript: the types are an ES module with a default export and named types (
import postgres, { type Sql } from 'postgres'). A reserved connection is no longer typed as havingbeginandend, which it never had.
New
Scheduling across connections: when every connection is busy, a query is pipelined on the connection where it should be done soonest, from how long each statement took before and how long what is in flight has run, and slow queries are kept together once the rest of the pool is needed for quick ones. In simulations of mixed workloads, the p99 of quick queries fell 2 to 100 times; on PostgreSQL, a 1 ms lookup no longer waits behind a report on a busy pool (p99.9 from 792 ms to 5 ms).
scheduler: falsepipelines on the busy connection with the fewest queries in flight instead; v3 went round-robin over the busy connections. Withmax: 1it is off, as there is only one connection.queue_timeout: seconds a query, transaction or reserve may wait for a connection before it rejects withQUEUE_TIMEOUT, unsent (#1036, #824)..signal(abortSignal)on a query: aborting rejects it if it is still waiting, or cancels it if it is running.Canceling a cursor between batches stops it.
.cancel()or an aborted.signal()while the cursor's callback runs, or while an async iterator over it is between batches, fetches no more rows, closes the portal and rejects with57014. v3 sent a cancel request that the idle server ignored, so the cursor ran on to the end (or, arriving late, could cancel the next query).sql` and `.join(items)joins fragments and values with a fragment as separator, leaving out falsy items and adding spaces where missing (#807, #813).Nested
sql.begininside a transaction runs in a savepoint (#985).sql.rollback()rolls back a transaction, or the savepoint it is called in, without throwing;sql.beginresolves with the callback's result (#500).Pipelining anywhere in a transaction is documented and tested: queries in a
Promise.allbetween awaited ones are sent together and run in the order they were made (#951).Custom types by name:
toandfromcan be type names, looked up when the pool starts, with array types, for extension types such as pgvector (#1115, #719).usingandawait using:sqlends the pool and a reserved connection is released when it goes out of scope (#886, #1094).unref_sockets: truelets the process exit while connections are idle, likeallowExitOnIdlein node-postgres (#869, #918).min: connections kept open once the pool is used;idle_timeoutcloses only those above it (#672).useras a function, called each time a connection opens, likepassword, for credentials that rotate (#881).Password file: with no password given,
PGPASSFILEor~/.pgpassis read as libpq reads it (#964).Named arguments: an object in the parentheses of a function call becomes
name => valuearguments,make_interval(${ sql({ days: 1 }) })(#1040).Errors are documented with their fields and how to tell them apart (#1140).
COPY row count: a
copy ... from stdinwritable hascountandcommandonce it has finished, with the number of rows the server copied (#465).Persistent replication slots:
slot: 'name'keeps the slot ofsql.subscribeacross restarts and streams from where it was last confirmed. A transaction is confirmed only once its handlers have finished, a handler that fails gets its transaction delivered again, and handlers may be async: they run one after the other in commit order while the stream waits.More from
sql.subscribe:truncateevents, and thelsn,timeandxidof the transaction on every change. Reconnecting retries with backoff.Channel binding: over TLS, SCRAM authenticates with SCRAM-SHA-256-PLUS (
tls-server-end-point) when the server offers it, binding the login to the server certificate.channel_bindingis'prefer'by default,'require'or'disable'as in libpq, also from the url orPGCHANNELBINDING;'require'rejects an unbound connection withCHANNEL_BINDING_REQUIRED(#1008).Direct TLS on Node.js with
sslnegotiation: 'direct'(PostgreSQL 17+) is opened as TLS from the first byte and is the fastest encrypted connection.Cloudflare Workers through the
workerdexport condition, oncloudflare:sockets, with TLS bystartTls.query.textandquery.parametersshow the text and values a query will be sent with, before it is sent.sql.stats: connections, opening, idle, leased and waiting, right now.Tracing channels:
postgres:query,postgres:connectandpostgres:transactionas diagnostics tracing channels, andpostgres:poolandpostgres:noticeas plain channels, for OpenTelemetry and other tracers without an option or a wrapper. Nothing is published, and nothing costs, without a subscriber. See Tracing.Prepared statements are prepared again when a column changes type. A query that the statement's parameter types no longer fit fails before it runs; it is now run once more with a fresh description and the statement prepared again, outside a transaction or reserved connection. On a pool of more than one connection that holds also while other queries are in flight; with
max: 1only for a query that is alone on the connection, so queries keep their order. v3 kept failing until the connection was replaced. Each connection reads rows and writes values only by what its own server described for the statement. When one connection sees a statement describe differently, the others prepare it again before their next use instead of trusting what they learned before.sql.close()closes the connections once their queries are done and leaves the pool usable.Named cursors: in a transaction or on a reserved connection every cursor has a portal of its own, so several can be open at once.
Stack traces of query errors lead to the line that made the query. Only the text of that line is kept, once per place in the code, so the function that made the query is not kept alive with it (#1274, #1276).
options.socketis also called with the host and port, and a socket can say it has done TLS itself (negotiated: true).onread: falsereads through the socket stream instead of a shared buffer, should a runtime ever misbehave with it.
Fixed
The open issues and pull requests were triaged into 33 correctness bugs, each with a regression test in the v4 suite. Among them:
One query on a cold pool opens one connection, not one more for each connection that opens while the first loads types.
Errors: the server's data type field is
data_type_name; v3 set it as'data type_name', with a space, and typed it astype_name.JSON.stringifyof aPostgresErrorincludes its message (#767, #1132).Cursors: the callback of the last batch is awaited before the cursor resolves, and a rejection from it rejects the cursor; v3 resolved without waiting and left the rejection unhandled. A callback that throws synchronously on a cursor in a transaction or on a reserved connection rejects the cursor and leaves the connection as it was; v3 gave the next query a malformed result.
Large objects:
readable({ start, end })stops atend; v3 ignored it and read to the end of the object.Bun: error stacks point at the calling line, as on Node; library frames were recognised only as
file://urls.Cloudflare Workers: a TLS handshake that Workers cannot complete, most often a certificate not signed by a public CA, rejects with
TLS_HANDSHAKE_FAILEDinstead ofCONNECTION_CLOSEDorCONNECT_TIMEOUT(#1213), andperf_hooksis no longer imported (#990). Writes are split into 16 KiB pieces, as Workers were reported to drop a plain connection on a larger write (#1268).A statement name the server already has, which a pooler that moves connections between clients can cause, is prepared again under a new name instead of failing with
42P05(#960).TypeScript:
ISqlis exported for functions that take the pool, a transaction or a reserved connection (#1163, #1150);PostgresErroris exported by name as a value as well as a type (#862, #703); nested arrays withnulland other values in helpers (#743); a typed query with a helper inside (#958); column lists that arestring, while unknown literal columns are still caught (#916); class instances andobjectas JSON (#664, #625);nullandfalsefor the timer options (#1178).Helpers follow the clause they are in, not the last keyword anywhere before them:
update t as x set ${ sql(o) }(#974),insert into t as x ${ sql(o) }(#517, #774),grant update on ${ sql(tables) }(#1101), rows inin (${ sql(rows) })(#820), a column list forinsert into t ${ sql(columns) } select ...(#769), objects in avalueshelper with picked columns, also inside a fragment (#1073, #1042), and fragments among the columns ofselect ${ sql([...]) }(#777). An insert or update helper without columns throwsNO_COLUMNSinstead of sending invalid SQL (#644). Several names outside a clause,order by ${ sql('a', 'b') }, become a list of identifiers; v3 threw aTypeError.An array or a plain object written as text, such as in a
valueslist cast afterwards, is written as an array literal or as JSON instead of1,2or[object Object](#741, #872, #765).Connection urls: bracketed IPv6 hosts (#1232), percent-encoded socket directories as hosts (#1057),
?host=and?port=as libpq reads them (#984), and passwords with characters that are not percent-encoded, which are used as written (#735, #890).Answers can no longer reach the wrong query: after a cancel, a query that could not be built or serialized, or an error in the middle of a result, every query still gets its own answer. (A cancel that reaches the server just as its query finishes can still stop the next query on that connection; that is the protocol.)
A transaction whose connection is lost rejects, and nothing it queued reaches the connection's next user.
A cursor started in
sql.beginand not awaited finishes before the transaction commits.Queries and transactions start in the order they were made: with
max: 1, a query made beforesql.beginruns before the transaction.While connections keep failing, queries and transactions reject at once with the connection error, each with its own error object, instead of waiting for the next attempt.
A failed connection attempt only rejects the waiting queries when no other attempt is under way and no connection can still serve them, so a connection that is still loading types is waited for.
A reserved connection released while its own queries are still in flight goes back to the pool only once they are answered and it is outside a transaction; otherwise it is closed.
connect_timeoutdestroys a TCP connection that is still being opened, so the process can exit.A server that is ready before it has accepted the authentication is rejected with
AUTHENTICATION_INCOMPLETE, so SCRAM cannot be skipped.An
onnoticethat throws during startup no longer fails the connection.sql.subscribeparses custom array types and domains like queries do.A custom serializer that returns something other than a string or a
Bufferrejects its query, also in a cursor, instead of hanging the connection.A cursor on the pool or a reserved connection whose callback throws on the last batch, or whose column parser throws, rejects and frees its connection instead of hanging it.
After
DEALLOCATE ALL, a statement prepared again is not forgotten because of an older query's error.The same query text in schemas of different shape (a
search_pathper tenant, say) gets the rows of its own schema on every connection.debuggets the values as they are sent and the parameter types, also on the first use of a statement.The types of
sql.listen()({ state, unlisten }) andsql.prepare()(returns the name) match what they return.notifyinside a transaction uses the transaction (#966).nullin arrays (#1258),Infinity(#728), years below 100 and offsets in seconds (#1185).PostgresErrorfrom a plain message (#703) and writable stacks (#1227).Keywords next to helpers and fragments (#1221).
end()stops connection attempts under way and settles every query; a reserved connection is never stranded.Array and domain types are fetched once per pool, on its first connection; if that query fails with a server error the pool carries on without them instead of asking again for every query.
COPY under back-pressure no longer stalls, and COPY TO STDOUT to a slow consumer is no slower with the shared read buffer than without it.
Performance
A statement whose parameter types are all known is prepared, described and run in one round trip; one with parameters only the server can type is described first, once per connection, as in v3.
int2,int4,oidandboolcolumns are decoded straight from the bytes when they use the built-in parsers; a custom parser still gets the text.A query on its way to a free connection goes straight to it, without the waiting queue.
Queries hold no more per-query state than they need, so almost nothing outlives a scavenge.
One growing buffer per connection, encoded in place and written once at the end of the tick.
Plain and direct TLS connections read into one buffer per connection (
onread) instead of a buffer per chunk, on Node, Bun and Deno.Rows, column descriptions and command tags are decoded by hand.
Once a result shape has delivered 16 rows, its rows are read by a function compiled for that shape, which builds each row as one object literal with every column already in place (about half the CPU per row at 20 columns, about 12% less at 5). Where code generation is not allowed, rows are built as before.
Testing
- 3.x
3.4.8
6 Jan 2026Prevent out of bound errors from commit-time failures de64f7a
Use lower max connections in Cloudflare Workers environment 94b7170
Prevent out of bound errors from commit-time failures de64f7a
Use lower max connections in Cloudflare Workers environment 94b7170
Omit Sql properties absent from TransactionSql 36a53f6
Better error if trying to run query during copy 3a43815
Fix PGAPPNAME env access by prioritizing connection.application_name 32feb25
3.4.6
20 May 20253.4.4
21 Mar 20243.4.2
27 Oct 2023Ensure transactions throw if connection is closed while there is no active query - fixes #658 788c819
Fix race conditions in auth startup - fixes #430 #668 33ae0ed
Adding support for sslrootcert option in connection string (#690) 0bee4c3
Keep query error instead of creating creating new object (#698) f2fb819
Add common parameter names to ConnectionParameters TS type (#707) ca2754c
3.4.0
10 Oct 2023Add sql.reserve method 7f6e0cc
Add sql.reserve method 7f6e0cc
Allow for incomplete custom types 1df4286
Allow array of Fragments in ParameterOrFragment 82908d3
Allow a falsy url string e4b158b
Fix crash on errors in logical streaming, but log and reconnect a4bf5fa
Fix replica identity changes when using subscribe 087c414
Fix a bun issue with stack traces cae4d97
Ensure number options are coerced from string - fixes #622 ba498fd
Support notify for transactions and reserved connections as well. fixes #611 0dac913
Use select helper inside parenthesis c2fe67b
3.3.5
31 May 20233.3.4
7 Mar 20233.3.0
30 Sep 2022Fix subscribe stream close 19c9684
Support transform in subscribe messages 4e28de9
Prevent transform of columns when using subscribe - fixes #474 4ea4a59
Fix query being executed when using describe on unsafe - fixes #424 3e47f0a
Ensure listen doesn't reconnect if first connect throws edfa360
Typescript related
3.2.3
23 May 20223.2.0
15 May 2022Add
sslmode=verify-fullsupport e67da29Add support for array of fragments 342bf55
Add passing of rest url params to connection (ootb support cockroach urls) 41ed84f
Fix Deno partial writes 452a30d
Fix
asdynamic helper 3300c40Fix some nested fragments usage 9bfa902
Fix missing columns on
Resultwhen using simple protocol - fixes #350 1e2e298
Typescript related
3.1.0
22 Apr 20223.0.6
19 Apr 20223.0.1
30 Mar 2022Improve connection queue handling + fix leak cee1a57
Add types to debug signature dbb668c
Throw proper query error if destroyed e148a0a
Transaction rejects with rethrown error - fixes #289 f7c8ae6
Only create origin stacktrace for tagged and debug - fixes #290 a782edf
Include types and readme in deno release - fixes #287 9068820
Disable fetch_types for Subscribe options 72e0cdb
3.0.0
24 Mar 2022- Breaking
Cursors are always called with
Resultarrays (previously cursor 1 would return a row object, where > 1 would return an array of rows) - Breaking
.writable()and.readable()is now async (returns a Promise that resolves to the stream) - Breaking
Queries now returns a lazy promise instead of being executed immediately. This means the query won't be sent until awaited (.then, .catch, .finally is called) or until
.execute()is manually called.
This is a complete rewrite to better support all the features that I was trying to get into v2. There are a few breaking changes from v2 beta, which some (myself included) was using in production, so I'm skipping a stable v2 release and going straight to v3.
Here are some of the new things available, but check the updated docs.
Dynamic query builder based on raw sql
Realtime subscribe to db changes through logical replication
Multi-host support for High Availability setups
Postgres input parameter types from
ParameterDescriptionDeno support
Cursors as async iterators
.describe()to only get query input types and column definitionsSupport for Large Objects
max_lifetimefor connectionsCancellation of requests
Converted to ESM (with CJS support)
Typescript support (Credit @minigugus)
Breaking changes from v2 -> v3
- Breaking
Cursors are always called with
Resultarrays (previously cursor 1 would return a row object, where > 1 would return an array of rows) - Breaking
.writable()and.readable()is now async (returns a Promise that resolves to the stream) - Breaking
Queries now returns a lazy promise instead of being executed immediately. This means the query won't be sent until awaited (.then, .catch, .finally is called) or until
.execute()is manually called. - Breaking
.stream()is renamed to.forEach - Breaking
Returned results are now it's own
Resultclass extendingArrayinstead of an Array with extra properties (actually shouldn't be breaking unless you're doing something funny) - Breaking
Parameters are now cast using the types returned from Postgres ParameterDescription with a fallback to the previously inferred types
- Breaking
Only tested with node v12 and up
- Breaking
Implicit array value to multiple parameter expansion removed (use sql([...]) instead)
Breaking changes from v1 -> v2 (v2 never moved on from beta)
- Breaking
All identifiers from
sql()in queries are now always quoted - Breaking
Undefined parameters are no longer allowed
- Breaking
Rename timeout option to
idle_timeout - Breaking
Default to 10 connections instead of number of CPUs
- Breaking
Numbers that cannot be safely cast to JS Number are returned as string. This happens for eg,
select count(*)becausecount()returns a 64 bit integer (int8), so if you know yourcount()won't be too big for a js number just cast in your query to int4 likeselect count(*)::int
- 1.x
1.0.2
21 Jan 20201.0.1
3 Jan 20201.0.0
22 Dec 2019Initial release
- 0.0.x
0.0.1
1 Jan 2015
A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.