feat: insert works
This commit is contained in:
@@ -8,23 +8,22 @@ use diesel::prelude::*;
|
||||
use diesel::sqlite::SqliteConnection;
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use crate::models::Post;
|
||||
use crate::models::NewPost;
|
||||
|
||||
fn main() {
|
||||
use crate::schema::posts::dsl::*;
|
||||
|
||||
let connection = establish_connection();
|
||||
let results = posts.filter(published.eq(true))
|
||||
.limit(5)
|
||||
.load::<Post>(&connection)
|
||||
.expect("Error loading posts");
|
||||
create_post(&connection, "hello world", "this is a post!");
|
||||
}
|
||||
|
||||
println!("Displaying {} posts", results.len());
|
||||
for post in results {
|
||||
println!("{}", post.title);
|
||||
println!("----------\n");
|
||||
println!("{}", post.body);
|
||||
}
|
||||
pub fn create_post(conn: &SqliteConnection, title: &str, body: &str) -> usize {
|
||||
use crate::schema::posts;
|
||||
|
||||
let new_post = NewPost { title, body };
|
||||
|
||||
diesel::insert_into(posts::table)
|
||||
.values(&new_post)
|
||||
.execute(conn)
|
||||
.expect("Error saving new post")
|
||||
}
|
||||
|
||||
pub fn establish_connection() -> SqliteConnection {
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
use crate::schema::posts;
|
||||
|
||||
#[derive(Queryable)]
|
||||
pub struct Post {
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub body: String,
|
||||
pub published: bool,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name = "posts"]
|
||||
pub struct NewPost<'a> {
|
||||
pub title: &'a str,
|
||||
pub body: &'a str,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user