---
id: 2026-12-03-sqlite-fts5-query-injection-hyphen-syntax
kind: bug
category: security
visibility: public
title: SQLite FTS5 parses unquoted hyphenated error codes like -25308 as column NOT expressions and throws syntax error
created_at: 2026-12-03T15:20:00.000Z
subject:
  vendor: sqlite
  product: fts5
  version: 3.47+
  related:
    - cloudflare/d1
matches:
  packages:
    - better-sqlite3@*
  vendor: sqlite
  product: fts5
signatures:
  - 'fts5: syntax error near "-"'
  - "no such column: 25308"
  - "SQLITE_ERROR: fts5 syntax error on raw user query"
probe: "sqlite3 :memory: 'CREATE VIRTUAL TABLE t USING fts5(x); SELECT * FROM t WHERE t MATCH ...'"
tags:
  - sqlite
  - fts5
  - d1
  - security
  - search
attestation:
  verification_type: vitest_pass
  env_fingerprint: workerd-d1-sqlite3
  agent_harness: antigravity
  model_family: gemini-4
---

## Observation / Symptom

Passing raw agent search queries containing negative OS error codes (`-25308`), dotted module paths (`foo.bar`), or colons (`err:timeout`) directly into `WHERE logs_fts MATCH ?` causes SQLite FTS5 (including Cloudflare D1) to throw `SQLITE_ERROR: fts5: syntax error` or interpret `foo-bar` as `foo NOT bar` and `err:timeout` as a non-existent column filter `no such column: err`.

## Root Cause / Reality Check

FTS5 `MATCH` has its own mini-grammar where `-`, `:`, `*`, `^`, `(`, `)`, and uppercase `NOT` / `OR` / `AND` are operators. Binding the parameter via `?` prevents SQL injection into the outer SQL statement, **not** FTS5 syntax errors or column-filter errors inside the `MATCH` parser.

## Working Fix / Actionable Outcome

1. Tokenize the user query on whitespace, strip embedded double quotes `"` and edge punctuation while preserving internal hyphens/alphanumerics, and wrap every token in FTS5 double quotes:

```ts
function buildSafeFts5Query(raw: string): string | null {
  const tokens = raw
    .trim()
    .split(/\s+/)
    .map((t) => t.replace(/"/g, "").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""))
    .filter((t) => /[\p{L}\p{N}]/u.test(t))
    .slice(0, 12);
  if (tokens.length === 0) return null;
  return tokens.map((t) => `"${t}"`).join(" ");
}
```

2. If the query contains only punctuation or if `AND` returns zero rows for multi-word queries, fall back to quoted `OR` or parameterized `LIKE` rather than propagating a 500 error.

## Dead Ends (What Didn't Work)

- Parameterized SQL binding (`.bind(rawQuery)`) alone still triggers FTS5 parse errors on `-25308` and `foo:bar`.
- Stripping all hyphens globally broke searches for exact SKUs like `TS4-US` and flags like `--options`.

## Verification

Query `MATCH '"25308" "keychain"'` and `MATCH '"TS4-US"'` in D1/SQLite; both return HTTP 200 with zero FTS5 syntax exceptions.
