### Install Tauri SQL Plugin Dependencies Source: https://github.com/tauri-apps/tauri-plugin-sql/blob/v1/README.md Instructions for adding the plugin to a Tauri project via Cargo for the Rust backend and package managers for the JavaScript guest bindings. ```toml [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["sqlite"] ``` ```sh pnpm add https://github.com/tauri-apps/tauri-plugin-sql#v1 ``` -------------------------------- ### Lazy Database Initialization with Database.get() Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Creates a database reference synchronously without connecting immediately. The connection is established automatically upon the first query execution. ```typescript import Database from "tauri-plugin-sql-api"; // Get database reference without connecting const db = Database.get("sqlite:myapp.db"); // Connection established on first query const users = await db.select("SELECT * FROM users"); ``` -------------------------------- ### Connecting to Databases with Database.load() Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Establishes an immediate asynchronous connection to a database. Supports SQLite (relative paths) and MySQL/PostgreSQL (connection strings). ```typescript import Database from "tauri-plugin-sql-api"; // SQLite - path relative to app data directory const sqliteDb = await Database.load("sqlite:test.db"); // MySQL - full connection string const mysqlDb = await Database.load("mysql://user:pass@host/database"); // PostgreSQL - full connection string const postgresDb = await Database.load("postgres://postgres:password@localhost/database"); ``` -------------------------------- ### Configure Database Drivers via Cargo Features Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Illustrates how to enable specific database drivers (SQLite, MySQL, or PostgreSQL) in the Cargo.toml file. Only one driver feature can be active at a time. ```toml # src-tauri/Cargo.toml # For SQLite (most common for desktop apps) [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["sqlite"] # For MySQL [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["mysql"] # For PostgreSQL [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["postgres"] ``` -------------------------------- ### Define and Register Database Migrations Source: https://github.com/tauri-apps/tauri-plugin-sql/blob/v1/README.md Create migration structs in Rust and register them with the plugin builder to manage schema evolution automatically on startup. ```rust use tauri_plugin_sql::{Builder, Migration, MigrationKind}; 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()); ``` -------------------------------- ### Register SQL Plugin in Tauri Source: https://github.com/tauri-apps/tauri-plugin-sql/blob/v1/README.md Initialize the SQL plugin within the main Rust entry point of the Tauri application. ```rust fn main() { tauri::Builder::default() .plugin(tauri_plugin_sql::Builder::default().build()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Execute Database Queries via JavaScript API Source: https://github.com/tauri-apps/tauri-plugin-sql/blob/v1/README.md Load a database connection and perform SQL operations using the JavaScript guest bindings. Syntax varies by driver type ($# for SQLite/Postgres, ? for MySQL). ```javascript import Database from "tauri-plugin-sql-api"; const db = await Database.load("sqlite:test.db"); await db.execute("INSERT INTO todos (id, title, status) VALUES ($1, $2, $3)", [1, "Task", "pending"]); ``` -------------------------------- ### Database Migrations (Rust) Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Registers database migrations to manage schema evolution automatically upon database load. ```APIDOC ## [METHOD] add_migrations() ### Description Registers a list of migrations for a specific database connection. Migrations are applied in order based on their version number. ### Parameters #### Request Body - **version** (integer) - Required - Unique version identifier for the migration. - **description** (string) - Required - Brief description of the migration. - **sql** (string) - Required - The SQL statement to execute. - **kind** (enum) - Required - MigrationKind::Up or MigrationKind::Down. ### Request Example ```rust Migration { version: 1, description: "create_users_table", sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);", kind: MigrationKind::Up, } ``` ``` -------------------------------- ### Retrieving Data with Database.select() Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Executes SELECT queries and returns rows as an array of objects. Supports TypeScript generics for type safety and parameterized queries. ```typescript import Database from "tauri-plugin-sql-api"; interface Todo { id: number; title: string; status: string; } const db = await Database.load("sqlite:test.db"); // Select all records const allTodos = await db.select("SELECT * FROM todos"); // Select with parameters (SQLite/PostgreSQL) const pendingTodos = await db.select( "SELECT * FROM todos WHERE status = $1", ["pending"] ); ``` -------------------------------- ### Handle Query Results in TypeScript Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Explains how to interpret the QueryResult interface returned by execute operations, including row counts and last inserted IDs. It also highlights the specific handling required for PostgreSQL RETURNING clauses. ```typescript import Database from "tauri-plugin-sql-api"; interface QueryResult { rowsAffected: number; lastInsertId: number; } const db = await Database.load("sqlite:test.db"); const result = await db.execute( "INSERT INTO users (name, email) VALUES ($1, $2)", ["John Doe", "john@example.com"] ); console.log(`Inserted user with ID: ${result.lastInsertId}`); console.log(`Rows affected: ${result.rowsAffected}`); // PostgreSQL requires RETURNING to get inserted ID const pgDb = await Database.load("postgres://user:pass@localhost/db"); const [inserted] = await pgDb.select<{ id: number }[]>( "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id", ["John Doe", "john@example.com"] ); console.log(`Inserted user with ID: ${inserted.id}`); ``` -------------------------------- ### Close Database Connections in TypeScript Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Demonstrates how to close specific or all active database connection pools using the Database.close() method. This ensures resources are properly released when database operations are complete. ```typescript import Database from "tauri-plugin-sql-api"; const db = await Database.load("sqlite:test.db"); // Perform operations... await db.execute("INSERT INTO logs (message) VALUES ($1)", ["App closed"]); // Close this specific database connection const success = await db.close("sqlite:test.db"); console.log(`Connection closed: ${success}`); // Or close all database connections await db.close(); ``` -------------------------------- ### QueryResult Interface Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Defines the structure of the object returned after executing SQL statements. ```APIDOC ## [INTERFACE] QueryResult ### Description The result object returned by execute() operations, containing metadata about the executed statement. ### Response #### Success Response (200) - **rowsAffected** (number) - Number of rows affected by the query. - **lastInsertId** (number) - Last inserted ID (always 0 for PostgreSQL). ### Response Example { "rowsAffected": 1, "lastInsertId": 101 } ``` -------------------------------- ### Database.close() Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Closes active database connection pools. Can be used to close a specific database by name or all active connections. ```APIDOC ## [METHOD] Database.close() ### Description Closes the database connection pool. Pass a database name to close a specific connection, or call without arguments to close all database pools. ### Method Async Method ### Parameters #### Query Parameters - **dbName** (string) - Optional - The name of the database connection to close. If omitted, all connections are closed. ### Request Example ```typescript await db.close("sqlite:test.db"); ``` ### Response #### Success Response (200) - **success** (boolean) - Returns true if the connection was successfully closed. ``` -------------------------------- ### Executing Data Modification Queries Source: https://context7.com/tauri-apps/tauri-plugin-sql/llms.txt Performs INSERT, UPDATE, and DELETE operations. Returns a QueryResult containing affected row counts and the last inserted ID. ```typescript import Database from "tauri-plugin-sql-api"; const db = await Database.load("sqlite:test.db"); // SQLite/PostgreSQL syntax uses $1, $2, $3 placeholders const insertResult = await db.execute( "INSERT INTO todos (id, title, status) VALUES ($1, $2, $3)", [1, "Learn Tauri", "pending"] ); // MySQL syntax uses ? placeholders const mysqlDb = await Database.load("mysql://user:pass@host/database"); await mysqlDb.execute( "INSERT INTO todos (id, title, status) VALUES (?, ?, ?)", [1, "Learn Tauri", "pending"] ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.