npm postgres 4.2.0

48 minutes ago

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 debug every query captured one up front. Now nothing is captured for queries that succeed, and a failing one gets the stack the runtime builds when your await resumes, through each async function above it: query errors, errors inside sql.begin and sql.reserve, cursors, forEach, .describe(), and a failed connection for sql.begin or sql.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.begin or sql.reserve waiting 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 with 57014, 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's transform (#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's sql, a transaction or a reserved connection can't see the app's transform, and with postgres.camel the keys of its JSON values were renamed. With a column transform, each of result.columns also 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.
  • decode on a custom type (#1335). A custom type can read its values from the bytes of their text with decode(x, start, end), so no string is made for parse. It returns what parse would, and reads the type's columns in query results, .parsers() included. Arrays of the type still go through parse, and a type without decode is read as before. Reading timestamptz as an ISO string with microseconds and int8 as a BigInt this way, 25,000 rows of 12 columns took about half the CPU and less than half the memory allocated.
  • require_auth limits the authentication methods the server may ask for, as libpq's (#1348). A comma separated list of password, md5, gss, sspi, scram-sha-256 and none, or the same with ! to allow all but those, also in the url or as PGREQUIREAUTH. Any other request ends the connection with AUTH_METHOD_REFUSED before 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 Instant or ZonedDateTime is written for timestamptz, a PlainDateTime for timestamp, a PlainDate for date, a PlainTime for time and a Duration for interval, and infer: true types 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 a TypeError, whatever the parameter's type. Results are still Dates, and custom types with parse read 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 with 57014; 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 sent UNLISTEN even 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 as 57P03 while it starts up. A lost connection already ended its LISTEN, so unlisten() now only drops the channel then, and a LISTEN that was being sent again on reconnect is followed by an UNLISTEN once 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 last unlisten().
  • A connection lost during the type load retries it (#1351, #1352). A terminated backend (57P01) or a connection exception (class 08) 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_REQUIRED or a protocol error came back as CONNECTION_CLOSED.
  • sql.array() is a type error (#1354, #1355). It was declared as returning never, which TypeScript accepts as any value, so code from 3.x compiled and then threw ARRAY_REMOVED.
  • A Date before 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.
  • onread is used on Deno 2.8 and later (#1346). Earlier versions don't implement it, so a plain connection threw Not implemented: LibuvStreamWrap.prototype.useUserBuffer.
  • The insert helper given an empty array throws NO_COLUMNS (#1341). sql([]) built insert 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 its query_timeout timer and listener behind.
  • A query trace's sent is 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 with PROTOCOL_ERROR or 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, Buffer or sql.typed() value in sql([...]) is one value, not a row (#1326). An in list took any object as a row, so sql([date]) became in (null), two dates a syntax error, and a Buffer or 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 as insert, so its callback never ran.
  • A comma separated port in a url or PGPORT gives one port per host, as libpq does (#1328). Each host got NaN. A list whose length doesn't match the hosts throws.
  • max from a url or PGMAX is a number (#1337). It stayed a string, so ?max=1 didn't turn the scheduler off as max: 1 does.
  • 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 like from or where in it, or an apostrophe, made insert into x -- rows from the import ${ sql(row) } or update x set -- the user's name ${ sql(row) } fail with TypeError: 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.
  • false or disable in a PG… environment variable turns that option off (#1340), as it already did in a url. PGPREPARE=false, PGFETCH_TYPES=false and PGSCHEDULER=false were kept as the string, which counts as on, so the option stayed enabled.
  • The npm package includes the licence text (#1339, #1344). UNLICENSE is now in the package's files, since npm only adds a file named LICENSE or LICENCE on its own.
  • A cursor used as an async iterator rejects when its connection closes between batches (#1330, #1166). Each next() gave the query a reject tied 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 next next() ended the loop as if all rows had been read, so for await … of query.cursor(n) returned a partial result without an error. The error is now kept and thrown from the next next(), as cursor(n, fn) rejects with it.
  • Canceling a sql.batch queued behind another query honors cancel_timeout. cancelBatch did not start the silence timer that cancel() starts for a queued query, so the batch and its cancel() stayed pending when the earlier query never finished.
  • A number for a timestamptz, timestamp or date parameter 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 with 22008, 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 as unknown (705) for a jsonb parameter went through JSON.stringify again and was stored as a JSON string, from the statement's second run on, or from its first when the untyped value was not null.

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 its select.
  • debug: true no longer costs an Error for every query. The stack it captured up front is replaced by the native one, so a successful query with debug on 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: 10 and about a third of it at max: 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.

Don't miss a new postgres release

NewReleases is sending notifications on new releases.