@databricks/lakebase

中文文档
0.7.0发布于 2026/10/19Apache-2.0TypeScriptESM + CJS近 30 天下载 15.1万

PostgreSQL driver for Databricks Lakebase Autoscaling with automatic OAuth token refresh

原始使用文档
文档目录23 节
  1. Overview
  2. Installation
  3. Quick Start
  4. Using Environment Variables
  5. With Explicit Configuration
  6. Authentication
  7. PostgreSQL Username Resolution
  8. Automatic resolution via Workspace API
  9. Configuration
  10. Logging
  11. 1. Config-Based Logger (Simple)
  12. 2. Custom Logger (Advanced)
  13. 3. Default Behavior
  14. ORM Examples
  15. Drizzle ORM
  16. Prisma
  17. TypeORM
  18. Sequelize
  19. OpenTelemetry Integration
  20. Setup
  21. Metrics Exported
  22. AppKit Integration
  23. Learn more about Lakebase Autoscaling

@databricks/lakebase

PostgreSQL driver for Databricks Lakebase Autoscaling with automatic OAuth token refresh.

Overview

@databricks/lakebase provides a drop-in replacement for the standard pg connection pool that automatically handles OAuth authentication for Databricks Lakebase Autoscaling (OLTP) databases.

It:

  • Returns a standard pg.Pool - works with any PostgreSQL library or ORM
  • Automatically refreshes OAuth tokens (1-hour lifetime, with 2-minute buffer)
  • Caches tokens to minimize API calls
  • Zero configuration with environment variables
  • Optional OpenTelemetry instrumentation

NOTE: This package is NOT compatible with the Databricks Lakebase Provisioned.

Installation

npm install @databricks/lakebase

Quick Start

Using Environment Variables

Set the following environment variables:

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

To find your LAKEBASE_ENDPOINT, run the Databricks CLI and use the name field from the output:

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

You can obtain the Project ID and Branch ID from the Lakebase Autoscaling UI, like the "Branch Overview" page. (Project list -> Project dashboard -> Branch overview).

Then use the driver:

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

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

With Explicit Configuration

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
});

Authentication

The driver supports Databricks authentication via:

  1. Default auth chain (.databrickscfg, environment variables)
  2. OAuth tokens (via Databricks SDK)
  3. Native Postgres password authentication

See Databricks authentication docs or Lakebase Autoscaling authentication docs for more information.

PostgreSQL Username Resolution

The driver resolves the PostgreSQL username (user configuration option) using the following priority order:

  1. config.user — explicit value passed to createLakebasePool
  2. PGUSER environment variable
  3. DATABRICKS_CLIENT_ID environment variable (service principals using OAuth M2M)

If none of these are set, the driver throws a ConfigurationError.

Automatic resolution via Workspace API

For human users authenticating with a PAT token or browser OAuth via ~/.databrickscfg, none of the above are typically set. Use getUsernameWithApiLookup to automatically fetch the username from the Databricks workspace before creating the pool:

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 extends the sync resolution above with a fourth step:

  1. currentUser.me() — fetches the current user's identity from the Databricks workspace API (works with PAT tokens and browser OAuth in ~/.databrickscfg)

Note: getUsernameWithApiLookup makes a network call to the Databricks workspace API when the sync resolution steps (config, PGUSER, DATABRICKS_CLIENT_ID) all fail. Call it once during initialization, not on every request.

Configuration

OptionEnvironment VariableDescriptionDefault
hostPGHOSTLakebase hostRequired
databasePGDATABASEDatabase nameRequired
endpointLAKEBASE_ENDPOINTEndpoint resource pathRequired
userPGUSER or DATABRICKS_CLIENT_IDUsername or service principal IDSee Username Resolution
portPGPORTPort number5432
sslModePGSSLMODESSL moderequire
max-Max pool connections10
idleTimeoutMillis-Idle connection timeout30000
connectionTimeoutMillis-Connection timeout10000
logger-Logger instance or config{ error: true }

Logging

By default, the driver logs errors only. You can configure logging in three ways:

1. Config-Based Logger (Simple)

Enable/disable specific log levels using boolean flags:

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. Custom Logger (Advanced)

Inject your own logger implementation for custom formatting or integrations:

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. Default Behavior

If no logger is provided, the driver defaults to error-only logging:

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

When used with AppKit, logging is automatically configured - see the AppKit Integration section.

ORM Examples

Drizzle ORM

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);

Prisma

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();

TypeORM

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();

Sequelize

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

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

OpenTelemetry Integration

The driver automatically uses OpenTelemetry's global registry when available. If your application initializes OpenTelemetry providers, the driver will automatically instrument queries and metrics with no additional configuration needed.

Setup

Install OpenTelemetry in your application:

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

Initialize OpenTelemetry in your application:

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();

The driver calls trace.getTracer('@databricks/lakebase') and metrics.getMeter('@databricks/lakebase') internally. If no global providers are registered, operations are automatic no-ops.

Metrics Exported

  • lakebase.token.refresh.duration - OAuth token refresh duration (histogram, ms)
  • lakebase.query.duration - Query execution duration (histogram, ms)
  • lakebase.pool.connections.total - Total connections in pool (gauge)
  • lakebase.pool.connections.idle - Idle connections (gauge)
  • lakebase.pool.connections.waiting - Clients waiting for connection (gauge)
  • lakebase.pool.errors - Pool errors by error code (counter)

AppKit Integration

This driver is also available as part of @databricks/appkit:

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

const pool = createLakebasePool();

Differences between standalone and AppKit:

  • Standalone (@databricks/lakebase): Silent by default - no logger configured
  • AppKit (@databricks/appkit): Automatically injects AppKit's logger with scope appkit:connectors:lakebase.

Learn more about Lakebase Autoscaling

For Lakebase Autoscaling documentation, see docs.databricks.com/aws/en/oltp/projects.

版本与发布记录

@databricks/lakebase 共发布 9 个版本,首次发布于 2026/02/18;过去 12 个月发布了 9 个版本。

版本发布日期距今
0.7.0latest2026/10/1923 天前
0.6.02026/09/082 个月前
0.5.02026/07/084 个月前
0.4.02026/05/016 个月前
0.3.02026/04/306 个月前
0.2.02026/02/248 个月前

关于 @databricks/lakebase 的常见问题

@databricks/lakebase 是什么?

PostgreSQL driver for Databricks Lakebase Autoscaling with automatic OAuth token refresh

如何安装 @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 和提交记录判断。