diff --git a/src/content/docs/ja/plugin/positioner.mdx b/src/content/docs/ja/plugin/positioner.mdx new file mode 100644 index 0000000000..aa8833d8a2 --- /dev/null +++ b/src/content/docs/ja/plugin/positioner.mdx @@ -0,0 +1,168 @@ +--- +title: Positioner(ウィンドウ配置) +description: ウィンドウを通常の場所に移動します。 +plugin: positioner +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +ウィンドウをよく知られた場所に配置します。 + +このプラグインは、[electron-positioner](https://github.com/jenslind/electron-positioner) を Tauri に移植したものです。 + +## 対応プラットフォーム + + + +## セットアップ + +はじめに、「positioner」プラグインをインストールしてください。 + +:::note +Rust コードからウィンドウの移動を行なうだけの場合は、`src-tauri/Cargo.toml` 内の依存関係のみが必要です。したがって、以下の「自動」セットアップを選択した場合は `lib.rs` から「プラグインの登録」を削除できます。 +::: + + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + { ' ' } + + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-positioner --target 'cfg(any(target_os = "macos", windows, target_os = "linux"))' + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .setup(|app| { + #[cfg(desktop)] + app.handle().plugin(tauri_plugin_positioner::init()); + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + 3. お好みの JavaScript パッケージ・マネージャーを使用して、「JavaScript Guest」バインディングをインストールします: + + + + + + + +「トレイの相対配置」を機能させるには追加の設定が必要です。 + + + 1. `Cargo.toml` ファイルに `tray-icon` 機能を追加します: + ```toml title="src-tauri/Cargo.toml" ins={2} + [dependencies] + tauri-plugin-positioner = { version = "2.0.0", features = ["tray-icon"] } + ``` + + 2. 「positioner」プラグインに `on_tray_event` を設定します: + ```rust title="src-tauri/src/lib.rs" ins={4-12} + pub fn run() { + tauri::Builder::default() + // これは「トレイ相対配置」を機能させるために必要です + .setup(|app| { + #[cfg(desktop)] + { + app.handle().plugin(tauri_plugin_positioner::init()); + tauri::tray::TrayIconBuilder::new() + .on_tray_icon_event(|tray_handle, event| { + tauri_plugin_positioner::on_tray_event(tray_handle.app_handle(), &event); + }) + .build(app)?; + } + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + + +## 使用法 + +このプラグインの API は、「JavaScript Guest」バインディングを通じて利用できます: + +```javascript +import { moveWindow, Position } from '@tauri-apps/plugin-positioner'; +// `"withGlobalTauri": true` を使用する場合は、 +// const { moveWindow, Position } = window.__TAURI__.positioner; を使用できます + +moveWindow(Position.TopRight); +``` + +Rust を通して Window 特性拡張(trait extention)を直接インポートして使用することができます: + +```rust +use tauri_plugin_positioner::{WindowExt, Position}; + +let mut win = app.get_webview_window("main").unwrap(); +let _ = win.as_ref().window().move_window(Position::TopRight); +``` + +## アクセス権限 Permissions + +デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、`capabilities` 設定でアクセス権限を変更する必要があります。 + +詳細については「[セキュリティ・レベル Capabilities](/ja/security/capabilities/)」の章を参照してください。また、プラグインのアクセス権限を設定するには「[プライグン・アクセス権の使用](/ja/learn/security/using-plugin-permissions/)」の章のステップ・バイ・ステップ・ガイドを参照してください。 + +```json title="src-tauri/capabilities/default.json" ins={4} +{ + "permissions": [ + ..., + "positioner:default", + ] +} +``` + + + +
+ 【※ この日本語版は、「Feb 22, 2025 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/plugin/process.mdx b/src/content/docs/ja/plugin/process.mdx new file mode 100644 index 0000000000..f019fdb0df --- /dev/null +++ b/src/content/docs/ja/plugin/process.mdx @@ -0,0 +1,137 @@ +--- +title: Process(現行プロセス) +description: 現在のプロセスにアクセスします。 +plugin: process +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import PluginPermissions from '@components/PluginPermissions.astro'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +このプラグインは、現在のプロセスにアクセスするための API を提供します。子プロセスを生成するには、[shell](/ja/plugin/shell/)プラグインを参照してください。 + +## 対応プラットフォーム + + + +## セットアップ + +はじめに、「process」プラグインをインストールしてください。 + + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-process + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_process::init()) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + 3. JavaScript でこのプラグインを使用する場合は、npm パッケージもインストールしてください: + + + + + + + + +## 使用法 + +「process」プラグインは、JavaScript と Rust の両方で利用できます。 + + + + +```javascript +import { exit, relaunch } from '@tauri-apps/plugin-process'; +// `"withGlobalTauri": true` を使用する場合は、 +// const { exit, relaunch } = window.__TAURI__.process; を使用できます + +// 指定されたステータス・コードでアプリを終了 +await exit(0); + +// アプリを再起動 +await relaunch(); +``` + + + + +`app` は [`AppHandle`](https://docs.rs/tauri/2.0.0/tauri/struct.AppHandle.html) のインスタンスであることに注意してください。 + +```rust +// 指定されたステータス・コードでアプリを終了 +app.exit(0); + +// アプリを再起動 +app.restart(); +``` + + + + +## アクセス権限 Permissions + +デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、`capabilities` 設定でアクセス権限を変更する必要があります。 + +詳細については「[セキュリティ・レベル Capabilities](/ja/security/capabilities/)」の章を参照してください。また、プラグインのアクセス権限を設定するには「[プライグン・アクセス権の使用](/ja/learn/security/using-plugin-permissions/)」の章のステップ・バイ・ステップ・ガイドを参照してください。 + +```json title="src-tauri/capabilities/default.json" ins={4} +{ + "permissions": [ + ..., + "process:default", + ] +} +``` + + + +
+ 【※ この日本語版は、「Feb 22, 2025 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/plugin/shell.mdx b/src/content/docs/ja/plugin/shell.mdx new file mode 100644 index 0000000000..c65fd621af --- /dev/null +++ b/src/content/docs/ja/plugin/shell.mdx @@ -0,0 +1,169 @@ +--- +title: Shell(シェル・アクセス) +description: システム・シェルにアクセスして子プロセスを生成します。 +plugin: shell +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +システム・シェルにアクセスします。子プロセスの生成が可能になります。 + +## 対応プラットフォーム + + + +## Opener プラグイン + +`shell.open` API のドキュメントをお探しであれば、新しい「[Opener プラグイン](/ja/plugin/opener/)」の章を参照してください。 + +## セットアップ + +はじめに、「shell」プラグインをインストールしてください。 + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + { ' ' } + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-shell + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_shell::init()) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + 3. お好みの JavaScript パッケージ・マネージャーを使用して、「JavaScript Guest」バインディングをインストールします: + + + + + + + +## 使用法 + +「shell」プラグインは JavaScript と Rust の両方で利用できます。 + + + + +```javascript +import { Command } from '@tauri-apps/plugin-shell'; +// `"withGlobalTauri": true` を使用する場合は、 +// const { Command } = window.__TAURI__.shell; を使用できます + +let result = await Command.create('exec-sh', [ + '-c', + "echo 'Hello World!'", +]).execute(); +console.log(result); +``` + + + + +```rust +use tauri_plugin_shell::ShellExt; + +let shell = app_handle.shell(); +let output = tauri::async_runtime::block_on(async move { + shell + .command("echo") + .args(["Hello from Rust!"]) + .output() + .await + .unwrap() +}); +if output.status.success() { + println!("Result: {:?}", String::from_utf8(output.stdout)); +} else { + println!("Exit with code: {}", output.status.code().unwrap()); +} +``` + + + + + +## アクセス権限 Permissions + +デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、`capabilities` 設定でアクセス権限を変更する必要があります。 + +詳細については「[セキュリティ・レベル Capabilities](/ja/security/capabilities/)」の章を参照してください。また、プラグインのアクセス権限を設定するには「[プライグン・アクセス権の使用](/ja/learn/security/using-plugin-permissions/)」の章のステップ・バイ・ステップ・ガイドを参照してください。 + +```json title="src-tauri/capabilities/default.json" ins={6-23} +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "shell:allow-execute", + "allow": [ + { + "name": "exec-sh", + "cmd": "sh", + "args": [ + "-c", + { + "validator": "\\S+" + } + ], + "sidecar": false + } + ] + } + ] +} +``` + + + +
+ 【※ この日本語版は、「Feb 22, 2025 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/plugin/single-instance.mdx b/src/content/docs/ja/plugin/single-instance.mdx new file mode 100644 index 0000000000..26c8fe4c3d --- /dev/null +++ b/src/content/docs/ja/plugin/single-instance.mdx @@ -0,0 +1,228 @@ +--- +title: Single Instance(インスタンスの単一実行) +description: 実行されているあなたの Tauri アプリ・インスタンスが一度に一つだけであることを保証します。 +plugin: single-instance +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +「Single Instance」プラグインを使用して、あなたの Tauri アプリのインスタンスが一度に一つだけ実行されていることを保証します。 + +## 対応プラットフォーム + + + +## セットアップ + +はじめに、「Single Instance」プラグインをインストールしてください。 + + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + {' '} + + + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-single-instance --target 'cfg(any(target_os = "macos", windows, target_os = "linux"))' + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="lib.rs" ins={5-6} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .setup(|app| { + #[cfg(desktop)] + app.handle().plugin(tauri_plugin_single_instance::init(|app, args, cwd| {})); + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + + + + + +:::note + +「Single Instance」プラグインを正常に動作させるためには、このプラグインを登録の先頭に置く必要があります。これにより、他のプラグインが干渉する前に「Single Instance」プラグインが実行されるようになります。 + +::: + +## 使用法 + +このプラグインがもうすでにインストールおよび初期化されていれば、すぐに正しく動作するはずです。ただし、`init()` メソッドを使用して機能を拡張することもできます。 + +プラグインの `init()` メソッドは、新しいアプリのインスタンスが開始されたときに呼び出される「クロージャ」を受け取りますが、このクロージャはプラグインによって閉じられます。 +このクロージャには三つの引数があります: + + + +1. **`app`:** アプリケーションの [AppHandle](https://docs.rs/tauri/2.0.0/tauri/struct.AppHandle.html)。 +2. **`args`:** この新しいインスタンスを開始するためにユーザーによって渡された引数のリスト。 +3. **`cwd`:** 「CWD」(現在の作業ディレクトリ Current Working Directory)は、新しいアプリケーション・インスタンスが起動されたディレクトリを示します。 + + + + + +**クロージャ** closure: 訳「関数閉包」。クロージャとは関数をまとめて/囲んで(バンドル)、その周囲の状態(レキシカル環境)への参照と組み合わせたもので、クロージャは関数にその外側のスコープへアクセスする機能を提供します(プログラム内で環境を共有するための仕組み)。JavaScript では、関数が作成されるたびに、つまり関数の作成時点で、クロージャが作成されます。《[mdn](https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Closures); [wikipedia](https://ja.wikipedia.org/wiki/クロージャ)》 + +**レキシカル環境** lexical environment: 訳「語彙環境」。「レキシカル環境」は仕様上の隠れた内部の関連オブジェクトです(言語仕様の動作説明を行なうための理論上の存在)。このオブジェクトをコード上で取得したり直接操作することはできません。各処理が発生するたびにレキシカル環境は作成され、必要に応じて参照されます。《[Javascript.info ](https://ja.javascript.info/closure#ref-806)、[静的スコープ wikipedia](https://ja.wikipedia.org/wiki/静的スコープ)》 + + + +そこで、「クロージャ」は以下のようになります: + +```rust +.plugin(tauri_plugin_single_instance::init(|app, args, cwd| { + // ここに、あなたのコードを記載します... +})) +``` + +### 新しいインスタンスにフォーカス + +デフォルトでは、アプリケーションが既に実行されている状態で新しいインスタンスを開始しても、何も実行されません。ユーザーが新しいインスタンスを開こうとしたときに、実行中のインスタンスのウィンドウにフォーカスを当てるには、コールバック・クロージャを以下のように変更してください。 + +```rust title="src-tauri/src/lib.rs" {1} {5-12} +use tauri::{AppHandle, Manager}; + +pub fn run() { + let mut builder = tauri::Builder::default(); + #[cfg(desktop)] + { + builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, cwd| { + let _ = app.get_webview_window("main") + .expect("no main window") + .set_focus(); + })); + } + + builder + .run(tauri::generate_context!()) + .expect("error while running tauri application"); +} +``` + +## SnapとFlatpakでの使用 + +Linuxでは、「Single Instance」プラグインは DBus を使用して、実行されるインスタンスが一つだけであることを保証します。この処理は、最初のインスタンスの実行開始時に DBus にサービスを発行することで実現しています。 +その後、後続のインスタンスが同じサービスを発行しようとしたときに、すでに別のサービスが発行されていた場合には、後続のインスタンスは最初のインスタンスに通知を行なうためにすでにあるサービスに要求を送信して、すぐに終了します。 + +これは、アプリが deb か rpm のパッケージ、あるいは AppImage としてバンドルされている場合には非常にうまく機能しますが、snap や flatpak のパッケージでは、デフォルトのままでは意図したとおりに機能しません。これは、これらのパッケージが制約のあるサンドボックス環境で実行されており、パッケージのマニフェストで明示的に宣言されていない限り、DBus サービスへの通信のほとんどがブロックされるためです。 + + + +**DBus** Desktop Bus: 「ディー・バス」。メッセージバスと呼ばれる、アプリケーション間でやりとりを行なうための、プロセス間通信 (IPC) 実装の一つ。プロセスの生成期間を調節し、それらのサービスが必要なときに簡単に呼び出すことができるようにします。《[wikipedia](https://ja.wikipedia.org/wiki/D-Bus)》 + + + +以下は、snap および flatpak パッケージで「Single Instance」プラグインを有効化するために必要なアクセス権限を宣言する手順です: + +### アプリ ID の取得 + +「Single Instance」プラグインは、`org.{id}.SingleInstance` という名前のサービスを発行します。 + +`{id}` は `tauri.conf.json` ファイルの `identifier` になりますが、ドット (`.`) とダッシュ (`-`) は下線 (`_`) に置き換えられます。 + +たとえば、あなたの `identifier` が `net.mydomain.MyApp` である場合: + +- `net_mydomain_MyApp` があなたのアプリの `{id}` であり、 +- `org.net_mydomain_MyApp.SingleInstance` があなたのアプリの「SingleInstance」サービスの名前になります。 + +以下に示すように、アプリに snap や flatpak のマニフェストで DBus サービスを使用することを許可するためには、「サービス名」が必要になります。 + +### Snap パッケージ + +あなたの「snapcraft.yml」ファイルで、「Single Instance」サービス用の「プラグ」と「スロット」を宣言し、アプリの宣言でその両方を使用します: + +```yaml title="snapcraft.yml" +# ... +slots: + single-instance: + interface: dbus + bus: session + name: org.net_mydomain_MyApp.SingleInstance # net_mydomain_MyApp の部分は「あなたのアプリ ID」に変更してください。 + +plugs: + single-instance-plug: + interface: dbus + bus: session + name: org.net_mydomain_MyApp.SingleInstance # net_mydomain_MyApp の部分は「あなたのアプリ ID」に変更してください。 + +# ..... +apps: + my-app: + # ... + plugs: + # .... + - single-instance-plug + slots: + # ... + - single-instance + + # .... +``` + +これにより、あなたのアプリは、期待通りに「Single Instance」プラグインが DBus サービスとの間でリクエストを送受信できるようになります。 + +### Flatpak パッケージ + +あなたの flatpak マニフェスト・ファイル(your.app.id.yml または your.app.id.json)で、「サービス名」を含む `--talk-name` と `--own-name` の終了引数(finish args)を宣言します: + +```yaml title="net.mydomain.MyApp.yml" +# ... +finish-args: + - --socket=wayland + - --socket=fallback-x11 + - --device=dri + - --share=ipc + # .... + - --talk-name=org.net_mydomain_MyApp.SingleInstance # net_mydomain_MyApp の部分は「あなたのアプリ ID」に変更してください。 + - --own-name=org.net_mydomain_MyApp.SingleInstance # net_mydomain_MyApp の部分は「あなたのアプリ ID」に変更してください。 +# ... +``` + +これにより、あなたのアプリで、期待どおりに、「Single Instance」プラグインが DBus サービスとの間でリクエストを送受信できるようになります。 + +## アクセス権限 Permissions + +このプラグインには現在 JavaScript API がないため、これを使用するための [capabilities](/ja/security/capabilities/) の設定を行なう必要はありません。 + +
+ 【※ この日本語版は、「Nov 3, 2025 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/plugin/sql.mdx b/src/content/docs/ja/plugin/sql.mdx new file mode 100644 index 0000000000..cc34f9d790 --- /dev/null +++ b/src/content/docs/ja/plugin/sql.mdx @@ -0,0 +1,358 @@ +--- +title: SQL(エス・キュー・エル) +description: フロントエンドが sqlx を介して SQL データベースと通信するためのインターフェースを提供する Tauri プラグイン。 +plugin: sql +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import PluginPermissions from '@components/PluginPermissions.astro'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +フロントエンドが [sqlx](https://github.com/launchbadge/sqlx) を介して SQL データベースと通信するためのインターフェースを提供するプラグインです。Cargo 機能によって有効化された SQLite、MySQL、PostgreSQL ドライバをサポートしています。 + +## 対応プラットフォーム + + + +## セットアップ + +はじめに、「SQL」プラグインをインストールしてください。 + + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + + + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-sql + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[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"); + } + ``` + + 3. お好みの JavaScript パッケージ・マネージャーを使用して、「JavaScript Guest」バインディングをインストールします: + + + + + + + + +このプラグインをインストールした後、サポートされているデータベース・エンジンを選択する必要があります。 +利用可能なデータベース・エンジンは、「Sqlite」、「MySQL」、「PostgreSQL」です。 +`src-tauri` フォルダーにある以下のコマンドを実行して、利用したいデータベース・エンジンを有効化します: + + + + + ```sh frame=none + cargo add tauri-plugin-sql --features sqlite + ``` + + + + + ```sh frame=none + cargo add tauri-plugin-sql --features mysql + ``` + + + + + ```sh frame=none + cargo add tauri-plugin-sql --features postgres + ``` + + + + +## 使用方法 + +プラグイン API のすべてが、JavaScript Guest バインディングを通して利用できます: + + + + +パスは [`tauri::api::path::BaseDirectory::AppConfig`](https://docs.rs/tauri/2.0.0/tauri/path/enum.BaseDirectory.html#variant.AppConfig) を基準とした相対パスです。 + +```javascript +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 ...'); +``` + + + + +```javascript +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 ...'); +``` + + + + +```javascript +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 ...'); +``` + + + + +## 構文 Syntax + +基本ライブラリとして [sqlx](https://docs.rs/sqlx/latest/sqlx/) を用い、そのクエリ構文を使用します。 + + + +クエリデータを代入するには「$#」構文を使用します + +```javascript +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] +); +``` + + + +クエリデータを代入するには「?」を使用します + +```javascript +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] +); +``` + + + + +クエリデータを代入するには「$#」構文を使用します + +```javascript +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] +); +``` + + + + +## 移行 Migrations + +このプラグインはデータベースの「移行」処理をサポートしており、時間の経過に伴うデータベースの「スキーマ進化」を管理できます。 + + + +**スキーマ進化** schema evolution: 「構造進化」。新しい要件やデータ・モデルの出現に伴い、データベースの構造を時とともに修正していくプロセス。《参考: [IBM](https://www.ibm.com/docs/ja/db2/12.1.0?topic=warehouse-schema-evolution-support); [wikipedia](https://en.wikipedia.org/wiki/Schema_evolution)》 + + + +### 「移行」の定義 + +Rustでは、いくつかの「移行 Migrations」処理が「[`Migration`](https://docs.rs/tauri-plugin-sql/latest/tauri_plugin_sql/struct.Migration.html)構造体」を用いて定義されています。それぞれの移行方式には、「一意のバージョン番号」、「内容説明」、実行する「SQL」、「移行の種類」(Up または Down)を含める必要があります。 + +「移行」の事例: + +```rust +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!` を使用してそのファイルをインクルード(取り込み)できます。 + +```rust +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`](https://docs.rs/tauri-plugin-sql/latest/tauri_plugin_sql/struct.Builder.html) 構造体に登録されます。特定のデータベース接続用の「移行」処理をプラグインに追加するには、`add_migrations` メソッドを使用します。 + +「移行追加」の事例: + +```rust title="src-tauri/src/main.rs" {1} {6-11} {17} +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](https://en.wikipedia.org/wiki/Connection_string)》 + + + +```json title="src-tauri/tauri.conf.json" {3-5} +{ + "plugins": { + "sql": { + "preload": ["sqlite:mydatabase.db"] + } + } +} +``` + +あるいは、クライアント側の `load()` でも、指定された接続文字列の「移行」処理を実行します: + +```ts +import Database from '@tauri-apps/plugin-sql'; +const db = await Database.load('sqlite:mydatabase.db'); +``` + +「移行」処理が正しい順序で定義されており、複数回実行しても安全であることを確認してください。 + +:::note +すべての「移行」処理はトランザクション内で実行されるため、アトミック性が確保されます。「移行」処理が失敗した場合、トランザクション全体がロールバック(巻き戻し/取り消し)され、データベースは一貫性のある状態のままになります。 +::: + + + +**トランザクション** transaction: 「取引・処理」の意味ですが、IT 分野では「コンピュータ内で実行される、分割できない一連の情報処理の一纏まりの単位」を意味します。《参照: [wikipedia](https://ja.wikipedia.org/wiki/トランザクション)》 + +**アトミック性** atomicity: 訳「不可分性/原子性」。トランザクション処理の信頼性を保証するために必要とされる性質。トランザクションに含まれる各タスクの組み合わせ(全操作)は原子(アトム)のように一体で分割できず(=不可分性)、「全てのタスク(全操作)が実行されてトランザクションが完了する」か、「全タスク中のタスクが一つでも失敗した場合には、全てのタスクが取り消される(トランザクションは未完了)」かのどちらかの状態しか許されないこと。 《参考: [wikipedia]()》 + + + +### 「移行」処理の管理 + +- **バージョン管理**: 各「移行]処理には「一意のバージョン番号」が必要です。これは、「移行」処理が正しい順序で適用されることを保証するために不可欠です。 +- **冪等性**(べきとうせい): エラーや予期しない結果を引き起こすことなく安全に再実行できるような方法で「移行」処理を記述します。 +- **テスト**: 「移行」処理が期待どおりに機能し、データベースの整合性が損なわれないことを確認するために、「移行」処理を徹底的にテストします。 + + + +**冪等性** idemotence / idempotency: 読み「べきとうせい」。ある操作を1度行なっても複数回行なっても同じ効果となること。《参考: [wikipedia](https://ja.wikipedia.org/wiki/冪等)》 + + + +## アクセス権限 Permissions + +デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、`capabilities` 設定でアクセス権限を変更する必要があります。 + +詳細については「[セキュリティ・レベル Capabilities](/ja/security/capabilities/)」の章を参照してください。また、プラグインのアクセス権限を設定するには「[プライグン・アクセス権の使用](/ja/learn/security/using-plugin-permissions/)」の章のステップ・バイ・ステップ・ガイドを参照してください。 + +```json title="src-tauri/capabilities/default.json" ins={4-5} +{ + "permissions": [ + ..., + "sql:default", + "sql:allow-execute", + ] +} +``` + + + +
+ +【※ この日本語版は、「Nov 4, 2025 英語版」に基づいています】 + +
diff --git a/src/content/docs/ja/plugin/store.mdx b/src/content/docs/ja/plugin/store.mdx new file mode 100644 index 0000000000..05bcf089bb --- /dev/null +++ b/src/content/docs/ja/plugin/store.mdx @@ -0,0 +1,211 @@ +--- +title: Store(キー値保存) +description: 永続的なキー値の保存。 +plugin: store +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; +import TranslationNote from '@components/i18n/TranslationNote.astro'; + + + +**Plugin 説明内容の英語表記部分について** Plugin の各章は、原文データからページ内容の一部が自動生成されているため、英語表記のままの部分があります。 + + + + + +このプラグインは、「永続的なキー値の保存」を提供します。これは、アプリケーションの状態を管理するための数あるオプションの一つです。これ以外のオプションの詳細については、[状態管理の概要](/ja/develop/state-management/) の章をご覧ください。 + +この「保存 Store」プラグインを使用すると、アプリの状態をファイルに保存・永続化でき、そのファイルはアプリの再起動時などを含め、必要に応じて保存・読み込みできます。このプロセスは非同期であるため、コード内で処理する必要があることに注意してください。WebView でも Rust でも使用できます。 + +## 対応プラットフォーム + + + +## セットアップ + +はじめに、「Store」プラグインをインストールしてください。 + + + + + 自分のプロジェクトのパッケージ・マネージャーを使用して依存関係を追加します: + + + + + + + 1. `src-tauri` フォルダで次のコマンドを実行して、このプラグインを `Cargo.toml` 内のプロジェクトの依存関係に追加します: + + ```sh frame=none + cargo add tauri-plugin-store + ``` + + 2. 追加したプラグインを初期化するために `lib.rs` を修正します: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_store::Builder::new().build()) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + 3. お好みの JavaScript パッケージ・マネージャーを使用して、「JavaScript Guest」バインディングをインストールします: + + + + + + + +## 使用方法 + + + + +```typescript +import { load } from '@tauri-apps/plugin-store'; +// `"withGlobalTauri": true`, を使用する場合は、 +// const { load } = window.__TAURI__.store; を使用できます + +// 新しい「Store」を作成するか、既存の「Store」をロードします。 +// 同じパスを持つ `Store` がすでに作成されている場合には、オプション設定が無視されることに注意してください。 +const store = await load('store.json', { autoSave: false }); + +// キー値を設定 +await store.set('some-key', { value: 5 }); + +// キー値を取得 +const val = await store.get<{ value: number }>('some-key'); +console.log(val); // { value: 5 } + +// 変更を行なった後、「Store」を手動で保存できます。 +// 手動保存しない場合には、正常終了時に保存されます。 +// もし `autoSave`を「数値」に設定するか「空のまま」にしておくと、 +// `autoSave` はデバウンス遅延(デフォルトでは 100 ミリ秒)後に変更内容をディスクに保存します。《下記訳注参照》 +await store.save(); +``` + + + + +```rust title="src-tauri/src/lib.rs" +use tauri::Wry; +use tauri_plugin_store::StoreExt; +use serde_json::json; + +#[cfg_attr(mobile, tauri::mobile_entry_point)] +pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_store::Builder::default().build()) + .setup(|app| { + // 新しい「Store」を作成するか、既存の「Store」をロードします。 + // これにより、「Store」がアプリのリソース・テーブルに追加されます + // そのため、その後の(rust と js の両方からの)`store` 呼び出しは、 + // 同じ「Store」を再利用します。 + let store = app.store("store.json")?; + + // 値は「serde_json::Value」のインスタンスでなければならないことに注意してください。 + // そうしないと、JavaScript バインディングとの互換性がなくなります。 + store.set("some-key", json!({ "value": 5 })); + + // 「store」から値を取得 + let value = store.get("some-key").expect("Failed to get value from store"); + println!("{}", value); // {"value":5} + + // リソース・テーブルから「store」を削除 + store.close_resource(); + + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); +} +``` + + + + + + +**デバウンス遅延** debounce delay: 特定のイベントが短時間に連続して発生(バウンス)した際に(たとえばキーボード入力時のチャタリング)、意図しない余計な入力信号を無視する(デバウンス)ために。タイマーによる処理遅延時間を設定してそのような入力イベントを無視し、最後の入力だけが一度だけ実行されるようにする手法。 + + + +### LazyStore API + +高レベル JavaScript API `LazyStore` もあり、これは最初のアクセス時にのみ「store」をロードします。 + +```typescript +import { LazyStore } from '@tauri-apps/plugin-store'; + +const store = new LazyStore('settings.json'); +``` + +## v1 版/v2 ベータ版(製品候補) からの移行 + + + + +```diff +- import { Store } from '@tauri-apps/plugin-store'; ++ import { LazyStore } from '@tauri-apps/plugin-store'; +``` + + + + +```diff +- with_store(app.handle().clone(), stores, path, |store| { +- store.insert("some-key".to_string(), json!({ "value": 5 }))?; +- Ok(()) +- }); ++ let store = app.store(path)?; ++ store.set("some-key".to_string(), json!({ "value": 5 })); +``` + + + + +## アクセス権限 Permissions + +デフォルトでは、潜在的に危険なプラグイン・コマンドとそのスコープ(有効範囲)はすべてブロックされており、アクセスできません。これらを有効にするには、`capabilities` 設定でアクセス権限を変更する必要があります。 + +詳細については「[セキュリティ・レベル Capabilities](/ja/security/capabilities/)」の章を参照してください。また、プラグインのアクセス権限を設定するには「[プライグン・アクセス権の使用](/ja/learn/security/using-plugin-permissions/)」の章のステップ・バイ・ステップ・ガイドを参照してください。 + +```json title="src-tauri/capabilities/default.json" ins={4} +{ + "permissions": [ + ..., + "store:default", + ] +} +``` + + + +
+ 【※ この日本語版は、「Nov 10, 2025 英語版」に基づいています】 +