From b4c7c3cd480e626ac78b49ab91a95340ccfef26a Mon Sep 17 00:00:00 2001 From: Melody Horn Date: Wed, 30 Jun 2021 15:58:48 -0600 Subject: finish inserting save_mut for models --- src/db/backend/sqlite.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'src/db/backend') diff --git a/src/db/backend/sqlite.rs b/src/db/backend/sqlite.rs index 002d0d3..eb4468c 100644 --- a/src/db/backend/sqlite.rs +++ b/src/db/backend/sqlite.rs @@ -1,6 +1,7 @@ use diesel::connection::Connection as _; pub use barrel::backend::Sqlite as SqlGenerator; +pub use diesel::sqlite::Sqlite as Backend; pub use diesel::sqlite::SqliteConnection as Connection; pub struct Database { @@ -20,3 +21,47 @@ impl Default for Database { } } } + +use diesel::{ + no_arg_sql_function, no_arg_sql_function_body, no_arg_sql_function_body_except_to_sql, QueryId, +}; +no_arg_sql_function!( + last_insert_rowid, + diesel::sql_types::BigInt, + "Represents the SQL last_insert_rowid() function" +); + +use diesel::{ + query_builder::{AsQuery, InsertStatement, QueryFragment, QueryId}, + query_dsl::methods::{FilterDsl, LoadQuery}, + sql_types::BigInt, + Column, Expression, Insertable, Queryable, +}; + +pub fn insert_and_retrieve<'a, Row, Table, Id>( + to_insert: &'a Row, + table: Table, + connection: &Connection, + id: Id, +) -> Row +where + &'a Row: Insertable, + Row: Queryable, + Table: diesel::Table + AsQuery + Copy, + InsertStatement>::Values>: QueryFragment, +
::Query: QueryFragment + + QueryId + + FilterDsl>, + Id: Column + Expression, +
>>::Output: + LoadQuery, +{ + use diesel::prelude::*; + to_insert + .insert_into(table) + .execute(connection) + .expect("error saving to database"); // TODO propagate error + diesel::QueryDsl::filter(table, id.eq(last_insert_rowid)) + .get_result(connection) + .expect("error loading from database") // TODO propagate error +} -- cgit v1.2.3