Skip to content

Windows 上 npm run db:setup 静默失败,导致 relation "sources" does not exist #7

Description

@lzy17553710908

在 Windows 上按照 README 执行 npm run db:setup 后,数据库中没有创建任何表。启动应用后访问 http://localhost:5173 报错 relation "sources" does not exist。

KIMI回复我:根本原因分析

  1. src/db/migrate.ts 的 Windows 兼容性 Bug
    migrate.ts 末尾使用以下方式判断脚本是否直接运行:if (import.meta.url === file://${process.argv[1]}) { migrate()... }

在 Windows 上:
import.meta.url = file:///D:/SAG/src/db/migrate.ts(正斜杠)
process.argv[1] = D:\SAG\src\db\migrate.ts(反斜杠)
两者永远不相等,导致 migrate() 函数从未被调用。命令静默退出,没有任何错误提示或日志。
同理 seed.ts 也有相同问题。
2. Windows 上额外的 PostgreSQL 端口竞争
Windows 上 wslrelay.exe 或其他本地 PostgreSQL 可能监听 localhost:5432,导致即使修复了 (1),迁移仍可能连接到错误的数据库实例。

复现步骤:

1.Windows 上克隆仓库
2.docker compose up -d 启动 PostgreSQL
3.npm run db:setup
4.docker exec -it sag_lite_postgres psql -U sag_lite -d sag_lite -c "\dt" → 没有任何表
5.npm run dev → 访问页面报错 relation "sources" does not exist

临时 workaround

通过 Docker 容器内直接执行 SQL 文件,绕过 migrate.ts:

复制迁移文件到容器并执行

docker cp migrations\001_init.sql sag_lite_postgres:/tmp/
docker exec sag_lite_postgres psql -U sag_lite -d sag_lite -f /tmp/001_init.sql

... 依次执行 002-007

建议修复:
修复 migrate.ts 和 seed.ts 的入口判断,使用跨平台的路径比较方式:
import { pathToFileURL } from "node:url";

// 替代原有的 if 判断
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
migrate()...
}

pathToFileURL 会自动处理 Windows 反斜杠路径,转换为正确的 file:// URL 格式。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions