开始使用 Drizzle 和 Appwrite Postgres

本指南假设你已熟悉:
  • dotenv - 用于管理环境变量的包 - 了解详情
  • tsx - 用于运行 TypeScript 文件的包 - 了解详情
  • Appwrite Postgres - Appwrite 提供的原生 PostgreSQL 数据库 - 了解详情
  • node-postgres - 用于查询 PostgreSQL 数据库的包 - 了解详情
Appwrite 也提供 MySQL

需要使用 MySQL?请参阅 Appwrite MySQL 指南

Appwrite 提供专用的原生 PostgreSQL 数据库,可通过 TLS 直接连接。Appwrite 没有专用驱动,因此本指南使用标准的 node-postgres 驱动。

有关创建 Appwrite Postgres 数据库的详细说明,请参阅 Appwrite PostgreSQL 文档。

基本文件结构

这是项目的基本文件结构。在 src/db 目录中,我们在 schema.ts 中有表定义。在 drizzle 文件夹中,有 SQL 迁移文件和快照。

📦 <project root>
 ├ 📂 drizzle
 ├ 📂 src
 │   ├ 📂 db
 │   │  └ 📜 schema.ts
 │   └ 📜 index.ts
 ├ 📜 .env
 ├ 📜 drizzle.config.ts
 ├ 📜 package.json
 └ 📜 tsconfig.json

第一步:安装 node-postgres 包

npm
yarn
pnpm
bun
npm i drizzle-orm@rc pg dotenv
npm i -D drizzle-kit@rc tsx @types/pg

第二步:设置连接变量

在项目根目录创建 .env 文件,并添加数据库连接变量:

DATABASE_URL=postgresql://admin:<password>@db-<hash>.<region>.appwrite.center:5432/<database>?sslmode=require
提示

在 Appwrite Console 中打开数据库并点击 “Credentials”,即可获取连接字符串。“Drizzle”、“DSN” 和 “.env” 选项卡中提供了可直接使用且已包含 sslmode=require 的连接字符串。详细步骤请参阅 Appwrite PostgreSQL 连接指南。

第三步:将 Drizzle ORM 连接到数据库

在 src 目录中创建 index.ts 文件并初始化连接:

node-postgres
node-postgres with config
your node-postgres driver
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';

const db = drizzle(process.env.DATABASE_URL!);
连接端口

Appwrite Postgres 在同一主机名下支持两个连接端口:

  • 端口 5432:直接连接 PostgreSQL 引擎,用于 Drizzle Kit 迁移和内省。
  • 端口 6432:通过连接池以事务模式连接。建议在无服务器和边缘环境中使用。详情请参阅 Appwrite Postgres 连接指南。

第四步:创建表

在 src/db 目录下创建一个 schema.ts 文件,并声明你的数据表:

src/db/schema.ts
import { integer, pgTable, varchar } from "drizzle-orm/pg-core";

export const usersTable = pgTable("users", {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  name: varchar({ length: 255 }).notNull(),
  age: integer().notNull(),
  email: varchar({ length: 255 }).notNull().unique(),
});

第五步:设置 Drizzle 配置文件

Drizzle 配置 - 一个配置文件,被 Drizzle Kit 使用,包含有关你的数据库连接、迁移文件夹和模式文件的所有信息。

在项目根目录下创建一个 drizzle.config.ts 文件,并添加以下内容:

drizzle.config.ts
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  out: './drizzle',
  schema: './src/db/schema.ts',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

第六步:将变更应用到数据库

您可以使用 drizzle-kit push 命令直接将更改应用到数据库中。这是一种方便的方法,适合在本地开发环境中快速测试新的架构设计或修改,允许快速迭代而无需管理迁移文件:

npx drizzle-kit push

在 文档 中了解更多关于 push 命令的信息。

小贴士

或者,您可以使用 drizzle-kit generate 命令生成迁移文件,然后使用 drizzle-kit migrate 命令应用这些迁移:

生成迁移:

npx drizzle-kit generate

应用迁移:

npx drizzle-kit migrate

在 文档 中了解更多关于迁移流程的信息。

第七步:填充数据并查询数据库

让我们更新 src/index.ts 文件,添加用于创建、读取、更新和删除用户的查询。

src/index.ts
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import { eq } from 'drizzle-orm';
import { usersTable } from './db/schema';
  
const db = drizzle(process.env.DATABASE_URL!);

async function main() {
  const user: typeof usersTable.$inferInsert = {
    name: 'John',
    age: 30,
    email: '[email protected]',
  };

  await db.insert(usersTable).values(user);
  console.log('New user created!')

  const users = await db.select().from(usersTable);
  console.log('Getting all users from the database: ', users)
  /*
  const users: {
    id: number;
    name: string;
    age: number;
    email: string;
  }[]
  */

  await db
    .update(usersTable)
    .set({
      age: 31,
    })
    .where(eq(usersTable.email, user.email));
  console.log('User info updated!')

  await db.delete(usersTable).where(eq(usersTable.email, user.email));
  console.log('User deleted!')
}

main();

第八步:运行 index.ts 文件

要运行任何 TypeScript 文件,你有几种选择,但我们这里先专注于一种:使用 tsx

你已经安装了 tsx,所以现在可以运行我们的查询了

运行 index.ts 脚本

npm
yarn
pnpm
bun
npx tsx src/index.ts
提示

我们建议使用 bun 来运行 TypeScript 文件。使用 bun,无论你的项目是配置为 CommonJS(CJS)、ECMAScript 模块(ESM)还是其他模块格式,这类脚本都可以顺利运行,无需额外设置或调整。
使用 bun 运行脚本,执行以下命令:

bun src/index.ts

如果你还没有安装 bun,请查看 Bun 安装文档