I want to create a function that uses Diesel to read all the data in postgresql and return it as a Vec
.
Error message
I believe this error message indicates that todos
does not implement the table
function. I don't think it's a problem because I have #[derive(Queryable)]
in the model.
error[E0599]: no function or associated item named `table` found for struct `schema::todos::table` in the current scope --> src/actions.rs:9:42 |9 | let entries: Vec<TodoEntry> = todos::table.load::<TodoEntry>(&connection).expect("Error loading todos"); | ^^^^^ function or associated item not found in `schema::todos::table` | ::: src/schema.rs:1:1 |1 | / table! {2 | | todos (id) {3 | | id -> Int4,4 | | body -> Text,5 | | }6 | | } | |_- function or associated item `table` not found for this | = help: items from traits can only be used if the trait is in scope = note: the following trait is implemented but not in scope; perhaps add a `use` for it: `use crate::diesel::associations::HasTable;`
The relevant code
Cargo.toml
[package]authors = ["hogehogehoge"]edition = "2018"name = "todo"version = "0.1.0"[dependencies]actix-web = "3"askama = "*"thiserror = "*"diesel = { version = "1.4.4", features = ["postgres", "r2d2"] }r2d2 = "0.8"dotenv = "0.15.0"
diesel.toml
[print_schema]file = "src/schema.rs"
actions.rs
This file has a function that returns the data registered in the db as a Vec
.
use diesel::pg::PgConnection;use crate::models;use crate::templates::TodoEntry;pub fn return_all(connection: &PgConnection) -> Result<Vec<TodoEntry>, diesel::result::Error> { use crate::schema::todos::dsl::*; let entries: Vec<TodoEntry> = todos::table.load::<TodoEntry>(&connection).expect("Error loading todos"); Ok(entries)}
templates.rs
This file determines the data type to register in the db and then add the
#[derive(Queryable)]pub struct Todo { pub id: u32, pub text: String,}
schema.rs
table! { todos (id) { id -> Int4, body -> Text, }}