Skip to content

Astro DB

Astro DB 是专为 Astro 设计的完全托管 SQL 数据库。本地开发或连接到在我们的 Astro Studio 平台上管理的托管数据库。

¥Astro DB is a fully-managed SQL database designed exclusively for Astro. Develop locally or connect to a hosted database managed on our Astro Studio platform.

¥Installation

将 Astro DB 添加到新的或现有的 Astro 项目(需要 astro@4.5 或更高版本)和 @astrojs/db 整合v0.8.1 或更高版本)。Astro 包含一个内置的 astro add 命令来为你自动执行此设置过程。

¥Add Astro DB to a new or existing Astro project (requires astro@4.5 or later) with the @astrojs/db integration (v0.8.1 or later). Astro includes a built-in astro add command to automate this setup process for you.

Terminal window
npx astro add db

如果你愿意,你可以改用 手动安装 @astrojs/db

¥If you prefer, you can install @astrojs/db manually instead.

¥Define your database

Astro DB 是配置、开发和查询数据的完整解决方案。每当你运行 astro dev 时都会创建一个本地数据库,使用 libSQL 来管理你的数据,而无需 Docker 或网络连接。

¥Astro DB is a complete solution to configuring, developing and querying your data. A local database is created whenever you run astro dev, using libSQL to manage your data without the need for Docker or a network connection.

使用 astro add 命令安装 @astrojs/db 将在你的项目中创建一个 db/config.ts 文件,你将在其中定义数据库表:

¥Installing @astrojs/db with the astro add command will create a db/config.ts file in your project where you will define your databases tables:

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

¥Tables

Astro DB 中的数据使用 SQL 表存储。表将数据结构化为行和列,其中列强制执行每行值的类型。

¥Data in Astro DB is stored using SQL tables. Tables structure your data into rows and columns, where columns enforce the type of each row value.

当你定义一个表时,Astro 将生成一个 TypeScript 接口以从你的项目中查询该表。当你使用属性自动补齐和类型检查访问数据时,结果是完全支持 TypeScript。

¥When you define a table, Astro will generate a TypeScript interface to query that table from your project. The result is full TypeScript support when you access your data with property autocompletion and type-checking.

要配置数据库表,请从 astro:db 导入并使用 defineTable()column 实用程序。

¥To configure a database table, import and use the defineTable() and column utilities from astro:db.

此示例配置一个 Comment 表,其中包含 authorbody 所需的文本列。然后,通过 defineDb() 导出将其提供给你的项目。

¥This example configures a Comment table with required text columns for author and body. Then, make it available to your project through the defineDb() export.

db/config.ts
import { defineDb, defineTable, column } from 'astro:db';
const Comment = defineTable({
columns: {
author: column.text(),
body: column.text(),
}
})
export default defineDb({
tables: { Comment },
})
See the table configuration reference for a complete reference of table options.

¥Columns

Astro DB 支持以下列类型:

¥Astro DB supports the following column types:

db/config.ts
import { defineTable, column } from 'astro:db';
const Comment = defineTable({
columns: {
// A string of text.
author: column.text(),
// A whole integer value.
likes: column.number(),
// A true or false value.
flagged: column.boolean(),
// Date/time values queried as JavaScript Date objects.
published: column.date(),
// An untyped JSON object.
metadata: column.json(),
}
});
See the table columns reference for more details.

¥Table References

表之间的关系是数据库设计中的常见模式。例如,Blog 表可能与 CommentAuthorCategory 的其他表密切相关。

¥Relationships between tables are a common pattern in database design. For example, a Blog table may be closely related to other tables of Comment, Author, and Category.

你可以定义这些表之间的关系,并使用引用列将它们保存到数据库模式中。要建立关系,你需要:

¥You can define these relations between tables and save them into your database schema using reference columns. To establish a relationship, you will need:

  • 引用表上的标识符列。这通常是具有 primaryKey 属性的 id 列。

  • 基表上的一列用于存储引用的 id。这使用 references 属性建立关系。

此示例显示了 Comment 表的 authorId 列引用 Author 表的 id 列。

¥This example shows a Comment table’s authorId column referencing an Author table’s id column.

db/config.ts
const Author = defineTable({
columns: {
id: column.number({ primaryKey: true }),
name: column.text(),
}
});
const Comment = defineTable({
columns: {
authorId: column.number({ references: () => Author.columns.id }),
body: column.text(),
}
});

¥Seed your database

在开发过程中,Astro 将使用你的 DB 配置根据你的模式生成本地类型。每次启动开发服务器时,这些变量都会重新生成,并允许你使用类型安全和自动补齐来查询和处理数据形状。

¥In development, Astro will use your DB config to generate local types according to your schemas. These will be generated fresh each time the dev server is started, and will allow you to query and work with the shape of your data with type safety and autocompletion.

要将用于测试和调试的开发数据植入 Astro 项目,请创建一个 db/seed.ts 文件。从 astro:db 导入 db 对象和任何配置的表。使用 db.insert() 函数提供表行数据对象数组。

¥To seed development data for testing and debugging into your Astro project, create a db/seed.ts file. Import both the db object and any configured table from astro:db. Use the db.insert() function to provide an array of table row data objects.

以下示例为 Comment 表定义了两行开发数据:

¥The following example defines two rows of development data for a Comment table:

db/seed.ts
import { db, Comment, Author } from 'astro:db';
export default async function() {
await db.insert(Author).values([
{ id: 1, name: "Kasim" },
{ id: 2, name: "Mina" },
]);
await db.insert(Comment).values([
{ authorId: 1, body: 'Hope you like Astro DB!' },
{ authorId: 2, body: 'Enjoy!'},
])
}

每当此文件发生更改时,你的开发服务器都会自动重新启动数据库,重新生成你的类型并从 seed.ts 中播种你的开发数据。

¥Your development server will automatically restart your database whenever this file changes, regenerating your types and seeding your development data from seed.ts.

¥Query your database

你可以使用提供的 db ORM 和查询构建器从项目中的任何 Astro 页面endpoint 查询数据库。

¥You can query your database from any Astro page or endpoint in your project using the provided db ORM and query builder.

import { db } from 'astro:db';

Astro DB 包含内置 Drizzle ORM 客户端。使用客户端无需设置或手动配置。运行 Astro 时,Astro DB db 客户端会自动配置为与你的数据库(本地或远程)通信。当你引用不存在的列或表时,它会使用你的确切数据库架构定义进行类型安全的 SQL 查询,并出现 TypeScript 错误。

¥Astro DB includes a built-in Drizzle ORM client. There is no setup or manual configuration required to use the client. The Astro DB db client is automatically configured to talk to your database (local or remote) when you run Astro. It uses your exact database schema definition for type-safe SQL queries with TypeScript errors when you reference a column or table that doesn’t exist.

¥Select

以下示例选择 Comment 表的所有行。这将返回来自 db/seed.ts 的完整种子开发数据数组,然后可用于你的页面模板:

¥The following example selects all rows of a Comment table. This returns the complete array of seeded development data from db/seed.ts which is then available for use in your page template:

src/pages/index.astro
---
import { db, Comment } from 'astro:db';
const comments = await db.select().from(Comment);
---
<h2>Comments</h2>
{
comments.map(({ author, body }) => (
<article>
<p>Author: {author}</p>
<p>{body}</p>
</article>
))
}
See the Drizzle select() API reference for a complete overview.

¥Insert

要接受用户输入,例如处理表单请求并将数据插入远程托管数据库,请为你的部署环境配置 Astro 项目的 按需渲染添加 SSR 适配器

¥To accept user input, such as handling form requests and inserting data into your remote hosted database, configure your Astro project for on-demand rendering and add an SSR adapter for your deployment environment.

此示例根据解析的表单 POST 请求将一行插入 Comment 表:

¥This example inserts a row into a Comment table based on a parsed form POST request:

src/pages/index.astro
---
import { db, Comment } from 'astro:db';
if (Astro.request.method === 'POST') {
// parse form data
const formData = await Astro.request.formData();
const author = formData.get('author');
const content = formData.get('content');
if (typeof author === 'string' && typeof content === 'string') {
// insert form data into the Comment table
await db.insert(Comment).values({ author, content });
}
}
// render the new list of comments on each request
const comments = await db.select().from(Comment);
---
<form method="POST" style="display: grid">
<label for="author">Author</label>
<input id="author" name="author" />
<label for="content">Content</label>
<textarea id="content" name="content"></textarea>
<button type="submit">Submit</button>
</form>
<!--render `comments`-->

你还可以从 API 端点查询数据库。此示例通过 id 参数从 Comment 表中删除一行:

¥You can also query your database from an API endpoint. This example deletes a row from a Comment table by the id param:

src/pages/api/comments/[id].ts
import type { APIRoute } from "astro";
import { db, Comment, eq } from 'astro:db';
export const DELETE: APIRoute = async (ctx) => {
await db.delete(Comment).where(eq(Comment.id, ctx.params.id ));
return new Response(null, { status: 204 });
}

See the Drizzle insert() API reference for a complete overview.

¥Filtering

要按特定属性查询表结果,请使用 部分选择的 Drizzle 选项。例如,将 .where() 调用 添加到你的 select() 查询并传递你想要进行的比较。

¥To query for table results by a specific property, use Drizzle options for partial selects. For example, add a .where() call to your select() query and pass the comparison you want to make.

以下示例查询 Comment 表中包含短语 “Astro DB。” 的所有行,使用 like() 运算符 检查短语是否存在于 body 中:

¥The following example queries for all rows in a Comment table that contain the phrase “Astro DB.” Use the like() operator to check if a phrase is present within the body:

src/pages/index.astro
---
import { db, Comment, like } from 'astro:db';
const comments = await db.select().from(Comment).where(
like(Comment.body, '%Astro DB%')
);
---

¥Drizzle utilities

用于构建查询的所有 Drizzle 实用程序都从 astro:db 模块中公开。这包括:

¥All Drizzle utilities for building queries are exposed from the astro:db module. This includes:

import { eq, gt, count, sql } from 'astro:db';

¥Relationships

你可以使用 SQL 连接从多个表中查询相关数据。要创建连接查询,请使用连接运算符扩展 db.select() 语句。每个函数都接受要连接的表和用于匹配两个表之间的行的条件。

¥You can query related data from multiple tables using a SQL join. To create a join query, extend your db.select() statement with a join operator. Each function accepts a table to join with and a condition to match rows between the two tables.

此示例使用 innerJoin() 函数根据 authorId 列将 Comment 作者与其相关的 Author 信息连接起来。这将返回一个对象数组,其中每个 AuthorComment 行作为顶层属性:

¥This example uses an innerJoin() function to join Comment authors with their related Author information based on the authorId column. This returns an array of objects with each Author and Comment row as top-level properties:

src/pages/index.astro
---
import { db, eq, Comment, Author } from 'astro:db';
const comments = await db.select()
.from(Comment)
.innerJoin(Author, eq(Comment.authorId, Author.id));
---
<h2>Comments</h2>
{
comments.map(({ Author, Comment }) => (
<article>
<p>Author: {Author.name}</p>
<p>{Comment.body}</p>
</article>
))
}

See the Drizzle join reference for all available join operators and config options.

¥Batch Transactions

所有远程数据库查询均作为网络请求进行。当进行大量查询时,你可能需要将 “batch” 个查询合并到一个事务中,或者在任何查询失败时自动回滚。

¥All remote database queries are made as a network request. You may need to “batch” queries together into a single transaction when making a large number of queries, or to have automatic rollbacks if any query fails.

此示例使用 db.batch() 方法在单个请求中植入多行:

¥This example seeds multiple rows in a single request using the db.batch() method:

db/seed.ts
import { db, Author, Comment } from 'astro:db';
export default async function () {
const queries = [];
// Seed 100 sample comments into your remote database
// with a single network request.
for (let i = 0; i < 100; i++) {
queries.push(db.insert(Comment).values({ body: `Test comment ${i}` }));
}
await db.batch(queries);
}

See the Drizzle db.batch() docs for more details.

Studio feature

Astro DB 可以连接到 Astro Studio 平台,以快速将托管数据库添加到你的项目中。你可以从 Astro Studio 仪表板查看、管理和部署新的托管数据库。

¥Astro DB can connect to the Astro Studio platform to quickly add a hosted database to your project. You can view, manage and deploy new hosted databases all from the Astro Studio dashboard.

Astro Studio 门户网站 允许你通过 Web 界面或使用 CLI 命令 连接和管理远程托管的 Astro DB 数据库。

¥The Astro Studio web portal allows you to connect to and manage your remote hosted Astro DB databases through a web interface or using CLI commands.

从你的 Studio 仪表板,你可以访问账户管理、帮助文章和支持消息控制台。

¥From your Studio dashboard, you have access to account management, help articles and a support message console.

访问 Astro Studio 进行注册或登录。

¥Visit Astro Studio to sign up or log in.

Studio feature

在 Astro Studio 中创建项目有两种方法:

¥There are two ways to create a project in Astro Studio:

  1. 使用 Astro Studio Web UI 从新的或现有的 GitHub 存储库创建。

    要开始,请单击标题中的 “创建项目” 按钮并按照说明进行操作。Astro Studio 将连接到你的 GitHub 存储库并为你的项目创建一个新的托管数据库。

  2. 使用 Astro Studio CLI 从任何本地 Astro 项目创建。你可以运行以下命令开始:

    Terminal window
    # Log in to Astro Studio with your GitHub account
    npx astro login
    # Link to a new project by following the prompts
    npx astro link
    # (Optional) Push your local db configuration to the remote database
    npx astro db push

一旦你登录并成功链接,你就可以运行所有 Astro DB 命令来管理你的远程数据库。

¥Once you are logged in and linked successfully, you can run all Astro DB commands to manage your remote database.

See the Astro DB CLI reference for all available commands.

Deploy with a Studio connection

Section titled Deploy with a Studio connection
Studio feature

你可以通过与 Studio 数据库的实时连接部署 Astro DB 项目。这在任何使用静态构建或 固态继电器适配器 的部署平台上都是可能的。

¥You can deploy your Astro DB project with a live connection to your Studio database. This is possible with any deployment platform using static builds or an SSR adapter.

首先,使用 --remote 标志配置你的构建命令以连接到 Studio。此示例将标志应用于项目 package.json 中的 "build" 脚本。如果你的部署平台接受构建命令,请确保将其设置为 npm run build

¥First, configure your build command to connect with Studio using the --remote flag. This example applies the flag to a "build" script in your project’s package.json. If your deployment platform accepts a build command, ensure this is set to npm run build.

package.json
{
"scripts": {
"build": "astro build --remote"
}
}
Studio feature

你需要创建一个应用令牌才能从生产部署访问 Studio 数据库。你可以通过导航到“设置”选项卡并选择“令牌”从 Studio 项目仪表板创建应用令牌。

¥You need to create an app token to access your Studio database from a production deploy. You can create an app token from your Studio project dashboard by navigating to the Settings tab and selecting Tokens.

复制生成的令牌,并使用名称 ASTRO_STUDIO_APP_TOKEN 在你的部署平台中将其作为环境变量/环境密钥应用。

¥Copy the generated token and apply as an environment variable / environment secret in your deployment platform using the name ASTRO_STUDIO_APP_TOKEN.

Studio feature

你可以使用 Studio CI 操作自动将架构更改推送到 Studio 数据库。这验证是否可以安全地进行更改,并在你合并到 main 时保持配置为最新。

¥You can automatically push schema changes to your Studio database with the Studio CI action. This verifies changes can be made safely, and keeps your configuration up-to-date whenever you merge to main.

关注 GitHub 的文档 在你的存储库中配置一个新的密钥,名称为 ASTRO_STUDIO_APP_TOKEN,并以你的 Studio 应用令牌作为密钥的值。

¥Follow GitHub’s documentation to configure a new secret in your repository with the name ASTRO_STUDIO_APP_TOKEN and your Studio app token as the value for the secret.

配置完密钥后,在项目的 .github/workflows 目录中创建一个新的 GitHub Actions 工作流文件,以检出存储库并安装 Node.js 作为步骤,并使用 withastro/action-studio 操作同步架构更改。

¥Once your secret is configured, create a new GitHub Actions workflow file in your project’s .github/workflows directory to checkout the repository and install Node.js as steps, and use the withastro/action-studio action to sync schema changes.

该操作将在所有 事件触发器 上运行 astro db verify,以确保可以安全地应用架构更改。如果你专门添加 push 触发器,则操作会将这些更改推送到你的 Studio 数据库。

¥The action will run astro db verify on all event triggers to ensure schema changes can be applied safely. If you add the push trigger specifically, the action will push those changes to your Studio database.

此示例 GitHub Action _studio.yml 会在 main 分支更新时推送更改:

¥This example GitHub Action _studio.yml pushes changes whenever the main branch is updated:

.github/workflows/_studio.yml
name: Astro Studio
env:
ASTRO_STUDIO_APP_TOKEN: ${{secrets.ASTRO_STUDIO_APP_TOKEN }}
on:
push:
branches:
- main
pull_request:
types: [opened, reopened, synchronize]
jobs:
DB:
permissions:
contents: read
actions: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: jaid/action-npm-install@v1.2.1
- uses: withastro/action-studio@main
Studio feature

随着项目的发展,你的表模式将随时间而变化。你可以安全地在本地测试配置更改,并在部署时推送到你的 Studio 数据库。

¥Your table schema will change over time as your project grows. You can safely test configuration changes locally and push to your Studio database when you deploy.

创建 Studio 项目从仪表板 时,你可以选择创建 GitHub CI 操作。这将在与存储库的主分支合并时自动迁移架构更改。

¥When creating a Studio project from the dashboard, you will have the option to create a GitHub CI action. This will automatically migrate schema changes when merging with your repository’s main branch.

你还可以使用 astro db push --remote 命令通过 CLI 将本地架构更改推送到 Astro Studio:

¥You can also push your local schema changes to Astro Studio via the CLI using the astro db push --remote command:

Terminal window
npm run astro db push --remote

此命令将验证你的本地更改是否可以在不丢失数据的情况下进行,并在必要时建议如何安全地更改你的架构以解决冲突。

¥This command will verify that your local changes can be made without data loss and, if necessary, suggest how to safely make changes to your schema in order to resolve conflicts.

¥Pushing breaking schema changes

如果你必须以与 Astro Studio 上托管的现有数据不兼容的方式更改表架构,则需要重置生产数据库。

¥If you must change your table schema in a way that is incompatible with your existing data hosted at Astro Studio, you will need to reset your production database.

要推送包含重大更改的表架构更新,请添加 --force-reset 标志以重置所有生产数据:

¥To push a table schema update that includes a breaking change, add the --force-reset flag to reset all production data:

Terminal window
npm run astro db push --remote --force-reset
Studio feature

将你的架构推送到 Astro Studio 后,可以重命名表。

¥It is possible to rename a table after pushing your schema to Astro Studio.

如果你没有任何重要的生产数据,则可以使用 --force-reset 标志进行 重置数据库。此标志将删除数据库中的所有表并创建新表,以便它与你当前的架构完全匹配。

¥If you do not have any important production data, then you can reset your database using the --force-reset flag. This flag will drop all of the tables in the database and create new ones so that it matches your current schema exactly.

要在保留生产数据的同时重命名表,你必须执行一系列非重大更改,以将本地架构安全地推送到 Astro 工作室。

¥To rename a table while preserving your production data, you must perform a series of non-breaking changes to push your local schema to Astro studio safely.

以下示例将表从 Comment 重命名为 Feedback

¥The following example renames a table from Comment to Feedback:

  1. In your database config file, add the deprecated: true property to the table you want to rename:

    db/config.ts
    const Comment = defineTable({
    deprecated: true,
    columns: {
    author: column.text(),
    body: column.text(),
    }
    });
  2. Add a new table schema (matching the existing table’s properties exactly) with the new name:

    db/config.ts
    const Comment = defineTable({
    deprecated: true,
    columns: {
    author: column.text(),
    body: column.text(),
    }
    });
    const Feedback = defineTable({
    columns: {
    author: column.text(),
    body: column.text(),
    }
    });
  3. Push to Astro Studio with astro db push --remote. This will add the new table and mark the old as deprecated.

  4. Update any of your local project code to use the new table instead of the old table. You might need to migrate data to the new table as well.

  5. Once you are confident that the old table is no longer used in your project, you can remove the schema from your config.ts:

    db/config.ts
    const Comment = defineTable({
    deprecated: true,
    columns: {
    author: column.text(),
    body: column.text(),
    }
    });
    const Feedback = defineTable({
    columns: {
    author: column.text(),
    body: column.text(),
    }
    });
  6. Push to Astro Studio again with astro db push --remote. The old table will be dropped, leaving only the new, renamed table.

Studio feature

你可能需要将数据推送到 Studio 数据库以进行播种或数据迁移。你可以使用 astro:db 模块编写 .ts 文件来编写类型安全查询。然后,使用命令 astro db execute <file-path> --remote 针对你的 Studio 数据库执行该文件:

¥You may need to push data to your Studio database for seeding or data migrations. You can author a .ts file with the astro:db module to write type-safe queries. Then, execute the file against your Studio database using the command astro db execute <file-path> --remote:

可以使用命令 astro db execute db/seed.ts --remote 播种以下注释:

¥The following Comments can be seeded using the command astro db execute db/seed.ts --remote:

db/seed.ts
import { Comment } from 'astro:db';
export default async function () {
await db.insert(Comment).values([
{ authorId: 1, body: 'Hope you like Astro DB!' },
{ authorId: 2, body: 'Enjoy!' },
])
}

See the CLI reference for a complete list of commands.

Studio feature

默认情况下,每当你运行 devbuild 命令时,Astro 都会使用本地数据库文件。运行每个命令时,都会从头开始重新创建表,并插入开发种子数据。

¥By default, Astro will use a local database file whenever you run the dev or build commands. Tables are recreated from scratch when each command is run, and development seed data will be inserted.

要连接到托管的 Studio 数据库,你可以添加 --remote 标志。在生产部署中使用此标志,以便对你的 Studio 数据库进行读写访问。这将允许你 接受并保留用户数据

¥To connect to your hosted Studio database, you can add the --remote flag. Use this flag for production deploys to have both readable and writable access to your Studio database. This will allow you to accept and persist user data.

Terminal window
# Build with a remote connection
astro build --remote
# Develop with a remote connection
astro dev --remote

要使用远程连接,你需要一个应用令牌来通过 Studio 进行身份验证。访问 Studio 仪表板获取令牌创建和设置说明。

¥To use a remote connection, you will need an app token to authenticate with Studio. Visit the Studio dashboard for token creation and setup instructions.

When you’re ready to deploy, see our Deploy with a Studio Connection guide.

从 Astro Studio 迁移到 Turso

Section titled 从 Astro Studio 迁移到 Turso

¥Migrate from Astro Studio to Turso

  1. In the Studio dashboard, navigate to the project you wish to migrate. In the settings tab, use the “Export Database” button to download a dump of your database.
  2. Follow the official instructions to install the Turso CLI and sign up or log in to your Turso account.
  3. Create a new database on Turso using the turso db create command.
    Terminal window
    turso db create [database-name]
  4. Fetch the database URL using the Turso CLI, and use it as the environment variable ASTRO_DB_REMOTE_URL.
    Terminal window
    turso db show [database-name]
    ASTRO_DB_REMOTE_URL=[your-database-url]
  5. Create a token to access your database, and use it as the environment variable ASTRO_DB_APP_TOKEN.
    Terminal window
    turso db tokens create [database-name]
    ASTRO_DB_APP_TOKEN=[your-app-token]
  6. Push your DB schema and metadata to the new Turso database.
    Terminal window
    astro db push --remote
  7. Import the database dump from step 1 into your new Turso DB.
    Terminal window
    turso db shell [database-name] < ./path/to/dump.sql
  8. Once you have confirmed your project connects to the new database, you can safely delete the project from Astro Studio.

Added in: @astrojs/db@0.14.0 New

Astro DB 可以从任何公开服务器的 libSQL 远程协议的平台连接到任何 libSQL 服务器,也可以自行托管。

¥Astro DB can connect to any libSQL server from any platform that exposes the libSQL remote protocol of the server, or can be self-hosted.

要将 Astro DB 连接到 libSQL 数据库,请设置以下环境变量:

¥To connect Astro DB to a libSQL database, set the following environment variables:

  • ASTRO_DB_REMOTE_URL:libSQL 服务器的连接 URL

  • ASTRO_DB_APP_TOKEN:libSQL 服务器的身份验证令牌

使用 libSQL 时,连接到数据库的 用于部署和推送更改的命令 与连接到 Astro Studio 托管数据库时相同。但是,当运行带有 --remote 选项的命令(如 astro buildastro db push)时,你的两个环境变量都需要在本地设置。

¥The commands for deploying and pushing changes to your database are the same when using libSQL as when connecting to an Astro Studio hosted database. However, both of your environment variables need to be set locally when running commands with the --remote option like astro build and astro db push.

libSQL 连接的详细信息(例如加密密钥、复制、同步间隔)可以配置为远程连接 URL 中的查询参数。

¥Details of the libSQL connection (e.g. encryption key, replication, sync interval) can be configured as query parameters in the remote connection URL.

例如,要让本地文件作为加密 libSQL 服务器的嵌入式副本工作,你可以设置以下环境变量:

¥For example, to have a local file work as an embedded replica to an encrypted libSQL server, you can set the following environment variables:

.env
ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io
ASTRO_DB_APP_TOKEN=token-to-your-remote-url

¥URL scheme and host

libSQL 支持 HTTP 和 WebSockets 作为远程服务器的传输协议。它还支持使用本地文件或内存数据库。可以使用连接 URL 中的以下 URL 方案配置这些:

¥libSQL supports both HTTP and WebSockets as the transport protocol for a remote server. It also supports using a local file or an in-memory DB. Those can be configured using the following URL schemes in the connection URL:

  • memory: 将使用内存数据库。在这种情况下,主机必须为空。

  • file: 将使用本地文件。主机是文件的路径(file:path/to/file.db)。

  • libsql: 将通过库首选的协议使用远程服务器(这可能因版本而异)。主机是服务器的地址(libsql://your.server.io)。

  • http: 将通过 HTTP 使用远程服务器。https: 可用于启用安全连接。主机与 libsql: 相同。

  • ws: 将通过 WebSockets 使用远程服务器。wss: 可用于启用安全连接。主机与 libsql: 相同。

libSQL 原生支持加密数据库。传递此搜索参数将使用给定的密钥启用加密:

¥libSQL has native support for encrypted databases. Passing this search parameter will enable encryption using the given key:

.env
ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key

嵌入式副本是 libSQL 客户端的一项功能,可在本地文件或内存中启用数据库的完整同步副本,以实现超快速读取。写入被发送到 syncUrl 上定义的远程数据库并与本地副本同步。

¥Embedded replicas are a feature of libSQL clients that enables a full synchronized copy of your database on a local file or in memory for ultra-fast reads. Writes are sent to a remote database defined on the syncUrl and synchronized with the local copy.

使用此属性传递单独的连接 URL,以将 DB 转换为另一个数据库的嵌入式副本。这只应与方案 file:memory: 一起使用。参数必须是 URL 编码的。

¥Use this property to pass a separate connection URL to turn the DB into an embedded replica of another database. This should only be used with the schemes file: and memory:. The parameter must be URL encoded.

例如,要在 libsql://your.server.io 上拥有数据库的内存嵌入式副本,你可以设置连接 URL 如下:

¥For example, to have an in-memory embedded replica of a database on libsql://your.server.io, you can set the connection URL as such:

.env
ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io

嵌入式副本同步之间的间隔(以秒为单位)。默认情况下,它仅在启动时和写入后同步。

¥Interval between embedded replicas synchronizations in seconds. By default it only synchronizes on startup and after writes.

此属性仅在 syncUrl 也设置时使用。例如,要设置内存嵌入式副本以每分钟同步一次,请设置以下环境变量:

¥This property is only used when syncUrl is also set. For example, to set an in-memory embedded replica to synchronize every minute set the following environment variable:

.env
ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60

¥Building Astro DB integrations

Astro 集成 可以使用额外的 Astro DB 表和种子数据扩展用户项目。

¥Astro integrations can extend user projects with additional Astro DB tables and seed data.

使用 astro:db:setup 钩子中的 extendDb() 方法注册其他 Astro DB 配置和种子文件。defineDbIntegration() 助手为 astro:db:setup 钩子提供 TypeScript 支持和自动补齐功能。

¥Use the extendDb() method in the astro:db:setup hook to register additional Astro DB config and seed files. The defineDbIntegration() helper provides TypeScript support and auto-complete for the astro:db:setup hook.

my-integration/index.ts
import { defineDbIntegration } from '@astrojs/db/utils';
export default function MyIntegration() {
return defineDbIntegration({
name: 'my-astro-db-powered-integration',
hooks: {
'astro:db:setup': ({ extendDb }) => {
extendDb({
configEntrypoint: '@astronaut/my-package/config',
seedEntrypoint: '@astronaut/my-package/seed',
});
},
// Other integration hooks...
},
});
}

集成 configseed 文件遵循与用户定义的等效文件相同的格式。

¥Integration config and seed files follow the same format as their user-defined equivalents.

集成中的类型安全操作

Section titled 集成中的类型安全操作

¥Type safe operations in integrations

在进行集成时,你可能无法从从 astro:db 导出的 Astro 生成的表类型中受益。为了实现完全类型安全,请使用 asDrizzleTable() 实用程序创建可用于数据库操作的表引用对象。

¥While working on integrations, you may not be able to benefit from Astro’s generated table types exported from astro:db. For full type safety, use the asDrizzleTable() utility to create a table reference object you can use for database operations.

例如,给定一个集成设置以下 Pets 数据库表:

¥For example, given an integration setting up the following Pets database table:

my-integration/config.ts
import { defineDb, defineTable, column } from 'astro:db';
export const Pets = defineTable({
columns: {
name: column.text(),
species: column.text(),
},
});
export default defineDb({ tables: { Pets } });

种子文件可以导入 Pets 并使用 asDrizzleTable() 将行插入到表中并进行类型检查:

¥The seed file can import Pets and use asDrizzleTable() to insert rows into your table with type checking:

my-integration/seed.ts
import { asDrizzleTable } from '@astrojs/db/utils';
import { db } from 'astro:db';
import { Pets } from './config';
export default async function() {
const typeSafePets = asDrizzleTable('Pets', Pets);
await db.insert(typeSafePets).values([
{ name: 'Palomita', species: 'cat' },
{ name: 'Pan', species: 'dog' },
]);
}

asDrizzleTable('Pets', Pets) 返回的值相当于 import { Pets } from 'astro:db',但即使 Astro 的类型生成无法运行,它仍然可用。你可以在任何需要查询或插入数据库的集成代码中使用它。

¥The value returned by asDrizzleTable('Pets', Pets) is equivalent to import { Pets } from 'astro:db', but is available even when Astro’s type generation can’t run. You can use it in any integration code that needs to query or insert into the database.

¥Self-hosted production deployment

如果你将站点部署到自管理主机(例如 虚拟专用服务器),则可以选择使用数据库文件,而不是连接到托管在 Astro Studio 上的数据库。

¥If you deploy your site to a self-managed host such as a virtual private server, you can choose to use a database file instead of connecting to a database hosted at Astro Studio.

如果你对风险感到满意,并且可以自己管理部署,则可以使用数据库文件而不是连接到 Studio。

¥If you are comfortable with the risks, and can manage deployment yourself, you can use a database file instead of connecting to Studio.

在构建期间将 ASTRO_DATABASE_FILE 环境变量设置为指向主机环境中的 .db 文件的路径:

¥Set the ASTRO_DATABASE_FILE environment variable to a path pointing to your .db file within the host environment during your build:

Terminal window
ASTRO_DATABASE_FILE=/srv/files/database.db astro build

构建将使用此路径作为生产数据库进行静态编译。当你部署和启动服务器时,它将连接到生产主机上此路径的文件。

¥The build will statically compile with this path as your production database. When you deploy and launch your server it will connect to the file at this path on the production host.

此外,必须使用此环境变量手动管理 推送任何表架构更改(也称为 “架构迁移”)。

¥Additionally, pushing any table schema changes (also known as “schema migrations”) must be managed manually using this environment variable.

Astro 中文网 - 粤ICP备13048890号