Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Use SQLite In A Tauri App

NOTE : This does not at all feel like the best way to do things. I tried using : [TODO: Code shorthand span ] 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

[TODO: Code shorthand span ]

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 [TODO: Code shorthand span ] here, but it doesn't look like it on first blush

Add this to [TODO: Code shorthand span ]

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 [TODO: Code shorthand span ] to the tauri setup in [TODO: Code shorthand span ] like :

rust
#![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");
}

Footnotes And References