Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 9 additions & 16 deletions canyon_crud/src/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ mod postgres_query_launcher {

pub async fn launch<'a, T>(
db_conn: &DatabaseConnection,
// datasource_name: &str,
stmt: String,
params: &'a [&'_ dyn QueryParameter<'_>],
) -> Result<DatabaseResult<T>, Box<(dyn std::error::Error + Send + Sync + 'static)>> {
Expand All @@ -173,21 +172,15 @@ mod postgres_query_launcher {
m_params.push(param.as_postgres_param());
}

let query_result = db_conn
.postgres_connection
.as_ref()
.unwrap()
.client
.query(&stmt, m_params.as_slice())
.await;

if let Err(error) = query_result {
Err(Box::new(error))
} else {
Ok(DatabaseResult::new_postgresql(
query_result.expect("A really bad error happened querying PostgreSQL"),
))
}
Ok(DatabaseResult::new_postgresql(
db_conn
.postgres_connection
.as_ref()
.unwrap()
.client
.query(&stmt, m_params.as_slice())
.await?,
))
}
}

Expand Down
16 changes: 4 additions & 12 deletions canyon_crud/src/query_elements/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,25 +163,18 @@ where

/// Launches the generated query against the database targeted
/// by the selected datasource
#[allow(clippy::question_mark)]
pub async fn query(
&'a mut self,
) -> Result<Vec<T>, Box<(dyn std::error::Error + Sync + Send + 'static)>> {
// Close the query, we are ready to go
self.query.sql.push(';');

let result = T::query(
Ok(T::query(
self.query.sql.clone(),
self.query.params.to_vec(),
self.datasource_name,
)
.await;

if let Err(error) = result {
Err(error)
} else {
Ok(result.ok().unwrap().get_entities::<T>())
}
.await?
.get_entities::<T>())
}

pub fn r#where<Z: FieldValueIdentifier<'a, T>>(&mut self, r#where: Z, op: impl Operator) {
Expand Down Expand Up @@ -511,8 +504,7 @@ where
)
}

let cap = columns.len() * 50; // Reserving an enough initial capacity per set clause
let mut set_clause = String::with_capacity(cap);
let mut set_clause = String::new();
set_clause.push_str(" SET ");

for (idx, column) in columns.iter().enumerate() {
Expand Down
75 changes: 75 additions & 0 deletions canyon_macros/src/canyon_entity_macro.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use proc_macro2::{Span, TokenStream};
use syn::NestedMeta;

pub(crate) fn parse_canyon_entity_proc_macro_attr(
attrs: Vec<NestedMeta>,
) -> (
Option<&'static str>,
Option<&'static str>,
Option<TokenStream>,
) {
let mut table_name: Option<&str> = None;
let mut schema_name: Option<&str> = None;

let mut parsing_attribute_error: Option<TokenStream> = None;

// The parse of the available options to configure the Canyon Entity
for element in attrs {
match element {
syn::NestedMeta::Meta(m) => {
match m {
syn::Meta::NameValue(nv) => {
let attr_arg_ident = nv
.path
.get_ident()
.expect("Something went wrong parsing the `table_name` argument")
.to_string();

if &attr_arg_ident == "table_name" || &attr_arg_ident == "schema" {
match nv.lit {
syn::Lit::Str(ref l) => {
if &attr_arg_ident == "table_name" {
table_name = Some(Box::leak(l.value().into_boxed_str()))
} else {
schema_name = Some(Box::leak(l.value().into_boxed_str()))
}
}
_ => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site(),
"Only string literals are valid values for the attributes"
).into_compile_error());
}
}
} else {
parsing_attribute_error = Some(
syn::Error::new(
Span::call_site(),
format!(
"Argument: `{:?}` are not allowed in the canyon_macro attr",
&attr_arg_ident
),
)
.into_compile_error(),
);
}
}
_ => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site(),
"Only argument identifiers with a value after an `=` sign are allowed on the `canyon_macros::canyon_entity` proc macro"
).into_compile_error());
}
}
}
syn::NestedMeta::Lit(_) => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site(),
"No literal values allowed on the `canyon_macros::canyon_entity` proc macro"
).into_compile_error());
}
}
}

(table_name, schema_name, parsing_attribute_error)
}
68 changes: 5 additions & 63 deletions canyon_macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
extern crate proc_macro;

mod canyon_entity_macro;
mod canyon_macro;
mod query_operations;
mod utils;

use canyon_connection::CANYON_TOKIO_RUNTIME;
use proc_macro::{Span, TokenStream as CompilerTokenStream};
use canyon_entity_macro::parse_canyon_entity_proc_macro_attr;
use proc_macro::TokenStream as CompilerTokenStream;
use proc_macro2::{Ident, TokenStream};
use quote::{quote, ToTokens};
use syn::{DeriveInput, Fields, Type, Visibility};
Expand Down Expand Up @@ -179,68 +181,8 @@ pub fn canyon_entity(
) -> CompilerTokenStream {
let attrs = syn::parse_macro_input!(_meta as syn::AttributeArgs);

let mut table_name: Option<&str> = None;
let mut schema_name: Option<&str> = None;

let mut parsing_attribute_error: Option<TokenStream> = None;

// The parse of the available options to configure the Canyon Entity
for element in &attrs {
match element {
syn::NestedMeta::Meta(m) => {
match m {
syn::Meta::NameValue(nv) => {
let attr_arg_ident = nv
.path
.get_ident()
.expect("Something went wrong parsing the `table_name` argument")
.to_string();

if &attr_arg_ident == "table_name" || &attr_arg_ident == "schema" {
match nv.lit {
syn::Lit::Str(ref l) => {
if &attr_arg_ident == "table_name" {
table_name = Some(Box::leak(l.value().into_boxed_str()))
} else {
schema_name = Some(Box::leak(l.value().into_boxed_str()))
}
}
_ => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site().into(),
"Only string literals are valid values for the attributes"
).into_compile_error());
}
}
} else {
parsing_attribute_error = Some(
syn::Error::new(
Span::call_site().into(),
format!(
"Argument: `{:?}` are not allowed in the canyon_macro attr",
&attr_arg_ident
),
)
.into_compile_error(),
);
}
}
_ => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site().into(),
"Only argument identifiers with a value after an `=` sign are allowed on the `canyon_macros::canyon_entity` proc macro"
).into_compile_error());
}
}
}
syn::NestedMeta::Lit(_) => {
parsing_attribute_error = Some(syn::Error::new(
Span::call_site().into(),
"No literal values allowed on the `canyon_macros::canyon_entity` proc macro"
).into_compile_error());
}
}
}
let (table_name, schema_name, parsing_attribute_error) =
parse_canyon_entity_proc_macro_attr(attrs);

let entity_res = syn::parse::<CanyonEntity>(input);

Expand Down
24 changes: 8 additions & 16 deletions canyon_macros/src/query_operations/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,13 @@ pub fn generate_delete_tokens(macro_data: &MacroTokens, table_schema_data: &Stri
/// the current instance of a T type, returning a result
/// indicating a possible failure querying the database.
async fn delete(&self) -> Result<(), Box<(dyn std::error::Error + Send + Sync + 'static)>> {
let stmt = format!("DELETE FROM {} WHERE {:?} = $1", #table_schema_data, #primary_key);

let result = <#ty as canyon_sql::crud::Transaction<#ty>>::query(
stmt,
<#ty as canyon_sql::crud::Transaction<#ty>>::query(
format!("DELETE FROM {} WHERE {:?} = $1", #table_schema_data, #primary_key),
&[#pk_field_value],
""
).await;
).await?;

if let Err(error) = result {
Err(error)
} else { Ok(()) }
Ok(())
}

/// Deletes from a database entity the row that matches
Expand All @@ -45,17 +41,13 @@ pub fn generate_delete_tokens(macro_data: &MacroTokens, table_schema_data: &Stri
async fn delete_datasource<'a>(&self, datasource_name: &'a str)
-> Result<(), Box<(dyn std::error::Error + Send + Sync + 'static)>>
{
let stmt = format!("DELETE FROM {} WHERE {:?} = $1", #table_schema_data, #primary_key);

let result = <#ty as canyon_sql::crud::Transaction<#ty>>::query(
stmt,
<#ty as canyon_sql::crud::Transaction<#ty>>::query(
format!("DELETE FROM {} WHERE {:?} = $1", #table_schema_data, #primary_key),
&[#pk_field_value],
datasource_name
).await;
).await?;

if let Err(error) = result {
Err(error)
} else { Ok(()) }
Ok(())
}
}
} else {
Expand Down
10 changes: 3 additions & 7 deletions canyon_macros/src/query_operations/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,17 +91,13 @@ pub fn generate_insert_tokens(macro_data: &MacroTokens, table_schema_data: &Stri
#primary_key
);

let result = <#ty as canyon_sql::crud::Transaction<#ty>>::query(
<#ty as canyon_sql::crud::Transaction<#ty>>::query(
stmt,
values,
datasource_name
).await;
).await?;

if let Err(error) = result {
Err(error)
} else {
Ok(())
}
Ok(())
}
};

Expand Down
Loading