Using Rust with Diesel, I want to fetch all records of a table. The below code works as intended:
use diesel::{prelude::*};
mod schema {
table! {
organization {
id -> Nullable<Integer>,
name -> Text,
country -> Text,
}
}
}
use self::schema::organization;
use self::schema::organization::dsl::{organization as all_orgs};
#[table_name="organization"]
#[derive(Serialize, Deserialize, Queryable, Insertable, Debug, Clone)]
pub struct Organization {
pub id: Option<i32>,
pub name: String,
pub country: String
}
impl Organization {
pub fn all(conn: &MysqlConnection) -> Vec<Organization> {
all_orgs.load::<Organization>(conn).unwrap()
}
}
However, how would I express this in raw SQL? This is primarily motivated by learning Rust/Diesel together, and wanting to benchmark performance.
Essentially, I want to do use the query:
SELECT id, name, country FROM organization
and parse that into Vec<Organization>
and return that from the given function.
Being new to Rust, I have no idea how to navigate around Diesel and make it happy! Some guidance would be greatly appreciated. I've looked into diesel::sql_query
on here: https://docs.diesel.rs/diesel/fn.sql_query.html, however changing my code to resemble that doesn't make it happy, code example below:
use diesel::{prelude::*, sql_query};
mod schema {
table! {
organization {
id -> Nullable<Integer>,
name -> Text,
country -> Text,
}
}
}
use self::schema::organization;
#[table_name="organization"]
#[derive(Serialize, Deserialize, Queryable, Insertable, Debug, Clone)]
pub struct Organization {
pub id: Option<i32>,
pub name: String,
pub country: String
}
impl Organization {
pub fn all(conn: &MysqlConnection) -> Vec<Organization> {
let orgs = sql_query("SELECT id, name, country FROM organization").load(&conn);
orgs.unwrap()
}
}
It results in a bunch of errors, namely:
error[E0277]: the trait bound `&diesel::MysqlConnection: diesel::Connection` is not satisfied
--> src/org.rs:26:81
|
26 | let orgs = sql_query("SELECT id, name, country FROM organization").load(&conn);
| -^^^^
| |
| the trait `diesel::Connection` is not implemented for `&diesel::MysqlConnection`
| help: consider removing the leading `&`-reference
|
= help: the following implementations were found:
<diesel::MysqlConnection as diesel::Connection>
= note: required because of the requirements on the impl of `LoadQuery<&diesel::MysqlConnection, _>` for `SqlQuery`
error[E0277]: the trait bound `Organization: QueryableByName<_>` is not satisfied
--> src/org.rs:26:76
|
26 | let orgs = sql_query("SELECT id, name, country FROM organization").load(&conn);
| ^^^^ the trait `QueryableByName<_>` is not implemented for `Organization`
|
= note: required because of the requirements on the impl of `LoadQuery<&diesel::MysqlConnection, Organization>` for `SqlQuery`
I'm a bit unsure of how to handle the above -- how do I use sql_query
and map it to the Organization
struct?