Turso
本指南讨论使用 Prisma ORM 和 Turso 背后的概念,解释 Turso 与其他数据库提供商之间的共性和差异,并引导你完成配置应用以与 Turso 集成的过程。
¥This guide discusses the concepts behind using Prisma ORM and Turso, explains the commonalities and differences between Turso and other database providers, and leads you through the process for configuring your application to integrate with Turso.
Prisma ORM 对 Turso 的支持目前处于 抢先体验 阶段。我们非常感谢你对此 GitHub 讨论 的反馈。
¥Prisma ORM support for Turso is currently in Early Access. We would appreciate your feedback in this GitHub discussion.
什么是 Turso?
¥What is Turso?
Turso 是一个边缘托管的分布式数据库,基于 库 SQL(SQLite 的开源和开放贡献分支),使你能够使数据更接近你的应用并最大限度地减少查询延迟。Turso 也可以托管在远程服务器上。
¥Turso is an edge-hosted, distributed database that's based on libSQL, an open-source and open-contribution fork of SQLite, enabling you to bring data closer to your application and minimize query latency. Turso can also be hosted on a remote server.
Prisma ORM 版本 5.4.2 及更高版本的 抢先体验 中提供了对 Turso 的支持。
¥Support for Turso is available in Early Access from Prisma ORM versions 5.4.2 and later.
与其他数据库提供商的共同点
¥Commonalities with other database providers
libSQL 与 SQLite 100% 兼容。libSQL 扩展了 SQLite 并添加了以下特性和功能:
¥libSQL is 100% compatible with SQLite. libSQL extends SQLite and adds the following features and capabilities:
-
支持复制
¥Support for replication
-
支持自动备份
¥Support for automated backups
-
能够将 Turso 作为其他程序(例如 Linux 内核)的一部分嵌入
¥Ability to embed Turso as part of other programs such as the Linux kernel
-
支持用户自定义函数
¥Supports user-defined functions
-
支持异步 I/O
¥Support for asynchronous I/O
要了解有关 libSQL 之间的差异以及它与 SQLite 有何不同的更多信息,请参阅 libSQL 声明。
¥To learn more about the differences between libSQL and how it is different from SQLite, see libSQL Manifesto.
将 Prisma ORM 与 Turso 结合使用的许多方面就像将 Prisma ORM 与任何其他关系数据库结合使用一样。你仍然可以:
¥Many aspects of using Prisma ORM with Turso are just like using Prisma ORM with any other relational database. You can still:
-
使用 Prisma 模式语言 为你的数据库建模
¥model your database with the Prisma Schema Language
-
在你的架构中使用 Prisma ORM 的现有
sqlite
数据库连接器¥use Prisma ORM's existing
sqlite
database connector in your schema -
在你的应用中使用 Prisma 客户端 与 Turso 的数据库服务器通信
¥use Prisma Client in your application to talk to the database server at Turso
需要考虑的差异
¥Differences to consider
Turso 和 SQLite 之间有许多差异需要考虑。在决定使用 Turso 和 Prisma ORM 时,你应该注意以下几点:
¥There are a number of differences between Turso and SQLite to consider. You should be aware of the following when deciding to use Turso and Prisma ORM:
-
远程和嵌入式 SQLite 数据库。libSQL 使用 HTTP 连接到远程 SQLite 数据库。libSQL 还支持远程数据库副本和嵌入式副本。嵌入式副本使你能够在应用内复制主数据库。
¥Remote and embedded SQLite databases. libSQL uses HTTP to connect to the remote SQLite database. libSQL also supports remote database replicas and embedded replicas. Embedded replicas enable you to replicate your primary database inside your application.
-
进行架构更改。由于 libSQL 使用 HTTP 连接到远程数据库,这使得它与 Prisma Migrate 不兼容。但是,你可以使用
prisma migrate diff
创建架构迁移,然后使用 Turso CLI 将更改应用到数据库。¥Making schema changes. Since libSQL uses HTTP to connect to the remote database, this makes it incompatible with Prisma Migrate. However, you can use
prisma migrate diff
to create a schema migration and then apply the changes to your database using Turso's CLI.
如何连接和查询 Turso 数据库
¥How to connect and query a Turso database
后续部分介绍如何创建 Turso 数据库、检索数据库凭据以及连接到数据库。
¥The subsequent section covers how you can create a Turso database, retrieve your database credentials and connect to your database.
如何配置数据库并检索数据库凭据
¥How to provision a database and retrieve database credentials
如果你没有现有数据库,可以通过运行以下命令来配置数据库:
¥If you don't have an existing database, you can provision a database by running the following command:
turso db create turso-prisma-db
上面的命令将在距离你所在位置最近的区域创建一个数据库。
¥The above command will create a database in the closest region to your location.
运行以下命令来检索数据库的连接字符串:
¥Run the following command to retrieve your database's connection string:
turso db show turso-prisma-db
接下来,创建一个允许你连接到数据库的身份验证令牌:
¥Next, create an authentication token that will allow you to connect to the database:
turso db tokens create turso-prisma-db
使用身份验证令牌和连接字符串更新 .env
文件:
¥Update your .env
file with the authentication token and connection string:
TURSO_AUTH_TOKEN="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..."
TURSO_DATABASE_URL="libsql://turso-prisma-db-user.turso.io"
如何连接到 Turso 数据库
¥How to connect to a Turso database
首先,启用 driverAdapters
预览功能标志:
¥To get started, enable the driverAdapters
Preview feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "sqlite"
url = "file:./dev.db" // will be ignored
}
生成 Prisma 客户端:
¥Generate Prisma Client:
npx prisma generate
安装 libSQL 包的 Prisma ORM 驱动程序适配器:
¥Install the Prisma ORM driver adapter for libSQL packages:
npm install @prisma/adapter-libsql
更新你的 Prisma 客户端实例:
¥Update your Prisma Client instance:
import { PrismaClient } from '@prisma/client'
import { PrismaLibSQL } from '@prisma/adapter-libsql'
const adapter = new PrismaLibSQL({
url: `${process.env.TURSO_DATABASE_URL}`,
authToken: `${process.env.TURSO_AUTH_TOKEN}`,
})
const prisma = new PrismaClient({ adapter })
你可以像平常一样使用 Prisma Client,并在项目中实现完全类型安全。
¥You can use Prisma Client as you normally would with full type-safety in your project.
在 prisma.config.ts
中通过驱动适配器使用 Prisma Migrate(抢先体验版)
¥Using Prisma Migrate via a driver adapter in prisma.config.ts
(Early Access)
从 v6.6.0 开始,你可以使用 prisma.config.ts
文件来更改数据库架构。
¥As of v6.6.0 and with a prisma.config.ts
file, you can use prisma db push
to make changes to your database schema.
此功能已在 抢先体验 和 v6.6.0 中引入,并支持以下命令:
¥This functionality has been introduced in Early Access in v6.6.0 and supports the following commands:
-
prisma db push
-
prisma db pull
-
prisma migrate diff
其他命令,例如 prisma migrate dev
和 prisma migrate deploy
,即将添加。
¥Other commands like prisma migrate dev
and prisma migrate deploy
will be added soon.
1. 安装 LibSQL 驱动适配器
¥ Install the LibSQL driver adapter
在终端中运行此命令:
¥Run this command in your terminal:
npm install @prisma/adapter-libsql
2. 设置环境变量
¥ Set environment variables
为了设置 LibSQL 适配器,你需要向 .env
文件添加一些密钥:
¥In order to set up the LibSQL adapter, you'll need to add a few secrets to a .env
file:
-
LIBSQL_DATABASE_URL
:Turso 数据库实例的连接 URL。¥
LIBSQL_DATABASE_URL
: The connection URL of your Turso database instance. -
LIBSQL_DATABASE_TOKEN
:你的 Turso 数据库实例的 token。¥
LIBSQL_DATABASE_TOKEN
: The token of your Turso database instance.
然后,你可以将这些文件添加到你的 .env
文件中,或者如果它们存储在不同的密钥存储中,则直接使用它们:
¥You can then add these to your .env
file or use them directly if they are stored in a different secret store:
LIBSQL_DATABASE_URL="..."
LIBSQL_DATABASE_TOKEN="..."
3. 设置 Prisma 配置文件
¥ Set up Prisma Config file
确保你的项目有一个 prisma.config.ts
文件。然后,设置 迁移驱动程序适配器 以使用 PrismaLibSQL
:
¥Make sure that you have a prisma.config.ts
file for your project. Then, set up the migration driver adapter to use PrismaLibSQL
:
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import { PrismaLibSQL } from '@prisma/adapter-libsql'
// import your .env file
import 'dotenv/config'
type Env = {
LIBSQL_DATABASE_URL: string
LIBSQL_DATABASE_TOKEN: string
}
export default defineConfig<Env>({
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),
migrate: {
async adapter(env) {
return new PrismaLibSQL({
url: env.LIBSQL_DATABASE_URL,
authToken: env.LIBSQL_DATABASE_TOKEN,
})
}
}
})
4. 迁移数据库
¥ Migrate your database
Prisma Migrate 现在将根据 prisma.config.ts
中提供的配置针对你的远程 Turso 数据库运行迁移。
¥Prisma Migrate now will run migrations against your remote Turso database based on the configuration provided in prisma.config.ts
.
要使用此工作流创建你的第一个迁移,请运行以下命令:
¥To create your first migration with this workflow, run the following command:
npx prisma db push
嵌入式 Turso 数据库副本
¥Embedded Turso database replicas
Turso 支持 嵌入式复制品。Turso 的嵌入式副本使你能够在应用内拥有主远程数据库的副本。嵌入式副本的行为与本地 SQLite 数据库类似。数据库查询速度更快,因为你的数据库位于应用内部。
¥Turso supports embedded replicas. Turso's embedded replicas enable you to have a copy of your primary, remote database inside your application. Embedded replicas behave similarly to a local SQLite database. Database queries are faster because your database is inside your application.
嵌入式数据库副本如何工作
¥How embedded database replicas work
当你的应用最初建立与数据库的连接时,主数据库将完成查询:
¥When your app initially establishes a connection to your database, the primary database will fulfill the query:
Turso 将 (1) 在你的应用中创建一个嵌入式副本,并 (2) 将数据从主数据库复制到副本,以便在本地可用:
¥Turso will (1) create an embedded replica inside your application and (2) copy data from your primary database to the replica so it is locally available:
嵌入式副本将满足后续的读取查询。libSQL 客户端提供了一个 sync()
方法,你可以调用该方法来确保嵌入式副本的数据保持最新。
¥The embedded replica will fulfill subsequent read queries. The libSQL client provides a sync()
method which you can invoke to ensure the embedded replica's data remains fresh.
通过嵌入式副本,这种设置可以保证应用的响应速度,因为数据可以在本地轻松获得并且访问速度更快。
¥With embedded replicas, this setup guarantees a responsive application, because the data will be readily available locally and faster to access.
与你可能熟悉的只读副本设置一样,写入操作会转发到主远程数据库并在传播到所有嵌入式副本之前执行。
¥Like a read replica setup you may be familiar with, write operations are forwarded to the primary remote database and executed before being propagated to all embedded replicas.
-
写操作传播被转发到数据库。
¥Write operations propagation are forwarded to the database.
-
数据库用 1 开始的更新响应服务器。
¥Database responds to the server with the updates from 1.
-
写操作将传播到数据库副本。
¥Write operations are propagated to the database replica.
你的应用的数据需求将决定你应该在远程数据库和嵌入式数据库副本之间同步数据的频率。例如,你可以使用中间件函数(例如 Express 和 Fastify)或 cron 作业来同步数据。
¥Your application's data needs will determine how often you should synchronize data between your remote database and embedded database replica. For example, you can use either middleware functions (e.g. Express and Fastify) or a cron job to synchronize the data.
如何在远程数据库和嵌入式副本之间同步数据
¥How to synchronize data between your remote database and embedded replica
要开始将嵌入式副本与 Prisma ORM 结合使用,请在应用中添加 libSQL 中的 sync()
方法。下面的示例展示了如何使用 Express 中间件同步数据。
¥To get started using embedded replicas with Prisma ORM, add the sync()
method from libSQL in your application. The example below shows how you can synchronize data using Express middleware.
import express from 'express'
const app = express()
// ... the rest of your application code
app.use(async (req, res, next) => {
await libsql.sync()
next()
})
app.listen(3000, () => console.log(`Server ready at http://localhost:3000`))
它也可以作为 Prisma 客户端扩展 实现。以下示例显示执行创建、更新或删除操作后的自动同步。
¥It could be also implemented as a Prisma Client extension. The below example shows auto-syncing after create, update or delete operation is performed.
const prisma = new PrismaClient().$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
const result = await query(args)
// Synchronize the embedded replica after any write operation
if (['create', 'update', 'delete'].includes(operation)) {
await libsql.sync()
}
return result
}
}
}
})