使用 Drizzle ORM 和 Deno 构建数据库应用
Drizzle ORM 是一个 TypeScript ORM,它提供了一种类型安全的方式来与您的数据库交互。在本教程中,我们将使用 Deno 和 PostgreSQL 设置 Drizzle ORM,以创建、读取、更新和删除恐龙数据
您可以在这个 GitHub 仓库中找到本教程的所有代码。
🚨️ Deno 2 发布了。 🚨️
凭借与 Node/npm 的向后兼容性、内置包管理、一体化零配置工具链以及原生 TypeScript 和 web API 支持,编写 JavaScript 从未如此简单。
安装 Drizzle
首先,我们将使用 Deno 的 npm 兼容性安装所需的依赖项。我们将把 Drizzle 与 Postgres 一起使用,但您也可以使用 MySQL 或 SQLite。(如果您没有 Postgres,可以在此处安装。)
deno install npm:drizzle-orm npm:drizzle-kit npm:pg npm:@types/pg
这将安装 Drizzle ORM 及其相关工具 — drizzle-kit 用于模式迁移,pg 用于 PostgreSQL 连接,以及 PostgreSQL 的 TypeScript 类型。这些包将允许我们以类型安全的方式与数据库交互,同时保持与 Deno 运行时环境的兼容性。
它还会项目根目录中创建一个 deno.json
文件来管理 npm 依赖项
{
"imports": {
"@types/pg": "npm:@types/pg@^8.11.10",
"drizzle-kit": "npm:drizzle-kit@^0.27.2",
"drizzle-orm": "npm:drizzle-orm@^0.36.0",
"pg": "npm:pg@^8.13.1"
}
}
配置 Drizzle
接下来,让我们在项目根目录中创建一个 drizzle.config.ts
文件。此文件将配置 Drizzle 以使用您的 PostgreSQL 数据库
import { defineConfig } from "drizzle-kit";
export default defineConfig({
out: "./drizzle",
schema: "./src/db/schema.ts",
dialect: "postgresql",
dbCredentials: {
url: Deno.env.get("DATABASE_URL")!,
},
});
这些配置设置决定了
- 迁移文件的输出位置 (
./drizzle
) - 模式定义文件的位置 (
./src/db/schema.ts
) - PostgreSQL 作为您的数据库方言,以及
- 如何使用存储在环境变量中的 URL 连接到您的数据库
drizzle-kit
将使用此配置来管理您的数据库模式并自动生成 SQL 迁移。
我们还需要在项目根目录中创建一个包含 DATABASE_URL
连接字符串的 .env
文件
DATABASE_URL=postgresql://[user[:password]@][host][:port]/[dbname]
请务必将登录凭据替换为您自己的凭据。
接下来,让我们连接到数据库并使用 Drizzle 来填充我们的表。
定义模式
您可以通过两种方式使用 Drizzle 定义表模式。如果您已经定义了 Postgres 表,则可以使用 pull
推断它们;否则,您可以在代码中定义它们,然后使用 Drizzle 创建新表。我们将在下面探讨这两种方法。
pull
推断模式
使用 如果您在添加 Drizzle 之前已经有 Postgres 表,那么您可以内省数据库模式以使用命令 npm:drizzle-kit pull
自动生成 TypeScript 类型和表定义。当您使用现有数据库或想要确保您的代码与数据库结构保持同步时,这尤其有用。
假设我们当前的数据库已经具有以下表模式
我们将运行以下命令来内省数据库并在 ./drizzle
目录下填充多个文件
deno --env -A --node-modules-dir npm:drizzle-kit pull
Failed to find Response internal state key
No config path provided, using default 'drizzle.config.ts'
Reading config file '/private/tmp/deno-drizzle-example/drizzle.config.ts'
Pulling from ['public'] list of schemas
Using 'pg' driver for database querying
[✓] 2 tables fetched
[✓] 8 columns fetched
[✓] 0 enums fetched
[✓] 0 indexes fetched
[✓] 1 foreign keys fetched
[✓] 0 policies fetched
[✓] 0 check constraints fetched
[✓] 0 views fetched
[i] No SQL generated, you already have migrations in project
[✓] You schema file is ready ➜ drizzle/schema.ts 🚀
[✓] You relations file is ready ➜ drizzle/relations.ts 🚀
--env
标志读取包含数据库 url 的 .env
文件,并使用 --node-modules-dir
标志创建一个 node_modules
文件夹,这将允许我们正确使用 drizzle-kit
。上面的命令将在 ./drizzle
目录中创建多个文件,这些文件定义了模式,跟踪更改,并为数据库迁移提供必要的信息
drizzle/schema.ts
:此文件使用 Drizzle ORM 的模式定义语法定义数据库模式。drizzle/relations.ts
:此文件旨在定义使用 Drizzle ORM 关系 API 的表之间关系。drizzle/0000_long_veda.sql
:一个 SQL 迁移文件,其中包含用于创建数据库表的 SQL 代码。该代码已注释掉 — 如果您想运行此迁移以在新环境中创建表,则可以取消注释此代码。drizzle/meta/0000_snapshot.json
:一个快照文件,表示您数据库模式的当前状态。drizzle/meta/_journal.json
:此文件跟踪已应用于您的数据库的迁移。它帮助 Drizzle ORM 了解哪些迁移已运行,哪些迁移仍需要应用。
首先在 Drizzle 中定义模式
如果您在 Postgres 中还没有定义现有表(例如,您正在启动一个全新的项目),您可以在代码中定义表和类型,并让 Drizzle 创建它们。
让我们创建一个新目录 ./src/db/
,并在其中创建一个 schema.ts
文件,我们将使用以下内容填充它
// schema.ts
import {
boolean,
foreignKey,
integer,
pgTable,
serial,
text,
timestamp,
} from "drizzle-orm/pg-core";
export const dinosaurs = pgTable("dinosaurs", {
id: serial().primaryKey().notNull(),
name: text(),
description: text(),
});
export const tasks = pgTable("tasks", {
id: serial().primaryKey().notNull(),
dinosaurId: integer("dinosaur_id"),
description: text(),
dateCreated: timestamp("date_created", { mode: "string" }).defaultNow(),
isComplete: boolean("is_complete"),
}, (table) => {
return {
tasksDinosaurIdFkey: foreignKey({
columns: [table.dinosaurId],
foreignColumns: [dinosaurs.id],
name: "tasks_dinosaur_id_fkey",
}),
};
});
dinosaurs
和 tasks
及其关系。了解有关使用 Drizzle 定义模式及其关系的更多信息。一旦我们定义了 ./src/db/schema.ts
,我们就可以通过创建迁移来创建表及其指定的关系
deno -A npm:drizzle-kit generate
Failed to find Response internal state key
No config path provided, using default 'drizzle.config.ts'
Reading config file '/private/tmp/drizzle/drizzle.config.ts'
2 tables
dinosaurs 3 columns 0 indexes 0 fks
tasks 5 columns 0 indexes 1 fks
上面的命令将创建一个 ./drizzle/
文件夹,其中包含迁移脚本和日志。
与数据库交互
现在我们已经设置了 Drizzle ORM,我们可以使用它来简化管理 Postgres 数据库中的数据。首先,Drizzle 建议将 schema.ts
和 relations.ts
复制到 ./src/db
目录中,以便在应用程序中使用。
让我们创建一个 ./src/db/db.ts
,它导出一些辅助函数,这将使我们更容易与数据库交互
import { drizzle } from "drizzle-orm/node-postgres";
import { dinosaurs as dinosaurSchema, tasks as taskSchema } from "./schema.ts";
import { dinosaursRelations, tasksRelations } from "./relations.ts";
import pg from "pg";
import { integer } from "drizzle-orm/sqlite-core";
import { eq } from "drizzle-orm/expressions";
// Use pg driver.
const { Pool } = pg;
// Instantiate Drizzle client with pg driver and schema.
export const db = drizzle({
client: new Pool({
connectionString: Deno.env.get("DATABASE_URL"),
}),
schema: { dinosaurSchema, taskSchema, dinosaursRelations, tasksRelations },
});
// Insert dinosaur.
export async function insertDinosaur(dinosaurObj: typeof dinosaurSchema) {
return await db.insert(dinosaurSchema).values(dinosaurObj);
}
// Insert task.
export async function insertTask(taskObj: typeof taskSchema) {
return await db.insert(taskSchema).values(taskObj);
}
// Find dinosaur by id.
export async function findDinosaurById(dinosaurId: typeof integer) {
return await db.select().from(dinosaurSchema).where(
eq(dinosaurSchema.id, dinosaurId),
);
}
// Find dinosaur by name.
export async function findDinosaurByName(name: string) {
return await db.select().from(dinosaurSchema).where(
eq(dinosaurSchema.name, name),
);
}
// Find tasks based on dinosaur id.
export async function findDinosaurTasksByDinosaurId(
dinosaurId: typeof integer,
) {
return await db.select().from(taskSchema).where(
eq(taskSchema.dinosaurId, dinosaurId),
);
}
// Update dinosaur.
export async function updateDinosaur(dinosaurObj: typeof dinosaurSchema) {
return await db.update(dinosaurSchema).set(dinosaurObj).where(
eq(dinosaurSchema.id, dinosaurObj.id),
);
}
// Update task.
export async function updateTask(taskObj: typeof taskSchema) {
return await db.update(taskSchema).set(taskObj).where(
eq(taskSchema.id, taskObj.id),
);
}
// Delete dinosaur by id.
export async function deleteDinosaurById(id: typeof integer) {
return await db.delete(dinosaurSchema).where(
eq(dinosaurSchema.id, id),
);
}
// Delete task by id.
export async function deleteTask(id: typeof integer) {
return await db.delete(taskSchema).where(eq(taskSchema.id, id));
}
现在我们可以将其中一些辅助函数导入到一个脚本中,我们可以在其中对数据库执行一些简单的 CRUD 操作。让我们创建一个新文件 ./src/script.ts
import {
deleteDinosaurById,
findDinosaurByName,
insertDinosaur,
insertTask,
updateDinosaur,
} from "./db/db.ts";
// Create a new dinosaur.
await insertDinosaur({
name: "Denosaur",
description: "Dinosaurs should be simple.",
});
// Find that dinosaur by name.
const res = await findDinosaurByName("Denosaur");
// Create a task with that dinosaur by its id.
await insertTask({
dinosaurId: res.id,
description: "Remove unnecessary config.",
isComplete: false,
});
// Update a dinosaur with a new description.
const newDeno = {
id: res.id,
name: "Denosaur",
description: "The simplest dinosaur.",
};
await updateDinosaur(newDeno);
// Delete the dinosaur (and any tasks it has).
await deleteDinosaurById(res.id);
我们可以运行它,它将对数据库执行所有操作
deno -A --env ./src/script.ts
下一步是什么?
Drizzle ORM 是一种流行的数据映射工具,可简化管理和维护数据模型以及与数据库的交互。希望本教程能让您开始了解如何在 Deno 项目中使用 Drizzle。
现在您已经基本了解了如何将 Drizzle ORM 与 Deno 一起使用,您可以
- 添加更复杂的数据库关系
- 使用 REST API 并使用 Hono 来提供您的恐龙数据
- 为您的数据库操作添加验证和错误处理
- 为您的数据库交互编写测试
- 将您的应用程序部署到云端
🦕 使用 Deno 和 Drizzle ORM 快乐编码!这种堆栈的类型安全性和简洁性使其成为构建现代 Web 应用程序的绝佳选择。
🚨️ 想要了解更多关于 Deno 的信息吗? 🚨️
查看我们新的学习 Deno 教程系列,您将在其中学习
……以及更多,以简短、精悍的视频形式呈现。每周二和周四发布新的教程。