SQL(エス・キュー・エル)
Plugin 説明内容の英語表記部分について Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。
フロントエンドが sqlx を介して SQL データベースと通信するためのインターフェースを提供するプラグインです。Cargo 機能によって有効化された SQLite、MySQL、PostgreSQL ドライバをサポートしています。
This plugin requires a Rust version of at least 1.77.2
| Platform | Level | Notes |
|---|---|---|
| windows | ||
| linux | ||
| macos | ||
| android | ||
| ios |
はじめに、「SQL」プラグインをインストールしてください。
自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します:
npm run tauri add sqlyarn run tauri add sqlpnpm tauri add sqldeno task tauri add sqlbun tauri add sqlcargo tauri add sql-
src-tauriフォルダで次のコマンドを実行して、このプラグインをCargo.toml内のプロジェクトの依存関係に追加します:cargo add tauri-plugin-sql -
追加したプラグインを初期化するために
lib.rsを修正します:src-tauri/src/lib.rs #[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {tauri::Builder::default().plugin(tauri_plugin_sql::Builder::default().build()).run(tauri::generate_context!()).expect("error while running tauri application");} -
お好みの JavaScript パッケージ・マネージャーを使用して、「JavaScript Guest」バインディングをインストールします:
npm install @tauri-apps/plugin-sqlyarn add @tauri-apps/plugin-sqlpnpm add @tauri-apps/plugin-sqldeno add npm:@tauri-apps/plugin-sqlbun add @tauri-apps/plugin-sql
このプラグインをインストールした後、サポートされているデータベース・エンジンを選択する必要があります。
利用可能なデータベース・エンジンは、「Sqlite」、「MySQL」、「PostgreSQL」です。
src-tauri フォルダーにある以下のコマンドを実行して、利用したいデータベース・エンジンを有効化します:
cargo add tauri-plugin-sql --features sqlitecargo add tauri-plugin-sql --features mysqlcargo add tauri-plugin-sql --features postgresプラグイン API のすべてが、JavaScript Guest バインディングを通して利用できます:
パスは tauri::api::path::BaseDirectory::AppConfig を基準とした相対パスです。
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 ...');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 ...');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 を用い、そのクエリ構文を使用します。
クエリデータを代入するには「$#」構文を使用します
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]);クエリデータを代入するには「?」を使用します
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]);クエリデータを代入するには「$#」構文を使用します
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]);このプラグインはデータベースの「移行」処理をサポートしており、時間の経過に伴うデータベースの「スキーマ進化」を管理できます。
スキーマ進化 schema evolution: 「構造進化」。新しい要件やデータ・モデルの出現に伴い、データベースの構造を時とともに修正していくプロセス。《参考: IBM; wikipedia》
Rustでは、いくつかの「移行 Migrations」処理が「Migration構造体」を用いて定義されています。それぞれの移行方式には、「一意のバージョン番号」、「内容説明」、実行する「SQL」、「移行の種類」(Up または Down)を含める必要があります。
「移行」の事例:
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! を使用してそのファイルをインクルード(取り込み)できます。
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,};「移行 Migrations」処理は、プラグインが提供する Builder 構造体に登録されます。特定のデータベース接続用の「移行」処理をプラグインに追加するには、add_migrations メソッドを使用します。
「移行追加」の事例:
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(), ) ...}プラグインが初期化される時に「移行 migrations」処理を適用するには、「接続文字列 connection string」を tauri.conf.json ファイルに追加します:
接続文字列 connection string: データ・ソースに関する情報とそれに接続する方法を指定する文字列。 《参考: wikipedia》
{ "plugins": { "sql": { "preload": ["sqlite:mydatabase.db"] } }}あるいは、クライアント側の load() でも、指定された接続文字列の「移行」処理を実行します:
import Database from '@tauri-apps/plugin-sql';const db = await Database.load('sqlite:mydatabase.db');「移行」処理が正しい順序で定義されており、複数回実行しても安全であることを確認してください。
トランザクション transaction: 「取引・処理」の意味ですが、IT 分野では「コンピュータ内で実行される、分割できない一連の情報処理の一纏まりの単位」を意味します。《参照: wikipedia》
アトミック性 atomicity: 訳「不可分性/原子性」。トランザクション処理の信頼性を保証するために必要とされる性質。トランザクションに含まれる各タスクの組み合わせ(全操作)は原子(アトム)のように一体で分割できず(=不可分性)、「全てのタスク(全操作)が実行されてトランザクションが完了する」か、「全タスク中のタスクが一つでも失敗した場合には、全てのタスクが取り消される(トランザクションは未完了)」かのどちらかの状態しか許されないこと。 《参考: wikipedia》
- バージョン管理: 各「移行]処理には「一意のバージョン番号」が必要です。これは、「移行」処理が正しい順序で適用されることを保証するために不可欠です。
- 冪等性(べきとうせい): エラーや予期しない結果を引き起こすことなく安全に再実行できるような方法で「移行」処理を記述します。
- テスト: 「移行」処理が期待どおりに機能し、データベースの整合性が損なわれないことを確認するために、「移行」処理を徹底的にテストします。
冪等性 idemotence / idempotency: 読み「べきとうせい」。ある操作を1度行なっても複数回行なっても同じ効果となること。《参考: wikipedia》
デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、capabilities 設定でアクセス権限を変更する必要があります。
詳細については「セキュリティ・レベル Capabilities」の章を参照してください。また、プラグインのアクセス権限を設定するには「プライグン・アクセス権の使用」の章のステップ・バイ・ステップ・ガイドを参照してください。
{ "permissions": [ ..., "sql:default", "sql:allow-execute", ]}Default Permission
Default Permissions
This permission set configures what kind of database operations are available from the sql plugin.
Granted Permissions
All reading related operations are enabled. Also allows to load or close a connection.
This default permission set includes the following:
allow-closeallow-loadallow-select
Permission Table
| Identifier | Description |
|---|---|
|
|
Enables the close command without any pre-configured scope. |
|
|
Denies the close command without any pre-configured scope. |
|
|
Enables the execute command without any pre-configured scope. |
|
|
Denies the execute command without any pre-configured scope. |
|
|
Enables the load command without any pre-configured scope. |
|
|
Denies the load command without any pre-configured scope. |
|
|
Enables the select command without any pre-configured scope. |
|
|
Denies the select command without any pre-configured scope. |
【※ この日本語版は、「Nov 4, 2025 英語版」に基づいています】
© 2025 Tauri Contributors. CC-BY / MIT