Functional BytesFunctional Bytes

Setting up the Tauri SQL Plugin

Install the plugin

Installing the plugin is straight forward - just follow the README in the GitHub.

Migrations

This part I was unable to find documentation for but was able to infer how to add them from the code in plugin code (plugin.rs).

The migrations can be added by specifying the database URL and a vector of migrations:

tauri::Builder::default()
    .setup(|app| setup(app))
    .plugin(
        tauri_plugin_sql::Builder::default()
            .add_migrations(
                "sqlite:database_name.db",
                vec![Migration {
                    version: 1,
                    description: "setup tables",
                    sql: include_str!("./migrations/001.setup.sql"),
                    kind: MigrationKind::Up,
                }],
            )
            .build(),
    )
    .run(tauri::generate_context!())
    .expect("error while running tauri application");

For the migration SQL, I've put them in a folder ./migrations and just numbered them sequentially.

I'm still new to rust so this might not be the best approach, but to move the migration definitions out of main.rs I moved it to a module db_migrations.rs:

use tauri_plugin_sql::{Migration, MigrationKind};

pub fn get_migrations() -> Vec<Migration> {
    return vec![Migration {
        version: 1,
        description: "setup tables",
        sql: include_str!("./migrations/001.setup.sql"),
        kind: MigrationKind::Up,
    }];
}

And then in main.rs updated the plugin definition to use this function:

// Include the added module
mod db_migrations;
...
.plugin(
    tauri_plugin_sql::Builder::default()
        .add_migrations(
            "sqlite:database_name.db",
            // Get the migrations using the functin defined in the module
            db_migrations::get_migrations()
        )
        .build(),
)
...

Running Migrations on Launch

This is another part that I was unable to find in the documentation but was able to figure out reading the relevant code in plugin.rs. For each database that you would like to run the migrations for at startup, you can add them to the preload option of the sql plugin configuration in src-tauri/tauri.conf.json:

{
  "build": {
    ...
  },
  ...
  "plugins": {
    "sql": {
      "preload": [
        "sqlite:database_name.db"
      ]
    }
  }
}

References