0

Im new to learning Rust. I am trying to create a POS as a side project for myself. I have a couple different sqlite database tables that match to these rust structs. These are the important ones for this question. Excuse the weird names I will refactor later.


pub struct TransactionFull {
    transaction_table: Transaction,
    transaction_customer: Customer,
    transaction_row: TransactionRow,
}

pub struct Transaction {
    pub id: String,
    pub number: String,
    pub date: String,
    pub cost: f32,
    pub tax: f32,
    pub customer: Option<String>, //customer_id
    pub message: Option<String>,
}

pub struct TransactionRow{
    pub id: String,
    pub transaction_id: String,
    pub product: String, //product_id
    pub quantity: f32,
    pub price_per_unit: f32,
}

pub struct Customer {
    pub id: String,
    pub name: String,
    pub active: bool,
    pub company: Option<String>,
    pub billing_address: Option<String>,
    pub phone_number: Option<String>,
    pub alt_contact: Option<String>,
    pub credit_available: Option<String>,
    pub percent_disc: Option<i32>,
}

This creates a one to many relationship between Transaction and TransactionRow as each transaction can have many products at a custom price.

When I try to fetch these from the database (local) my code looks something like this

// this is paraphrased to reduce length
let sql = "SELECT ... FROM transaction_table INNER JOIN transaction_row ... LEFT JOIN customer ...";

let mut stmt = db.prepare(&sql)?;
let rows = stmt.query_map([], |row| {
    let transaction_table = Transaction{} // uses row.get() to fill fields
    let transaction_row= TransactionRow{} // uses row.get() to fill fields
    let transaction_customer= Customer{} // uses row.get() to fill fields

    let transaction_full = TransactionFull{
         transaction_table,
         transaction_row,
         transaction_customer,
    }

    Ok(())
}

I have populated these tables so that this query should return four rows, as there are two transactions with two transaction rows each. One transaction has a customer and one doesn't. The weird bit here is that with a left join and transaction_customer && transaction_full I get one row returned. With a left join and no transaction_customer or transaction_full I get 4 rows returned as expected.

Firstly it would be nice to be able to make TransactionFull take a Vec instead of having to map the results of this again.

Secondly I can't figure out why the decisions I make in query_map (mapping the customer) seem to effect the rows from the query which hasn't changed

0 Answers0