Skip to content

@astrojs/ db

Astro DB 是专为 Astro 生态系统设计的完全托管 SQL 数据库:在 Astro 中本地开发并部署到任何 libSQL 兼容数据库

¥Astro DB is a fully-managed SQL database designed for the Astro ecosystem: develop locally in Astro and deploy to any libSQL-compatible database.

使用 Astro DB,你将拥有一个功能强大、本地、类型安全的工具来查询和建模内容作为关系数据库。

¥With Astro DB you have a powerful, local, type-safe tool to query and model content as a relational database.

See the Astro DB guide for full usage and examples.

¥Installation

Astro 包含一个 astro add 命令来自动设置官方集成。如果你愿意,你可以改用 安装集成手动

¥Astro includes an astro add command to automate the setup of official integrations. If you prefer, you can install integrations manually instead.

在新的终端窗口中运行以下命令之一。

¥Run one of the following commands in a new terminal window.

终端窗口
npx astro add db

¥Manual Installation

如果你希望自己从头开始设置,请跳过 astro add 并按照这些说明自行安装 Astro DB。

¥If you prefer to set things up from scratch yourself, skip astro add and follow these instructions to install Astro DB yourself.

¥ Install the integration from npm via a package manager

终端窗口
npm install @astrojs/db

¥ Add the integration to astro.config.mjs

astro.config.mjs
import { defineConfig } from 'astro/config';
import db from '@astrojs/db';
export default defineConfig({
integrations: [
db()
]
});

¥ Configure your database

在项目的根目录中创建一个 db/config.ts 文件。这是一个特殊文件,Astro 将自动加载并使用它配置你的数据库表。

¥Create a db/config.ts file at the root of your project. This is a special file that Astro will automatically load and use to configure your database tables.

db/config.ts
import { defineDb } from 'astro:db';
export default defineDb({
tables: {},
})

¥Configuration

类型:'node' | 'web'
默认:'node'

¥Type: 'node' | 'web'
Default: 'node'

Added in: @astrojs/db@0.18.0

配置用于在生产环境中连接数据库的驱动程序。

¥Configures the driver to use to connect to your database in production.

默认情况下,Astro DB 使用基于 Node.js 的 libSQL 驱动程序进行生产部署。对于大多数使用 Node.js 运行时的 Astro 托管或自托管网站,node 驱动模式已足够使用。这允许你通过多种协议连接到数据库,包括 memory:file:ws:wss:libsqlhttphttps,以及 嵌入式副本 等更高级的功能。

¥By default, Astro DB uses a Node.js-based libSQL driver for production deployments. The node driver mode is sufficient for most Astro hosted or self-hosted websites with Node.js runtimes. This allows you to connect to your database over several protocols, including memory:, file:, ws:, wss:, libsql, http, and https, as well as allowing for more advanced features such as embedded replicas.

当部署到非 Node.js 运行时环境(例如 Cloudflare Workers 或 Deno)的无服务器环境时,可以使用基于 Web 的 libSQL 驱动程序。使用 web 模式部署时,你可以通过 libsqlhttphttps 建立基于 Web 的连接。

¥When deploying to a serverless environment on a non-Node.js runtime, such as Cloudflare Workers or Deno, a web-based libSQL driver is available. When deploying using the web mode, you will be able to make web-based connections over libsql, http, or https.

要在非 Node.js 环境中使用 Web libSQL 驱动程序模式,请在适配器的配置中设置 mode 属性:

¥To use the web libSQL driver mode for non-Node.js environments, set the mode property in your adapter’s configuration:

astro.config.mjs
import { defineConfig } from 'astro/config';
import db from '@astrojs/db';
export default defineConfig({
integrations: [
db({
mode: 'web'
})
]
});

¥Table configuration reference

类型:ColumnsConfig

¥Type: ColumnsConfig

使用 columns 对象配置表列:

¥Table columns are configured using the columns object:

import { defineTable, column, NOW } from 'astro:db';
const Comment = defineTable({
columns: {
id: column.number({ primaryKey: true }),
author: column.text(),
content: column.text({ optional: true }),
published: column.date({ default: NOW }),
},
});

使用 column 实用程序配置列。column 支持以下类型:

¥Columns are configured using the column utility. column supports the following types:

  • column.text(...) - 存储纯文本或富文本内容

  • column.number(...) - 存储整数和浮点值

  • column.boolean(...) - 存储真/假值

  • column.date(...) - 存储 Date 对象,解析为 ISO 字符串以进行数据存储

  • column.json(...) - 存储任意 JSON blob,解析为字符串化的 JSON 以进行数据存储

所有列中都有一些共享的配置值:

¥There are a few shared configuration values across all columns:

  • primaryKey - 将 numbertext 列设置为唯一标识符。

  • optional - Astro DB 默认对所有列使用 NOT NULL。将 optional 设置为 true 以允许空值。

  • default - 设置新插入条目的默认值。这接受静态值或 sql 字符串作为生成的值(如时间戳)。

  • unique - 将列标记为唯一。这可以防止表中的条目出现重复值。

  • references - 按列引用相关表。这将建立外键约束,这意味着每个列值在引用表中都必须具有匹配的值。

text 列可以选择性地定义一个字符串字面量列表,用作生成类型的枚举。但是,不会执行运行时验证。移除、添加和更改值的操作应在你的项目代码中处理。

¥A text column can optionally define a list of string literals to serve as an enum for generating types. However, no runtime validation will be performed. Removing, adding, and changing values should be handled in your project code.

db/config.ts
import { defineTable, column } from 'astro:db';
// Table definition
const UserTable = defineTable({
columns: {
id: column.number({ primaryKey: true }),
name: column.text(),
rank: column.text({ enum: ['user', 'mod', 'admin'] }),
},
});
// Resulting type definition
type UserTableInferInsert = {
id?: string;
name: string;
rank: "user" | "mod" | "admin";
}

类型:{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]

¥Type: { on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]

表索引用于提高给定列或列组合的查找速度。indexes 属性接受指定要索引的列的配置对象数组:

¥Table indexes are used to improve lookup speeds on a given column or combination of columns. The indexes property accepts an array of configuration objects specifying the columns to index:

db/config.ts
import { defineTable, column } from 'astro:db';
const Comment = defineTable({
columns: {
authorId: column.number(),
published: column.date(),
body: column.text(),
},
indexes: [
{ on: ["authorId", "published"], unique: true },
]
});

这将在 authorIdpublished 列上生成一个名为 Comment_authorId_published_idx 的唯一索引。

¥This will generate a unique index on the authorId and published columns with the name Comment_authorId_published_idx.

每个索引都有以下配置选项:

¥The following configuration options are available for each index:

  • on - 要索引的单个列或列名数组。

  • unique(可选) - 设置为 true 以在索引列中强制使用唯一值。

  • name(可选) - 唯一索引的自定义名称。这将根据被索引的表和列名称覆盖 Astro 生成的名称(例如 Comment_authorId_published_idx)。自定义名称是全局的,因此请确保索引名称在表之间不冲突。

类型:{ columns: string | string[]; references: () => Column | Column[]; }[]

¥Type: { columns: string | string[]; references: () => Column | Column[]; }[]

外键用于建立两个表之间的关系。foreignKeys 属性接受可能在表之间关联一个或多个列的配置对象数组:

¥Foreign keys are used to establish a relationship between two tables. The foreignKeys property accepts an array of configuration objects that may relate one or more columns between tables:

db/config.ts
import { defineTable, column } from 'astro:db';
const Author = defineTable({
columns: {
firstName: column.text(),
lastName: column.text(),
},
});
const Comment = defineTable({
columns: {
authorFirstName: column.text(),
authorLastName: column.text(),
body: column.text(),
},
foreignKeys: [
{
columns: ["authorFirstName", "authorLastName"],
references: () => [Author.columns.firstName, Author.columns.lastName],
},
],
});

每个外键配置对象都接受以下属性:

¥Each foreign key configuration object accepts the following properties:

  • columns - 与引用表关联的单个列或列名数组。

  • references - 一个返回引用表中的单列或列数组的函数。

¥Astro DB CLI reference

Astro DB 包含一组 CLI 命令,用于与你的本地和 libSQL 兼容数据库交互。

¥Astro DB includes a set of CLI commands to interact with your local and libSQL-compatible database.

使用 GitHub CI 操作时会自动调用这些命令,也可以使用 astro db CLI 手动调用。

¥These commands are called automatically when using a GitHub CI action, and can be called manually using the astro db CLI.

标志:

¥Flags:

  • --force-reset 如果需要重大架构更改,请重置所有生产数据。

安全地将数据库配置更改推送到你的项目数据库。这将检查是否存在数据丢失风险,并指导你完成任何推荐的迁移步骤。如果必须进行重大架构更改,请使用 --force-reset 标志重置所有生产数据。

¥Safely push database configuration changes to your project database. This will check for any risk of data loss and guide you on any recommended migration steps. If a breaking schema change must be made, use the --force-reset flag to reset all production data.

检查本地和远程数据库配置之间是否存在任何差异。这由 astro db push 自动运行。verify 将比较你的本地 db/config.ts 文件与远程数据库,并在检测到更改时触发警告。

¥Check for any differences between your local and remote database configurations. This is automatically run by astro db push. verify will compare your local db/config.ts file with the remote database and warn if changes are detected.

标志:

¥Flags:

  • --remote 针对你的 libSQL 兼容数据库运行。省略针对你的开发服务器运行。

执行 .ts.js 文件以读取或写入数据库。这接受文件路径作为参数,并支持使用 astro:db 模块编写类型安全查询。使用 --remote 标志针对你的 libSQL 兼容数据库运行,或省略该标志针对你的开发服务器运行。请参阅如何使用 种子开发数据 获取示例文件。

¥Execute a .ts or .js file to read or write to your database. This accepts a file path as an argument, and supports usage of the astro:db module to write type-safe queries. Use the --remote flag to run against your libSQL-compatible database, or omit the flag to run against your development server. See how to seed development data for an example file.

标志:

¥Flags:

  • --query 要执行的原始 SQL 查询。

  • --remote 针对你的 libSQL 兼容数据库运行。省略针对你的开发服务器运行。

对数据库执行原始 SQL 查询。使用 --remote 标志针对你的 libSQL 兼容数据库运行,或省略该标志针对你的开发服务器运行。

¥Execute a raw SQL query against your database. Use the --remote flag to run against your libSQL-compatible database, or omit the flag to run against your development server.

¥Astro DB utility reference

类型:(err: unknown) => boolean

¥Type: (err: unknown) => boolean

Added in: @astrojs/db@0.9.1

isDbError() 函数检查错误是否为 libSQL 数据库异常。这可能包括使用引用时的外键约束错误,或插入数据时缺少字段。你可以将 isDbError() 与 try / catch 块结合使用,以处理应用中的数据库错误:

¥The isDbError() function checks if an error is a libSQL database exception. This may include a foreign key constraint error when using references, or missing fields when inserting data. You can combine isDbError() with a try / catch block to handle database errors in your application:

src/pages/api/comment/[id].ts
import { db, Comment, isDbError } from 'astro:db';
import type { APIRoute } from 'astro';
export const POST: APIRoute = (ctx) => {
try {
await db.insert(Comment).values({
id: ctx.params.id,
content: 'Hello, world!'
});
} catch (e) {
if (isDbError(e)) {
return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 });
}
return new Response('An unexpected error occurred', { status: 500 });
}
return new Response(null, { status: 201 });
};

更多集成

前端框架

适配器

其他集成

Astro v5.16 中文网 - 粤ICP备13048890号