Function update

Source
pub fn update<T: SqlQuery + 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 SqlQuery 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 an update object
    let update_user = UpdateUser {
        id: 1,  // User ID to update
        name: "New Name".to_string(),
        email: "new@example.com".to_string(),
        state: 1,
    };
 
    // Execute the update
    let update_result = update(&conn, update_user)?;
    println!("Update result: {:?}", update_result);
    Ok(())
}