Welcome to the Tauri crud tutorial Wiki!

ยท

8 min read

 yellow crab vs green cow

Introduction

This Wiki is your central hub for all documentation related to the Tauri crud tutorial. Whether you're a developer, contributor, or user, you'll find valuable information here to help you understand and navigate our project.

Sections

  • Tauri Prerequisites

  • Create Table

  • Edit Table

Tauri Prerequisites

Before you begin working with Tauri, make sure you have the following prerequisites installed on your system:

Ensure you follow the Tauri guide for getting started to install the necessary tools:

Node.js

Tauri and many of its associated tools require Node.js. If you don't have Node.js installed, you can download it from the official website:

Please make sure you have Node.js installed on your system before proceeding with the Tauri setup.

Other Prerequisites

Depending on your project and platform, you may also need other specific dependencies. Refer to the Tauri documentation for platform-specific requirements.

With these prerequisites in place, you'll be ready to start working with Tauri and building powerful cross-platform applications.

Getting Started: Vite with Tauri

If you prefer to use the Vite build tool with Tauri, you can follow the steps below to get started. Please note that you can also use the npm create tauri-app command, which simplifies the setup process. However, we recommend reading this guide to understand the setup.

Follow the Tauri Tutorial

To set up Tauri with Vite, follow the Tauri tutorial for Vite setup:

This tutorial will walk you through the necessary steps to configure Vite and Tauri for your project. It provides detailed instructions on creating a Tauri application with Vite, so you can get started quickly.

Use npm create tauri-app

As mentioned earlier, you can use the following command to create a Tauri application with Vite:

npm create tauri-app@latest

This command will set up a new Tauri project with Vite, saving you time and effort in the initial setup.

By following the Tauri Vite setup tutorial or using the npm create tauri-app command, you'll be on your way to building powerful cross-platform applications with Tauri and Vite.

Happy coding!

Creating a Table with Tauri, Vue.js, and Rusqlite

Step 1: Project Structure

In your project structure, you should have the following files and directories:

src/App.vue

<template>
  <!-- ... -->
</template>

<script setup>
// ... Import statements
</script>

<style scoped>
</style>

src/components/CreateTable.vue

<template>
  <!-- ... -->
</template>

<script>
// ... Vue component script
</script>

src-tauri/src/main.rs

Step 2: Create the Create Table Component

In src/App.vue, import and use the CreateTable component:

<template>
  <div class="container">
    <header>
      <h1>Tauri CRUD Example</h1>
      <p>A simple CRUD application using Tauri and Rust's Rusqlite</p>
    </header>
    <main>
      <section>
        <h2>Create Table Component</h2>
        <CreateTable />
      </section>
    </main>
  </div>
</template>

<script setup>
import CreateTable from "./components/CreateTable.vue";
</script>

<style scoped>
</style>

Step 3: Implement the Create Table Component

In src/components/CreateTable.vue, create a button to create the table:

<template>
  <div>
    <h1>Create Table</h1>
    <button @click="createTable">Create Table</button>
  </div>
</template>

<script>
import { invoke } from '@tauri-apps/api/tauri';

export default {
  methods: {
    async createTable() {
      try {
        const response = await invoke('create_table');
        console.log('Table created:', response);
      } catch (error) {
        console.error('Error creating table:', error);
      }
    },
  },
};
</script>

Step 4: Implement the Rust Function

In Cargo.toml, add the Rusqlite dependency:

[dependencies]
rusqlite = "0.29.0"

In src-tauri/src/main.rs, implement the Rust function to create the table:

use rusqlite::{Connection, params};
use serde::{Deserialize, Serialize};
use tauri::Result;

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
struct PacketInfo {
    mac_source: String,
    mac_destination: String,
    ethertype: String,
    ip_source: String,
    ip_destination: String,
    protocol: String,
    port_source: String,
    port_destination: String,
    count: u32,
}

#[tauri::command]
fn create_table() -> Result<()> {
    // Open a connection to the SQLite database
    let conn = Connection::open("my_database.db").unwrap();

    // Create a table to store data
    conn.execute(
        "CREATE TABLE IF NOT EXISTS packet_info (
            id INTEGER PRIMARY KEY,
            mac_source TEXT,
            mac_destination TEXT,
            ethertype TEXT,
            ip_source TEXT,
            ip_destination TEXT,
            protocol TEXT,
            port_source TEXT,
            port_destination TEXT,
            count INTEGER
        )",
        [],
    ).unwrap();
    println!("Table created.");
    Ok(())
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![create_table])
        .run(tauri::generate_context!())
        .expect("Error while running Tauri application");
}

Conclusion

In this tutorial, you have learned how to create a table using Tauri, Vue.js, and Rusqlite. You can now initiate the table creation by clicking the "Create Table" button in your application.

Feel free to customize and extend this example to build more complex CRUD functionality with Tauri.

Editing a Table with Tauri, Vue.js, and Rusqlite

In this tutorial, we will learn how to edit existing records in a table using Tauri, Vue.js, and the Rusqlite database. We'll build upon the previous tutorial, Creating a Table with Tauri, Vue.js, and Rusqlite, where we created a table.

Prerequisites

Before starting this tutorial, ensure that you have completed the prerequisites mentioned in the Tauri documentation.

Step 1: Project Structure

In your project structure, you should already have the following files and directories:

  • src/App.vue

  • src/components/EditTable.vue

  • src-tauri/src/main.rs

If you don't have these files, refer to the previous tutorial to set up your project structure.

Step 2: Create the Edit Table Component

In src/App.vue, import and use the EditTable component:

      <section>
        <h2>Add Packet Info Component</h2>
        <EditTable />
      </section>
import EditTable from "./components/EditTable.vue";

Step 3: Implement the Edit Table Component

In src/components/EditTable.vue, create a form to edit existing records in the table:

<template>
    <div>
      <h2>Add Packet Information</h2>
      <form @submit.prevent="submitForm">
        <div class="form-group">
          <label for="mac_source">MAC Source:</label>
          <input type="text" id="mac_source" v-model="packetInfo.mac_source" required />
        </div>
        <div class="form-group">
          <label for="mac_destination">MAC Destination:</label>
          <input type="text" id="mac_destination" v-model="packetInfo.mac_destination" required />
        </div>
        <!-- Add other form fields for PacketInfo properties -->
        <button type="submit">Add Packet Info</button>
      </form>
    </div>
  </template>

  <script>
  import { invoke } from '@tauri-apps/api'

  export default {
    data() {
      return {
        packetInfo: {
          mac_source: "",
          mac_destination: "",
          ethertype: "",
          ip_source: "",
          ip_destination: "",
          protocol: "",
          port_source: "",
          port_destination: "",
          count: 0,
        },
      };
    },
    methods: {
      async submitForm() {
        try {
          // Send the packetInfo object to Rust for insertion
          invoke('insert_packet_info', {packet_info: this.packetInfo})
          .then((response) => console.log(response))
        } catch (error) {
          console.error(error);
          alert("An error occurred while adding packet info.");
        }
      },
    },
  };
  </script>

  <style scoped>
  /* Add your component-specific styles here */
  </style>

Step 4: Implement the Rust Function

In src-tauri/src/main.rs, implement the Rust function to edit the table records. You can modify the existing create_table command to handle edits.

#[tauri::command(rename_all = "snake_case")]
fn insert_packet_info(packet_info: PacketInfo) -> Result<()> {
    println!("I was invoked from JS, with this message: {:?}", &packet_info);
    // Open a connection to the SQLite database
    let conn = Connection::open("my_database.db").unwrap();

    // Insert the provided `PacketInfo` into the table
    conn.execute(
        "INSERT INTO packet_info (mac_source, mac_destination, ethertype, ip_source, ip_destination, protocol, port_source, port_destination, count)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
        params![
            packet_info.mac_source,
            packet_info.mac_destination,
            packet_info.ethertype,
            packet_info.ip_source,
            packet_info.ip_destination,
            packet_info.protocol,
            packet_info.port_source,
            packet_info.port_destination,
            packet_info.count,
        ],
    ).unwrap();

    Ok(())
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![create_table,insert_packet_info])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Conclusion

In this tutorial, you have learned how to set up the structure for editing a table in a Tauri, Vue.js, and Rusqlite project. You can customize the EditTable component and the Rust function edit_table to handle specific editing operations for your application.

Feel free to extend this example to build a full CRUD application with Tauri and Rusqlite, allowing users to create, read, update, and delete records in the database.

Continue exploring Tauri and Vue.js to create powerful desktop applications with embedded databases.

Get a Table with Tauri, Vue.js, and Rusqlite

In this tutorial, we will learn how to get existing records in a table using Tauri, Vue.js, and the Rusqlite database. We'll build upon the previous tutorial, editing a Table with Tauri, Vue.js, and Rusqlite, where we edited a table.

Step 1: Project Structure

In your project structure, you should already have the following files and directories:

  • src/App.vue

  • src/components/GetTable.vue

  • src-tauri/src/main.rs

If you don't have these files, refer to the previous tutorial to set up your project structure.

Step 2: Create the Edit Table Component

In src/App.vue, import and use the GetTable component:

      <section>
        <h2>Get Table Component</h2>
        <GetTable />
      </section>
import GetTable from "./components/GetTable.vue";

Step 3: Implement the Edit Table Component

In src/components/GetTable.vue, create a form to edit existing records in the table:

<template>
    <div>
      <h1>Packet Information</h1>
      <button @click="createTable">Get</button>
      <ul>
        <li v-for="packetInfo in packetInfoList" :key="packetInfo.id">
          <span><strong>MAC Source:</strong> {{ packetInfo.mac_source }}</span><br>
          <span><strong>MAC Destination:</strong> {{ packetInfo.mac_destination }}</span><br>
        </li>
      </ul>
    </div>
  </template>


<script>
  import { invoke } from '@tauri-apps/api/tauri';

  export default {
    data() {
      return {
        packetInfoList: [], // Store retrieved packet information here
      };
    },
    methods: {
      async createTable() {
        try {
          // Now fetch the data from the database using another command
          this.packetInfoList = await invoke('get_packet_infos');

        } catch (error) {
          console.error(error);
        }
      },
    },
  };
</script>

Step 4: Implement the Rust Function

In src-tauri/src/main.rs, implement the Rust function to edit the table records. You can modify the existing create_table command to handle edits.

#[tauri::command]
fn get_packet_infos() -> Result<Vec<PacketInfo>> {
    // Open a connection to the SQLite database
    let conn = Connection::open("my_database.db").unwrap();

    // Retrieve data from the table
    let mut stmt = conn.prepare("SELECT * FROM packet_info").unwrap();
    let packet_info_iter = stmt.query_map([], |row| {
        Ok(PacketInfo {
            mac_source: row.get(1)?,
            mac_destination: row.get(2)?,
            ethertype: row.get(3)?,
            ip_source: row.get(4)?,
            ip_destination: row.get(5)?,
            protocol: row.get(6)?,
            port_source: row.get(7)?,
            port_destination: row.get(8)?,
            count: row.get(9)?,
        })
    }).unwrap();

    let mut packet_infos = Vec::new();

    for packet_info in packet_info_iter {
        packet_infos.push(packet_info.unwrap());
    }

    Ok(packet_infos)
}

Conclusion

In this tutorial, you have learned how to set up the structure for editing a table in a Tauri, Vue.js, and Rusqlite project. You can customize the EditTable component and the Rust function edit_table to handle specific editing operations for your application.

Feel free to extend this example to build a full CRUD application with Tauri and Rusqlite, allowing users to create, read, update, and delete records in the database.

Continue exploring Tauri and Vue.js to create powerful desktop applications with embedded databases.

Did you find this article valuable?

Support Cyprien AVICO by becoming a sponsor. Any amount is appreciated!

ย