Create a .env file in the root of your project and add your database connection variable:
第 3 步 - 将 Drizzle ORM 连接到数据库
在 src/db 目录中创建一个 index.ts 文件并初始化连接:
node-postgres
带配置的 node-postgres
你的 node-postgres 驱动程序
多租户
Nile 提供 虚拟租户数据库。当你查询 Nile 时,可以设置租户上下文,Nile 会将你的查询指向此特定租户的虚拟数据库。所有带有租户上下文的查询只会应用于该租户(即 select * from table 将仅返回该租户的记录)。要了解有关如何使用 Drizzle 设置租户上下文的更多信息,请查看 官方 Nile-Drizzle 示例。
第 4 步 - 创建一个表
在 src/db 目录中创建一个 schema.ts 文件并声明你的表。由于 Nile 是多租户应用的 PostgreSQL,我们的模式包括一个用于租户的表和一个带有 tenant_id 列的待办事项表(我们称之为租户感知表):
第 5 步 - 设置 Drizzle 配置文件
Drizzle config - a configuration file that is used by Drizzle Kit and contains all the information about your database connection, migration folder and schema files.
Create a drizzle.config.ts file in the root of your project and add the following content:
第 6 步 - 将更改应用到数据库
You can directly apply changes to your database using the drizzle-kit push command. This is a convenient method for quickly testing new schema designs or modifications in a local development environment, allowing for rapid iterations without the need to manage migration files:
To run any TypeScript files, you have several options, but let’s stick with one: using tsx
You’ve already installed tsx, so we can run our queries now
Run index.ts script
npm
yarn
pnpm
bun
tips
We suggest using bun to run TypeScript files. With bun, such scripts can be executed without issues or additional
settings, regardless of whether your project is configured with CommonJS (CJS), ECMAScript Modules (ESM), or any other module format.
To run a script with bun, use the following command: