home ~ projects ~ socials

Use SQLite In A Tauri App

NOTE: This does not at all feel like the best way to do things. I tried using: tauri::PathResolver but couldn't figure out how to get it to work.

Also, bascially don't use these notes yet, there still a work in progress, but I'm trying to get othet stuff working too


Create a new Tauri App

cargo create-tauri-app

Fill out the stuff


cd into the new direcory

Do:

npm add https://github.com/tauri-apps/tauri-plugin-sql#v1

Might need to do npm install here, but it doesn't look like it on first blush


Add this to src-tauri/Cargo.toml

// NOTE: THis isn't necessary, I don't think
// but 
[dependencies.tauri-plugin-sql]
git = "https://github.com/tauri-apps/plugins-workspace"
branch = "v1"
features = ["sqlite"]

Add .plugin(tauri_plugin_sql::Builder::default().build()) to the tauri setup in src-tauri/src/main.rs like:

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use dirs;
use rusqlite::{params, Connection, Result};
use std::fs;
use std::path::PathBuf;

fn init_db() {
    if !db_path().exists() {
        match create_db() {
            Ok(_) => println!("Created Database"),
            Err(e) => println!("{}", e),
        }
    } else {
        println!("Database already exists");
    }
}

fn create_db() -> Result<()> {
    println!("Creating database");
    let db_path = db_path();
    let db_dir = db_path.parent().unwrap();
    if !db_dir.exists() {
        fs::create_dir_all(db_dir).unwrap();
    }
    let conn = Connection::open(db_path.to_str().unwrap())?;
    conn.execute(
        "CREATE TABLE widget (
            id INTEGER PRIMARY KEY,
            item TEXT NOT NULL
        )",
        (),
    )?;
    conn.execute("INSERT INTO widget (item) VALUES (?1)", params!["alfa"])?;
    conn.execute("INSERT INTO widget (item) VALUES (?1)", params!["bravo"])?;
    Ok(())
}

#[tauri::command]
fn db_path() -> PathBuf {
    let home_dir = dirs::home_dir().unwrap();
    PathBuf::from(
        home_dir.to_str().unwrap().to_string() + "/.config/sqlite_tauri_test/database.sqlite",
    )
}

fn main() {
    tauri::Builder::default()
        .setup(|_app| {
            init_db();
            Ok(())
        })
        .plugin(tauri_plugin_sql::Builder::default().build())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
-- end of line --

References