Skip to content

fix(core): search across all collections fails when one has no title field (#1178) - #1550

Merged
ascorbic merged 3 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1178-search-titleless-collections
Jul 9, 2026
Merged

ascorbic merged 3 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1178-search-titleless-collections

Conversation

@ColoradoClimbr

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes the search API and MCP search tool throwing D1_ERROR: no such column: c.title when searching across all collections (no collections filter) and any search-enabled collection has no title field.

title is an optional user-defined field, not a system column on ec_* tables (the system columns are id, slug, status, author_id, primary_byline_id, created_at, updated_at, published_at, scheduled_at, deleted_at, version, live_revision_id, draft_revision_id, locale, translation_group). searchSingleCollection and getSuggestions selected c.title unconditionally, so the cross-collection path errored whenever it reached a collection without a title field. Passing an explicit collections list that happened to have titles masked the bug — which matches the report (works with ["pages","posts"], fails without collections).

The codebase already handles this exact gotcha in api/handlers/dashboard.ts (fetchRecentItems checks _emdash_fields for a title field and falls back to slug); this PR applies the same precedent to search.

Changes

  • Add FTSManager.hasTitleColumn(slug) — checks _emdash_fields for a title field (mirrors the dashboard handler).
  • searchSingleCollection: select NULL as title when the collection has no title column (results keep their slug; SearchResult.title is already optional).
  • getSuggestions: skip collections without a title field (a Suggestion.title is required and the query already filters on c.title IS NOT NULL, so these collections contribute nothing anyway).
  • Regression test reproducing the reported error across the searchWithDb and getSuggestions "all collections" paths.

Closes #1178

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes (oxlint, 0 diagnostics on changed files)
  • pnpm test passes (targeted: all search/MCP-search/suggest/i18n/schema suites — 138 tests green, incl. the new regression test)
  • pnpm format has been run (tabs; consistent with surrounding code)
  • I have added/updated tests for my changes
  • User-visible strings in the admin UI are wrapped for translation — n/a (no admin UI strings; server-side error codes only)
  • I have added a changeset (emdash patch)
  • New features link to an approved Discussion — n/a (bug fix)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (Claude Code)

Screenshots / test output

Before (new test on the unpatched tree):

× searches across all collections when one lacks a title field
× returns suggestions across all collections, skipping ones without a title
  SqliteError: no such column: c.title
    ❯ searchSingleCollection src/search/query.ts:220
    ❯ getSuggestions src/search/query.ts:360

After:

Test Files  1 passed (1)
     Tests  2 passed (2)

…eld (#1178)

`title` is an optional user-defined field, not a system column on `ec_*`
tables. `searchSingleCollection` and `getSuggestions` selected `c.title`
unconditionally, so searching across all collections (no `collections`
filter) threw `D1_ERROR: no such column: c.title` whenever any
search-enabled collection lacked a `title` field. Scoping to collections
that happen to have a title masked the bug.

Add `FTSManager.hasTitleColumn` and use it to select `NULL` for the title
when the column is absent (results keep their slug) in
`searchSingleCollection`, and to skip title-less collections in
`getSuggestions` (a suggestion requires a title and the query already
filters on `c.title IS NOT NULL`).

Adds a regression test covering the cross-collection search and
suggestion paths with a collection that has no title field.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@changeset-bot

changeset-bot Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c9fdd9c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jun 24, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR fixes a real, well-diagnosed bug: cross-collection search and autocomplete failed when any search-enabled collection lacked a title field, because the SQL selected c.title unconditionally. The approach is sound and follows the precedent in api/handlers/dashboard.ts of checking _emdash_fields to discover whether a collection has a user-defined title.

I read the diff, the changed search stack (fts-manager.ts, query.ts), the dashboard handler for comparison, the search API routes, and the MCP tool registration. The fix correctly:

  • selects NULL as title for title-less collections in searchSingleCollection, keeping SearchResult.title optional as documented;
  • skips title-less collections in getSuggestions, where a required Suggestion.title cannot be produced;
  • covers both the REST search endpoint and the MCP search tool (which calls searchWithDb);
  • adds a focused regression test reproducing the reported failure paths.

The changeset reads as user-facing release notes, and the test matches the existing integration style.

The one concern is query count: hasTitleColumn() issues two DB round-trips per collection, and it is invoked once per searched collection in both searchWithDb and getSuggestions. AGENTS.md is explicit that "one query beats two" on D1. The dashboard implementation avoids this by discovering all title-bearing collections in a single bulk query. Today this is a correctness fix with a bounded performance cost; for sites with many search-enabled collections the extra round trips will add up, so I’d like to see the metadata folded into one of the existing per-collection queries or batched across the whole list before merge. Outside of that, this is a clean, minimal bug fix.

* that selects `c.title` must check this first; otherwise collections
* without a title field raise "no such column: c.title" (#1178).
*/
async hasTitleColumn(collectionSlug: string): Promise<boolean> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] hasTitleColumn() performs two round-trips per call (_emdash_collections lookup + _emdash_fields lookup). It is called once per searched collection from both searchWithDb and getSuggestions, so cross-collection search on a site with N search-enabled collections adds 2N extra D1 round-trips. AGENTS.md emphasizes minimizing query counts on D1, and api/handlers/dashboard.ts already shows the better pattern: a single bulk query joining _emdash_fields and _emdash_collections, then using a Set.

The cheapest refactor is to extend getSearchableFields() (or add a getSearchMetadata() helper) to return both the searchable fields and whether a title field exists, since both queries already hit _emdash_collections and _emdash_fields:

async getSearchMetadata(collectionSlug: string): Promise<{ searchableFields: string[]; hasTitle: boolean }> {
  const collection = await this.db
    .selectFrom("_emdash_collections")
    .select("id")
    .where("slug", "=", collectionSlug)
    .executeTakeFirst();

  if (!collection) {
    return { searchableFields: [], hasTitle: false };
  }

  const fields = await this.db
    .selectFrom("_emdash_fields")
    .select(["slug", "searchable"])
    .where("collection_id", "=", collection.id)
    .execute();

  return {
    searchableFields: fields.filter((f) => f.searchable === 1).map((f) => f.slug),
    hasTitle: fields.some((f) => f.slug === "title"),
  };
}

Then use getSearchMetadata(collection) in searchSingleCollection instead of the two separate calls. This keeps the fix correct while honoring the codebase’s query-count discipline.

Comment thread packages/core/src/search/query.ts Outdated
// query filters on `c.title IS NOT NULL`). Collections without a
// `title` field can't produce one, and selecting `c.title` would
// error, so skip them. See #1178.
if (!(await ftsManager.hasTitleColumn(collection))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] In getSuggestions, validateIdentifier(collection) now runs after getSearchConfig() and hasTitleColumn(). For an invalid collection slug those two helper calls still issue DB queries (and waste round-trips) before validation finally throws. Move validateIdentifier(collection, "collection slug"); to the top of the loop body, before any DB lookups:

Suggested change
if (!(await ftsManager.hasTitleColumn(collection))) {
for (const collection of collections) {
// Validate before any DB lookups or raw SQL interpolation.
validateIdentifier(collection, "collection slug");
const ftsManager = new FTSManager(db);
const config = await ftsManager.getSearchConfig(collection);
if (!config?.enabled) {
continue;
}
// Suggestions are title-based (Suggestion.title is required and the
// query filters on `c.title IS NOT NULL`). Collections without a
// `title` field can't produce one, and selecting `c.title` would
// error, so skip them. See #1178.
if (!(await ftsManager.hasTitleColumn(collection))) {
continue;
}
const ftsTable = ftsManager.getFtsTableName(collection);

This is consistent with searchSingleCollection(), which validates the slug first, and avoids pointless queries for malformed input.

@pkg-pr-new

pkg-pr-new Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1550

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1550

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1550

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1550

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1550

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1550

emdash

npm i https://pkg.pr.new/emdash@1550

create-emdash

npm i https://pkg.pr.new/create-emdash@1550

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1550

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1550

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1550

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1550

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1550

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1550

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1550

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1550

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1550

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1550

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1550

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1550

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1550

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1550

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1550

commit: c9fdd9c

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jun 24, 2026
Addresses review feedback on #1550: hasTitleColumn() issued two DB
round-trips per collection and was called once per collection in both
searchWithDb() and getSuggestions(), so a site with many search-enabled
collections paid a growing number of extra queries per search request.

Adds FTSManager.getCollectionsWithTitleColumn(), which resolves title-
column membership for a whole collection list in one query (mirroring
the pattern in dashboard.ts's fetchRecentItems). searchWithDb() and
getSuggestions() now precompute this once and pass the per-collection
result into searchSingleCollection() instead of querying per collection.
searchCollection() (single-collection callers) keeps the original
hasTitleColumn() fallback.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 3, 2026
@ascorbic ascorbic added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels Jul 6, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This re-review confirms the PR is a clean, correct fix for #1178 and the prior performance concern is resolved.

The author addressed my previous feedback by replacing the per-collection hasTitleColumn() round-trips with a single bulk query (FTSManager.getCollectionsWithTitleColumn) in both searchWithDb and getSuggestions. That satisfies AGENTS.md's "one query beats two" rule for the multi-collection path, which is where the cost scaled with collection count.

What I checked:

  • The diff (.flue-pr.diff): adds hasTitleColumn + bulk getCollectionsWithTitleColumn, passes the bulk result into searchSingleCollection, and skips title-less collections in getSuggestions.
  • packages/core/src/search/query.ts: multi-collection callers now issue one metadata query instead of two per collection; SearchResult.title remains optional so NULL is fine; suggestions correctly skip collections that cannot produce a required Suggestion.title.
  • packages/core/src/search/fts-manager.ts: bulk query is parameterized and joins _emdash_fields/_emdash_collections safely.
  • packages/core/src/api/handlers/dashboard.ts: the precedent for discovering title-bearing collections in one query is followed correctly.
  • packages/core/src/mcp/server.ts: the MCP search tool calls searchWithDb, so it is covered by the same fix.
  • The regression test in packages/core/tests/integration/search/title-less-collection.test.ts reproduces both the failing paths and verifies the bulk helper directly.
  • The changeset is user-facing and describes the observable fix.

No blocking issues remain. I have one optional suggestion to eliminate the duplicated title-discovery logic and give single-collection callers the same one-query benefit.

* collection defines a field with slug `title`. Search and suggestion SQL
* that selects `c.title` must check this first; otherwise collections
* without a title field raise "no such column: c.title" (#1178).
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] hasTitleColumn() duplicates the same _emdash_fields/_emdash_collections lookup that getCollectionsWithTitleColumn() already performs, and it costs two queries for single-collection callers (e.g. searchCollection).

You can delegate to the bulk method to remove the duplication and reduce those callers to one query:

Suggested change
*/
async hasTitleColumn(collectionSlug: string): Promise<boolean> {
const withTitle = await this.getCollectionsWithTitleColumn([collectionSlug]);
return withTitle.has(collectionSlug);
}

A non-existent collection will still resolve to false because it won't appear in the join result.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in c9fdd9c.

hasTitleColumn() ran two round-trips (collection lookup + field
lookup) that getCollectionsWithTitleColumn() already covers in one
query. Delegates single-collection callers to the bulk method.

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@ascorbic
ascorbic merged commit cbc7d6b into emdash-cms:main Jul 9, 2026
48 checks passed
@emdashbot emdashbot Bot mentioned this pull request Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core bot:review Trigger an emdashbot code review on this PR cla: signed review/needs-rereview New commits since the last review size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: search MCP tool returns D1_ERROR: no such column: c.title when collections argument is omitted

2 participants