如何使用Drizzle ORM连接PostgreSQL非public模式?
使用Drizzle ORM连接PostgreSQL非public模式的正确方式
核心问题说明
PostgreSQL连接字符串里的schema参数并非Drizzle ORM支持的配置项,而schemaFilter配置不当会触发意外的schema删除操作。正确配置需要从schema定义、数据库连接、迁移配置三个维度入手:
1. 定义数据库表时明确指定目标schema
在Drizzle中创建表结构时,直接通过schema()函数绑定目标模式,确保所有表归属到指定的非public schema下:
import { pgTable, serial, text } from "drizzle-orm/pg-core"; import { schema } from "drizzle-orm"; // 绑定到manytomany schema const manytomanySchema = schema("manytomany"); // 在该schema下定义表 export const users = manytomanySchema.table("users", { id: serial("id").primaryKey(), name: text("name").notNull(), });
2. 配置数据库连接时设置search_path
让PostgreSQL默认使用指定的schema,避免每次查询手动指定。可通过两种方式配置:
方式一:在Pool配置中添加options
import { drizzle } from "drizzle-orm/node-postgres"; import { Pool } from "pg"; const pool = new Pool({ connectionString: "postgresql://postgres:pwd@localhost:5432/drizzle", // 设置默认搜索路径为manytomany,可保留public作为降级选项 options: "-c search_path=manytomany,public", }); export const db = drizzle(pool);
方式二:在连接字符串中拼接options参数
postgresql://postgres:pwd@localhost:5432/drizzle?options=-c%20search_path%3Dmanytomany%2Cpublic
3. 迁移配置避免误删schema
之前触发DROP SCHEMA是因为schemaFilter逻辑不符合预期,正确的迁移配置需指定目标schema并关闭严格模式:
import { defineConfig } from "drizzle-kit"; export default defineConfig({ schema: "./src/db/schema.ts", out: "./drizzle", dialect: "postgresql", dbCredentials: { connectionString: "postgresql://postgres:pwd@localhost:5432/drizzle", }, // 指定要处理的schema列表 schemas: ["manytomany"], // 关闭严格模式,防止删除不在schemas列表中的schema strict: false, });
内容的提问来源于stack exchange,提问作者EBDS
相关产品推荐
相关产品推荐

