Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(database): skip pg_search migrations without the extension and guard startup (#20944)

YuTengjing406f6afecc9f
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.md
index d09d7cf8958..ff09c205b18 100644
--- a/.agents/acceptance/references/probe-field-notes.md
+++ b/.agents/acceptance/references/probe-field-notes.md
@@ -493,10 +493,10 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
- **Situation**: `init-dev-env.sh setup-db` needs Docker (paradedb + redis images), but
Docker Desktop's VM can wedge indefinitely (`no route to host` to 192.168.65.x, empty
vm/console.log). Verified working substitute:
- - **Postgres**: local brew Postgres 17 (pgvector available). The only paradedb-specific
- migrations are `0090_enable_pg_search` / `0093_add_bm25_indexes_with_icu` — no-op them
- in the worktree (`SELECT 1;`), everything else applies clean.
- - **Redis is a hard dependency of Better Auth sign-in** — with a dead REDIS\_URL the seed
+ - **Postgres**: local brew Postgres 17 (pgvector available). Migrations apply clean: the
+ `pg_search` / BM25 migrations skip themselves without the extension. Set
+ `FTS_SEARCH_PROVIDER=pg_like` so product search works.
+ - **Redis is a hard dependency of Better Auth sign-in** — with a dead REDIS_URL the seed
login 500s (`[Better Auth]: Error: Connection is closed`). `brew install redis`,
`redis-server --port 6380 --daemonize yes`.
- **S3**: `s3rver` (npm) on 29000 with a CORS config for the bucket. Its presigned-URL
@@ -745,7 +745,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
- **Read the cause from `async_tasks.error`, not the toast**: `docker exec <pg> psql -U postgres -d postgres -c "select status, error from async_tasks order by created_at desc limit 3;"`.
- **Three separate walls, in the order you hit them**:
1. `start async task error: JWKS_KEY environment variable is not set` → see E22. The bootstrap now exports a persisted `JWKS_KEY`; you only hit this on a server started outside `init-dev-env.sh`.
- 2. `InvalidProviderAPIKey` → the seeded user's stored `ai_providers.key_vaults` may hold a key encrypted with a different `KEY_VAULTS_SECRET`. Clear it (`update ai_providers set key_vaults = null where id = '<provider>'`) so the server env key is used; provide `<PROVIDER>_API_KEY` plus, for a relay endpoint, `<PROVIDER>_PROXY_URL` (`apps/server/src/modules/ModelRuntime/index.ts` reads `process.env[`${UPPER}\_PROXY\_URL`]`).
+ 2. `InvalidProviderAPIKey` → the seeded user's stored `ai_providers.key_vaults` may hold a key encrypted with a different `KEY_VAULTS_SECRET`. Clear it (`update ai_providers set key_vaults = null where id = '<provider>'`) so the server env key is used; provide `<PROVIDER>_API_KEY` plus, for a relay endpoint, `<PROVIDER>_PROXY_URL` (`apps/server/src/modules/ModelRuntime/index.ts` reads `process.env[`${UPPER}\_PROXY_URL`]`).
3. `SSRF blocked: ... is not allowed. Because, It is private IP address.` → any reference image living in the local s3rver is fetched **server-side**. The bootstrap now exports `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`; set it yourself on a server started another way.
- **Then note which model the product actually picked** before attributing quality or format to a model: read the product's own selector rather than assuming (`selectAgentArtworkModel(enabledImageModelList(...))` over CDP). Disabling a provider row is enough to change the pick.
- **Style presets that attach reference images can still fail after all three**: local presigned URLs may return an S3 XML error body, which reaches the model as `Unsupported MIME type: application/xml`. Pick a preset with no reference images to test generation itself.
@@ -788,7 +788,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
conclusion. If a run "should" have hit your code and didn't, prove the server is running your
code FIRST — drop a `console.error` on the path and restart — before debugging the code itself.
-### E27. ✅ `source`-ing an unquoted JSON env var silently corrupts it (JWKS\_KEY → gateway auth\_failed)
+### E27. ✅ `source`-ing an unquoted JSON env var silently corrupts it (JWKS_KEY → gateway auth_failed)
- **Situation**: writing an env file for the local gateway loop with
`JWKS_KEY={"keys":[{"kty":"RSA",...}]}` on one line, then `set -a; source that-file`.
@@ -821,10 +821,10 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
and pick one from there. Also: a send that "resolves fine but creates no operation" is a UI-gate
symptom; **screenshot the composer** instead of re-reading your store call.
-### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` — NODE\_PATH into .pnpm fixes it
+### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` — NODE_PATH into .pnpm fixes it
- **Situation**: in a fresh git-worktree install, `init-dev-env.sh seed-user`
- (which runs `node <<'NODE'` from the repo root) throws MODULE\_NOT\_FOUND for
+ (which runs `node <<'NODE'` from the repo root) throws MODULE_NOT_FOUND for
`bcryptjs`, even though `pnpm install` succeeded.
- **Cause not fully established**: `bcryptjs` exists in `node_modules/.pnpm/`
but is not linked at the repo-root `node_modules` top level in that install
@@ -832,7 +832,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
resolve it.
- **Works**: prefix the call with
`NODE_PATH="$PWD/node_modules/.pnpm/bcryptjs@<ver>/node_modules"` (check the
- exact version dir first). CJS stdin scripts honor NODE\_PATH; seeding then
+ exact version dir first). CJS stdin scripts honor NODE_PATH; seeding then
completes normally.
- Same run also (re)confirmed: `init-dev-env.sh dev` ports are DYNAMIC (e.g.
next on 33803, vite on 32459) — never hardcode 3010; re-run
@@ -953,7 +953,7 @@ posix_spawn '<cmd>'` — NOT node's `spawn <cmd> ENOENT`. Any stderr-text patter
Telegram/Slack/Discord. A real bind needs a live bot issuing a `random_id` link token —
unavailable in an isolated env.
- **Works**: take the page's own refresh-after-link path instead. With a signed-in user, seed
- (1) a `messenger_account_links` row for (user, platform, tenant\_id='') and (2) an enabled
+ (1) a `messenger_account_links` row for (user, platform, tenant_id='') and (2) an enabled
`system_bot_providers` row for the platform — `credentials` must be encrypted with
`KeyVaultsGateKeeper.initWithEnvKey()` (same `KEY_VAULTS_SECRET` as the dev server), e.g.
telegram `{ botToken, botUsername }`. Then open
@@ -962,7 +962,7 @@ posix_spawn '<cmd>'` — NOT node's `spawn <cmd> ENOENT`. Any stderr-text patter
(`shouldShowSingleAccountSuccess` — existing link + no active token → success).
- `botUsername` drives the "Open in <platform>" deep-link CTA; re-encrypt the credentials
WITHOUT it to exercise the no-deep-link fallback. Note the platform config is cached
- in-process for 30s (`packages/app-config/src/messenger.ts` CACHE\_TTL\_MS) — wait out the TTL
+ in-process for 30s (`packages/app-config/src/messenger.ts` CACHE_TTL_MS) — wait out the TTL
after editing the row before reloading.
- Locale for evidence shots: `window.__LOBE_STORES.global().switchLocale('zh-CN')` then reload.
@@ -991,7 +991,7 @@ an action against the wrong row. For drag interactions (annotation canvases), di
`MouseEvent`s (`mousedown/mousemove/mouseup` with `bubbles:true` and computed `clientX/Y`) on the
target element.
-### E34. Shell proxy env (HTTP\_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops
+### E34. Shell proxy env (HTTP_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops
**Situation**: `init-dev-env.sh dev` launched from a shell where a system proxy (Clash etc.) exported
`HTTP_PROXY`/`HTTPS_PROXY`. The server booted fine, pages served, but `POST /api/auth/sign-in/email`
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 6f41d32360a..c8a6e33e1c3 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -59,12 +59,12 @@ router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> ex
## Changing a Searchable Entity
-### Scope for pg\_like
+### Scope for pg_like
`pg_like` primarily serves individual users with small datasets. Review it for correct matching,
permissions, and usable result ordering at that scale. For richer search quality or larger datasets,
recommend self-hosted Elasticsearch or Elastic Cloud. Do not add indexes or change the database
-schema as part of pg\_like optimization. Keep repairs bounded; distinguish new implementation bugs
+schema as part of pg_like optimization. Keep repairs bounded; distinguish new implementation bugs
from shared provider limitations and deliberate lightweight-search trade-offs. Do not infer a
personal-user performance problem from large shared development datasets without representative
measurements.
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
index 740bd040f94..93cacb6a2fb 100644
--- a/.agents/skills/testing/SKILL.md
+++ b/.agents/skills/testing/SKILL.md
@@ -14,7 +14,7 @@ user-invocable: false
# Run specific test file
bunx vitest run --silent='passed-only' '[file-path]'
-# Database package (client-db, PGlite — default, skips BM25/pg_search)
+# Database package (client-db, PGlite — default, no pg_search; BM25 migrations skip themselves)
cd packages/database && bunx vitest run --silent='passed-only' '[file]'
# Database package (server-db, Postgres — BM25/pgvector parity, what CI measures coverage in)
diff --git a/.agents/skills/testing/references/db-model-test.md b/.agents/skills/testing/references/db-model-test.md
index 376119895db..489595737ae 100644
--- a/.agents/skills/testing/references/db-model-test.md
+++ b/.agents/skills/testing/references/db-model-test.md
@@ -14,10 +14,10 @@ Test the `packages/database` Model and Repository layers.
`getTestDB()` (`src/core/getTestDB.ts`) returns different engines based on the
`TEST_SERVER_DB` env var:
-| Mode | Engine | When | Notes |
-| ----------------------- | ----------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **client-db** (default) | PGlite (in-memory) | `bunx vitest run` | Migration runner **skips any SQL containing `pg_search` / `bm25`** — the ParadeDB BM25 `@@@` operator does not exist here. |
-| **server-db** | node-postgres → `DATABASE_TEST_URL` | `TEST_SERVER_DB=1` | CI uses the `paradedb/paradedb` image (has `pg_search`). **Coverage is measured in this mode** (`test:coverage` → `vitest.config.server.mts`, uploaded to Codecov). |
+| Mode | Engine | When | Notes |
+| ----------------------- | ----------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **client-db** (default) | PGlite (in-memory) | `bunx vitest run` | Runs the real migrations; the `pg_search` / BM25 migrations **skip themselves** because PGlite has no `pg_search`, so the ParadeDB BM25 `@@@` operator does not exist here. |
+| **server-db** | node-postgres → `DATABASE_TEST_URL` | `TEST_SERVER_DB=1` | CI uses the `paradedb/paradedb` image (has `pg_search`). **Coverage is measured in this mode** (`test:coverage` → `vitest.config.server.mts`, uploaded to Codecov). |
```bash
# 1. Client environment (fast, default — what most local runs use)
diff --git a/Dockerfile b/Dockerfile
index 826fb06763c..924acdc3eb7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -122,6 +122,7 @@ COPY --from=builder /app/public/_spa-workbench /app/public/_spa-workbench
COPY --from=builder /app/packages/database/migrations /app/migrations
COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
COPY --from=builder /app/scripts/migrateServerDB/errorHint.js /app/errorHint.js
+COPY --from=builder /app/scripts/migrateServerDB/pgSearchGuard.js /app/pgSearchGuard.js
COPY --from=builder /app/fts-search-elasticsearch-reindex.cjs /app/fts-search-elasticsearch-reindex.cjs
COPY --from=builder /app/fts-search-elasticsearch-sync.cjs /app/fts-search-elasticsearch-sync.cjs
COPY --from=builder /app/fts-search-ineligible-message-cleanup.cjs /app/fts-search-ineligible-message-cleanup.cjs
diff --git a/docs/self-hosting/advanced/full-text-search.mdx b/docs/self-hosting/advanced/full-text-search.mdx
index eac94748908..d332015e40f 100644
--- a/docs/self-hosting/advanced/full-text-search.mdx
+++ b/docs/self-hosting/advanced/full-text-search.mdx
@@ -26,12 +26,12 @@ LobeHub supports three product-search backends:
fall back to another backend when the selected provider is unavailable.
<Callout type="warning">
- `FTS_SEARCH_PROVIDER=elasticsearch` does not make historical database migrations skip
- `pg_search`. The current Elasticsearch migration workflow is intended for an existing LobeHub
- database that has already applied the `pg_search` migrations. A fresh database on a service that
- cannot install `pg_search` is not currently supported merely by selecting Elasticsearch:
- `bun run db:migrate` still reaches migrations that create the extension and BM25 indexes, and
- fails when the database service does not provide them.
+ Database migrations install `pg_search` and its BM25 indexes only when the database provides the
+ extension, and skip that step otherwise. On PostgreSQL without `pg_search`, set
+ `FTS_SEARCH_PROVIDER=pg_like` or `elasticsearch` before starting LobeHub. While the provider is
+ `pg_search`, including when it is unset, the database migration step stops with an error naming
+ the fix if the extension or any LobeHub BM25 index is missing, so the Docker container does not
+ start and a Vercel build fails.
</Callout>
## Choose a backend
@@ -50,6 +50,14 @@ migrations to install the extension and the LobeHub-managed BM25 indexes, then k
FTS_SEARCH_PROVIDER=pg_search
```
+If you install `pg_search` on a database that ran the LobeHub migrations without it, create the
+extension and the BM25 indexes from a LobeHub source checkout before selecting this provider:
+
+```bash
+psql "$DATABASE_URL" -c 'CREATE EXTENSION IF NOT EXISTS pg_search'
+psql "$DATABASE_URL" -f packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
+```
+
### Use `pg_like` on plain PostgreSQL
Choose `pg_like` when your PostgreSQL service cannot install `pg_search` (many managed providers) and
@@ -73,9 +81,10 @@ What to expect compared with the other backends:
personal and small-team instances; for large message or memory tables, prefer `pg_search` or
Elasticsearch.
-The same migration limitation as Elasticsearch applies: `pg_like` does not remove the historical
-`pg_search` migrations, so a fresh database still has to run on an image that provides the
-extension until those migrations become optional.
+New databases and upgrades both work on PostgreSQL without `pg_search`: the migrations skip the
+extension and BM25 indexes there. If you previously replaced the `0090_enable_pg_search.sql` or
+`0093_add_bm25_indexes_with_icu.sql` migration files to get past a failed upgrade, remove that
+override.
### Use Elasticsearch
@@ -87,9 +96,9 @@ service-free `pg_like` backend first.
Neon stopped offering `pg_search` to new projects on March 19, 2026. Retirement timelines for
existing projects follow the notice Neon sends for that project. LobeHub users who receive such a
notice should use
-[Migrate from pg\_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) to choose
+[Migrate from pg_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) to choose
`pg_like` or Elasticsearch. Check Neon's
-[current pg\_search notice](https://neon.com/docs/extensions/pg_search) before acting.
+[current pg_search notice](https://neon.com/docs/extensions/pg_search) before acting.
There are two supported ways to run Elasticsearch. Both use the same backfill and incremental
sync commands and the same `ES_INDEX_NAMESPACE`; they differ only in how LobeHub reaches the
@@ -116,15 +125,14 @@ Elasticsearch runs with security disabled and is reachable only inside the Compo
plaintext, no-API-key connection must be enabled explicitly with `ES_ALLOW_INSECURE_HTTP=true`. See
[Run Elasticsearch with Docker Compose](#run-elasticsearch-with-docker-compose) below.
-#### Database requirement for both options
+#### Database support for both options
-Selecting Elasticsearch does not remove the historical `pg_search` migrations. Until that
-follow-up ships, every LobeHub database, including a fresh Docker Compose install, must still run on
-a PostgreSQL image that can install `pg_search`, such as the bundled `paradedb/paradedb:latest-pg17`.
-Elasticsearch then takes over search traffic after the backfill; the `pg_search` objects can be
-removed later with the supported cleanup command.
+Elasticsearch works with PostgreSQL with or without `pg_search`: LobeHub migrations skip the
+BM25 setup on a database that does not provide the extension. When the database already has
+`pg_search` objects, Elasticsearch takes over search traffic after the backfill, and the objects can
+be removed later with the supported cleanup command.
-See [Migrate from pg\_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) for
+See [Migrate from pg_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) for
guidance on choosing a backend and starting the migration.
## How Elasticsearch synchronization works
diff --git a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
index 6d66f9c220f..12e70dbd040 100644
--- a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
+++ b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
@@ -24,10 +24,10 @@ LobeHub 支持三种产品搜索后端:
`pg_like`,默认值是 `pg_search`。选中的后端不可用时,LobeHub 不会静默切换到另一个后端。
<Callout type="warning">
- 设置 `FTS_SEARCH_PROVIDER=elasticsearch` 不会让历史数据库迁移跳过 `pg_search`。当前
- Elasticsearch 迁移流程面向已经执行过 `pg_search` 迁移的现有 LobeHub 数据库。对于无法安装
- `pg_search` 的数据库服务,仅选择 Elasticsearch 目前还不能完成全新建库:`bun run db:migrate`
- 仍会执行创建扩展和 BM25 索引的历史迁移,并在数据库服务不提供它们时失败。
+ 数据库迁移只在数据库提供 `pg_search` 扩展时安装它和 BM25 索引,否则跳过这一步。在没有
+ `pg_search` 的 PostgreSQL 上,请在启动 LobeHub 前设置 `FTS_SEARCH_PROVIDER=pg_like` 或
+ `elasticsearch`。后端为 `pg_search`(包括未设置时的默认值)而数据库缺少该扩展或任一 LobeHub
+ BM25 索引时,数据库迁移步骤会报错并给出修复方法:Docker 容器不会启动,Vercel 构建会失败。
</Callout>
## 如何选择
@@ -43,6 +43,13 @@ LobeHub 支持三种产品搜索后端:
FTS_SEARCH_PROVIDER=pg_search
```
+如果数据库是在执行完 LobeHub 迁移之后才安装 `pg_search` 的,请在 LobeHub 源码目录中先创建扩展和 BM25 索引,再选择这个后端:
+
+```bash
+psql "$DATABASE_URL" -c 'CREATE EXTENSION IF NOT EXISTS pg_search'
+psql "$DATABASE_URL" -f packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
+```
+
### 在普通 PostgreSQL 上使用 `pg_like`
如果 PostgreSQL 服务无法安装 `pg_search`(很多托管数据库都是如此),而部署规模又小到不值得单独运维一套搜索服务,可以选择 `pg_like`。它不需要扩展、不需要额外索引、也不需要同步任务:所有搜索都以不区分大小写的子串匹配(`ILIKE`)直接在与 `pg_search` 相同的数据表和权限范围上执行。
@@ -57,13 +64,13 @@ FTS_SEARCH_PROVIDER=pg_like
- **排序。** 结果按简单的相关度打分排序:整字段完全匹配高于前缀匹配,前缀匹配高于短语包含,短语包含高于仅包含全部词语;标题类字段的权重高于正文。
- **性能。** 查询会扫描权限范围内的数据行而不是走搜索索引。个人和小团队实例完全够用;消息或记忆表很大时,请优先考虑 `pg_search` 或 Elasticsearch。
-迁移限制与 Elasticsearch 相同:`pg_like` 不会移除历史 `pg_search` 迁移,在这些迁移变为可选之前,全新建库仍必须运行在能提供该扩展的镜像上。
+在没有 `pg_search` 的 PostgreSQL 上,全新建库和升级都能完成:迁移会跳过扩展和 BM25 索引。如果你之前为了完成升级替换过 `0090_enable_pg_search.sql` 或 `0093_add_bm25_indexes_with_icu.sql` 迁移文件,请移除这项覆盖。
### 使用 Elasticsearch
如果搜索需要独立容量、希望把搜索存储从事务 PostgreSQL 中拆开,并且能够持续运行同步任务,可以选择 Elasticsearch。个人或小型部署在数据库停止支持 `pg_search` 时,应优先考虑无需额外服务的 `pg_like`。
-Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`。现有项目的停用安排以 Neon 发给该项目的通知为准;收到停用通知的 LobeHub 用户应按 [Neon pg\_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)选择 `pg_like` 或 Elasticsearch。执行前请核对 Neon 的[最新 pg\_search 公告](https://neon.com/docs/extensions/pg_search)。
+Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`。现有项目的停用安排以 Neon 发给该项目的通知为准;收到停用通知的 LobeHub 用户应按 [Neon pg_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)选择 `pg_like` 或 Elasticsearch。执行前请核对 Neon 的[最新 pg_search 公告](https://neon.com/docs/extensions/pg_search)。
Elasticsearch 有两种受支持的运行方式。两者使用同一套回填和增量同步命令、同一个
`ES_INDEX_NAMESPACE`,区别只在于 LobeHub 如何连接集群。
@@ -86,14 +93,12 @@ Elasticsearch 关闭了安全认证,只能在 Compose 内部网络访问,因
`ES_ALLOW_INSECURE_HTTP=true` 显式允许无 API 密钥的明文连接。详见下文
[使用 Docker Compose 运行 Elasticsearch](#使用-docker-compose-运行-elasticsearch)。
-#### 两种方式共同的数据库限制
+#### 两种方式的数据库支持
-选择 Elasticsearch 不会移除历史 `pg_search` 迁移。在这项后续工作完成前,所有 LobeHub 数据库(包括全新的 Docker
-Compose 安装)仍必须运行在能够安装 `pg_search` 的 PostgreSQL 镜像上,例如自带的
-`paradedb/paradedb:latest-pg17`。回填完成后由 Elasticsearch 接管搜索流量;`pg_search`
-相关对象可以之后通过项目提供的清理命令移除。
+Elasticsearch 不要求 PostgreSQL 支持 `pg_search`:数据库不提供该扩展时,LobeHub 迁移会跳过 BM25
+相关设置。如果数据库中已有 `pg_search` 对象,回填完成后由 Elasticsearch 接管搜索流量,这些对象可以之后通过项目提供的清理命令移除。
-选择建议和迁移入口,请参阅 [Neon pg\_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)。
+选择建议和迁移入口,请参阅 [Neon pg_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)。
## Elasticsearch 如何同步数据
diff --git a/docs/self-hosting/advanced/neon-pg-search-migration.mdx b/docs/self-hosting/advanced/neon-pg-search-migration.mdx
index 36b69cf93ff..f2803eed0c0 100644
--- a/docs/self-hosting/advanced/neon-pg-search-migration.mdx
+++ b/docs/self-hosting/advanced/neon-pg-search-migration.mdx
@@ -9,11 +9,11 @@ tags:
- Self-hosting
---
-# Migrate from pg\_search on Neon
+# Migrate from pg_search on Neon
According to [Neon's `pg_search` notice](https://neon.com/docs/extensions/pg_search), Neon no longer offers the extension to new projects. If Neon has notified you that `pg_search` will also be retired from an existing project, complete this guide before the deadline in that notice. Timelines can differ between projects, so use the notice sent for your project. This migration changes only the search backend; source data such as chat history remains in the existing PostgreSQL database.
-This guide is for an existing LobeHub instance that has already applied the historical database migrations. For a new database, first read the database limitations in [Full-Text Search](/docs/self-hosting/advanced/full-text-search).
+This guide is for an existing LobeHub instance. A new database without `pg_search` needs no migration: set `FTS_SEARCH_PROVIDER=pg_like` before the first start, as described in [Full-Text Search](/docs/self-hosting/advanced/full-text-search).
## 1. Check whether you need to migrate
@@ -44,7 +44,7 @@ Elastic Cloud and Docker Elasticsearch are the same search backend in different
The current LobeHub Elasticsearch sync worker is a persistent process and cannot run as-is inside a Vercel-only deployment. Choose `pg_like` unless you also operate a persistent server for that worker.
</Callout>
-## 3. Migrate to pg\_like (recommended)
+## 3. Migrate to pg_like (recommended)
1. **Upgrade and back up.** Upgrade LobeHub to a version that includes `pg_like`, then create a backup using your database provider's normal process.
diff --git a/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx b/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx
index c69deef2641..cdc8cf28a22 100644
--- a/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx
+++ b/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx
@@ -9,11 +9,11 @@ tags:
- 私有部署
---
-# Neon pg\_search 迁移指南
+# Neon pg_search 迁移指南
根据 [Neon 的 `pg_search` 公告](https://neon.com/docs/extensions/pg_search),Neon 已停止为新项目提供该扩展。如果 Neon 通知你的现有项目也将停用 `pg_search`,请在通知中的截止日期前完成迁移;不同项目的时间可能不同,请以 Neon 发给你的通知为准。迁移只更换搜索后端,聊天记录等原始数据仍保存在原来的 PostgreSQL 数据库中。
-本文面向已经运行 LobeHub、并且已经完成历史数据库迁移的现有实例。新建数据库请先阅读[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)中的数据库限制。
+本文面向已经运行 LobeHub 的现有实例。没有 `pg_search` 的新数据库不需要迁移:首次启动前设置 `FTS_SEARCH_PROVIDER=pg_like` 即可,详见[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。
## 1. 确认是否需要迁移
@@ -44,7 +44,7 @@ Elastic Cloud 和 Docker Elasticsearch 是同一种搜索后端,只是 Elastic
当前 LobeHub 的 Elasticsearch 同步 worker 是常驻进程,纯 Vercel 部署无法直接运行它。除非你另外准备了常驻服务器,否则请选择 `pg_like`。
</Callout>
-## 3. 迁移到 pg\_like(推荐)
+## 3. 迁移到 pg_like(推荐)
1. **升级并备份。** 将 LobeHub 升级到包含 `pg_like` 的版本,并按数据库服务的说明创建备份。
diff --git a/packages/database/migrations/0090_enable_pg_search.sql b/packages/database/migrations/0090_enable_pg_search.sql
index 3dd2c02830e..d0864238915 100644
--- a/packages/database/migrations/0090_enable_pg_search.sql
+++ b/packages/database/migrations/0090_enable_pg_search.sql
@@ -1,2 +1,15 @@
-- Custom SQL migration file, put your code below! --
-CREATE EXTENSION IF NOT EXISTS pg_search;
\ No newline at end of file
+-- pg_search is optional: plain PostgreSQL services (Aiven, RDS, Neon projects without the
+-- extension) run LobeHub with FTS_SEARCH_PROVIDER=pg_like or elasticsearch, so a missing
+-- extension must not block the remaining migrations. The pg_search provider still fails
+-- visibly at query time when its extension or BM25 indexes are absent.
+-- Editing this shipped migration is safe: Drizzle only compares `created_at`, so databases
+-- that already applied it never re-run it.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_available_extensions WHERE name = 'pg_search') THEN
+ CREATE EXTENSION IF NOT EXISTS pg_search;
+ ELSE
+ RAISE NOTICE 'pg_search is not available on this database; skipping BM25 search setup';
+ END IF;
+END $$;
diff --git a/packages/database/migrations/0093_add_bm25_indexes_with_icu.sql b/packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
index d607cd0a3a9..d2bcd4fd4cc 100644
--- a/packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
+++ b/packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
@@ -2,213 +2,314 @@
-- All tables include user_id (keyword tokenizer + fast) for filter pushdown into tantivy index scan.
-- Enum/filter fields (type, status, role, etc.) use keyword+fast for the same reason.
-- Large tables (documents, messages) are placed last to avoid blocking smaller index builds.
+-- Each index is created only when pg_search is installed (see 0090); EXECUTE defers parsing
+-- the `bm25` access method so databases without the extension skip it instead of failing.
+-- To adopt pg_search later, install the extension and re-run this file with psql.
-- 1. agents: title, description, slug, tags(jsonb), system_role, user_id
DROP INDEX IF EXISTS agents_bm25_idx;--> statement-breakpoint
-CREATE INDEX agents_bm25_idx ON agents
-USING bm25 (id, title, description, slug, tags, system_role, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "slug": {"tokenizer": {"type": "icu"}},
- "system_role": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }',
- json_fields = '{
- "tags": {"tokenizer": {"type": "icu"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX agents_bm25_idx ON agents
+ USING bm25 (id, title, description, slug, tags, system_role, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "slug": {"tokenizer": {"type": "icu"}},
+ "system_role": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }',
+ json_fields = '{
+ "tags": {"tokenizer": {"type": "icu"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 2. topics: title, content, description, user_id
DROP INDEX IF EXISTS topics_bm25_idx;--> statement-breakpoint
-CREATE INDEX topics_bm25_idx ON topics
-USING bm25 (id, title, content, description, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX topics_bm25_idx ON topics
+ USING bm25 (id, title, content, description, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 3. files: name, user_id, file_type
DROP INDEX IF EXISTS files_bm25_idx;--> statement-breakpoint
-CREATE INDEX files_bm25_idx ON files
-USING bm25 (id, name, user_id, file_type)
-WITH (
- key_field = 'id',
- text_fields = '{
- "name": {"tokenizer": {"type": "icu"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
- "file_type": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX files_bm25_idx ON files
+ USING bm25 (id, name, user_id, file_type)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "name": {"tokenizer": {"type": "icu"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "file_type": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 4. knowledge_bases: name, description, user_id
DROP INDEX IF EXISTS knowledge_bases_bm25_idx;--> statement-breakpoint
-CREATE INDEX knowledge_bases_bm25_idx ON knowledge_bases
-USING bm25 (id, name, description, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "name": {"tokenizer": {"type": "icu"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX knowledge_bases_bm25_idx ON knowledge_bases
+ USING bm25 (id, name, description, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "name": {"tokenizer": {"type": "icu"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 5. user_memories: title, summary, details, memory_layer, memory_category, status, user_id
DROP INDEX IF EXISTS user_memories_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_bm25_idx ON user_memories
-USING bm25 (id, title, summary, details, memory_layer, memory_category, status, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "summary": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "details": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "memory_layer": {"fast": true, "tokenizer": {"type": "keyword"}},
- "memory_category": {"fast": true, "tokenizer": {"type": "keyword"}},
- "status": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_bm25_idx ON user_memories
+ USING bm25 (id, title, summary, details, memory_layer, memory_category, status, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "summary": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "details": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "memory_layer": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "memory_category": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "status": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 6. chat_groups: title, description, content, user_id
DROP INDEX IF EXISTS chat_groups_bm25_idx;--> statement-breakpoint
-CREATE INDEX chat_groups_bm25_idx ON chat_groups
-USING bm25 (id, title, description, content, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX chat_groups_bm25_idx ON chat_groups
+ USING bm25 (id, title, description, content, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 7. user_memories_contexts: title, description, current_status, type, user_id
DROP INDEX IF EXISTS user_memories_contexts_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_contexts_bm25_idx ON user_memories_contexts
-USING bm25 (id, title, description, current_status, type, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "current_status": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_contexts_bm25_idx ON user_memories_contexts
+ USING bm25 (id, title, description, current_status, type, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "current_status": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 8. user_memories_preferences: conclusion_directives, suggestions, type, user_id
DROP INDEX IF EXISTS user_memories_preferences_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_preferences_bm25_idx ON user_memories_preferences
-USING bm25 (id, conclusion_directives, suggestions, type, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "conclusion_directives": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "suggestions": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_preferences_bm25_idx ON user_memories_preferences
+ USING bm25 (id, conclusion_directives, suggestions, type, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "conclusion_directives": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "suggestions": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 9. user_memories_activities: notes, narrative, feedback, type, status, user_id
DROP INDEX IF EXISTS user_memories_activities_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_activities_bm25_idx ON user_memories_activities
-USING bm25 (id, notes, narrative, feedback, type, status, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "notes": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "narrative": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "feedback": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "status": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_activities_bm25_idx ON user_memories_activities
+ USING bm25 (id, notes, narrative, feedback, type, status, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "notes": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "narrative": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "feedback": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "status": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 10. user_memories_identities: description, role, type, relationship, user_id
DROP INDEX IF EXISTS user_memories_identities_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_identities_bm25_idx ON user_memories_identities
-USING bm25 (id, description, role, type, relationship, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "role": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "relationship": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_identities_bm25_idx ON user_memories_identities
+ USING bm25 (id, description, role, type, relationship, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "role": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "relationship": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 11. user_memories_experiences: situation, reasoning, possible_outcome, action, key_learning, type, user_id
DROP INDEX IF EXISTS user_memories_experiences_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memories_experiences_bm25_idx ON user_memories_experiences
-USING bm25 (id, situation, reasoning, possible_outcome, action, key_learning, type, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "situation": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "reasoning": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "possible_outcome": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "action": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "key_learning": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memories_experiences_bm25_idx ON user_memories_experiences
+ USING bm25 (id, situation, reasoning, possible_outcome, action, key_learning, type, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "situation": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "reasoning": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "possible_outcome": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "action": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "key_learning": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 12. user_memory_persona_documents: tagline, persona, user_id
DROP INDEX IF EXISTS user_memory_persona_documents_bm25_idx;--> statement-breakpoint
-CREATE INDEX user_memory_persona_documents_bm25_idx ON user_memory_persona_documents
-USING bm25 (id, tagline, persona, user_id)
-WITH (
- key_field = 'id',
- text_fields = '{
- "tagline": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "persona": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX user_memory_persona_documents_bm25_idx ON user_memory_persona_documents
+ USING bm25 (id, tagline, persona, user_id)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "tagline": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "persona": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 13. documents (large table): title, description, content, slug, user_id, file_type, source_type
DROP INDEX IF EXISTS documents_bm25_idx;--> statement-breakpoint
-CREATE INDEX documents_bm25_idx ON documents
-USING bm25 (id, title, description, content, slug, user_id, file_type, source_type)
-WITH (
- key_field = 'id',
- text_fields = '{
- "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "slug": {"tokenizer": {"type": "icu"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
- "file_type": {"fast": true, "tokenizer": {"type": "keyword"}},
- "source_type": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);--> statement-breakpoint
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX documents_bm25_idx ON documents
+ USING bm25 (id, title, description, content, slug, user_id, file_type, source_type)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "title": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "description": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "slug": {"tokenizer": {"type": "icu"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "file_type": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "source_type": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;--> statement-breakpoint
-- 14. messages (largest table): content, summary, user_id, role
DROP INDEX IF EXISTS messages_bm25_idx;--> statement-breakpoint
-CREATE INDEX messages_bm25_idx ON messages
-USING bm25 (id, content, summary, user_id, role)
-WITH (
- key_field = 'id',
- text_fields = '{
- "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "summary": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
- "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
- "role": {"fast": true, "tokenizer": {"type": "keyword"}}
- }'
-);
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_search') THEN
+ EXECUTE $bm25$
+ CREATE INDEX messages_bm25_idx ON messages
+ USING bm25 (id, content, summary, user_id, role)
+ WITH (
+ key_field = 'id',
+ text_fields = '{
+ "content": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "summary": {"tokenizer": {"type": "icu", "stemmer": "English", "stopwords_language": "English"}},
+ "user_id": {"fast": true, "tokenizer": {"type": "keyword"}},
+ "role": {"fast": true, "tokenizer": {"type": "keyword"}}
+ }'
+ )
+ $bm25$;
+ END IF;
+END $$;
diff --git a/packages/database/src/core/getTestDB.ts b/packages/database/src/core/getTestDB.ts
index 73c198be27d..b965fbcfe52 100644
--- a/packages/database/src/core/getTestDB.ts
+++ b/packages/database/src/core/getTestDB.ts
@@ -2,11 +2,10 @@ import { join } from 'node:path';
import { PGlite } from '@electric-sql/pglite';
import { vector } from '@electric-sql/pglite/vector';
-import { sql } from 'drizzle-orm';
-import { readMigrationFiles } from 'drizzle-orm/migrator';
import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
import { migrate as nodeMigrate } from 'drizzle-orm/node-postgres/migrator';
import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';
+import { migrate as pgliteMigrate } from 'drizzle-orm/pglite/migrator';
import { Pool as NodePool } from 'pg';
import { serverDBEnv } from '@/config/db';
@@ -46,33 +45,8 @@ export const getTestDB = async (): Promise<LobeChatDatabase> => {
const pglite = new PGlite({ extensions: { vector } });
testClientDB = pgliteDrizzle({ client: pglite, schema });
- // Custom migration that skips pg_search-related SQL for PGlite compatibility
- const migrations = readMigrationFiles({ migrationsFolder });
-
- await testClientDB.execute(sql`CREATE SCHEMA IF NOT EXISTS "drizzle"`);
- await testClientDB.execute(sql`
- CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (
- id SERIAL PRIMARY KEY,
- hash text NOT NULL,
- created_at bigint
- )
- `);
-
- for (const migration of migrations) {
- const skipSql = migration.sql.some(
- (s) => s.toLowerCase().includes('pg_search') || s.toLowerCase().includes('bm25'),
- );
-
- if (!skipSql) {
- for (const stmt of migration.sql) {
- await testClientDB.execute(sql.raw(stmt));
- }
- }
-
- await testClientDB.execute(
- sql`INSERT INTO "drizzle"."__drizzle_migrations" (hash, created_at) VALUES (${migration.hash}, ${migration.folderMillis})`,
- );
- }
+ // pg_search migrations skip themselves when the extension is unavailable, as in PGlite.
+ await pgliteMigrate(testClientDB, { migrationsFolder });
return testClientDB as unknown as LobeChatDatabase;
};
diff --git a/packages/database/src/core/pgSearchMigrations.test.ts b/packages/database/src/core/pgSearchMigrations.test.ts
new file mode 100644
index 00000000000..97b8ff15e55
--- /dev/null
+++ b/packages/database/src/core/pgSearchMigrations.test.ts
@@ -0,0 +1,77 @@
+import { join } from 'node:path';
+
+import { PGlite } from '@electric-sql/pglite';
+import { vector } from '@electric-sql/pglite/vector';
+import { sql } from 'drizzle-orm';
+import { readMigrationFiles } from 'drizzle-orm/migrator';
+import { drizzle } from 'drizzle-orm/pglite';
+import { migrate } from 'drizzle-orm/pglite/migrator';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+// @ts-ignore tsgo handle esm import cjs and compatibility issues
+import {
+ assertPgSearchReady,
+ PgSearchNotReadyError,
+} from '../../../../scripts/migrateServerDB/pgSearchGuard';
+
+const migrationsFolder = join(__dirname, '../../migrations');
+
+/**
+ * Self-hosted deployments on plain PostgreSQL (Aiven, RDS, Neon without pg_search) select
+ * `FTS_SEARCH_PROVIDER=pg_like` or `elasticsearch`, so the historical pg_search migrations must
+ * skip themselves instead of aborting the upgrade. PGlite ships without pg_search, matching them.
+ */
+describe('pg_search migrations on a database without the extension', () => {
+ const client = new PGlite({ extensions: { vector } });
+ const db = drizzle({ client });
+
+ beforeAll(async () => {
+ await migrate(db, { migrationsFolder });
+ // Replaying every migration takes ~1s alone but can exceed the default timeout under a
+ // fully parallel suite.
+ }, 30_000);
+
+ afterAll(async () => {
+ await client.close();
+ });
+
+ it('applies every migration and skips BM25 setup', async () => {
+ const applied = await db.execute<{ count: number }>(
+ sql`SELECT count(*)::int AS count FROM drizzle.__drizzle_migrations`,
+ );
+ expect(applied.rows[0].count).toBe(readMigrationFiles({ migrationsFolder }).length);
+
+ const extension = await db.execute(sql`SELECT 1 FROM pg_extension WHERE extname = 'pg_search'`);
+ expect(extension.rows).toHaveLength(0);
+
+ const bm25Indexes = await db.execute(
+ sql`SELECT indexname FROM pg_indexes WHERE indexname LIKE '%_bm25_idx'`,
+ );
+ expect(bm25Indexes.rows).toHaveLength(0);
+ });
+
+ /** The migration entrypoints run this guard, so a skipped pg_search cannot reach the first search. */
+ describe('startup guard', () => {
+ const query = (text: string) => db.execute(sql.raw(text));
+
+ it('stops a deployment that leaves the provider at the pg_search default', async () => {
+ const error = await assertPgSearchReady(query, {}).catch((error_: unknown) => error_);
+
+ expect(error).toBeInstanceOf(PgSearchNotReadyError);
+ expect((error as Error).message).toContain('`pg_search` (the default)');
+ expect((error as Error).message).toContain('FTS_SEARCH_PROVIDER=pg_like');
+ });
+
+ it('stops a deployment that selects pg_search explicitly', async () => {
+ await expect(
+ assertPgSearchReady(query, { FTS_SEARCH_PROVIDER: 'pg_search' }),
+ ).rejects.toBeInstanceOf(PgSearchNotReadyError);
+ });
+
+ it.each(['pg_like', 'elasticsearch'])('lets %s start without pg_search', async (provider) => {
+ await expect(
+ assertPgSearchReady(query, { FTS_SEARCH_PROVIDER: provider }),
+ ).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/scripts/migrateServerDB/docker.cjs b/scripts/migrateServerDB/docker.cjs
index bcfa1b56897..02ccc98f3a1 100644
--- a/scripts/migrateServerDB/docker.cjs
+++ b/scripts/migrateServerDB/docker.cjs
@@ -3,6 +3,7 @@ const { Pool } = require('pg');
const { drizzle } = require('drizzle-orm/node-postgres');
const migrator = require('drizzle-orm/node-postgres/migrator');
const { PGVECTOR_HINT } = require('./errorHint');
+const { assertPgSearchReady, PgSearchNotReadyError } = require('./pgSearchGuard');
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not set, please set it in your environment variables.');
@@ -17,6 +18,7 @@ const runMigrations = async () => {
await migrator.migrate(db, {
migrationsFolder: path.join(__dirname, './migrations'),
});
+ await assertPgSearchReady((text) => client.query(text));
console.log('✅ database migration pass.');
console.log('-------------------------------------');
@@ -24,6 +26,11 @@ const runMigrations = async () => {
};
runMigrations().catch((err) => {
+ if (err instanceof PgSearchNotReadyError) {
+ console.error(err.message);
+ process.exit(1);
+ }
+
console.error(
'❌ Database migrate failed. Please check your database is valid and DATABASE_URL is set correctly. The error detail is below:',
);
diff --git a/scripts/migrateServerDB/index.ts b/scripts/migrateServerDB/index.ts
index bf41db00c88..52a98327548 100644
--- a/scripts/migrateServerDB/index.ts
+++ b/scripts/migrateServerDB/index.ts
@@ -2,11 +2,14 @@ import path from 'node:path';
import * as dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
+import { sql } from 'drizzle-orm';
import { migrate as neonMigrate } from 'drizzle-orm/neon-serverless/migrator';
import { migrate as nodeMigrate } from 'drizzle-orm/node-postgres/migrator';
// @ts-ignore tsgo handle esm import cjs and compatibility issues
import { DB_FAIL_INIT_HINT, DUPLICATE_EMAIL_HINT, PGVECTOR_HINT } from './errorHint';
+// @ts-ignore tsgo handle esm import cjs and compatibility issues
+import { assertPgSearchReady, PgSearchNotReadyError } from './pgSearchGuard';
import { runWithLockRetry } from './retry';
// Load environment variables in priority order:
@@ -32,6 +35,7 @@ const runMigrations = async () => {
await neonMigrate(serverDB, { migrationsFolder });
}
});
+ await assertPgSearchReady((text: string) => serverDB.execute(sql.raw(text)));
console.log('✅ database migration pass. use: %s ms', Date.now() - time);
@@ -43,6 +47,11 @@ const connectionString = process.env.DATABASE_URL;
// only migrate database if the connection string is available
if (connectionString) {
runMigrations().catch((err) => {
+ if (err instanceof PgSearchNotReadyError) {
+ console.error(err.message);
+ process.exit(1);
+ }
+
console.error('❌ Database migrate failed:', err);
const errMsg = err.message as string;
diff --git a/scripts/migrateServerDB/pgSearchGuard.js b/scripts/migrateServerDB/pgSearchGuard.js
new file mode 100644
index 00000000000..902a98915a6
--- /dev/null
+++ b/scripts/migrateServerDB/pgSearchGuard.js
@@ -0,0 +1,116 @@
+/**
+ * Startup guard for deployments whose full-text search resolves to ParadeDB `pg_search`.
+ *
+ * Migrations 0090 and 0093 skip the extension and its BM25 indexes on PostgreSQL services that do
+ * not provide `pg_search` (Aiven, RDS, Neon), so `pg_like` and Elasticsearch deployments can
+ * upgrade. A deployment that still selects `pg_search` there would otherwise start normally and
+ * fail on every search, so the migration entrypoints stop it here with the fix instead.
+ *
+ * Plain CommonJS because the Docker image runs it beside `docker.cjs` without bundling.
+ */
+
+/** Mirrors the self-hosted default in `packages/env/src/ftsSearch.ts`; parity is tested. */
+const DEFAULT_FTS_SEARCH_PROVIDER = 'pg_search';
+
+/** BM25 indexes created by `0093_add_bm25_indexes_with_icu.sql`; parity is tested. */
+const PG_SEARCH_BM25_INDEX_NAMES = [
+ 'agents_bm25_idx',
+ 'chat_groups_bm25_idx',
+ 'documents_bm25_idx',
+ 'files_bm25_idx',
+ 'knowledge_bases_bm25_idx',
+ 'messages_bm25_idx',
+ 'topics_bm25_idx',
+ 'user_memories_activities_bm25_idx',
+ 'user_memories_bm25_idx',
+ 'user_memories_contexts_bm25_idx',
+ 'user_memories_experiences_bm25_idx',
+ 'user_memories_identities_bm25_idx',
+ 'user_memories_preferences_bm25_idx',
+ 'user_memory_persona_documents_bm25_idx',
+];
+
+const DOCS_URL = 'https://lobehub.com/docs/self-hosting/advanced/full-text-search';
+
+class PgSearchNotReadyError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = 'PgSearchNotReadyError';
+ }
+}
+
+/** Unset falls back to the default; any other value is validated by the application env schema. */
+const resolveFtsSearchProvider = (env) => env.FTS_SEARCH_PROVIDER ?? DEFAULT_FTS_SEARCH_PROVIDER;
+
+/**
+ * @param {(text: string) => Promise<{ rows: Record<string, unknown>[] }>} query
+ * @returns {Promise<{ extensionInstalled: boolean, missingIndexes: string[] }>}
+ */
+const readPgSearchReadiness = async (query) => {
+ const extension = await query(`SELECT 1 FROM pg_extension WHERE extname = 'pg_search'`);
+ // Migrations and runtime queries use unqualified table names, so check the tables that
+ // `search_path` resolves to rather than assuming the `public` schema.
+ const indexes = await query(`
+ SELECT index_relation.relname AS index_name
+ FROM pg_index AS index_record
+ JOIN pg_class AS index_relation ON index_relation.oid = index_record.indexrelid
+ JOIN pg_am AS access_method ON access_method.oid = index_relation.relam
+ WHERE access_method.amname = 'bm25'
+ AND pg_table_is_visible(index_record.indrelid)
+ AND index_record.indisvalid
+ `);
+ const present = new Set(indexes.rows.map((row) => row.index_name));
+
+ return {
+ extensionInstalled: extension.rows.length > 0,
+ missingIndexes: PG_SEARCH_BM25_INDEX_NAMES.filter((name) => !present.has(name)),
+ };
+};
+
+const formatPgSearchNotReadyMessage = ({ extensionInstalled, missingIndexes }, env) => {
+ const problem = extensionInstalled
+ ? `the database is missing ${missingIndexes.length} of its BM25 indexes (${missingIndexes.join(', ')})`
+ : 'the database does not have the ParadeDB `pg_search` extension installed';
+
+ return `------------------------------------------------------------------------------------------
+❌ Full-text search is set to \`pg_search\`${env.FTS_SEARCH_PROVIDER ? '' : ' (the default)'}, but ${problem}.
+LobeHub will not start, because every search would fail.
+
+Choose one and restart:
+
+1) Use extension-free PostgreSQL search (recommended for Aiven, RDS, Neon and most managed PostgreSQL):
+
+ FTS_SEARCH_PROVIDER=pg_like
+
+2) Use Elasticsearch: set FTS_SEARCH_PROVIDER=elasticsearch and its ES_* variables.
+
+3) Keep pg_search: install the extension on this database, then create the BM25 indexes from a
+ LobeHub source checkout:
+
+ psql "$DATABASE_URL" -c 'CREATE EXTENSION IF NOT EXISTS pg_search'
+ psql "$DATABASE_URL" -f packages/database/migrations/0093_add_bm25_indexes_with_icu.sql
+
+Details: ${DOCS_URL}
+`;
+};
+
+/**
+ * Throw `PgSearchNotReadyError` when the resolved provider is `pg_search` but the database cannot
+ * serve it. Other providers never touch `pg_search`, so they skip the check.
+ */
+const assertPgSearchReady = async (query, env = process.env) => {
+ if (resolveFtsSearchProvider(env) !== 'pg_search') return;
+
+ const readiness = await readPgSearchReadiness(query);
+ if (readiness.extensionInstalled && readiness.missingIndexes.length === 0) return;
+
+ throw new PgSearchNotReadyError(formatPgSearchNotReadyMessage(readiness, env));
+};
+
+module.exports = {
+ DEFAULT_FTS_SEARCH_PROVIDER,
+ PG_SEARCH_BM25_INDEX_NAMES,
+ PgSearchNotReadyError,
+ assertPgSearchReady,
+ readPgSearchReadiness,
+};
diff --git a/scripts/migrateServerDB/pgSearchGuard.test.ts b/scripts/migrateServerDB/pgSearchGuard.test.ts
new file mode 100644
index 00000000000..f30b6b23940
--- /dev/null
+++ b/scripts/migrateServerDB/pgSearchGuard.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { getFtsSearchConfig } from '../../packages/env/src/ftsSearch';
+import { PG_SEARCH_BM25_INDEXES } from '../pgSearchCleanup/inventory';
+import {
+ assertPgSearchReady,
+ DEFAULT_FTS_SEARCH_PROVIDER,
+ PG_SEARCH_BM25_INDEX_NAMES,
+ PgSearchNotReadyError,
+} from './pgSearchGuard';
+
+type Rows = { rows: Record<string, unknown>[] };
+
+/** Answer the extension and index catalog queries with a fixed database state. */
+const fakeCatalog =
+ (state: { extension: boolean; indexes: readonly string[] }) =>
+ async (text: string): Promise<Rows> =>
+ text.includes('pg_extension')
+ ? { rows: state.extension ? [{ '?column?': 1 }] : [] }
+ : { rows: state.indexes.map((index_name) => ({ index_name })) };
+
+describe('pgSearchGuard', () => {
+ it('uses the same default provider as the application env', () => {
+ vi.stubEnv('FTS_SEARCH_PROVIDER', undefined);
+ expect(getFtsSearchConfig().FTS_SEARCH_PROVIDER).toBe(DEFAULT_FTS_SEARCH_PROVIDER);
+ vi.unstubAllEnvs();
+ });
+
+ it('checks the same BM25 indexes that pg_search cleanup manages', () => {
+ expect([...PG_SEARCH_BM25_INDEX_NAMES].sort()).toEqual(
+ PG_SEARCH_BM25_INDEXES.map(({ name }) => name).sort(),
+ );
+ });
+
+ it('passes a pg_search database with every BM25 index', async () => {
+ const query = fakeCatalog({ extension: true, indexes: PG_SEARCH_BM25_INDEX_NAMES });
+ await expect(assertPgSearchReady(query, {})).resolves.toBeUndefined();
+ });
+
+ it('names the missing BM25 indexes when the extension was installed afterwards', async () => {
+ const query = fakeCatalog({
+ extension: true,
+ indexes: PG_SEARCH_BM25_INDEX_NAMES.filter((name) => name !== 'messages_bm25_idx'),
+ });
+
+ const error = await assertPgSearchReady(query, { FTS_SEARCH_PROVIDER: 'pg_search' }).catch(
+ (error_: unknown) => error_,
+ );
+ expect(error).toBeInstanceOf(PgSearchNotReadyError);
+ expect((error as Error).message).toContain('missing 1 of its BM25 indexes (messages_bm25_idx)');
+ expect((error as Error).message).toContain('0093_add_bm25_indexes_with_icu.sql');
+ });
+});