# @geekmidas/db 中文文档

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

版本：9\.6\.1
npm 元数据更新时间：2026-11-16T09:27:59.462Z
中文译文更新时间：2026-11-16T09:32:24.069Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40geekmidas/db
原文对照：https://npmcn.com/package/%40geekmidas/db/?lang=original
项目主页：https://github.com/geekmidas/toolbox#readme
源码仓库：https://github.com/geekmidas/toolbox

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

- 包体积（解压后）：160 kB，62 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：pg ~8\.16\.3，knex ~3\.1\.0，kysely \>=0\.28\.2 \<0\.30\.0，vitest ^3\.2\.4 \|\| ^4\.1\.11，db-errors ~0\.2\.3，objection ~3\.1\.5
- 首次发布：2025-10-01T15:28:14.035Z
- 最新版本发布：2026-11-16T09:27:59.111Z
- 近 30 天下载量：14541（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：206（近 12 个月 202 个）

## 中文简介

为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易.

## 安装

```sh
npm install @geekmidas/db
```

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

## README

# @geekmidas/db (英语)

为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易.

## 特征

-   ✅ **灵活交易处理**: 与Kysely公司、交易和受控交易公司合作
-   ✅ **自动交易检测**: 嵌入时重用已存在的交易
-   ✅ **类型安全**: 具有通用数据库图案的完整类型脚本支持
-   ✅ **连接摘要**: 所有数据库连接类型的单一帮助
-   ✅ **无依赖**: 只依赖 Kysely 的同行

## 安装

```bash
pnpm add @geekmidas/db
```

### 同伴依赖关系

```bash
pnpm add kysely pg
```

## 快速启动

```typescript
import { withTransaction } from '@geekmidas/db/kysely';
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { Kysely } from 'kysely';

interface Database {
  users: {
    id: string;
    email: string;
    name: string;
  };
  posts: {
    id: string;
    userId: string;
    title: string;
  };
}

async function createUserWithPost(
  db: DatabaseConnection<Database>,
  userData: { email: string; name: string },
  postData: { title: string }
) {
  return withTransaction(db, async (trx) => {
    // Create user
    const user = await trx
      .insertInto('users')
      .values(userData)
      .returningAll()
      .executeTakeFirstOrThrow();

    // Create post for user
    const post = await trx
      .insertInto('posts')
      .values({
        userId: user.id,
        title: postData.title
      })
      .returningAll()
      .executeTakeFirstOrThrow();

    return { user, post };
  });
}
```

## API 参考

### `withTransaction`

执行交易中的召回。 如果连接已经是交易, 它会重用它 。 否则,它会产生新的交易.

```typescript
function withTransaction<DB, T>(
  db: DatabaseConnection<DB>,
  cb: (trx: Transaction<DB>) => Promise<T>
): Promise<T>
```

**参数:**

-   `db` - 数据库连接(Kysely, 交易,或控制交易)
-   `cb` - 接收交易的召回功能

**回返情况:**

-   承诺解决回调值

### `DatabaseConnection<T>`

所有支持的数据库连接类型的类型联盟 :

```typescript
type DatabaseConnection<T> =
  | Kysely<T>
  | Transaction<T>
  | ControlledTransaction<T>;
```

## 用法实例

### 基本交易

```typescript
import { withTransaction } from '@geekmidas/db/kysely';
import { Kysely } from 'kysely';

const db = new Kysely<Database>({ /* config */ });

async function transferFunds(fromId: string, toId: string, amount: number) {
  return withTransaction(db, async (trx) => {
    // Deduct from sender
    await trx
      .updateTable('accounts')
      .set({ balance: sql`balance - ${amount}` })
      .where('id', '=', fromId)
      .execute();

    // Add to receiver
    await trx
      .updateTable('accounts')
      .set({ balance: sql`balance + ${amount}` })
      .where('id', '=', toId)
      .execute();

    return { success: true };
  });
}
```

### 嵌入式交易

帮助者自动检测现有交易并重用:

```typescript
async function createUser(
  db: DatabaseConnection<Database>,
  email: string
) {
  return withTransaction(db, async (trx) => {
    const user = await trx
      .insertInto('users')
      .values({ email })
      .returningAll()
      .executeTakeFirstOrThrow();

    // This will reuse the same transaction
    await createAuditLog(trx, 'user_created', user.id);

    return user;
  });
}

async function createAuditLog(
  db: DatabaseConnection<Database>,
  action: string,
  userId: string
) {
  // If db is already a transaction, it's reused
  return withTransaction(db, async (trx) => {
    await trx
      .insertInto('audit_logs')
      .values({ action, userId, timestamp: new Date() })
      .execute();
  });
}
```

### 仓库模式

使用 `DatabaseConnection` 用于灵活性的存储器类型 :

```typescript
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';

class UserRepository {
  constructor(private db: DatabaseConnection<Database>) {}

  async create(data: NewUser): Promise<User> {
    return withTransaction(this.db, async (trx) => {
      return trx
        .insertInto('users')
        .values(data)
        .returningAll()
        .executeTakeFirstOrThrow();
    });
  }

  async update(id: string, data: UserUpdate): Promise<User> {
    return withTransaction(this.db, async (trx) => {
      return trx
        .updateTable('users')
        .set(data)
        .where('id', '=', id)
        .returningAll()
        .executeTakeFirstOrThrow();
    });
  }
}

// Can be used with any connection type
const db = new Kysely<Database>({ /* config */ });
const repo = new UserRepository(db);

// Or within a transaction
await withTransaction(db, async (trx) => {
  const repo = new UserRepository(trx);
  await repo.create({ email: 'user@example.com' });
});
```

### 有交易的服务模式

```typescript
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';

class OrderService {
  constructor(
    private db: DatabaseConnection<Database>,
    private inventoryService: InventoryService,
    private paymentService: PaymentService
  ) {}

  async createOrder(
    userId: string,
    items: OrderItem[]
  ): Promise<Order> {
    return withTransaction(this.db, async (trx) => {
      // All operations share the same transaction
      const order = await trx
        .insertInto('orders')
        .values({ userId, status: 'pending' })
        .returningAll()
        .executeTakeFirstOrThrow();

      // These services can accept the transaction
      await this.inventoryService.reserveItems(trx, items);
      await this.paymentService.processPayment(trx, order.id);

      // Update order status
      return trx
        .updateTable('orders')
        .set({ status: 'completed' })
        .where('id', '=', order.id)
        .returningAll()
        .executeTakeFirstOrThrow();
    });
  }
}

class InventoryService {
  async reserveItems(
    db: DatabaseConnection<Database>,
    items: OrderItem[]
  ) {
    return withTransaction(db, async (trx) => {
      for (const item of items) {
        await trx
          .updateTable('inventory')
          .set({ reserved: sql`reserved + ${item.quantity}` })
          .where('productId', '=', item.productId)
          .execute();
      }
    });
  }
}
```

### 处理错误

交易自动滚回错误 :

```typescript
import { withTransaction } from '@geekmidas/db/kysely';

async function processOrder(db: DatabaseConnection<Database>, orderId: string) {
  try {
    return await withTransaction(db, async (trx) => {
      const order = await trx
        .selectFrom('orders')
        .where('id', '=', orderId)
        .selectAll()
        .executeTakeFirstOrThrow();

      if (order.status !== 'pending') {
        throw new Error('Order already processed');
      }

      // Update order
      await trx
        .updateTable('orders')
        .set({ status: 'processing' })
        .where('id', '=', orderId)
        .execute();

      // If this throws, the entire transaction rolls back
      await processPayment(trx, orderId);

      return order;
    });
  } catch (error) {
    console.error('Transaction failed:', error);
    // Transaction has been rolled back
    throw error;
  }
}
```

### 用交易测试

使用交易进行测试隔离 :

```typescript
import { describe, it, beforeEach, afterEach } from 'vitest';
import type { Transaction } from 'kysely';

describe('UserRepository', () => {
  let trx: Transaction<Database>;

  beforeEach(async () => {
    trx = await db.transaction().execute(async (t) => t);
  });

  afterEach(async () => {
    await trx.rollback();
  });

  it('should create user', async () => {
    const repo = new UserRepository(trx);
    const user = await repo.create({ email: 'test@example.com' });

    expect(user.email).toBe('test@example.com');
    // Transaction will be rolled back after test
  });
});
```

## 类型安全

软件包为数据库操作提供了完整的类型安全:

```typescript
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';

interface Database {
  users: {
    id: Generated<string>;
    email: string;
    name: string | null;
  };
}

function updateUser(
  db: DatabaseConnection<Database>,
  id: string,
  data: { name: string }
) {
  return withTransaction(db, async (trx) => {
    // Full autocomplete and type checking
    return trx
      .updateTable('users')
      .set(data) // Type-checked against users table
      .where('id', '=', id)
      .returningAll()
      .executeTakeFirstOrThrow();
  });
}
```

## 高级图案

### 工作模式股

```typescript
class UnitOfWork {
  private transaction: Transaction<Database> | null = null;

  constructor(private db: Kysely<Database>) {}

  async begin() {
    this.transaction = await this.db.transaction().execute(async (t) => t);
  }

  async commit() {
    if (this.transaction) {
      await this.transaction.commit();
      this.transaction = null;
    }
  }

  async rollback() {
    if (this.transaction) {
      await this.transaction.rollback();
      this.transaction = null;
    }
  }

  getConnection(): DatabaseConnection<Database> {
    return this.transaction || this.db;
  }
}

// Usage
const uow = new UnitOfWork(db);
await uow.begin();

try {
  const userRepo = new UserRepository(uow.getConnection());
  const orderRepo = new OrderRepository(uow.getConnection());

  await userRepo.create({ email: 'user@example.com' });
  await orderRepo.create({ userId: '123' });

  await uow.commit();
} catch (error) {
  await uow.rollback();
  throw error;
}
```

### 连接集合

```typescript
import { Pool } from 'pg';
import { Kysely, PostgresDialect } from 'kysely';

const pool = new Pool({
  host: 'localhost',
  database: 'mydb',
  max: 10
});

const db = new Kysely<Database>({
  dialect: new PostgresDialect({ pool })
});

// Use with withTransaction
async function processData(data: unknown[]) {
  return withTransaction(db, async (trx) => {
    // Each transaction gets a connection from the pool
    for (const item of data) {
      await trx.insertInto('items').values(item).execute();
    }
  });
}
```

## 最佳做法

1.  **使用数据库连接类型**: 接受 `DatabaseConnection` 与交易有关的职能
    
    ```typescript
    async function myFunction(db: DatabaseConnection<Database>) { }
    ```
    
2.  **让交易处理重用**: 不要手动检查交易类型
    
    ```typescript
    // Good
    await withTransaction(db, async (trx) => { });
    
    // Avoid
    if (db.isTransaction) { /* ... */ } else { /* ... */ }
    ```
    
3.  **保持交易简短**: 迅速执行以避免阻塞
    
    ```typescript
    // Good
    await withTransaction(db, async (trx) => {
      await trx.insertInto('users').values(data).execute();
    });
    
    // Avoid long-running operations
    await withTransaction(db, async (trx) => {
      await fetch('https://api.example.com'); // Bad!
    });
    ```
    
4.  **处理错误**: 让交易自动滚回错误
    
5.  **测试**: 使用自动回滚的测试隔离交易
    

## 相关软件包

-   [凯斯利](https://github.com/kysely-org/kysely) - 安全型SQL查询构建器
-   [@geekmidas/ testkit (英语)](https://npmcn.com/package/%40geekmidas/testkit) - 与数据库工厂测试公用事业

## 许可证

麻省理工学院

## 常见问题

### @geekmidas/db 是什么？

为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易\.

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

在项目目录运行 npm install @geekmidas/db，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：pg（~8\.16\.3）、knex（~3\.1\.0）、kysely（\>=0\.28\.2 \<0\.30\.0）、vitest（^3\.2\.4 \|\| ^4\.1\.11）、db-errors（~0\.2\.3）、objection（~3\.1\.5）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

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

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

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

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

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

@geekmidas/db 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

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

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

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

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

