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
Section titled “在 Astro 中初始化 Turso”¥Initializing Turso in Astro
¥Prerequisites
配置环境变量
Section titled “配置环境变量”¥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.
TURSO_DATABASE_URL=libsql://...TURSO_AUTH_TOKEN=安装 LibSQL 客户端
Section titled “安装 LibSQL 客户端”¥Install LibSQL Client
安装 @libsql/client 以将 Turso 连接到 Astro:
¥Install the @libsql/client to connect Turso to Astro:
npm install @libsql/clientpnpm add @libsql/clientyarn add @libsql/client初始化新客户端
Section titled “初始化新客户端”¥Initialize a new client
在 src 文件夹中创建一个文件 turso.ts 并调用 createClient,将 TURSO_DATABASE_URL 和 TURSO_AUTH_TOKEN 传递给它:
¥Create a file turso.ts in the src folder and invoke createClient, passing it TURSO_DATABASE_URL and TURSO_AUTH_TOKEN:
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:
---import { turso } from '../turso'
const { rows } = await turso.execute('SELECT * FROM posts')---
<ul> {rows.map((post) => ( <li>{post.title}</li> ))}</ul>SQL 占位符
Section titled “SQL 占位符”¥SQL Placeholders
execute() 方法可以采用 将变量传递给 SQL 语句的对象,例如 slug 或分页。
¥The execute() method can take an object to pass variables to the SQL statement, such as slug, or pagination.
以下示例从 posts 表 WHERE 中获取单个条目,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.
---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 资源
Section titled “Turso 资源”¥Turso Resources