Repository navigation
fix(core): search across all collections fails when one has no title field (#1178) - #1550
Conversation
…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 detectedLatest commit: c9fdd9c The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
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 |
There was a problem hiding this comment.
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 titlefor title-less collections insearchSingleCollection, keepingSearchResult.titleoptional as documented; - skips title-less collections in
getSuggestions, where a requiredSuggestion.titlecannot be produced; - covers both the REST search endpoint and the MCP
searchtool (which callssearchWithDb); - 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> { |
There was a problem hiding this comment.
[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.
| // 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))) { |
There was a problem hiding this comment.
[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:
| 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.
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
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.
There was a problem hiding this comment.
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): addshasTitleColumn+ bulkgetCollectionsWithTitleColumn, passes the bulk result intosearchSingleCollection, and skips title-less collections ingetSuggestions. packages/core/src/search/query.ts: multi-collection callers now issue one metadata query instead of two per collection;SearchResult.titleremains optional soNULLis fine; suggestions correctly skip collections that cannot produce a requiredSuggestion.title.packages/core/src/search/fts-manager.ts: bulk query is parameterized and joins_emdash_fields/_emdash_collectionssafely.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 MCPsearchtool callssearchWithDb, so it is covered by the same fix.- The regression test in
packages/core/tests/integration/search/title-less-collection.test.tsreproduces 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). | ||
| */ |
There was a problem hiding this comment.
[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:
| */ | |
| 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.
hasTitleColumn() ran two round-trips (collection lookup + field lookup) that getCollectionsWithTitleColumn() already covers in one query. Delegates single-collection callers to the bulk method.
What does this PR do?
Fixes the
searchAPI and MCPsearchtool throwingD1_ERROR: no such column: c.titlewhen searching across all collections (nocollectionsfilter) and any search-enabled collection has notitlefield.titleis an optional user-defined field, not a system column onec_*tables (the system columns areid, 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).searchSingleCollectionandgetSuggestionsselectedc.titleunconditionally, so the cross-collection path errored whenever it reached a collection without atitlefield. Passing an explicitcollectionslist that happened to have titles masked the bug — which matches the report (works with["pages","posts"], fails withoutcollections).The codebase already handles this exact gotcha in
api/handlers/dashboard.ts(fetchRecentItemschecks_emdash_fieldsfor atitlefield and falls back toslug); this PR applies the same precedent to search.Changes
FTSManager.hasTitleColumn(slug)— checks_emdash_fieldsfor atitlefield (mirrors the dashboard handler).searchSingleCollection: selectNULL as titlewhen the collection has notitlecolumn (results keep theirslug;SearchResult.titleis already optional).getSuggestions: skip collections without atitlefield (aSuggestion.titleis required and the query already filters onc.title IS NOT NULL, so these collections contribute nothing anyway).searchWithDbandgetSuggestions"all collections" paths.Closes #1178
Type of change
Checklist
pnpm typecheckpassespnpm lintpasses (oxlint, 0 diagnostics on changed files)pnpm testpasses (targeted: all search/MCP-search/suggest/i18n/schema suites — 138 tests green, incl. the new regression test)pnpm formathas been run (tabs; consistent with surrounding code)emdashpatch)AI-generated code disclosure
Screenshots / test output
Before (new test on the unpatched tree):
After: