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 --- tosin-macros/src/lib.rs | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) (limited to 'tosin-macros') diff --git a/tosin-macros/src/lib.rs b/tosin-macros/src/lib.rs index ff62f3d..1019540 100644 --- a/tosin-macros/src/lib.rs +++ b/tosin-macros/src/lib.rs @@ -82,17 +82,24 @@ fn to_field_spec(field: &syn::Field) -> FieldInfo { } } else if field_type == &parse_type("Id") { // TODO foreign key constraint + FieldInfo { + tosin_field: quote! { ::tosin::db::models::Field::IntField { name: stringify!(#field_name) } }, + diesel_column: quote! { #field_name -> BigInt }, + diesel_type: quote! { ::tosin::db::sql_types::BigInt }, + } + } else if field_type == &parse_type("u64") { + // TODO allow at all since some dbs can't express that type FieldInfo { tosin_field: quote! { ::tosin::db::models::Field::IntField { name: stringify!(#field_name) } }, diesel_column: quote! { #field_name -> Integer }, diesel_type: quote! { ::tosin::db::sql_types::Integer }, } - } else if field_type == &parse_type("usize") { + } else if field_type == &parse_type("i64") { // TODO default FieldInfo { tosin_field: quote! { ::tosin::db::models::Field::IntField { name: stringify!(#field_name) } }, - diesel_column: quote! { #field_name -> Integer }, - diesel_type: quote! { ::tosin::db::sql_types::Integer }, + diesel_column: quote! { #field_name -> BigInt }, + diesel_type: quote! { ::tosin::db::sql_types::BigInt }, } } else if field_type == &parse_type("String") { let max_length = model_options @@ -211,13 +218,22 @@ fn impl_model(ast: &syn::DeriveInput) -> TokenStream { } } - pub fn save_mut(&mut self, connection: &mut tosin::db::backend::Connection) { + pub fn save_mut(&mut self, connection: &tosin::db::backend::Connection) { + use diesel::prelude::*; if self.id.is_none() { // no id yet, so not from db, so insert - let new_self = tosin::db::insert_into(#lowercase_name::table) - .values(&self) - .get_result(connection) - .expect("error saving to database"); // TODO propagate error + // unfortunately InsertStatement::get_result is only supported on pg for now, + // so we have to pull this shit + let new_self = tosin::db::backend::insert_and_retrieve::< + Self, // row + #lowercase_name::table, // table + #lowercase_name::id, // id + >( + self, + #lowercase_name::table, + connection, + #lowercase_name::id + ); *self = new_self; } else { todo!("update existing db item"); @@ -246,6 +262,7 @@ fn impl_model(ast: &syn::DeriveInput) -> TokenStream { type Values = <(#(#insertable_types,)*) as tosin::db::Insertable<#lowercase_name::table>>::Values; fn values(self) -> Self::Values { + use diesel::ExpressionMethods; (#(#insertable_values,)*).values() } } -- cgit v1.2.3