Search⌘ K
AI Features

Read and Search Resources

Explore how to read data from databases and implement search functionality in Rust web applications using Diesel. Understand how to efficiently retrieve product information and their variants, and apply filtering techniques to enable searching by product name. Gain practical experience with CRUD operations crucial for scalable backend development.

We'll cover the following...

Reading

The code to obtain data from one resource can be very straightforward if you are used to ORMs.

Rust 1.40.0
use diesel::sqlite::SqliteConnection;
use diesel::result::Error;
use diesel::{QueryDsl, RunQueryDsl};
use ::shoe_store::models::Product;
fn show_product(id: i32, conn: &SqliteConnection) -> Result<Product, Error> {
use ::shoe_store::schema::products::dsl::products;
products
.find(id)
.first(conn)
}

We use first as a translation for LIMIT 1 SQL clause to find the product with the required id. Now, we can create a test.

Rust 1.40.0
use diesel::result::Error;
use diesel::Connection;
use ::shoe_store::establish_connection_test;
use ::shoe_store::models::{Product, NewCompleteProduct, NewProduct, NewVariantValue, NewVariant};
#[test]
fn show_product_test() {
let connection = establish_connection_test();
connection.test_transaction::<_, Error, _>(|| {
let product_id =
create_product(NewCompleteProduct {
product: NewProduct {
name: "boots".to_string(),
cost: 13.23,
active: true
},
variants: vec![
NewVariantValue {
variant: NewVariant {
name: "size".to_string()
},
values: vec![
Some(12.to_string()),
Some(14.to_string()),
Some(16.to_string()),
Some(18.to_string())
]
}
]
}, &connection).unwrap();
assert_eq!(
serde_json::to_string(&show_product(product_id, &connection).unwrap()).unwrap(),
serde_json::to_string(
&Product {
id: 1,
name: "boots".to_string(),
cost: 13.23,
active: true
}
).unwrap()
);
Ok(())
});
}

In the previous code, we use create_product to create a product, then ...