Prisma - ORM
- model your database with the Prisma Schema Language 使用 Prisma 架构语言对数据库进行建模
- use Prisma ORM's existing sqlite database connector in your schema 在您的架构中使用 Prisma ORM 的现有 sqlite 数据库连接器
- use Prisma Client in your application to talk to the database server at D1 在应用程序中使用 Prisma Client 与 D1 的数据库服务器通信
@prisma/adapter-d1 driver adapter. 用于给 server 侧创建实例
v6.6
[email protected]
之后根目录需要新增一个 prisma.config.ts
文件用于运行 prisma 同步 d1 数据库的 nodejs 脚本
ts
import path from 'node:path'
import type { PrismaConfig } from 'prisma'
import { PrismaD1HTTP } from '@prisma/adapter-d1'
// import your .env file
import 'dotenv/config' // ✨ 需要额外安装一个依赖dotenv
type Env = {
CLOUDFLARE_D1_TOKEN: string
CLOUDFLARE_ACCOUNT_ID: string
CLOUDFLARE_DATABASE_ID: string
}
export default {
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),
migrate: {
async adapter(env) {
return new PrismaD1HTTP({
CLOUDFLARE_D1_TOKEN: env.CLOUDFLARE_D1_TOKEN,
CLOUDFLARE_ACCOUNT_ID: env.CLOUDFLARE_ACCOUNT_ID,
CLOUDFLARE_DATABASE_ID: env.CLOUDFLARE_DATABASE_ID,
})
},
},
} satisfies PrismaConfig<Env>
👆 需要额外安装一个依赖 pnpm add dotenv -D
环境变量 里的.env
文件
text
DATABASE_URL="file:./prisma/db.sqlite"
CLOUDFLARE_ACCOUNT_ID="0773..."
CLOUDFLARE_DATABASE_ID="01f30366-..."
CLOUDFLARE_D1_TOKEN="F8Cg..."
DATABASE_URL
需要设置为 file:./prisma/db.sqlite
,即使本地没有这个文件?
npx prisma db push
sqlite
导入 json 数据
bash
npx wrangler d1 execute an-monkey-db \
--command="INSERT INTO Income (id, owner, time, baseSalary, overtimeMeal, housingFund, leaveDeduction, housingFundDeduction, medicalInsurance, pensionInsurance, unemploymentInsurance, tax, rent, createdAt, updatedAt)
SELECT
json_extract(value, '$.id'),
json_extract(value, '$.owner'),
json_extract(value, '$.time'),
json_extract(value, '$.baseSalary'),
json_extract(value, '$.overtimeMeal'),
json_extract(value, '$.housingFund'),
json_extract(value, '$.leaveDeduction'),
json_extract(value, '$.housingFundDeduction'),
json_extract(value, '$.medicalInsurance'),
json_extract(value, '$.pensionInsurance'),
json_extract(value, '$.unemploymentInsurance'),
json_extract(value, '$.tax'),
json_extract(value, '$.rent'),
json_extract(value, '$.createdAt'),
json_extract(value, '$.updatedAt')
FROM json_each('$(cat processed-income-data.json)')" --remote