New
- An error's stack is the native async stack of the code awaiting it. A query error used to get a stack captured when the query was made, trimmed by matching Postgres.js's own file paths and spliced in, and with
debugevery query captured one up front. Now nothing is captured for queries that succeed, and a failing one gets the stack the runtime builds when yourawaitresumes, through each async function above it: query errors, errors insidesql.beginandsql.reserve, cursors,forEach,.describe(), and a failed connection forsql.beginorsql.reserve. Synchronous functions that only pass a query on without awaiting it aren't part of an async stack, and Bun's runtime doesn't yet follow the chain through a query, so there the stack has none of your frames. - A
sql.beginorsql.reservewaiting for a connection can be cancelled (#1322). Their promise has.cancel()and.signal(), as a query does. While it waits, either takes it out of the queue and rejects it with57014, so the transaction callback never runs and no connection is handed over. Before, a caller with a deadline could not give up its place, and the callback ran once a connection freed up. Once it has its connection, both do nothing. sql`…`.transform(false)gives a query's results without the instance'stransform(#1333). Its columns keep the server's names, and its values and rows are what the server and its parsers give, so a query with.parsers()gets exactly what its parsers return. Code given an app'ssql, a transaction or a reserved connection can't see the app'stransform, and withpostgres.camelthe keys of its JSON values were renamed. With a column transform, each ofresult.columnsalso has_name, the name the server gave the column.- The function form of
.parsers()gets the column's position (#1333)..parsers((column, i) => …)can pick a parser for each of several columns with the same name. decodeon a custom type (#1335). A custom type can read its values from the bytes of their text withdecode(x, start, end), so no string is made forparse. It returns whatparsewould, and reads the type's columns in query results,.parsers()included. Arrays of the type still go throughparse, and a type withoutdecodeis read as before. Readingtimestamptzas an ISO string with microseconds andint8as aBigIntthis way, 25,000 rows of 12 columns took about half the CPU and less than half the memory allocated.require_authlimits the authentication methods the server may ask for, as libpq's (#1348). A comma separated list ofpassword,md5,gss,sspi,scram-sha-256andnone, or the same with!to allow all but those, also in the url or asPGREQUIREAUTH. Any other request ends the connection withAUTH_METHOD_REFUSEDbefore anything is sent, so a server that isn't the one you meant to reach can't ask for the password in the clear.- Temporal values are written as their date and time types (#1350). An
InstantorZonedDateTimeis written fortimestamptz, aPlainDateTimefortimestamp, aPlainDatefordate, aPlainTimefortimeand aDurationforinterval, andinfer: truetypes them so. They are sent without the time zone and calendar annotations, years before 1 as BC and a negative duration with each field negative, since PostgreSQL reads neither[Europe/Copenhagen]nor-P1D. Before, any Temporal value threw aTypeError, whatever the parameter's type. Results are stillDates, and custom types withparseread them as Temporal.
Fixed
- A query cancelled while the server describes its parameters is not run (#1347). A query whose parameter types the server names first is written in two parts, and a
.cancel()or.signal()between them only sent a cancel request, which found nothing running, so the second part ran the query anyway. It is now not written, and the query rejects with57014; in a transaction the transaction fails, as with any canceled query. unlisten()resolves while the server can't be reached or refuses connections (#1359). It sentUNLISTENeven when the listening connection was gone, so it waited for a new connection, as long as the reconnect backoff, and then rejected with that connection's error:ECONNREFUSED,CONNECT_TIMEOUT, or one the server sent, such as57P03while it starts up. A lost connection already ended itsLISTEN, sounlisten()now only drops the channel then, and aLISTENthat was being sent again on reconnect is followed by anUNLISTENonce it's back. The channel's retry timer is cleared too, so it no longer kept the process alive for up to 20 seconds after the lastunlisten().- A connection lost during the type load retries it (#1351, #1352). A terminated backend (
57P01) or a connection exception (class08) counted as the server's answer, so the pool marked types loaded with none read, and arrays of custom types came back as text for the rest of its life. - A failed sign-in keeps its own error (#1349, #1353). On Cloudflare Workers closing the socket settled the attempt first, so
CHANNEL_BINDING_REQUIREDor a protocol error came back asCONNECTION_CLOSED. sql.array()is a type error (#1354, #1355). It was declared as returningnever, which TypeScript accepts as any value, so code from 3.x compiled and then threwARRAY_REMOVED.- A
Datebefore year 1 or after year 9999 is written in a form PostgreSQL accepts (#1356).toISOString()writes those years with a sign and six digits, so a date read from the database couldn't be written back. - A message longer than its type can be ends the connection with
PROTOCOL_ERROR, as in libpq (#1346). Only row descriptions, rows, parameter descriptions, copy data, errors, notices, notifications and function results may be longer than 30,000 bytes; any other was taken at its word up to 1 GB, so a stream out of step allocated a buffer that size and waited for it. onreadis used on Deno 2.8 and later (#1346). Earlier versions don't implement it, so a plain connection threwNot implemented: LibuvStreamWrap.prototype.useUserBuffer.- The insert helper given an empty array throws
NO_COLUMNS(#1341).sql([])builtinsert into x (). Columns given beside it,sql([], 'a'), still build("a"). - A second
.signal()replaces the first, and a cursor's async iterator clears its timer and abort listener (#1342). The first signal stayed attached and could still cancel the query, and an iterator that finished left itsquery_timeouttimer and listener behind. - A query trace's
sentis when its bytes are written (#1347). It was set when the query was accepted, before the write that waits for the current turn to end. - A TLS connection on Deno reads results larger than one socket read again (#1346). 4.0 paused the socket when startup handed it to the connection and resumed it after. Deno's
node:tls, at least in Deno 2.1 which Supabase Edge Functions run, corrupts what it reads after a pause and resume, so a result spanning more than one read failed withPROTOCOL_ERRORor hung, and a misread message length under 1 GB was allocated as a buffer of that size. Startup now holds what arrives during the handover instead of pausing, as v3 never paused there. - A
Date,Bufferorsql.typed()value insql([...])is one value, not a row (#1326). Aninlist took any object as a row, sosql([date])becamein (null), two dates a syntax error, and aBufferor typed value was split into its fields, so the list matched the wrong rows without an error. sql.subscribe()takes the command in any case (#1327).'INSERT:users'was accepted but kept as written, while events arrive asinsert, so its callback never ran.- A comma separated
portin a url orPGPORTgives one port per host, as libpq does (#1328). Each host gotNaN. A list whose length doesn't match the hosts throws. maxfrom a url orPGMAXis a number (#1337). It stayed a string, so?max=1didn't turn the scheduler off asmax: 1does.- A helper after an SQL comment builds the right clause (#1329). A
--or/* */comment before${ sql(...) }was read as SQL when the helper looked back for its clause, so a comment with a word likefromorwherein it, or an apostrophe, madeinsert into x -- rows from the import ${ sql(row) }orupdate x set -- the user's name ${ sql(row) }fail withTypeError: x.replace is not a function. Comments are now skipped, nested block comments included, while--and/*inside quoted strings, quoted identifiers and dollar quotes are left alone. falseordisablein aPG…environment variable turns that option off (#1340), as it already did in a url.PGPREPARE=false,PGFETCH_TYPES=falseandPGSCHEDULER=falsewere kept as the string, which counts as on, so the option stayed enabled.- The npm package includes the licence text (#1339, #1344).
UNLICENSEis now in the package'sfiles, since npm only adds a file namedLICENSEorLICENCEon its own. - A cursor used as an async iterator rejects when its connection closes between batches (#1330, #1166). Each
next()gave the query arejecttied to its own promise, which had already resolved with the last batch while the loop body ran. An error from the connection closing then was lost, and the nextnext()ended the loop as if all rows had been read, sofor await … of query.cursor(n)returned a partial result without an error. The error is now kept and thrown from the nextnext(), ascursor(n, fn)rejects with it. - Canceling a
sql.batchqueued behind another query honorscancel_timeout.cancelBatchdid not start the silence timer thatcancel()starts for a queued query, so the batch and itscancel()stayed pending when the earlier query never finished. - A number for a
timestamptz,timestampordateparameter is written as epoch milliseconds again (#1324). 4.0 sent a number as its digits before the server had named the parameter's type, so${ Date.now() }for a timestamp failed with22008, where v3 wrote it as that instant. The first time a statement with a number parameter runs, the pool now waits for the server's parameter types, at the cost of one round trip, and remembers them for that statement. - A value typed with
sql.typed()is written as its own type when the server types the other parameters (#1334). A statement with an untyped parameter learns its parameter types from the server, and once it had them it wrote every value with the serializer of the server's type, a typed value included. JSON text typed asunknown(705) for ajsonbparameter went throughJSON.stringifyagain and was stored as a JSON string, from the statement's second run on, or from its first when the untyped value was notnull.
Performance
- A helper finds its clause with less work. Looking back from
${ sql(...) }for the clause it belongs to tested each character with a regular expression. It now compares character ranges, so building a query with helpers takes over a quarter less time on one line, and 60% less for a helper 30 lines after itsselect. debug: trueno longer costs anErrorfor every query. The stack it captured up front is replaced by the native one, so a successful query withdebugon takes less than half the time it did.- Less work for each query in the client. The protocol writer and the pool's queue had a getter that put them in V8's slow dictionary mode, so every call on them was a hash lookup. They now keep plain fields with shared methods. A tagged query finds its prepared statement by comparing parameter types, without joining them into a string. A query declares all its fields when it is created, the command tag is read without making strings, and one timestamp serves all results in a chunk. With these and the two entries below, a client against an in-process server uses 2.7 µs of CPU per query where 4.1.1 used 5.0 µs.
- Placing a query reads plain fields in one pass. The pool read each connection's state through getters on every query, in up to four passes over all connections, so the cost of placing a query grew with the pool. A connection now keeps the state the pool reads as plain fields declared once, and the pool reads them from an array in one pass, with a second only when the scheduler is needed. Placement is unchanged. With 20 queries in flight per connection, the client uses about a quarter less CPU per query at
max: 10and about a third of it atmax: 90. - The scheduler weighs a connection's queue without walking it. With a query of more than 5 ms in flight, the pool picks a connection for each query by its queued work, and summed the estimated cost of every query queued on every connection to do it. Each connection now keeps that sum, and a count of its slow queries, as queries are queued and finish. With 200 fast queries in flight beside 20 slow ones, the client uses about a tenth less CPU per query.