# @btst/db 中文文档

规范地址：https://npmcn.com/package/%40btst/db/

版本：3\.0\.1
npm 元数据更新时间：2026-10-28T17:38:08.307Z
中文译文更新时间：2026-11-08T18:31:21.817Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40btst/db
原文对照：https://npmcn.com/package/%40btst/db/?lang=original
项目主页：https://github.com/better-stack-ai/better-auth/tree/main/packages/btst#readme
源码仓库：https://github.com/better-stack-ai/better-auth

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：18 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：better-auth 1\.7\.14，@better-auth/core 1\.7\.14，@better-auth/utils 0\.5\.1
- 首次发布：2025-10-13T22:05:51.621Z
- 最新版本发布：2026-10-28T17:38:07.895Z
- 近 30 天下载量：5667（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：14（近 12 个月 13 个）

## 中文简介

Btst的核心数据库公用事业和计划定义

## 安装

```sh
npm install @btst/db
```

也可以使用：`pnpm add @btst/db`、`yarn add @btst/db`、`bun add @btst/db`

## README

# 更好的数据库

**没有认证域的数据库公用设备——一个聚焦的Fetter Auth数据库层.**

更好的DB给了你更好的Auth的被证明的适配器模式和CLI驱动的策略生成,完全专注于数据库管理.

## 特征

-   🎯 **重点** ——数据库公用设施不具有认证复杂性
-   🔄 **上流同步** – 保持与更好的 Auth 更新保持一致
-   🔧 **作战测试** ——以"更好的奥思"被证明的建筑为主
-   🚀 **多种操作程序** - 普里斯玛、德利兹尔、克赛利、蒙戈德比等
-   🔌 **广泛** ——自定义表格插件系统
-   ⚡ **CLI驱动** ——以单一命令生成计划

## 快速启动

```bash
# Install core and your preferred adapter
npm install @btst/db @btst/adapter-prisma
npm install -D @btst/cli
```

定义您的方案 :

```typescript
// db.ts
import { defineDb } from "@btst/db";

export const db = defineDb({
  post: {
    modelName: "post",
    fields: {
      title: {
        type: "string",
        required: true,
      },
      content: {
        type: "string",
        required: true,
      },
      published: {
        type: "boolean",
        defaultValue: false,
      },
      authorId: {
        type: "string",
        required: true,
      },
      createdAt: {
        type: "date",
        defaultValue: () => new Date(),
      },
    },
  },
  author: {
    modelName: "author",
    fields: {
      name: {
        type: "string",
        required: true,
      },
      email: {
        type: "string",
        required: true,
        unique: true,
      },
    },
  },
});

export default db;
```

生成和运行迁移 :

```bash
# Generate Prisma schema
npx btst generate --config=db.ts --orm=prisma --output=schema.prisma

# Or for Kysely (requires database connection)
DATABASE_URL=sqlite:./dev.db npx btst generate --config=db.ts --orm=kysely --output=migrations/schema.sql
# Or: npx btst generate --config=db.ts --orm=kysely --output=migrations/schema.sql --database-url=sqlite:./dev.db

# Run migrations
npx prisma migrate dev
```

在您的应用程序中使用 :

```typescript
import { prismaAdapter } from "@btst/adapter-prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
const adapter = prismaAdapter(prisma)({});

// Create
await adapter.create({
  model: "post",
  data: { title: "Hello", content: "World", authorId: "1" },
});

// Query
const posts = await adapter.findMany({
  model: "post",
  where: [{ field: "published", value: true }],
});
```

## CLI 命令

### 初始化

```bash
npx btst init [--output=db.ts]
```

### 生成

```bash
# Prisma
npx btst generate --config=db.ts --orm=prisma --output=schema.prisma

# Drizzle
npx btst generate --config=db.ts --orm=drizzle --output=src/db/schema.ts

# Kysely (requires database connection for introspection)
# Using DATABASE_URL environment variable
DATABASE_URL=sqlite:./dev.db npx btst generate --config=db.ts --orm=kysely --output=migrations/schema.sql

# Or using --database-url flag
npx btst generate --config=db.ts --orm=kysely --output=migrations/schema.sql --database-url=sqlite:./dev.db
npx btst generate --config=db.ts --orm=kysely --output=migrations/schema.sql --database-url=postgres://user:pass@localhost:5432/db

# By default, auth tables (User, Session, Account, Verification) are filtered out
# To include them, add --include-better-auth flag
npx btst generate --config=db.ts --orm=prisma --output=schema.prisma --include-better-auth
```

### 迁移

```bash
# Kysely only - for Prisma/Drizzle use their native tools
# Using DATABASE_URL environment variable or --database-url param
DATABASE_URL=sqlite:./dev.db npx btst migrate --config=db.ts

# Or using --database-url flag
npx btst migrate --config=db.ts --database-url=sqlite:./dev.db
npx btst migrate --config=db.ts --database-url=postgres://user:pass@localhost:5432/db

# Generate SQL to file instead of running migrations
npx btst migrate --config=db.ts --output=migrations.sql --database-url=sqlite:./dev.db

# By default, auth tables (User, Session, Account, Verification) are filtered out
# To include them, add --include-better-auth flag
npx btst migrate --config=db.ts --output=migrations.sql --include-better-auth --database-url=sqlite:./dev.db
```

## 字段类型

```typescript
defineDb({
  example: {
    modelName: "example",
    fields: {
      // Basic types
      textField: { type: "string" },
      numberField: { type: "number" },
      booleanField: { type: "boolean" },
      dateField: { type: "date" },
      jsonField: { type: "json" },
      
      // Required/Optional
      required: { type: "string", required: true },
      optional: { type: "string", required: false },
      
      // Unique
      uniqueField: { type: "string", unique: true },
      
      // Defaults
      active: { type: "boolean", defaultValue: false },
      createdAt: { type: "date", defaultValue: () => new Date() },
      
      // References
      userId: {
        type: "string",
        references: {
          model: "user",
          field: "id",
          onDelete: "cascade",
        },
      },
    },
  },
})
```

## 适应器 API

所有适配器都提供这些方法:

```typescript
// Create
adapter.create({ model: "post", data: {...} })

// Read
adapter.findOne({ model: "post", where: [...] })
adapter.findMany({ model: "post", where: [...], limit: 10 })
adapter.count({ model: "post", where: [...] })

// Update
adapter.update({ model: "post", where: [...], update: {...} })
adapter.updateMany({ model: "post", where: [...], update: {...} })

// Delete
adapter.delete({ model: "post", where: [...] })
adapter.deleteMany({ model: "post", where: [...] })
```

见 [更好的 Auth 适配器指南](https://www.better-auth.com/docs/guides/create-a-db-adapter) 详细情况.

## 插件

以可重复使用的插件扩展您的计划 :

```typescript
import { defineDb } from "@btst/db";
import { todoPlugin } from "@btst/plugins";

export const db = defineDb({
  post: {
    modelName: "post",
    fields: {
      title: { type: "string", required: true },
    },
  },
}).use(todoPlugin);
```

创建自定义插件 :

```typescript
import { createDbPlugin } from "@btst/db";

export const tagsPlugin = createDbPlugin("tags", {
  tag: {
    modelName: "tag",
    fields: {
      name: {
        type: "string",
        required: true,
        unique: true,
      },
    },
  },
});
```

## 可用的适配器

```bash
npm install @btst/adapter-prisma    # Prisma
npm install @btst/adapter-drizzle   # Drizzle
npm install @btst/adapter-kysely    # Kysely
npm install @btst/adapter-memory    # Memory (testing)
npm install @btst/adapter-mongodb   # MongoDB
```

## 与更好的Auth的关系

更好的DB是一个薄薄的包裹 围绕Better Auth的数据库层:

**我们所保存的:**

-   所有适配器执行
-   QQ CLI 生成行为
-   实地类型系统
-   ++ 插件架构

**我们排除的:**

-   \* 认证表格(用户、会话、账户)
-   ++ OAuth 配置
-   认证中间软件

**版本 :** `@btst/*@1.4.x` 音轨 `better-auth@1.4.x`

## 从Better Auth 迁移

替换导入 :

```typescript
// Before
import { prismaAdapter } from "better-auth/adapters/prisma";

// After
import { prismaAdapter } from "@btst/adapter-prisma";
```

将配置替换为方案 :

```typescript
// Before
export const auth = betterAuth({
  database: prismaClient,
  plugins: [...]
});

// After
export const db = defineDb({
  // your tables using Better Auth schema format
  post: {
    modelName: "post",
    fields: {
      title: { type: "string", required: true },
    },
  },
});
```

更新 CLI :

```bash
# Before
npx @better-auth/cli generate

# After
npx btst generate
```

## 实例

### 博客平台

```typescript
import { defineDb } from "@btst/db";

export const db = defineDb({
  post: {
    modelName: "post",
    fields: {
      title: {
        type: "string",
        required: true,
      },
      slug: {
        type: "string",
        required: true,
        unique: true,
      },
      content: {
        type: "string",
        required: true,
      },
      published: {
        type: "boolean",
        defaultValue: false,
      },
      authorId: {
        type: "string",
        required: true,
        references: {
          model: "author",
          field: "id",
          onDelete: "cascade",
        },
      },
      createdAt: {
        type: "date",
        defaultValue: () => new Date(),
      },
    },
  },
  author: {
    modelName: "author",
    fields: {
      name: {
        type: "string",
        required: true,
      },
      email: {
        type: "string",
        required: true,
        unique: true,
      },
      bio: {
        type: "string",
        required: false,
      },
    },
  },
  category: {
    modelName: "category",
    fields: {
      name: {
        type: "string",
        required: true,
      },
      slug: {
        type: "string",
        required: true,
        unique: true,
      },
    },
  },
});
```

### 电子商务

```typescript
export const db = defineDb({
  product: {
    modelName: "product",
    fields: {
      name: {
        type: "string",
        required: true,
      },
      slug: {
        type: "string",
        required: true,
        unique: true,
      },
      price: {
        type: "number",
        required: true,
      },
      inventory: {
        type: "number",
        defaultValue: 0,
      },
      categoryId: {
        type: "string",
        required: false,
        references: {
          model: "category",
          field: "id",
          onDelete: "set null",
        },
      },
    },
  },
  order: {
    modelName: "order",
    fields: {
      orderNumber: {
        type: "string",
        required: true,
        unique: true,
      },
      customerId: {
        type: "string",
        required: true,
        references: {
          model: "customer",
          field: "id",
          onDelete: "cascade",
        },
      },
      status: {
        type: "string",
        required: true,
        defaultValue: "pending",
      },
      total: {
        type: "number",
        required: true,
      },
      createdAt: {
        type: "date",
        defaultValue: () => new Date(),
      },
    },
  },
  orderItem: {
    modelName: "order_item",
    fields: {
      orderId: {
        type: "string",
        required: true,
        references: {
          model: "order",
          field: "id",
          onDelete: "cascade",
        },
      },
      productId: {
        type: "string",
        required: true,
        references: {
          model: "product",
          field: "id",
          onDelete: "cascade",
        },
      },
      quantity: {
        type: "number",
        required: true,
      },
      price: {
        type: "number",
        required: true,
      },
    },
  },
});
```

## 资源

-   [更好的 Auth 文档](https://better-auth.com/docs/concepts/database)
-   [GitHub 问题](https://github.com/better-auth/better-auth/issues)
-   [讨论情况](https://github.com/better-auth/better-auth/discussions)

## 许可证

麻省理工学院

## 常见问题

### @btst/db 是什么？

Btst的核心数据库公用事业和计划定义

### 如何安装 @btst/db？

在项目目录运行 npm install @btst/db，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：better-auth（1\.7\.14）、@better-auth/core（1\.7\.14）、@better-auth/utils（0\.5\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @btst/db 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @btst/db 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @btst/db 可以商用吗？

@btst/db 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @btst/db 的下载量有多少？

根据 npm 官方下载统计，@btst/db 在 2026/10/09 – 2026/11/07 这 30 天内被下载 5,667 次，日均约 189 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @btst/db 还在维护吗？

最新版本 3\.0\.1 发布于 2026/10/29（11 天前）；至今共发布 14 个版本，其中过去 12 个月发布了 13 个；首次发布于 2025/10/14。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

