{
  "id": "add-postgres-full-text-search",
  "type": "prompts",
  "category": "prompts",
  "locale": "fr",
  "url": "/fr/prompts/add-postgres-full-text-search",
  "title": "Prompt pour ajouter la recherche plein texte PostgreSQL",
  "description": "Prompt IA copier-coller pour ajouter la recherche plein texte native PostgreSQL avec tsvector, index GIN et résultats classés à une application Next.js existante.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "postgres",
    "sql",
    "search",
    "nextjs",
    "typescript"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Utilisez ce prompt pour ajouter une véritable recherche plein texte PostgreSQL à une application existante — en utilisant `tsvector`, un index GIN et `ts_rank` — sans que l'agent ait recours à Elasticsearch, Algolia ou une API de recherche tierce.\n\n## Prompt principal\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js App Router project with TypeScript and PostgreSQL (using the\n`postgres` npm package, not Prisma or Drizzle).\n\nTask: add full-text search over the `posts` table (columns: id, title, body, created_at).\n\nDatabase changes:\n1. Write a migration file `migrations/0010_add_fts.sql` that:\n   - Adds a generated column: `search_vector tsvector GENERATED ALWAYS AS\n     (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,''))) STORED;`\n   - Creates a GIN index: `CREATE INDEX posts_search_idx ON posts USING GIN (search_vector);`\n2. Do NOT use `pg_trgm` or LIKE queries — use `@@` with `to_tsquery` or `websearch_to_tsquery`.\n\nApplication changes:\n- Create `src/lib/search.ts` with a `searchPosts(query: string, limit = 20)` function that:\n  - Uses `websearch_to_tsquery('english', $1)` to parse the query safely.\n  - Returns rows ordered by `ts_rank(search_vector, query_vector) DESC`.\n  - Returns `{ id, title, body_excerpt, rank }` — body_excerpt via `ts_headline`.\n  - Uses parameterized queries only — no string interpolation.\n- Create a Server Action `src/lib/actions/search.ts` that calls `searchPosts` and returns results.\n- Create `src/components/SearchBox.tsx` (Client Component) with a debounced input (300 ms) that\n  calls the Server Action via `useTransition` and renders results.\n\nDo not install pg_search, Meilisearch, or any search service. Stop and list files before coding.\n```\n\n## Notes d'implémentation\n\n- `websearch_to_tsquery` est plus sûr que `to_tsquery` pour les entrées utilisateur car il tolère les requêtes malformées (opérateurs manquants, caractères spéciaux) sans générer d'erreur PostgreSQL.\n- La colonne `tsvector` générée est automatiquement mise à jour lors des INSERT/UPDATE — aucun déclencheur nécessaire.\n- `ts_headline` nécessite le texte de la colonne d'origine et le vecteur de requête ; transmettez les deux depuis le SELECT.\n- L'index GIN rend la recherche rapide sur les grandes tables ; sans lui, les requêtes effectuent un balayage séquentiel.\n\n## Modifications de fichiers attendues\n\n```txt\nmigrations/0010_add_fts.sql              (new)\nsrc/lib/search.ts                        (new)\nsrc/lib/actions/search.ts               (new — Server Action)\nsrc/components/SearchBox.tsx            (new — Client Component)\n```\n\n## Critères d'acceptation\n\n- `psql -f migrations/0010_add_fts.sql` s'exécute sans erreur sur le schéma existant.\n- La recherche d'un mot qui n'apparaît que dans `title` renvoie le bon article.\n- La recherche d'une phrase avec une faute de frappe (ex. \"postgress\") ne renvoie aucun résultat sans planter.\n- Les résultats sont classés avec les articles les plus pertinents en premier.\n\n## Commandes de test\n\n```bash\npsql \"$DATABASE_URL\" -f migrations/0010_add_fts.sql\nbun run typecheck\nbun run dev\n# type a search term in SearchBox and verify ranked results appear\npsql \"$DATABASE_URL\" -c \"EXPLAIN ANALYZE SELECT * FROM posts WHERE search_vector @@ websearch_to_tsquery('english','test');\"\n# confirm \"Index Scan using posts_search_idx\" appears in output\n```\n\n## Erreurs courantes de l'IA\n\n- Utiliser `LIKE '%query%'` au lieu de l'opérateur plein texte `@@`.\n- Utiliser `to_tsquery('english', $1)` avec des entrées utilisateur brutes — se casse sur des requêtes comme `\"foo bar\"`.\n- Oublier l'index GIN, laissant la recherche en balayage séquentiel.\n- Appeler `searchPosts` dans un composant client au lieu de l'envelopper dans une action serveur.\n\n## Correctif du prompt\n\n```txt title=\"Fix Prompt\"\nThe search is using LIKE or crashing on special characters. Fix in order:\n1. Replace any LIKE clause with `search_vector @@ websearch_to_tsquery('english', $1)`.\n2. If `to_tsquery` is used directly with user input, replace it with `websearch_to_tsquery`.\n3. Confirm the GIN index exists: `CREATE INDEX IF NOT EXISTS posts_search_idx ON posts USING GIN (search_vector);`\nShow only the corrected diff. Do not modify unrelated files.\n```"
}