25 SQL

原文链接: https://tauri.app/plugin/sql/

为前端提供通过 sqlx 与 SQL 数据库通信的接口,支持 SQLite、MySQL 与 PostgreSQL。

支持的平台

平台支持程度说明
Windows完整支持
Linux完整支持
macOS完整支持
Android完整支持
iOS完整支持

设置

自动

使用你的项目包管理器添加依赖:

1
npm run tauri add sql
1
yarn run tauri add sql
1
pnpm tauri add sql
1
deno task tauri add sql
1
bun tauri add sql
1
cargo tauri add sql

手动

  1. 在 src-tauri 文件夹中运行以下命令,把插件加入 Cargo.toml 里的项目依赖:

    1
    
    cargo add tauri-plugin-sql
    
  2. 修改 lib.rs 初始化插件:

    1
    2
    3
    4
    5
    6
    7
    
    #[cfg_attr(mobile, tauri::mobile_entry_point)]
    pub fn run() {
        tauri::Builder::default()
            .plugin(tauri_plugin_sql::init())
            .run(tauri::generate_context!())
            .expect("error while running tauri application");
    }
    
  3. 用你偏好的 JavaScript 包管理器安装 JavaScript 端绑定:

1
npm install @tauri-apps/plugin-sql
1
yarn add @tauri-apps/plugin-sql
1
pnpm add @tauri-apps/plugin-sql
1
deno add npm:@tauri-apps/plugin-sql
1
bun add @tauri-apps/plugin-sql

用法

该插件的所有 API 都可以通过 JavaScript 端绑定使用:

数据库

路径相对于 tauri::api::path::BaseDirectory::AppConfig。

1
2
3
4
5
6
import Database from '@tauri-apps/plugin-sql';
// 使用 `"withGlobalTauri": true` 时,你可以这样写
// const Database = window.__TAURI__.sql;

const db = await Database.load('sqlite:test.db');
await db.execute('INSERT INTO ...');
1
2
3
4
5
6
import Database from '@tauri-apps/plugin-sql';
// 使用 `"withGlobalTauri": true` 时,你可以这样写
// const Database = window.__TAURI__.sql;

const db = await Database.load('mysql://user:password@host/test');
await db.execute('INSERT INTO ...');
1
2
3
4
5
6
import Database from '@tauri-apps/plugin-sql';
// 使用 `"withGlobalTauri": true` 时,你可以这样写
// const Database = window.__TAURI__.sql;

const db = await Database.load('postgres://user:password@host/test');
await db.execute('INSERT INTO ...');

语法

我们使用 sqlx 作为底层库,并采用它的查询语法。

数据库

替换查询数据时使用 “$#” 语法

1
2
3
4
5
6
7
8
9
const result = await db.execute(
  'INSERT into todos (id, title, status) VALUES ($1, $2, $3)',
  [todos.id, todos.title, todos.status]
);

const result = await db.execute(
  'UPDATE todos SET title = $1, status = $2 WHERE id = $3',
  [todos.title, todos.status, todos.id]
);

替换查询数据时使用 “?”

1
2
3
4
5
6
7
8
9
const result = await db.execute(
  'INSERT into todos (id, title, status) VALUES (?, ?, ?)',
  [todos.id, todos.title, todos.status]
);

const result = await db.execute(
  'UPDATE todos SET title = ?, status = ? WHERE id = ?',
  [todos.title, todos.status, todos.id]
);

替换查询数据时使用 “$#” 语法

1
2
3
4
5
6
7
8
9
const result = await db.execute(
  'INSERT into todos (id, title, status) VALUES ($1, $2, $3)',
  [todos.id, todos.title, todos.status]
);

const result = await db.execute(
  'UPDATE todos SET title = $1, status = $2 WHERE id = $3',
  [todos.title, todos.status, todos.id]
);

迁移

该插件支持数据库迁移,让你可以随时间管理数据库结构的演进。

定义迁移

迁移在 Rust 中使用 Migration 结构体定义。每个迁移都应包含唯一版本号、描述、要执行的 SQL,以及迁移类型(Up 或 Down)。

迁移示例:

1
2
3
4
5
6
7
8
use tauri_plugin_sql::{Migration, MigrationKind};

let migration = Migration {
    version: 1,
    description: "create_initial_tables",
    sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
    kind: MigrationKind::Up,
};

如果你想使用文件中的 SQL,可以用 include_str! 引入:

1
2
3
4
5
6
7
8
use tauri_plugin_sql::{Migration, MigrationKind};

let migration = Migration {
    version: 1,
    description: "create_initial_tables",
    sql: include_str!("../drizzle/0000_graceful_boomer.sql"),
    kind: MigrationKind::Up,
};

把迁移加入插件 Builder

迁移通过插件提供的 Builder 结构体注册。使用 add_migrations 方法,为某个特定数据库连接把你的迁移加入插件。

添加迁移的示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use tauri_plugin_sql::{Builder, Migration, MigrationKind};

fn main() {
    let migrations = vec![
        // 在这里定义你的迁移
        Migration {
            version: 1,
            description: "create_initial_tables",
            sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
            kind: MigrationKind::Up,
        }
    ];

    tauri::Builder::default()
        .plugin(
            tauri_plugin_sql::Builder::default()
                .add_migrations("sqlite:mydatabase.db", migrations)
                .build(),
        )
        ...
}

应用迁移

要在插件初始化时应用迁移,请把连接字符串加入 tauri.conf.json 文件:

1
2
3
4
5
6
7
{
  "plugins": {
    "sql": {
      "preload": ["sqlite:mydatabase.db"]
    }
  }
}

另外,客户端的 load() 也会为给定的连接字符串运行迁移:

1
2
import Database from '@tauri-apps/plugin-sql';
const db = await Database.load('sqlite:mydatabase.db');

请确保迁移按正确顺序定义,并且可以安全地重复运行。

迁移管理

  • 版本控制:每个迁移必须有唯一的版本号。这对确保迁移按正确顺序应用至关重要。
  • 幂等性:以可以安全重复运行、不会引发错误或意外后果的方式编写迁移。
  • 测试:彻底测试迁移,确保它们按预期工作,且不会损害数据库的完整性。

权限

默认情况下,所有有潜在危险的插件命令和作用域都被阻止,无法访问。你必须在 capabilities 配置中修改权限才能启用它们。

更多信息请参阅能力概述,以及使用插件权限的分步指南。

1
2
3
4
5
6
7
{
  "permissions": [
    ...,
    "sql:default",
    "sql:allow-execute"
  ]
}
最后修改 September 26, 2026: 更新 (630b11f59)