Skip to content

Turso 和 Astro

Turso 是一个基于 libSQL(SQLite 的一个分支)构建的分布式数据库。它针对低查询延迟进行了优化,使其适用于全球应用。

¥Turso is a distributed database built on libSQL, a fork of SQLite. It is optimized for low query latency, making it suitable for global applications.

在 Astro 中初始化 Turso

标题部分 在 Astro 中初始化 Turso

¥Initializing Turso in Astro

¥Prerequisites

  • Turso CLI 已安装并登录

  • 带有架构的 Turso 数据库

  • 你的数据库 URL

  • 访问令牌

¥Configure environment variables

使用以下命令获取你的数据库 URL:

¥Obtain your database URL using the following command:

终端窗口
turso db show <database-name> --url

为数据库创建一个身份验证令牌:

¥Create an auth token for the database:

终端窗口
turso db tokens create <database-name>

将上述两个命令的输出添加到项目根目录下的 .env 文件中。如果此文件不存在,请创建一个。

¥Add the output from both commands above into your .env file at the root of your project. If this file does not exist, create one.

.env
TURSO_DATABASE_URL=libsql://...
TURSO_AUTH_TOKEN=

¥Install LibSQL Client

安装 @libsql/client 以将 Turso 连接到 Astro:

¥Install the @libsql/client to connect Turso to Astro:

终端窗口
npm install @libsql/client

¥Initialize a new client

src 文件夹中创建一个文件 turso.ts 并调用 createClient,将 TURSO_DATABASE_URLTURSO_AUTH_TOKEN 传递给它:

¥Create a file turso.ts in the src folder and invoke createClient, passing it TURSO_DATABASE_URL and TURSO_AUTH_TOKEN:

src/turso.ts
import { createClient } from "@libsql/client/web";
export const turso = createClient({
url: import.meta.env.TURSO_DATABASE_URL,
authToken: import.meta.env.TURSO_AUTH_TOKEN,
});

¥Querying your database

要从数据库访问信息,请在任何 .astro 组件内导入 turso执行 SQL 查询

¥To access information from your database, import turso and execute a SQL query inside any .astro component.

以下示例从你的表中获取所有 posts,然后在 <BlogIndex /> 组件中显示标题列表:

¥The following example fetches all posts from your table, then displays a list of titles in a <BlogIndex /> component:

src/components/BlogIndex.astro
---
import { turso } from '../turso'
const { rows } = await turso.execute('SELECT * FROM posts')
---
<ul>
{rows.map((post) => (
<li>{post.title}</li>
))}
</ul>

¥SQL Placeholders

execute() 方法可以采用 将变量传递给 SQL 语句的对象,例如 slug 或分页。

¥The execute() method can take an object to pass variables to the SQL statement, such as slug, or pagination.

以下示例从 postsWHERE 中获取单个条目,slug 是从 Astro.params 中检索到的值,然后显示帖子的标题。

¥The following example fetches a single entry from the posts table WHERE the slug is the retrieved value from Astro.params, then displays the title of the post.

src/pages/index.astro
---
import { turso } from '../turso'
const { slug } = Astro.params
const { rows } = await turso.execute({
sql: 'SELECT * FROM posts WHERE slug = ?',
args: [slug!]
})
---
<h1>{rows[0].title}</h1>

¥Turso Resources

更多后端服务指南

Astro 中文网 - 粤ICP备13048890号