Skip to content

Astro DB

Astro DB 是一个完全托管的 SQL 数据库,专为 Astro 生态系统设计。在 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 是配置、开发和查询数据的完整解决方案。每当你运行 astro dev 来管理数据时,都会在 .astro/content.db 中创建本地数据库,而无需 Docker 或网络连接。

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

¥Installation

使用内置的 astro add 命令安装 @astrojs/db 整合

¥Install the @astrojs/db integration using the built-in astro add command:

终端窗口
npx astro add db

¥Define your database

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

¥Installing @astrojs/db with the astro add command will automatically create a db/config.ts file in your project where you will define your database 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.

通过提供现有 libSQL 数据库中数据的结构或你将在新数据库中收集的数据来定义 db/config.ts 文件中的表。这将允许 Astro 生成 TypeScript 接口以从你的项目中查询该表。当你使用属性自动补齐和类型检查访问数据时,结果是完全支持 TypeScript。

¥Define your tables in your db/config.ts file by providing the structure of the data in your existing libSQL database, or the data you will collect in a new database. This will allow Astro to 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. Then, define a name (case-sensitive) for your table and the type of data in each column.

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

¥This example configures a Comment table with required text columns for author and body. Then, makes 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 for development

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

¥In development, Astro will use your DB config to generate local types according to your schemas. These will be generated fresh from your seed file 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.

除非你在开发期间 连接到远程数据库,否则你将无法在开发期间访问生产数据。这可以保护你的数据,同时允许你使用具有类型安全性的工作数据库进行测试和开发。

¥You will not have access to production data during development unless you connect to a remote database during development. This protects your data while allowing you to test and develop with a working database with type-safety.

要将用于测试和调试的开发数据植入 Astro 项目,请创建一个 db/seed.ts 文件。导入 db 对象和 astro: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 your tables defined in astro:db. insert some initial data into each table. This development data should match the form of both your database schema and production data.

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

¥The following example defines two rows of development data for a Comment table, and an Author 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 this development data from seed.ts fresh each time.

连接 libSQL 数据库以进行生产

标题部分 连接 libSQL 数据库以进行生产

¥Connect a libSQL database for production

Astro DB 可以连接到任何本地 libSQL 数据库或任何公开 libSQL 远程协议的服务器,无论是托管的还是自托管的。

¥Astro DB can connect to any local libSQL database or to any server that exposes the libSQL remote protocol, whether managed or self-hosted.

要将 Astro DB 连接到 libSQL 数据库,请设置从数据库提供程序获取的以下环境变量:

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

  • ASTRO_DB_REMOTE_URL:到本地或远程 libSQL DB 位置的连接 URL。这可能包括 URL 配置选项,例如同步和加密作为参数。

  • ASTRO_DB_APP_TOKEN:你的 libSQL 服务器的身份验证令牌。这是远程数据库所必需的,而 本地数据库,如文件或内存 数据库则不需要

根据你的服务,你可能可以访问 CLI 或 Web UI 来检索这些值。以下部分将演示如何连接到 Turso 并设置这些值作为示例,但你可以自由使用任何提供程序。

¥Depending on your service, you may have access to a CLI or web UI to retrieve these values. The following section will demonstrate connecting to Turso and setting these values as an example, but you are free to use any provider.

¥Getting started with Turso

Turso 是 libSQL 背后的公司,libSQL 是为 Astro DB 提供支持的 SQLite 的开源分支。它们提供了一个完全托管的 libSQL 数据库平台,并且与 Astro 完全兼容。

¥Turso is the company behind libSQL, the open-source fork of SQLite that powers Astro DB. They provide a fully managed libSQL database platform and are fully compatible with Astro.

以下步骤将指导你完成安装 Turso CLI、登录(或注册)、创建新数据库、获取所需环境变量以及将架构推送到远程数据库的过程。

¥The steps below will guide you through the process of installing the Turso CLI, logging in (or signing up), creating a new database, getting the required environmental variables, and pushing the schema to the remote database.

  1. Install the Turso CLI.

  2. Log in or sign up to Turso.

  3. Create a new database. In this example the database name is andromeda.

    终端窗口
    turso db create andromeda
  4. Run the show command to see information about the newly created database:

    终端窗口
    turso db show andromeda

    Copy the URL value and set it as the value for ASTRO_DB_REMOTE_URL.

    .env
    ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io
  5. Create a new token to authenticate requests to the database:

    终端窗口
    turso db tokens create andromeda

    Copy the output of the command and set it as the value for ASTRO_DB_APP_TOKEN.

    .env
    ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io
    ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw
  6. Push your DB schema and metadata to the new Turso database.

    终端窗口
    astro db push --remote
  7. Congratulations, now you have a database connected! Give yourself a break. 👾

    终端窗口
    turso relax

要探索 Turso 的更多功能,请查看 Turso 文档

¥To explore more features of Turso, check out the Turso docs.

¥Connecting to remote databases

Astro DB 允许你连接到本地和远程数据库。默认情况下,Astro 使用本地数据库文件执行 devbuild 命令,每次都重新创建表并插入开发种子数据。

¥Astro DB allows you to connect to both local and remote databases. By default, Astro uses a local database file for dev and build commands, recreating tables and inserting development seed data each time.

要连接到托管的远程数据库,请使用 --remote 标志。此标志启用对远程数据库的可读和可写访问,允许你在生产环境中使用 接受并保留用户数据

¥To connect to a hosted remote database, use the --remote flag. This flag enables both readable and writable access to your remote database, allowing you to accept and persist user data in production environments.

配置你的构建命令以使用 --remote 标志:

¥Configure your build command to use the --remote flag:

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

你还可以在命令行中直接使用该标志:

¥You can also use the flag directly in the command line:

终端窗口
# Build with a remote connection
astro build --remote
# Develop with a remote connection
astro dev --remote

--remote 标志在构建期间和服务器上都使用与远程数据库的连接。确保在本地开发环境和部署平台中设置必要的环境变量。

¥The --remote flag uses the connection to the remote DB both locally during the build and on the server. Ensure you set the necessary environment variables in both your local development environment and your deployment platform.

部署 Astro DB 项目时,请确保你的部署平台的构建命令设置为 npm run build(或你的包管理器的等效命令),以利用在你的 package.json 中配置的 --remote 标志。

¥When deploying your Astro DB project, make sure your deployment platform’s build command is set to npm run build (or the equivalent for your package manager) to utilize the --remote flag configured in your package.json.

¥Remote URL configuration options

ASTRO_DB_REMOTE_URL 环境变量配置数据库的位置以及其他选项(如同步和加密)。

¥The ASTRO_DB_REMOTE_URL environment variable configures the location of your database as well as other options like sync and encryption.

¥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 连接的详细信息(例如加密密钥、复制、同步间隔)可以配置为远程连接 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 an encrypted local file work as an embedded replica to a 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

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 creates 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,以将数据库转换为另一个数据库的嵌入副本。这只应与方案 file:memory: 一起使用。参数必须是 URL 编码的。

¥Use this property to pass a separate connection URL to turn the database 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 replica 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

¥Query your database

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

¥You can query your database from any Astro page, endpoint, or action 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 communicate with 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 项目的 按需渲染添加适配器

¥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 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 body = formData.get('body');
if (typeof author === 'string' && typeof body === 'string') {
// Insert form data into the Comment table
await db.insert(Comment).values({ author, body });
}
}
// 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="body">Body</label>
<textarea id="body" name="body"></textarea>
<button type="submit">Submit</button>
</form>
<!-- Render `comments` -->

你还可以使用 Astro 操作 将数据插入 Astro DB 表。以下示例使用操作将一行插入 Comment 表:

¥You can also use Astro actions to insert data into an Astro DB table. The following example inserts a row into a Comment table using an action:

src/actions/index.ts
import { db, Comment } from 'astro:db';
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
export const server = {
addComment: defineAction({
// Actions include type safety with Zod, removing the need
// to check if typeof {value} === 'string' in your pages
input: z.object({
author: z.string(),
body: z.string(),
}),
handler: async (input) => {
const updatedComments = await db
.insert(Comment)
.values(input)
.returning(); // Return the updated comments
return updatedComments;
},
}),
};

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

¥Delete

你还可以从 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 parameter:

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 delete() 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.

将更改推送到数据库

标题部分 将更改推送到数据库

¥Pushing changes to your database

你可以将开发过程中所做的更改推送到数据库。

¥You can push changes made during development to your database.

¥Pushing table schemas

随着项目的增长,你的表模式可能会随时间而变化。你可以安全地在本地测试配置更改,并在部署时推送到远程数据库。

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

你可以使用 astro db push --remote 命令通过 CLI 将本地架构更改推送到远程数据库:

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

终端窗口
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

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

¥If you must change your table schema in a way that is incompatible with your existing data hosted on your remote database, 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:

终端窗口
npm run astro db push --remote --force-reset

¥Renaming tables

将架构推送到远程数据库后,可以重命名表。

¥It is possible to rename a table after pushing your schema to your remote database.

如果你没有任何重要的生产数据,则可以使用 --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.

要在保留生产数据的同时重命名表,你必须执行一系列非破坏性更改,以将本地架构安全地推送到远程数据库。

¥To rename a table while preserving your production data, you must perform a series of non-breaking changes to push your local schema to your remote database 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 your remote database 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 your remote database again with astro db push --remote. The old table will be dropped, leaving only the new, renamed table.

¥Pushing table data

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

¥You may need to push data to your remote 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 remote 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.

¥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.

集成中的类型安全操作

标题部分 集成中的类型安全操作

¥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.

从 Astro Studio 迁移到 Turso

标题部分 从 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.
    终端窗口
    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.
    终端窗口
    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.
    终端窗口
    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.
    终端窗口
    astro db push --remote
  7. Import the database dump from step 1 into your new Turso DB.
    终端窗口
    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.
Astro 中文网 - 粤ICP备13048890号