Function update

Source
pub fn update<T: SqlCommand + UpdateParams>(
    conn: &Connection,
    entity: T,
) -> Result<usize, Error>
Expand description

§update

Updates a record in the database.

§Parameters

  • conn: SQLite database connection
  • entity: The entity to update (must implement SqlCommand and UpdateParams traits)

§Return Value

  • Result<usize, Error>: On success, returns the number of rows affected; on failure, returns Error

§Struct Definition

Structs used with this function should be annotated with the following derive macros:

use parsql_macros::{Updateable, UpdateParams};

#[derive(Updateable, UpdateParams)]  // Required macros
#[table("table_name")]              // Table name to update
#[update("field1, field2")]         // Fields to update
#[where_clause("id = ?")]           // Update condition
pub struct MyEntity {
    pub id: i64,                    // Field used in the where clause
    pub field1: String,             // Fields to update
    pub field2: i32,
}

§Example Usage

use rusqlite::{Connection, Result};
use parsql_macros::{Updateable, UpdateParams};
use parsql_sqlite::update;

fn main() -> Result<()> {
    // Create database connection
    let conn = Connection::open("test.db")?;
    conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, state INTEGER)", [])?;
    conn.execute("INSERT INTO users (id, name, email, state) VALUES (1, 'Old Name', 'old@example.com', 0)", [])?;

    // Define an entity for updating
    #[derive(Updateable, UpdateParams)]
    #[table("users")]
    #[update("name, email")]
    #[where_clause("id = ?")]
    pub struct UpdateUser {
        pub id: i64,
        pub name: String,
        pub email: String,
        pub state: i16,  // Not included in the update
    }

    // Create the update parameters (update user with id 1)
    let update_query = UpdateUser {
        id: 1,
        name: String::from("John Updated"),
        email: String::from("john.updated@example.com"),
        state: 1,
    };

    // Execute update
    let update_result = update(&conn, update_query)?;
    println!("Update result: {:?}", update_result);
    Ok(())
}