# PostgreSQL (/docs/adapters/postgresql)

将 Better Auth 与 PostgreSQL 集成。



PostgreSQL 是一个功能强大的开源关系型数据库管理系统，以其高级特性、可扩展性以及对复杂查询和大型数据集的支持而闻名。
阅读更多关于 [PostgreSQL](https://www.postgresql.org/) 的信息。

## 示例用法 [#示例用法]

确保你已安装并配置好 PostgreSQL。
然后，你可以直接将其连接到 Better Auth。

```ts title="auth.ts"
import { betterAuth } from "better-auth";
import { Pool } from "pg";

export const auth = betterAuth({
  database: new Pool({
    connectionString: "postgres://user:password@localhost:5432/database",
  }),
});
```

<Callout>
  更多信息请阅读 Kysely 关于
  [PostgresDialect](https://kysely-org.github.io/kysely-apidoc/classes/PostgresDialect.html) 的文档。
</Callout>

## 模式生成与迁移 [#模式生成与迁移]

[Better Auth CLI](/docs/concepts/cli) 允许你根据 Better Auth 的配置和插件生成或迁移数据库模式。

<table>
  <thead>
    <tr className="border-b">
      <th>
        <p className="font-bold text-[16px] mb-1">
          PostgreSQL 模式生成
        </p>
      </th>

      <th>
        <p className="font-bold text-[16px] mb-1">
          PostgreSQL 模式迁移
        </p>
      </th>
    </tr>
  </thead>

  <tbody>
    <tr className="h-10">
      <td>
        ✅ 支持
      </td>

      <td>
        ✅ 支持
      </td>
    </tr>
  </tbody>
</table>

<Tabs items="[&#x22;migrate&#x22;, &#x22;generate&#x22;]">
  <Tab value="migrate">
    <CodeBlockTabs defaultValue="npm" groupId="persist-install">
      <CodeBlockTabsList>
        <CodeBlockTabsTrigger value="npm">
          npm
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="pnpm">
          pnpm
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="yarn">
          yarn
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="bun">
          bun
        </CodeBlockTabsTrigger>
      </CodeBlockTabsList>

      <CodeBlockTab value="npm">
        ```bash
        npx auth@latest migrate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="pnpm">
        ```bash
        pnpm dlx auth@latest migrate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="yarn">
        ```bash
        yarn dlx auth@latest migrate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="bun">
        ```bash
        bun x auth@latest migrate
        ```
      </CodeBlockTab>
    </CodeBlockTabs>
  </Tab>

  <Tab value="generate">
    <CodeBlockTabs defaultValue="npm" groupId="persist-install">
      <CodeBlockTabsList>
        <CodeBlockTabsTrigger value="npm">
          npm
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="pnpm">
          pnpm
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="yarn">
          yarn
        </CodeBlockTabsTrigger>

        <CodeBlockTabsTrigger value="bun">
          bun
        </CodeBlockTabsTrigger>
      </CodeBlockTabsList>

      <CodeBlockTab value="npm">
        ```bash
        npx auth@latest generate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="pnpm">
        ```bash
        pnpm dlx auth@latest generate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="yarn">
        ```bash
        yarn dlx auth@latest generate
        ```
      </CodeBlockTab>

      <CodeBlockTab value="bun">
        ```bash
        bun x auth@latest generate
        ```
      </CodeBlockTab>
    </CodeBlockTabs>
  </Tab>
</Tabs>

## 连接 [#连接]

当 Better-Auth 需要在一条查询中从多个表获取相关数据时，数据库连接非常有用。
`/get-session`、`/get-full-organization` 等端点都能从这一功能中获益，
根据数据库延迟的不同，性能提升最高可达 2 倍至 3 倍。

Kysely PostgreSQL 方言自 `1.4.0` 版本起即可开箱支持连接。
要启用此功能，请在认证配置中将 `advanced.database.joins` 设置为 `true`。

```ts title="auth.ts"
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  advanced: {
    database: {
      joins: true,
    },
  },
});
```

## 使用非默认模式 [#使用非默认模式]

PostgreSQL 默认使用 `public` 模式。你可以通过 `database.schemaName` 显式选择其他模式，或配置 PostgreSQL 的 `search_path`。

如果两者都已配置，Better Auth 将使用 `database.schemaName`。其他未限定模式的查询仍会使用连接的 `search_path`。

### 设置 `database.schemaName` [#设置-databaseschemaname]

<Tabs items="[&#x22;Kysely dialect&#x22;, &#x22;Kysely instance&#x22;]">
  <Tab value="Kysely dialect">
    ```ts title="auth.ts"
    import { betterAuth } from "better-auth";
    import { PostgresDialect } from "kysely";
    import { Pool } from "pg";

    export const auth = betterAuth({
      database: {
        dialect: new PostgresDialect({
          pool: new Pool({
            connectionString: "postgres://user:password@localhost:5432/database",
          }),
        }),
        type: "postgres",
        schemaName: "auth", // [!code highlight]
      },
    });
    ```
  </Tab>

  <Tab value="Kysely instance">
    ```ts title="auth.ts"
    import { betterAuth } from "better-auth";
    import { db } from "./database";

    export const auth = betterAuth({
      database: {
        db,
        type: "postgres",
        schemaName: "auth", // [!code highlight]
      },
    });
    ```
  </Tab>
</Tabs>

该模式适用于运行时查询和 CLI 迁移。`npx auth@latest migrate` 会在需要时创建该模式，并忽略其他模式中同名的表。

`npx auth@latest generate` 会先创建模式，再开始生成迁移：

```sql
create schema if not exists "auth";
```

后续所有语句都会使用带模式限定的表名，例如 `"auth"."user"`。

Better Auth 使用的 PostgreSQL 角色必须能够创建该模式及其中的表。否则，请在运行 `npx auth@latest migrate` 前创建该模式并向该角色授予访问权限。

### 设置 `search_path` [#设置-search_path]

直接传入 `pg.Pool` 时，或者希望连接上的所有未限定模式的查询都使用同一模式时，请改用 PostgreSQL 的 `search_path`。

使用 `search_path` 时，Better Auth CLI 要求该模式已存在。运行 `npx auth@latest migrate` 前，请创建该模式并向连接角色授予访问权限。

<Tabs items="[&#x22;Pool options&#x22;, &#x22;Connection string&#x22;]">
  <Tab value="Pool options">
    ```ts title="auth.ts"
    import { betterAuth } from "better-auth";
    import { Pool } from "pg";

    export const auth = betterAuth({
      database: new Pool({
        connectionString: "postgres://user:password@localhost:5432/database",
        options: "-c search_path=auth",
      }),
    });
    ```
  </Tab>

  <Tab value="Connection string">
    ```ts title="auth.ts"
    import { betterAuth } from "better-auth";
    import { Pool } from "pg";

    export const auth = betterAuth({
      database: new Pool({
        connectionString: "postgres://user:password@localhost:5432/database?options=-c%20search_path%3Dauth",
      }),
    });
    ```
  </Tab>
</Tabs>

要将该模式设为 PostgreSQL 角色连接到特定数据库时的默认模式：

```sql
ALTER ROLE your_role IN DATABASE your_database
SET search_path TO auth;
```

更改此默认值后，请重新连接。运行 `SHOW search_path` 以验证当前值。

## 其他信息 [#其他信息]

PostgreSQL 的支持是通过 [Kysely](https://kysely.dev/) 适配器实现的，Kysely 支持的任何数据库也均受支持。(<Link href="/docs/adapters/other-relational-databases">点击这里了解更多</Link>)

如果你在寻求性能提升或优化技巧，可以查看我们的 <Link href="/docs/guides/optimizing-for-performance">性能优化指南</Link>。

