bknd-database-provision

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Provision Production Database

配置生产环境数据库

Set up and configure a production database for your Bknd application.
为你的Bknd应用设置并配置生产环境数据库。

Prerequisites

前置条件

  • Bknd application with schema defined
  • Account on chosen database provider (for cloud databases)
  • Environment for storing connection credentials
  • 已定义Schema的Bknd应用
  • 所选数据库服务商的账号(针对云数据库)
  • 用于存储连接凭证的环境

When to Use UI Mode

何时使用UI模式

  • Creating databases via provider dashboards (Turso, Neon, Cloudflare, Supabase)
  • Managing database settings and access tokens
  • Viewing database metrics and logs
  • 通过服务商控制台创建数据库(Turso、Neon、Cloudflare、Supabase)
  • 管理数据库设置和访问令牌
  • 查看数据库指标和日志

When to Use Code Mode

何时使用代码模式

  • Configuring database connection in Bknd
  • CLI commands for database creation
  • Schema sync and migrations
  • 在Bknd中配置数据库连接
  • 使用CLI命令创建数据库
  • Schema同步与迁移

Database Selection Guide

数据库选择指南

DatabaseBest ForPlatform CompatibilityCost
SQLite FileVPS, Docker, single-serverNode.js, BunFree
LibSQL/TursoServerless, edge, globalAll platformsFree tier
Cloudflare D1Cloudflare WorkersCloudflare onlyFree tier
PostgreSQLComplex queries, transactionsVPS, DockerSelf-hosted
NeonServerless PostgresVercel, LambdaFree tier
SupabasePostgres + extrasAnyFree tier
XataServerless + searchAnyFree tier

数据库适用场景平台兼容性成本
SQLite FileVPS、Docker、单服务器环境Node.js、Bun免费
LibSQL/Turso无服务器、边缘计算、全球分布式部署所有平台免费层级可用
Cloudflare D1Cloudflare Workers部署仅支持Cloudflare免费层级可用
PostgreSQL复杂查询、事务处理、大型数据集VPS、Docker自托管
Neon无服务器、自动扩容的Postgres,适配Vercel、Lambda所有平台免费层级可用
Supabase带扩展功能的Postgres(认证、存储、实时同步)所有平台免费层级可用
Xata内置搜索功能的无服务器Postgres所有平台免费层级可用

SQLite File (VPS/Docker)

SQLite File(VPS/Docker)

Best for: Single-server deployments with full control
适用场景: 需要完全控制的单服务器部署环境

Step 1: Configure Connection

步骤1:配置连接

typescript
// bknd.config.ts
export default {
  app: (env) => ({
    connection: {
      url: env.DB_URL ?? "file:data.db",  // Relative to cwd
    },
  }),
};
typescript
// bknd.config.ts
export default {
  app: (env) => ({
    connection: {
      url: env.DB_URL ?? "file:data.db",  // Relative to cwd
    },
  }),
};

Step 2: Set Environment Variable

步骤2:设置环境变量

bash
undefined
bash
undefined

Relative path (project directory)

相对路径(项目目录内)

DB_URL=file:data.db
DB_URL=file:data.db

Absolute path (recommended for production)

绝对路径(生产环境推荐)

DB_URL=file:/var/data/myapp/bknd.db
undefined
DB_URL=file:/var/data/myapp/bknd.db
undefined

Step 3: Ensure Directory Exists

步骤3:确保目录存在

bash
mkdir -p /var/data/myapp
bash
mkdir -p /var/data/myapp

Docker Volume

Docker卷配置

yaml
undefined
yaml
undefined

docker-compose.yml

docker-compose.yml

services: bknd: volumes: - bknd-data:/app/data environment: - DB_URL=file:/app/data/bknd.db
volumes: bknd-data:

---
services: bknd: volumes: - bknd-data:/app/data environment: - DB_URL=file:/app/data/bknd.db
volumes: bknd-data:

---

LibSQL / Turso

LibSQL / Turso

Best for: Serverless, edge deployments, global distribution
适用场景: 无服务器、边缘计算、全球分布式部署

Step 1: Install Turso CLI

步骤1:安装Turso CLI

bash
undefined
bash
undefined

macOS/Linux

macOS/Linux

Authenticate

认证登录

turso auth login
undefined
turso auth login
undefined

Step 2: Create Database

步骤2:创建数据库

bash
undefined
bash
undefined

Create database

创建数据库

turso db create my-bknd-db
turso db create my-bknd-db

Optional: Specify region

可选:指定区域

turso db create my-bknd-db --location lax # Los Angeles
undefined
turso db create my-bknd-db --location lax # 洛杉矶
undefined

Step 3: Get Connection Details

步骤3:获取连接信息

bash
undefined
bash
undefined

Get connection URL

获取连接URL

turso db show my-bknd-db --url
turso db show my-bknd-db --url

Output: libsql://my-bknd-db-username.turso.io

输出:libsql://my-bknd-db-username.turso.io

Create auth token

创建认证令牌

turso db tokens create my-bknd-db
turso db tokens create my-bknd-db

Output: eyJhbGciOi...

输出:eyJhbGciOi...

undefined
undefined

Step 4: Configure Bknd

步骤4:配置Bknd

typescript
// bknd.config.ts
export default {
  app: (env) => ({
    connection: {
      url: env.DB_URL,       // libsql://...
      authToken: env.DB_TOKEN,
    },
  }),
};
typescript
// bknd.config.ts
export default {
  app: (env) => ({
    connection: {
      url: env.DB_URL,       // libsql://...
      authToken: env.DB_TOKEN,
    },
  }),
};

Step 5: Set Environment Variables

步骤5:设置环境变量

bash
DB_URL=libsql://my-bknd-db-username.turso.io
DB_TOKEN=eyJhbGciOi...
bash
DB_URL=libsql://my-bknd-db-username.turso.io
DB_TOKEN=eyJhbGciOi...

Turso Locations

Turso可用区域

Common regions:
ams
(Amsterdam),
fra
(Frankfurt),
lax
(LA),
lhr
(London),
nrt
(Tokyo),
syd
(Sydney)
bash
turso db locations  # List all regions

常见区域:
ams
(阿姆斯特丹)、
fra
(法兰克福)、
lax
(洛杉矶)、
lhr
(伦敦)、
nrt
(东京)、
syd
(悉尼)
bash
turso db locations  # 列出所有区域

Cloudflare D1

Cloudflare D1

Best for: Cloudflare Workers deployments
适用场景: Cloudflare Workers部署

Step 1: Create D1 Database

步骤1:创建D1数据库

bash
wrangler d1 create my-bknd-db
Output:
Created D1 database 'my-bknd-db'
database_name = "my-bknd-db"
database_id = "abc123-def456-..."
bash
wrangler d1 create my-bknd-db
输出:
Created D1 database 'my-bknd-db'
database_name = "my-bknd-db"
database_id = "abc123-def456-..."

Step 2: Configure wrangler.toml

步骤2:配置wrangler.toml

toml
name = "my-bknd-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[d1_databases]]
binding = "DB"
database_name = "my-bknd-db"
database_id = "abc123-def456-..."
toml
name = "my-bknd-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[d1_databases]]
binding = "DB"
database_name = "my-bknd-db"
database_id = "abc123-def456-..."

Step 3: Configure Bknd Adapter

步骤3:配置Bknd适配器

typescript
// src/index.ts
import { hybrid, type CloudflareBkndConfig } from "bknd/adapter/cloudflare";
import { d1Sqlite } from "bknd/adapter/cloudflare";

export default hybrid<CloudflareBkndConfig>({
  app: (env) => ({
    connection: d1Sqlite({ binding: env.DB }),
    isProduction: true,
  }),
});
typescript
// src/index.ts
import { hybrid, type CloudflareBkndConfig } from "bknd/adapter/cloudflare";
import { d1Sqlite } from "bknd/adapter/cloudflare";

export default hybrid<CloudflareBkndConfig>({
  app: (env) => ({
    connection: d1Sqlite({ binding: env.DB }),
    isProduction: true,
  }),
});

D1 CLI Commands

D1 CLI命令

bash
undefined
bash
undefined

List databases

列出数据库

wrangler d1 list
wrangler d1 list

Execute SQL (local dev)

执行SQL(本地开发)

wrangler d1 execute my-bknd-db --local --command "SELECT * FROM posts"
wrangler d1 execute my-bknd-db --local --command "SELECT * FROM posts"

Execute SQL (production)

执行SQL(生产环境)

wrangler d1 execute my-bknd-db --command "SELECT * FROM posts"
wrangler d1 execute my-bknd-db --command "SELECT * FROM posts"

Export backup

导出备份

wrangler d1 backup create my-bknd-db

---
wrangler d1 backup create my-bknd-db

---

PostgreSQL (Self-Hosted)

PostgreSQL(自托管)

Best for: Complex queries, large datasets, existing Postgres infrastructure
适用场景: 复杂查询、大型数据集、已有Postgres基础设施

Step 1: Install Adapter

步骤1:安装适配器

bash
npm install postgres
bash
npm install postgres

or

npm install pg
undefined
npm install pg
undefined

Step 2: Configure Connection

步骤2:配置连接

Using
postgres
(recommended):
typescript
import { PostgresJsConnection } from "bknd/adapter/postgres";

export default {
  app: (env) => ({
    connection: new PostgresJsConnection({
      connectionString: env.DATABASE_URL,
    }),
  }),
};
Using
pg
:
typescript
import { PgPostgresConnection } from "bknd/adapter/postgres";

export default {
  app: (env) => ({
    connection: new PgPostgresConnection({
      connectionString: env.DATABASE_URL,
    }),
  }),
};
使用
postgres
(推荐):
typescript
import { PostgresJsConnection } from "bknd/adapter/postgres";

export default {
  app: (env) => ({
    connection: new PostgresJsConnection({
      connectionString: env.DATABASE_URL,
    }),
  }),
};
使用
pg
typescript
import { PgPostgresConnection } from "bknd/adapter/postgres";

export default {
  app: (env) => ({
    connection: new PgPostgresConnection({
      connectionString: env.DATABASE_URL,
    }),
  }),
};

Step 3: Set Connection String

步骤3:设置连接字符串

bash
DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require

bash
DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require

Neon (Serverless Postgres)

Neon(无服务器Postgres)

Best for: Vercel, serverless, auto-scaling Postgres
适用场景: Vercel、无服务器、自动扩容的Postgres

Step 1: Create Project at neon.tech

步骤1:在neon.tech创建项目

  1. Sign up at neon.tech
  2. Create new project
  3. Copy connection string from dashboard
  1. 访问neon.tech注册账号
  2. 创建新项目
  3. 从控制台复制连接字符串

Step 2: Install Neon Dialect

步骤2:安装Neon方言包

bash
npm install kysely-neon
bash
npm install kysely-neon

Step 3: Configure Connection

步骤3:配置连接

typescript
import { createCustomPostgresConnection } from "bknd";
import { NeonDialect } from "kysely-neon";

const neon = createCustomPostgresConnection("neon", NeonDialect);

export default {
  app: (env) => ({
    connection: neon({
      connectionString: env.NEON_DATABASE_URL,
    }),
  }),
};
typescript
import { createCustomPostgresConnection } from "bknd";
import { NeonDialect } from "kysely-neon";

const neon = createCustomPostgresConnection("neon", NeonDialect);

export default {
  app: (env) => ({
    connection: neon({
      connectionString: env.NEON_DATABASE_URL,
    }),
  }),
};

Step 4: Set Environment Variable

步骤4:设置环境变量

bash
NEON_DATABASE_URL=postgres://user:password@ep-xxx.us-east-1.aws.neon.tech/neondb?sslmode=require

bash
NEON_DATABASE_URL=postgres://user:password@ep-xxx.us-east-1.aws.neon.tech/neondb?sslmode=require

Supabase

Supabase

Best for: Full-featured Postgres with extras (auth, storage, realtime)
适用场景: 带扩展功能的Postgres(认证、存储、实时同步)

Step 1: Create Project at supabase.com

步骤1:在supabase.com创建项目

  1. Sign up at supabase.com
  2. Create new project
  3. Go to Settings > Database > Connection string
  1. 访问supabase.com注册账号
  2. 创建新项目
  3. 进入设置 > 数据库 > 连接字符串

Step 2: Get Direct Connection String

步骤2:获取直接连接字符串

Use "Direct connection" (not pooler) for Bknd:
postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:5432/postgres
为Bknd使用「直接连接」(而非连接池):
postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:5432/postgres

Step 3: Configure Connection

步骤3:配置连接

typescript
export default {
  app: (env) => ({
    connection: {
      url: env.SUPABASE_DB_URL,
    },
  }),
};
typescript
export default {
  app: (env) => ({
    connection: {
      url: env.SUPABASE_DB_URL,
    },
  }),
};

Step 4: Set Environment Variable

步骤4:设置环境变量

bash
SUPABASE_DB_URL=postgresql://postgres:your-password@db.abcdefgh.supabase.co:5432/postgres

bash
SUPABASE_DB_URL=postgresql://postgres:your-password@db.abcdefgh.supabase.co:5432/postgres

Xata

Xata

Best for: Serverless Postgres with built-in search
适用场景: 内置搜索功能的无服务器Postgres

Step 1: Create Database at xata.io

步骤1:在xata.io创建数据库

  1. Sign up at xata.io
  2. Create workspace and database
  1. 访问xata.io注册账号
  2. 创建工作区和数据库

Step 2: Install Xata Dialect

步骤2:安装Xata方言包

bash
npm install @xata.io/kysely
bash
npm install @xata.io/kysely

Step 3: Configure Connection

步骤3:配置连接

typescript
import { createCustomPostgresConnection } from "bknd";
import { XataDialect } from "@xata.io/kysely";

const xata = createCustomPostgresConnection("xata", XataDialect);

export default {
  app: (env) => ({
    connection: xata({
      apiKey: env.XATA_API_KEY,
      workspace: "your-workspace",
      database: "your-database",
    }),
  }),
};

typescript
import { createCustomPostgresConnection } from "bknd";
import { XataDialect } from "@xata.io/kysely";

const xata = createCustomPostgresConnection("xata", XataDialect);

export default {
  app: (env) => ({
    connection: xata({
      apiKey: env.XATA_API_KEY,
      workspace: "your-workspace",
      database: "your-database",
    }),
  }),
};

Schema Sync

Schema同步

After configuring your database, Bknd auto-syncs schema on first request. For manual control:
bash
undefined
配置完成后,Bknd会在首次请求时自动同步Schema。如需手动控制:
bash
undefined

Dry run (preview changes)

试运行(预览变更)

npx bknd sync --dry-run
npx bknd sync --dry-run

Apply changes

应用变更

npx bknd sync
npx bknd sync

Force sync (use with caution)

强制同步(谨慎使用)

npx bknd sync --force

---
npx bknd sync --force

---

Connection Testing

连接测试

Verify Connection

验证连接

typescript
// test-connection.ts
import { app } from "bknd";

const bknd = app({
  connection: {
    url: process.env.DB_URL!,
    authToken: process.env.DB_TOKEN,
  },
});

async function test() {
  await bknd.build();
  console.log("Connection successful!");
  console.log("Entities:", Object.keys(bknd.modules.data.entities));
  process.exit(0);
}

test().catch((e) => {
  console.error("Connection failed:", e);
  process.exit(1);
});
Run:
bash
npx tsx test-connection.ts

typescript
// test-connection.ts
import { app } from "bknd";

const bknd = app({
  connection: {
    url: process.env.DB_URL!,
    authToken: process.env.DB_TOKEN,
  },
});

async function test() {
  await bknd.build();
  console.log("连接成功!");
  console.log("实体:", Object.keys(bknd.modules.data.entities));
  process.exit(0);
}

test().catch((e) => {
  console.error("连接失败:", e);
  process.exit(1);
});
运行:
bash
npx tsx test-connection.ts

Common Pitfalls

常见问题

"Connection refused" or "ECONNREFUSED"

"Connection refused"或"ECONNREFUSED"

Problem: Can't connect to database
Fix:
  • Verify connection URL format
  • Check firewall/security group rules
  • Ensure database is running
  • For cloud: verify IP allowlist includes your server
问题: 无法连接到数据库
解决方法:
  • 验证连接URL格式是否正确
  • 检查防火墙/安全组规则
  • 确保数据库服务正在运行
  • 云数据库:验证服务器IP已加入数据库的IP白名单

"Auth token required" (LibSQL/Turso)

"Auth token required"(LibSQL/Turso)

Problem: Missing or invalid auth token
Fix:
bash
undefined
问题: 缺少或无效的认证令牌
解决方法:
bash
undefined

Generate new token

生成新令牌

turso db tokens create my-bknd-db
turso db tokens create my-bknd-db

Set in environment

设置到环境变量

export DB_TOKEN="eyJhbGciOi..."
undefined
export DB_TOKEN="eyJhbGciOi..."
undefined

"D1 binding not found"

"D1 binding not found"

Problem:
env.DB is undefined
in Cloudflare Workers
Fix: Check wrangler.toml binding name matches code:
toml
[[d1_databases]]
binding = "DB"  # Must match env.DB
问题: Cloudflare Workers中
env.DB
未定义
解决方法: 检查wrangler.toml中的绑定名称与代码是否一致:
toml
[[d1_databases]]
binding = "DB"  # 必须与代码中的env.DB匹配

"SSL required" (PostgreSQL)

"SSL required"(PostgreSQL)

Problem: Connection fails without SSL
Fix: Add
?sslmode=require
to connection string:
bash
DATABASE_URL=postgresql://user:pass@host:5432/db?sslmode=require
问题: 未使用SSL导致连接失败
解决方法: 在连接字符串中添加
?sslmode=require
bash
DATABASE_URL=postgresql://user:pass@host:5432/db?sslmode=require

"Unknown database" or "Database does not exist"

"Unknown database"或"Database does not exist"

Problem: Database not created
Fix:
bash
undefined
问题: 数据库未创建
解决方法:
bash
undefined

Turso

Turso

turso db create my-bknd-db
turso db create my-bknd-db

D1

D1

wrangler d1 create my-bknd-db
wrangler d1 create my-bknd-db

PostgreSQL

PostgreSQL

createdb my-bknd-db
undefined
createdb my-bknd-db
undefined

Schema Sync Fails

Schema同步失败

Problem: Migrations fail on production database
Fix:
bash
undefined
问题: 生产环境数据库迁移失败
解决方法:
bash
undefined

Preview changes first

先预览变更

npx bknd sync --dry-run
npx bknd sync --dry-run

If stuck, use --force (data loss possible!)

若卡住,使用--force(可能导致数据丢失!)

npx bknd sync --force --drop

---
npx bknd sync --force --drop

---

Migration from Development

从开发环境迁移

Export Development Data

导出开发环境数据

bash
undefined
bash
undefined

SQLite

SQLite

sqlite3 data.db .dump > backup.sql
sqlite3 data.db .dump > backup.sql

Using API

通过API导出

undefined
undefined

Import to Production

导入到生产环境

bash
undefined
bash
undefined

Via seed function (recommended)

通过种子函数导入(推荐)

See bknd-seed-data skill

参考bknd-seed-data技能

Direct SQL (SQLite to SQLite only)

直接执行SQL(仅适用于SQLite到SQLite)

cat backup.sql | turso db shell my-bknd-db

---
cat backup.sql | turso db shell my-bknd-db

---

DOs and DON'Ts

注意事项

DO:
  • Use cloud databases (Turso, D1, Neon) for serverless
  • Store credentials in environment variables
  • Test connection before deploying
  • Use SSL for PostgreSQL connections
  • Keep auth tokens secure
  • Enable backups for production data
DON'T:
  • Use file-based SQLite in serverless/edge
  • Hardcode credentials in source code
  • Share auth tokens across environments
  • Skip connection testing
  • Use
    --force --drop
    without backups
  • Expose database directly to internet (use Bknd API)

建议:
  • 无服务器部署使用云数据库(Turso、D1、Neon)
  • 将凭证存储在环境变量中
  • 部署前测试连接
  • PostgreSQL连接使用SSL
  • 妥善保管认证令牌
  • 为生产数据启用备份
禁止:
  • 在无服务器/边缘环境使用文件型SQLite
  • 在源代码中硬编码凭证
  • 跨环境共享认证令牌
  • 跳过连接测试
  • 未备份时使用
    --force --drop
  • 直接将数据库暴露到公网(使用Bknd API)

Related Skills

相关技能

  • bknd-deploy-hosting - Deploy to hosting platforms
  • bknd-production-config - Production security settings
  • bknd-env-config - Environment variable setup
  • bknd-seed-data - Populate database with initial data
  • bknd-local-setup - Local development (pre-production)
  • bknd-deploy-hosting - 部署到托管平台
  • bknd-production-config - 生产环境安全设置
  • bknd-env-config - 环境变量配置
  • bknd-seed-data - 为数据库填充初始数据
  • bknd-local-setup - 本地开发环境搭建(预生产)