# @databricks/lakebase 中文文档

规范地址：https://npmcn.com/package/%40databricks/lakebase/

版本：0\.7\.0
npm 元数据更新时间：2026-10-19T11:34:26.559Z
中文译文更新时间：2026-11-11T13:06:58.341Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：178 kB，65 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2026-02-18T12:37:54.130Z
- 最新版本发布：2026-10-19T11:34:26.386Z
- 近 30 天下载量：150718（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 9 个）

## 中文简介

Databricks Lakebase 自动升级并自动刷新 OAuth 令牌的 PostgreSQL 驱动程序

## 安装

```sh
npm install @databricks/lakebase
```

也可以使用：`pnpm add @databricks/lakebase`、`yarn add @databricks/lakebase`、`bun add @databricks/lakebase`

## README

# @ databricks/ lakebase( 数据砖)

用于 Databricks Lakebase 自动升级的 PostgreSQL 驱动程序,并自动刷新 OAuth 令牌 .

## 概览

`@databricks/lakebase` 为标准提供即时替换 `pg` 连接池,可以自动处理Databricks Lakebase Auterscale(OLTP)数据库的OAuth认证.

它会:

-   返回标准 `pg.Pool` - 与PostgreSQL图书馆或ORM合作
-   自动刷新 OAuth 令牌 (1小时寿命, 2分钟缓冲)
-   刷卡以最小化 API 调用
-   带有环境变量的零配置
-   可选的 OpenTelection 仪器

**注:** 此软件包与 Databricks Lakebase 提供兼容 .

## 安装

```bash
npm install @databricks/lakebase
```

## 快速启动

### 使用环境变量

设置以下环境变量:

```bash
export PGHOST=your-lakebase-host.databricks.com
export PGDATABASE=your_database_name
export LAKEBASE_ENDPOINT=projects/6bef4151-4b5d-4147-b4d0-c2f4fd5b40db/branches/br-broad-pine-y12n6gnv/endpoints/ep-summer-frost-y131l3vx
export PGUSER=your_user # optionally, defaults to DATABRICKS_CLIENT_ID
export PGSSLMODE=require
```

为了找到你 `LAKEBASE_ENDPOINT`并使用 `name` 来自输出的字段 :

```bash
databricks postgres list-endpoints projects/{project-id}/branches/{branch-id}
```

您可以从Lakebase自动缩放UI获取项目ID和分站ID,如"Branch Overview"页面. (项目清单 -- > 项目仪表板 - > 分支概览).

然后使用驱动程序 :

```typescript
import { createLakebasePool } from "@databricks/lakebase";

const pool = createLakebasePool();
const result = await pool.query("SELECT * FROM users");
console.log(result.rows);
```

### 有明确的配置

```typescript
import { createLakebasePool } from "@databricks/lakebase";

const pool = createLakebasePool({
  host: "your-lakebase-host.databricks.com", // defaults to PGHOST environment variable
  database: "your_database_name", // defaults to PGDATABASE environment variable
  endpoint:
    "projects/6bef4151-4b5d-4147-b4d0-c2f4fd5b40db/branches/br-broad-pine-y12n6gnv/endpoints/ep-summer-frost-y131l3vx", // defaults to LAKEBASE_ENDPOINT environment variable
  user: "user_id", // Optional, defaults to PGUSER or DATABRICKS_CLIENT_ID
  max: 10, // Connection pool size
});
```

## 认证

驱动程序通过:

1.  **默认认证链** (单位:千美元)`.databrickscfg`,环境变量)
2.  **证书** (通过Databricks SDK)
3.  **本地 Postgres 密码认证**

见 [数据砖认证文件](https://docs.databricks.com/en/dev-tools/auth/index.html) 或者说 [Lakebase 自动缩放认证文件](https://docs.databricks.com/aws/en/oltp/projects/authentication#overview) 更多信息.

## PostgreSQL 用户名分辨率

驱动程序解决 PostgreSQL 用户名(`user` 配置选项)使用下列优先排序:

1.  `config.user` 明确价值转至 `createLakebasePool`
2.  `PGUSER` 环境变量
3.  `DATABRICKS_CLIENT_ID` 环境变量(使用 OAuth M2M 的服务本能)

如果没有设定, 司机会丢一个 `ConfigurationError`。 。 。 .

### 通过工作空间 API 自动解析

对于使用 PAT 令牌或浏览器通过 OAuth 认证的人类用户 `~/.databrickscfg`,则上述内容一般没有设定。 使用 `getUsernameWithApiLookup` 在创建池前从 Databricks 工作空间自动获取用户名 :

```typescript
import { createLakebasePool, getUsernameWithApiLookup } from "@databricks/lakebase";

// Tries config/env vars first, then falls back to currentUser.me() API call
const user = await getUsernameWithApiLookup();

const pool = createLakebasePool({ user });
```

`getUsernameWithApiLookup` 以第四步扩展上面的同步分辨率 :

4.  `currentUser.me()` ——从 Databricks 工作空间 API 中获取当前用户的身份( 与 PAT 令牌和浏览器 OAuth 一起工作) `~/.databrickscfg`(中文(简体) )

> **说明:** `getUsernameWithApiLookup` 当同步解析步骤(配置,)时,向 Databricks 工作空间 API 发出网络呼叫, `PGUSER`, (中文(简体) ), `DATABRICKS_CLIENT_ID`所有失败。 在初始化期间拨打一次电话,而不是在每次请求时拨打一次.

## 配置

| 选项 | 环境变量 | 说明 | 默认 |
| --- | --- | --- | --- |
| `host` | `PGHOST` | 湖边主机 | _需求_ |
| `database` | `PGDATABASE` | 数据库名称 | _需求_ |
| `endpoint` | `LAKEBASE_ENDPOINT` | 端点资源路径 | _需求_ |
| `user` | `PGUSER` 或者说 `DATABRICKS_CLIENT_ID` | 用户名或服务主ID | 见 [用户名解析度](https://npmcn.com/package/%40databricks/lakebase/#readme-username-resolution) |
| `port` | `PGPORT` | 端口编号 | `5432` |
| `sslMode` | `PGSSLMODE` | SSL 模式 | `require` |
| `max` | \- 说吧 | 最大池连接 | `10` |
| `idleTimeoutMillis` | \- 说吧 | 中断连接超时 | `30000` |
| `connectionTimeoutMillis` | \- 说吧 | 连接超时 | `10000` |
| `logger` | \- 说吧 | 锁定实例或配置 | `{ error: true }` |

## 日志

默认情况下, 驱动程序只记录错误 。 您可以以三种方式配置日志:

### 1\. 基于配置的Logger(简单)

使用布尔标记启用/ 禁用特定日志级别 :

```typescript
import { createLakebasePool } from "@databricks/lakebase";

// Development mode: enable debug and error logs
const pool = createLakebasePool({
  logger: { debug: true, error: true },
});

// Production mode: errors only (same as default)
const pool = createLakebasePool({
  logger: { error: true },
});

// Verbose mode: all logs enabled
const pool = createLakebasePool({
  logger: { debug: true, info: true, warn: true, error: true },
});

// Silent mode: all logs disabled
const pool = createLakebasePool({
  logger: { debug: false, info: false, warn: false, error: false },
});
```

### 2\. 自定义 Logger (高级)

输入自定义格式化或集成的日志执行 :

```typescript
const logger = {
  debug: (msg: string, ...args: unknown[]) => console.debug(msg, ...args),
  info: (msg: string, ...args: unknown[]) => console.log(msg, ...args),
  warn: (msg: string, ...args: unknown[]) => console.warn(msg, ...args),
  error: (msg: string, ...args: unknown[]) => console.error(msg, ...args),
};

const pool = createLakebasePool({ logger });
```

### 3\. 默认行为

如果没有提供日志, 驱动程序默认只记录出错 :

```typescript
// These are equivalent:
const pool1 = createLakebasePool();
const pool2 = createLakebasePool({ logger: { error: true } });
```

当使用 AppKit 时, 日志会自动配置 - 见 [AppKit 整合](https://npmcn.com/package/%40databricks/lakebase/#readme-appkit-integration) 节.

## ORM 示例

### 滴入外科手术

```typescript
import { drizzle } from "drizzle-orm/node-postgres";
import { createLakebasePool } from "@databricks/lakebase";

const pool = createLakebasePool();
const db = drizzle(pool);

const users = await db.select().from(usersTable);
```

### 普里斯马

```typescript
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
import { createLakebasePool } from "@databricks/lakebase";

const pool = createLakebasePool();
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

const users = await prisma.user.findMany();
```

### 类型ORM

```typescript
import { DataSource } from "typeorm";
import { createLakebasePool } from "@databricks/lakebase";

const pool = createLakebasePool();

const dataSource = new DataSource({
  type: "postgres",
  synchronize: true,
  ...getLakebaseOrmConfig(),
  entities: [
    // Your entity classes
  ],
});

await dataSource.initialize();
```

### 排序

```typescript
import { Sequelize } from "sequelize";
import { getLakebaseOrmConfig } from "@databricks/lakebase";

const sequelize = new Sequelize({
  dialect: "postgres",
  ...getLakebaseOrmConfig(),
});
```

## 打开远程集成

驱动程序在可用时会自动使用 OpenTeleometry 的全球注册. 如果您的应用程序初始化了 OpenTeleometry 服务商, 驱动程序会自动进行仪器查询和测量, 而不需要额外的配置 .

### 设置

在应用程序中安装 OpenTeleometry :

```bash
npm install @opentelemetry/api @opentelemetry/sdk-node
```

在应用程序中初始化 OpenTelection :

```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";

const sdk = new NodeSDK({
  // Your OTEL configuration
});

sdk.start(); // Registers global providers

// Now create your pool - it automatically uses the global providers
import { createLakebasePool } from "@databricks/lakebase";
const pool = createLakebasePool();
```

司机打电话来 `trace.getTracer('@databricks/lakebase')` 财务报告和审定财务报表 `metrics.getMeter('@databricks/lakebase')` 内部。 如果没有全球供应商注册,业务就是自动禁用.

### 导出量

-   `lakebase.token.refresh.duration` - OAuth 令牌刷新持续时间(图像,ms)
-   `lakebase.query.duration` - 查询处决期限(图像、ms)
-   `lakebase.pool.connections.total` - 池内总连接量(大)
-   `lakebase.pool.connections.idle` - 闲置连接(高架)
-   `lakebase.pool.connections.waiting` - 等待连接的客户端(大容量)
-   `lakebase.pool.errors` - 错误代码(计数器)的集合错误

## AppKit 整合

此驱动程序也可用作为 [@ databricks/ appkit (数据砖)](https://www.npmjs.com/package/@databricks/appkit)数字 :

```typescript
import { createLakebasePool } from "@databricks/appkit";

const pool = createLakebasePool();
```

**独立和 AppKit 之间的差异 :**

-   **独立** (单位:千美元)`@databricks/lakebase`: 默认沉默 - 没有配置日志
-   **应用程序** (单位:千美元)`@databricks/appkit`: 自动注入 AppKit 有范围的记录器 `appkit:connectors:lakebase`。 。 。 .

## 学习更多关于 Lakebase 自动缩放

Lakebase 自动缩放文档见 [docs.databricks.com/aws/en/oltp/项目](https://docs.databricks.com/aws/en/oltp/projects/)。 。 。 .

## 常见问题

### @databricks/lakebase 是什么？

Databricks Lakebase 自动升级并自动刷新 OAuth 令牌的 PostgreSQL 驱动程序

### 如何安装 @databricks/lakebase？

在项目目录运行 npm install @databricks/lakebase，或使用 pnpm add / yarn add / bun add。

### @databricks/lakebase 支持 TypeScript 吗？

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

### @databricks/lakebase 支持 ESM 还是 CommonJS？

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

### @databricks/lakebase 可以商用吗？

@databricks/lakebase 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @databricks/lakebase 的下载量有多少？

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

### @databricks/lakebase 还在维护吗？

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

