Skip to content

Dashboard 500 on D1: fetchRecentItems UNION ALL exceeds SQLITE_LIMIT_COMPOUND_SELECT #895

Closed

Description

@cristianuibar

Summary

GET /_emdash/api/dashboard returns HTTP 500 with {"error":{"code":"DASHBOARD_STATS_ERROR","message":"Failed to load dashboard statistics"}} on Cloudflare D1 (and miniflare's D1 emulator) when the project has enough title-bearing collections. The admin dashboard fails to render for every authenticated user.

Root cause is in fetchRecentItems (packages/core/src/api/handlers/dashboard.ts): it composes a single chained UNION ALL across every title-bearing collection and wraps it in an outer SELECT * FROM (combined) ORDER BY updated_at DESC LIMIT 10. D1 enforces a SQLITE_LIMIT_COMPOUND_SELECT cap that is tighter than the default 500 used by better-sqlite3, so the query fails on D1 even though the same SQL runs fine against a local sqlite file.

This is a regression from 0.7.0 (where the dashboard worked on D1) to 0.8.0, and is unchanged in 0.9.0.

Environment

  • emdash: 0.8.0 (also reproduced on 0.9.0, source unchanged)
  • @emdash-cms/cloudflare: 0.8.0 (and 0.9.0)
  • Astro: 5.x with @astrojs/cloudflare adapter, output: "server"
  • Runtime: Cloudflare Workers (production) and miniflare via pnpm dev (local)
  • Project: 12 collections total, 9 of them title-bearing (pages, hero, cta, faq, logo_grid, feature_list, stat_block, posts, legal_pages)

Reproduction

  1. Create or use an emdash 0.8 project on Cloudflare D1 with at least 9 title-bearing collections (each defining a title field).
  2. Run pnpm seed and pnpm dev.
  3. Log into /_emdash/admin (passkey).
  4. Watch the network tab and dev-server stderr.

Result: every dashboard load fires GET /_emdash/api/dashboard twice and both return 500.

Server stack trace (local pnpm dev)

[ERROR] [vite] Dashboard stats error: Error: D1_ERROR: too many terms in compound SELECT: SQLITE_ERROR
    at D1DatabaseSessionAlwaysPrimary._sendOrThrow (cloudflare-internal:d1-api:139:19)
    at cloudflare-internal:d1-api:366:41
    ... 7 lines matching cause stack trace ...
    at renderEndpoint (.../chunk-AI5DR33A.js:46:18)
  [cause]: Error: too many terms in compound SELECT: SQLITE_ERROR
      at D1DatabaseSessionAlwaysPrimary._sendOrThrow (cloudflare-internal:d1-api:140:24)
      at cloudflare-internal:d1-api:366:41
      at D1Connection.executeQuery (.../chunk-V24LZAOZ.js:73:21)
      at .../chunk-O7MX2KDY.js:5895:22
      at DefaultConnectionProvider.provideConnection (.../chunk-O7MX2KDY.js:11936:14)
      at _DefaultQueryExecutor.executeQuery (.../chunk-O7MX2KDY.js:5894:12)
      at fetchRecentItems (.../[email protected]/.../api/handlers/dashboard.ts:184:17)
      at handleDashboardStats (.../[email protected]/.../api/handlers/dashboard.ts:82:23)
      at Module.GET (.../[email protected]/.../astro/routes/api/dashboard.ts:26:18)

The same stack reproduces on staging Cloudflare D1 via wrangler tail.

Root cause analysis

fetchRecentItems builds a Kysely raw-SQL composition roughly equivalent to:

SELECT * FROM (
  SELECT id, 'col1' AS slug_lit, 'Label 1' AS label_lit, COALESCE(title, slug, id) AS title,
         slug, status, updated_at, author_id
    FROM ec_col1 WHERE deleted_at IS NULL
  UNION ALL
  SELECT id, 'col2' AS slug_lit, 'Label 2' AS label_lit, COALESCE(title, slug, id) AS title, ...
    FROM ec_col2 WHERE deleted_at IS NULL
  UNION ALL
  ... one arm per title-bearing collection ...
) ORDER BY updated_at DESC LIMIT 10;

When the chained arm count crosses D1's compound SELECT cap, D1 rejects the query. The cap is undocumented for D1 specifically but is clearly lower than SQLite's upstream default of 500. We hit it at 9 arms.

The schema, migrations, seed and auth path are all correct: I verified by running the entire handler logic against the local sqlite via better-sqlite3 plus Kysely 0.27 (the same dialect family). All five steps inside handleDashboardStats complete cleanly under better-sqlite3. The failure is specific to the D1 driver path.

This bug was introduced in 0.8.0 because the equivalent 0.7.0 code path did not use this single-statement UNION ALL composition. 0.9.0 ships an identical dashboard.ts (verified by md5: fa72b1b1b2dc0f601e27174470857b12 for both v0.8.0 and v0.9.0).

Proposed fix

Replace the chained UNION ALL composition with N per-collection queries executed concurrently, then merge, sort and slice in JS. Equivalent semantics, no schema changes, no D1-specific branching, fetches at most N * limit rows for a small final limit.

Sketch:

const perCollection = await Promise.all(
  titleBearingCollections.map(({ slug, label }) =>
    db
      .selectFrom(getTableName(slug))
      .select(['id', 'slug', 'status', 'updated_at', 'author_id', 'title'])
      .where('deleted_at', 'is', null)
      .orderBy('updated_at', 'desc')
      .limit(10)
      .execute()
      .then(rows =>
        rows.map(r => ({
          ...r,
          collection_slug: slug,
          collection_label: label,
          title: r.title ?? r.slug ?? r.id,
        })),
      ),
  ),
);

const merged = perCollection
  .flat()
  .sort((a, b) => (b.updated_at > a.updated_at ? 1 : -1))
  .slice(0, 10);

This also avoids the per-arm sql.lit(label) interpolation which had its own UTF-8 risk for non-ASCII labels.

If the maintainer prefers to keep a single-statement query, an alternative is to chunk the UNION ALL into fixed-size groups (for example 4 arms per group), Promise.all the groups, and merge in JS. The per-collection variant is simpler and likely cheaper for D1.

Workaround

We are running a local pnpm patch emdash against the affected file to apply the per-collection fix. Happy to send it as a PR if helpful.

Severity

This blocks the emdash admin dashboard for any project on Cloudflare D1 with enough title-bearing collections (we hit it at 9). Auth works, the rest of the admin loads, but the first screen after login returns the failed-stats panel.

Activity

  1. added a commit that references this issue on May 6, 2026
    699e1b3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions