agent-native icon indicating copy to clipboard operation
agent-native copied to clipboard

A Drizzle subquery built from `getDb()` throws "unresolved query chain" only before the first connection, so tests pass and cold starts fail

Open renansantos opened this issue 1 month ago • 2 comments

Environment: multi-app workspace, app based on the chat template, @agent-native/core 0.222.1, Postgres 17 (Docker) and PGlite 0.5.10 (the app's Vitest database). Windows 11, Node 24.20, but nothing here is platform-specific. The code is unchanged on main at 0f850d9988.

What happens: a read action builds a query with a Drizzle subquery, both from getDb():

const db = getDb();
await db
  .select({ id: items.id })
  .from(items)
  .where(inArray(items.id, db.select({ id: items.id }).from(items)));

It passes in the app's tests and on a dev server that has already run a query. On the first query of a process (pnpm action <name> from the command line, a freshly started server, a cold serverless function) it throws:

getDb(): accessed an unresolved query chain synchronously (reading 'getSQL'). This chain was embedded as a raw value instead of being awaited first — e.g. a subquery passed straight into another expression. Await the chain before using its result.

Reproduction, in a Vitest file of a chat-template app (the database is the in-memory PGlite its config already sets):

const run = () =>
  getDb()
    .select({ id: items.id })
    .from(items)
    .where(inArray(items.id, getDb().select({ id: items.id }).from(items)));

const attempt = async () => {
  try { await run(); return "ok"; } catch (e) { return (e as Error).message; }
};

const cold = await attempt();       // "getDb(): accessed an unresolved query chain synchronously (reading 'getSQL')…"
await getDb().execute("select 1");
const warm = await attempt();       // builds the SQL and reaches the database

warm sends select "id" from "items" where "items"."id" in (select "id" from "items") (in this bare test it then fails only because the table was not migrated).

Why: getDb() in packages/core/src/db/create-get-db.ts returns the real Drizzle instance once the connection is ready (if (_db) return _db, :1187), and before that a createLazyProxy (:1133) that records the call chain and replays it on await. Embedding a subquery makes Drizzle read getSQL synchronously; the real instance answers, the proxy can't without a connection and throws. So the same code works or not depending on whether something earlier in the process opened the connection. In an app's tests the migration opens it before any action runs, so the cold path is never exercised.

The message also points the wrong way: awaiting the subquery runs it and returns rows, while the caller wants its SQL inside the outer query.

Workaround: write the subquery with the sql template (sql`${items.id} IN (SELECT id FROM ${items} WHERE …)`), or build it with Drizzle's QueryBuilder from drizzle-orm/pg-core, which needs no connection.

Possible fix: when the proxy is asked for getSQL (or shouldOmitSQLParens), replay the recorded chain on a connection-less QueryBuilder for the same dialect and answer from it, so a subquery behaves the same cold and warm. If that isn't wanted, make the message say to build the subquery with sql or QueryBuilder instead of awaiting it, and mention it in the storing-data skill. A test that builds the query above before the first connection and expects the same SQL as after it would cover it.

renansantos avatar Nov 03 '26 11:11 renansantos

Thanks for the detailed report and the pointer to createLazyProxy, it made this quick to confirm. A fix is in review in https://github.com/BuilderIO/agent-native/pull/8637: select subqueries like inArray(col, db.select(...).from(t)) now build their SQL on a connection-less QueryBuilder, so they work on the first query after a cold start. Chains that can't be built that way (such as inserts) still throw, with a clearer message. Until it ships, your sql template workaround stands. We'll update here once it merges.

builderio-bot avatar Nov 03 '26 11:11 builderio-bot

Thanks for the report - this is fixed by https://github.com/BuilderIO/agent-native/pull/8637, which is merged and will be on beta shortly.

builder-factory avatar Nov 04 '26 19:11 builder-factory