Skip to content

Commit

Permalink
added an article to demonstrate how to use sqlite with tauri apps on …
Browse files Browse the repository at this point in the history
…the rust side
  • Loading branch information
mohamedeliwa committed Mar 3, 2025
1 parent 86fda60 commit bcc569f
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions content/posts/how_to_use_sqlx_with_tauri.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
+++
title = "How to use SQLX (SQLite) with Tauri (Rust side)"
description = "How to install SQLx with the SQLite feature and use it with Tauri, focusing on the Rust side."
weight = 1
date = "2025-03-03"

[extra]
+++

This article demonstrates how to install SQLx with the SQLite feature and use it with Tauri, focusing on the Rust side.

## Install SQLx

To install SQLx with the Tokio runtime and SQLite support, add the following to the `[dependencies]` section of your `src-tauri/Cargo.toml` file:

```toml
[dependencies]
# SQLx with Tokio (no TLS) and SQLite support
sqlx = { version = "0.8", features = [ "runtime-tokio", "sqlite"] }
```

## Connect to the Database

Create an asynchronous method to establish a connection to the SQLite database and return a connection pool:

```rs
async fn establish_connection() -> SqlitePool {
SqlitePoolOptions::new()
.max_connections(5)
.connect("sqlite://")
.await
.expect("Unable to connect to SQLite database")
}
```

## Store the Connection Pool

Create a struct to store the database connection pool:

```rs
struct AppData {
db_pool: SqlitePool,
}
```

Next, initialize the connection pool:

```rs
// Create a connection pool
let db_pool: SqlitePool = block_on(establish_connection());
```

Store the connection pool in the application state:

```rs
app.manage(AppData { db_pool });
```

## Access the Database in an Async Command

To interact with the database from an asynchronous command, define a Tauri command like this:

```rs
#[tauri::command]
async fn db_test(state: State<'_, AppData>) -> Result<(), String> {
// You can now interact with the database using `state.db_pool`
Ok(())
}
```

0 comments on commit bcc569f

Please sign in to comment.