Skip to content

feat(search): execute booru queries end-to-end (AST → SQL) - #11

Merged
deckyfx merged 1 commit into
mainfrom
feat/search-exec
Jun 29, 2026
Merged

deckyfx merged 1 commit into
mainfrom
feat/search-exec

Conversation

@deckyfx

@deckyfx deckyfx commented Jun 29, 2026 •

Copy link
Copy Markdown
Owner

Completes the search pipeline started in #5: the parsed query AST now compiles to a Drizzle WHERE and filters the assets listing. Honors the Search Rule — db never parses text; the Core-owned Search Engine walks the AST → SQL.

What's included

  • core/search — compileAssetSearch(query): walks the query AST into a Drizzle condition.
    • Metatags → asset columns: rating: (enum equality), width/height/size (numeric eq/gt/gte/lt/lte and lo..hi, lo.., ..hi ranges).
    • Tag terms → an asset_tags EXISTS subquery (valid SQL now; matches once tagging lands), with * → % LIKE.
    • and/or/not via Drizzle; unknown metatag keys and invalid values are dropped, not errored.
  • db — findMany/count accept an optional prebuilt where: SQL so a page and its total share one filter.
  • core — AssetService.list accepts query; trims then compiles it once per call (count + page reuse the same filter).
  • api — GET /api/v1/assets?q= (capped at 1024 chars) forwards to the service.

Tests

  • Search Engine integration coverage: rating equality, numeric comparison, multi-metatag AND, ranges, negation, tag-term-with-no-tags, and pagination metadata under a filter.
  • API q-forwarding unit test (stubbed core).

Test safety

The destructive integration suites (they TRUNCATE) now read a dedicated, opt-in TEST_DATABASE_URL instead of the app's DATABASE_URL, so a misconfigured dev/prod env can never be wiped — unset → they skip. CI points it at its ephemeral Postgres; .env.example documents it. Applied to the pre-existing repository suite too for a consistent guarantee.

Validation

  • bun run typecheck ✓
  • bun run test ✓ (111 pass; 19 integration skip without TEST_DATABASE_URL)
  • bun run lint:boundaries ✓
  • CodeRabbit CLI: reviewed pre-push; 2 findings (1 critical) applied; re-review clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for searching assets with query filters in the API and app backend.
    • Search now includes tag, rating, size, and range-based filters, plus negation and multi-term matching.
  • Bug Fixes

    • Pagination totals now respect active search filters.
    • Integration tests now use an optional throwaway database and are skipped when not configured.
  • Tests

    • Added broader integration coverage for search behavior and repository filtering.
    • CI now points destructive tests to the ephemeral test database.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f7312aa-a659-408a-bd03-f280b87f1a6c

📥 Commits

Reviewing files that changed from the base of the PR and between b21ff97 and 9893499.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • .env.example
  • .github/workflows/ci.yml
  • apps/api/src/server.ts
  • apps/api/test/server.test.ts
  • packages/core/package.json
  • packages/core/src/search/asset-query.ts
  • packages/core/src/services/asset-service.ts
  • packages/core/test/asset-search.test.ts
  • packages/db/src/repositories/asset-repository.ts
  • packages/db/test/asset-repository.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • .github/workflows/ci.yml
  • .env.example
  • packages/core/package.json
  • packages/core/test/asset-search.test.ts
  • packages/db/test/asset-repository.test.ts
  • apps/api/test/server.test.ts
  • packages/core/src/services/asset-service.ts
  • apps/api/src/server.ts
  • packages/core/src/search/asset-query.ts
  • packages/db/src/repositories/asset-repository.ts

📝 Walkthrough

Walkthrough

Adds booru search query support to asset listing: a new compileAssetSearch function compiles a parsed AST into Drizzle SQL conditions (tags, rating, numeric metatags, logical operators). AssetRepository gains a where filter on findMany/count, AssetService.list accepts an optional query string, and the API endpoint exposes a q parameter. Integration tests use a dedicated TEST_DATABASE_URL.

Changes

Asset Search Query Pipeline

Layer / File(s) Summary
AssetRepository filter contract
packages/db/src/repositories/asset-repository.ts
AssetPage extended with where?: SQL; AssetRepository.count and findMany updated to accept and apply the filter; createAssetRepository implementation updated accordingly.
compileAssetSearch SQL compiler
packages/core/src/search/asset-query.ts, packages/core/package.json
New module exports compileAssetSearch that compiles a QueryNode AST into Drizzle SQL: and/or/not logic, tag EXISTS subqueries with glob-to-LIKE conversion, rating enum equality, and numeric metatag comparisons and range syntax. Adds drizzle-orm dependency.
AssetService list wiring
packages/core/src/services/asset-service.ts
ListAssetsOptions gains query?: string; AssetService.list compiles it once into a where filter passed to both repository.findMany and repository.count.
API endpoint q parameter
apps/api/src/server.ts, apps/api/test/server.test.ts
GET /api/v1/assets accepts optional q string (max 1024) and forwards it as options.query; unit test asserts the decoded value is passed through and the endpoint returns 200.
Integration tests and TEST_DATABASE_URL
packages/core/test/asset-search.test.ts, packages/db/test/asset-repository.test.ts, .github/workflows/ci.yml, .env.example
New asset-search integration suite gated on TEST_DATABASE_URL inserts deterministic assets and asserts filtering for all supported query features. Existing repository tests switched from DATABASE_URL to TEST_DATABASE_URL. CI and .env.example document and supply the opt-in URL.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • deckyfx/bunbooru#5: Introduced the booru query lexer, parser, and QueryNode AST that compileAssetSearch in this PR consumes.

Poem

🐇 Hoppity-hop through the query tree,
Tags and ratings, now searchable with glee!
rating:safe and width:gt:100 too,
The SQL compiles, the filters ring true.
A throwaway DB keeps the data clean —
The snappiest search that bunnies have seen! 🌸

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: booru query search is now executed end-to-end from AST compilation to SQL filtering.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/search-exec

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/core/test/asset-search.test.ts (1)

105-106: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add one positive tag-match case.

This only proves tag queries return zero when no asset_tags rows exist. A broken EXISTS join or *→% translation would still pass, so the end-to-end tag path is still unverified.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/asset-search.test.ts` around lines 105 - 106, The current
asset-search test only covers the no-tags case, so it does not verify that tag
matching actually works end to end. Update the test in asset-search.test.ts,
near the existing “compiles tag terms but matches nothing until tags exist”
case, to add one positive assertion that creates an asset_tags row and confirms
service.list({ query: "1girl" }) returns a matching result. Use the existing
service.list path and tag-query handling to ensure the EXISTS join and wildcard
translation are both exercised.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/search/asset-query.ts`:
- Around line 93-100: The range parser in rangeCondition currently accepts
malformed multi-bound inputs like size:1..2..3 because split("..") only uses the
first two segments and silently truncates the rest. Update rangeCondition in
asset-query.ts to reject any value that contains more than one ".." separator
(or otherwise has extra segments) and return undefined for such invalid syntax,
while preserving the existing valid single-bound and between handling.

---

Nitpick comments:
In `@packages/core/test/asset-search.test.ts`:
- Around line 105-106: The current asset-search test only covers the no-tags
case, so it does not verify that tag matching actually works end to end. Update
the test in asset-search.test.ts, near the existing “compiles tag terms but
matches nothing until tags exist” case, to add one positive assertion that
creates an asset_tags row and confirms service.list({ query: "1girl" }) returns
a matching result. Use the existing service.list path and tag-query handling to
ensure the EXISTS join and wildcard translation are both exercised.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 12644d21-1c34-4e75-9e59-2e8392e73dd4

📥 Commits

Reviewing files that changed from the base of the PR and between bd1982f and b21ff97.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • .env.example
  • .github/workflows/ci.yml
  • .gitignore
  • apps/api/src/server.ts
  • apps/api/test/server.test.ts
  • packages/core/package.json
  • packages/core/src/search/asset-query.ts
  • packages/core/src/services/asset-service.ts
  • packages/core/test/asset-search.test.ts
  • packages/db/src/repositories/asset-repository.ts
  • packages/db/test/asset-repository.test.ts

Comment thread packages/core/src/search/asset-query.ts Resolved
deckyfx added a commit that referenced this pull request Jun 29, 2026
`rangeCondition` split on every `..` and destructured the first two parts,
so an invalid range like `width:1..2..3` silently compiled to `BETWEEN 1
AND 2` and returned the wrong assets. Require exactly one separator; treat
anything else as malformed → ignored, consistent with how the compiler drops
other invalid terms. Adds a regression test.

Addresses CodeRabbit review on PR #11.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Complete the search pipeline started in #5: the parsed query AST compiles to
a Drizzle WHERE and filters the assets listing.

- core: add the Search Engine (`compileAssetSearch`) — walks the query AST
  into a Drizzle condition. Metatags map to asset columns (`rating:` enum
  equality; `width`/`height`/`size` numeric eq/gt/gte/lt/lte and `lo..hi`
  ranges, with malformed multi-bound ranges like `1..2..3` ignored, not
  silently truncated); tag terms compile to an `asset_tags` EXISTS subquery
  (valid SQL now, matching once tagging lands). and/or/not via Drizzle;
  unknown keys and invalid values are dropped, not errored.
- db: `findMany`/`count` accept an optional prebuilt `where: SQL` so the page
  and its total share one filter (db never parses text).
- core: `AssetService.list` accepts `query`; trims then compiles it once.
- api: `GET /api/v1/assets?q=` (capped at 1024 chars) forwards to the service.
- tests: integration coverage for rating/numeric/range/negation/tag and
  pagination metadata under a filter; API q-forwarding unit test.

Test safety: the destructive integration suites (they TRUNCATE) read a
dedicated, opt-in `TEST_DATABASE_URL` instead of the app's `DATABASE_URL`, so
a misconfigured dev/prod env can never be wiped — unset → they skip. CI sets
it to its ephemeral Postgres; `.env.example` documents it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@deckyfx
deckyfx force-pushed the feat/search-exec branch from 01a0c3d to 9893499 Compare June 29, 2026 10:44
@deckyfx

deckyfx commented Jun 29, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@deckyfx
deckyfx merged commit 7c10755 into main Jun 29, 2026
2 checks passed
@deckyfx
deckyfx deleted the feat/search-exec branch June 29, 2026 12:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant