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

A Drizzle subquery with `.as()` (or a `$with` CTE) built from a cold `getDb()` still throws

Open renansantos opened this issue 2 weeks ago • 2 comments

Environment: @agent-native/core 0.229.0, main at adfa32747f (2026-11-16), drizzle-orm 0.45.2. First seen on 0.227.0. Any platform.

What happens: this is a follow-up to #8636 / #8637. Since #8637, a select chain built from getDb() before the connection is ready can be embedded as a subquery, for example in inArray(col, db.select(...).from(...)). An aliased subquery still fails in the same situation:

const named = db.select({ id: t.id, at: t.at }).from(t).as("named");
await db.select({ id: named.id }).from(named).orderBy(desc(named.at));

throws

getDb(): accessed an unresolved query chain synchronously (reading 'getSQL'). Only select-style query chains can be embedded as a subquery before the database is ready; await this chain before using its result.

The chain is select-only, the case the message says is supported. It fails whether the outer query reads the subquery's fields (named.id) or selects it whole (.from(named) with select()), and whether the fields are columns or sql\...`.as(). It passes once anything has awaited the connection. A CTE fails too, with a raw error instead of the explicit message: db.$with("sq").as(db.select(...).from(t))throwsTypeError: Cannot convert object to primitive valuefrom drizzle'sescapeName`.

We hit it in an action run with pnpm action in a fresh process, where ctx.db is still the lazy proxy when the action builds its queries.

Reproduction: in packages/core/src/db/, next to the #8637 tests in create-get-db.spec.ts:

import { desc } from "drizzle-orm";
import { PgDialect, pgTable, QueryBuilder, text } from "drizzle-orm/pg-core";
import { afterEach, describe, expect, it, vi } from "vitest";

describe("cold getDb() proxy: aliased subquery", () => {
  afterEach(() => {
    vi.resetModules();
  });

  async function coldDbFactory(): Promise<() => any> {
    vi.doMock("./client.js", async (importOriginal) => {
      const actual = await importOriginal<typeof import("./client.js")>();
      return {
        ...actual,
        isPgliteUrl: vi.fn(() => true),
        loadPgliteDrizzle: vi.fn(() => new Promise(() => {})),
      };
    });
    const { createGetDb } = await import("./create-get-db.js");
    return createGetDb({});
  }

  const history = pgTable("history", { id: text("id"), at: text("at") });

  it("connection-less builder: aliased subquery in FROM works", () => {
    const named = new QueryBuilder()
      .select({ id: history.id, at: history.at })
      .from(history)
      .as("named");
    const outer = new QueryBuilder()
      .select({ id: named.id })
      .from(named)
      .orderBy(desc(named.at));
    expect(new PgDialect().sqlToQuery(outer.getSQL()).sql).toContain('"named"');
  });

  it("cold proxy: same aliased subquery in FROM", async () => {
    const db = (await coldDbFactory())();
    const named = db
      .select({ id: history.id, at: history.at })
      .from(history)
      .as("named");
    const outer = new QueryBuilder()
      .select({ id: named.id })
      .from(named)
      .orderBy(desc(named.at));
    expect(new PgDialect().sqlToQuery(outer.getSQL()).sql).toContain('"named"');
  });

  it("cold proxy: aliased subquery selected whole", async () => {
    const db = (await coldDbFactory())();
    const named = db.select({ id: history.id }).from(history).as("named");
    const outer = new QueryBuilder().select().from(named);
    expect(new PgDialect().sqlToQuery(outer.getSQL()).sql).toContain('"named"');
  });

  it("cold proxy: CTE", async () => {
    const db = (await coldDbFactory())();
    const cte = db.$with("sq").as(db.select({ id: history.id }).from(history));
    const outer = new QueryBuilder().with(cte).select().from(cte);
    expect(new PgDialect().sqlToQuery(outer.getSQL()).sql).toContain('"sq"');
  });
});

Result on main: the first test passes; the next two throw the getDb() error above, and the CTE test throws TypeError: Cannot convert object to primitive value. The same failures show up against real PGlite when the outer query is executed before and after await getDb().execute(sql\select 1`)`: fails cold, passes warm.

Cause: in createLazyProxy (packages/core/src/db/create-get-db.ts, around lines 1174–1215), every property read and call on the cold proxy returns another proxy whose target is a function. So .as("named") returns a proxy, not a drizzle Subquery. Drizzle's is(value, Subquery) returns false for anything whose typeof is not "object", so it treats the value as an SQL wrapper and reads getSQL. The proxy replays the chain offline (replayChainOffline), gets a real Subquery, which has no getSQL, and throws (line 1199). For $with, the chain does not start with select, so replayChainOffline returns undefined, and drizzle fails later while escaping the alias.

Building the subquery with new QueryBuilder() works with a cold outer query, which points at the fix.

Possible fix: in the proxy's apply, when the call being applied is as on a chain that starts with select / selectDistinct / selectDistinctOn, return replayChainOffline(newChain) (a real Subquery), falling back to the proxy when it returns undefined. Do the same for $with(alias).as(...) by replaying against new QueryBuilder(), or at least throw the explicit getDb() message for it instead of the TypeError.

Workaround: await any query (or await ctx.db) before building the subquery, or build the subquery with new QueryBuilder().

renansantos avatar Nov 16 '26 21:11 renansantos

Thanks — a fix for cold aliased subqueries and CTEs is in review: https://github.com/BuilderIO/agent-native/pull/9268.

builder-factory avatar Nov 16 '26 22:11 builder-factory

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

builder-factory avatar Nov 16 '26 23:11 builder-factory