Skip to content

Commit 51c81bb

Browse files
committed
Minimal intermediate cleanup
1 parent 2e48471 commit 51c81bb

8 files changed

Lines changed: 106 additions & 115 deletions

File tree

canyon_macros/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -260,9 +260,9 @@ pub fn canyon_entity(
260260
let mut new_entity = CanyonRegisterEntity::default();
261261
let e = Box::leak(entity.struct_name.to_string().into_boxed_str());
262262
new_entity.entity_name = e;
263-
new_entity.entity_db_table_name = table_name.unwrap_or(
264-
Box::leak(helpers::default_database_table_name_from_entity_name(e).into_boxed_str())
265-
);
263+
new_entity.entity_db_table_name = table_name.unwrap_or(Box::leak(
264+
helpers::default_database_table_name_from_entity_name(e).into_boxed_str(),
265+
));
266266
new_entity.user_schema_name = schema_name;
267267

268268
// The entity fields

canyon_macros/src/utils/helpers.rs

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -21,45 +21,40 @@ pub fn table_schema_parser(macro_data: &MacroTokens<'_>) -> Result<String, Token
2121
let name_values_result: Result<Punctuated<MetaNameValue, Token![,]>, syn::Error> =
2222
attr.parse_args_with(Punctuated::parse_terminated);
2323

24-
match name_values_result {
25-
Ok(meta_name_values) => {
26-
for nv in meta_name_values {
27-
let ident = nv.path.get_ident();
28-
if let Some(i) = ident {
29-
let identifier = i.to_string();
30-
match &nv.lit {
31-
syn::Lit::Str(s) => {
32-
if identifier == "table_name" {
33-
table_name = Some(s.value())
34-
} else if identifier == "schema" {
35-
schema = Some(s.value())
36-
} else {
37-
return Err(
38-
syn::Error::new_spanned(
39-
Ident::new(&identifier, i.span()),
40-
"Only string literals are valid values for the attribute arguments"
41-
).into_compile_error()
42-
);
43-
}
44-
},
45-
_ =>
24+
if let Ok(meta_name_values) = name_values_result {
25+
for nv in meta_name_values {
26+
let ident = nv.path.get_ident();
27+
if let Some(i) = ident {
28+
let identifier = i;
29+
match &nv.lit {
30+
syn::Lit::Str(s) => {
31+
if identifier == "table_name" {
32+
table_name = Some(s.value())
33+
} else if identifier == "schema" {
34+
schema = Some(s.value())
35+
} else {
4636
return Err(
4737
syn::Error::new_spanned(
48-
Ident::new(&identifier, i.span()),
49-
"Only string literals are valid values for the attribute arguments"
38+
Ident::new(&identifier.to_string(), i.span()),
39+
"Only string literals are valid values for the attribute arguments"
5040
).into_compile_error()
51-
),
41+
);
42+
}
5243
}
53-
} else {
54-
return Err(syn::Error::new(
55-
Span::call_site(),
44+
_ => return Err(syn::Error::new_spanned(
45+
Ident::new(&identifier.to_string(), i.span()),
5646
"Only string literals are valid values for the attribute arguments",
5747
)
58-
.into_compile_error());
48+
.into_compile_error()),
5949
}
50+
} else {
51+
return Err(syn::Error::new(
52+
Span::call_site(),
53+
"Only string literals are valid values for the attribute arguments",
54+
)
55+
.into_compile_error());
6056
}
6157
}
62-
Err(_) => return Ok(macro_data.ty.to_string()),
6358
}
6459

6560
let mut final_table_name = String::new();
@@ -70,7 +65,9 @@ pub fn table_schema_parser(macro_data: &MacroTokens<'_>) -> Result<String, Token
7065
if let Some(t_name) = table_name {
7166
final_table_name.push_str(t_name.as_str())
7267
} else {
73-
final_table_name.push_str(macro_data.ty.to_string().as_str())
68+
let defaulted =
69+
&default_database_table_name_from_entity_name(&macro_data.ty.to_string());
70+
final_table_name.push_str(defaulted)
7471
}
7572

7673
return Ok(final_table_name);

canyon_observer/src/constants.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
pub const NUMERIC_PK_DATATYPE: [&str; 6] = ["i16", "u16", "i32", "u32", "i64", "u64"];
22

33
pub mod queries {
4-
pub const INSERT_INTO_CANYON_MEMORY: &str =
4+
pub const INSERT_INTO_CANYON_MEMORY: &str =
55
"INSERT INTO canyon_memory (filepath, struct_name, declared_table_name) \
66
VALUES ($1, $2, $3)";
7-
pub const UPDATE_CANYON_MEMORY: &str =
7+
pub const UPDATE_CANYON_MEMORY: &str =
88
"UPDATE canyon_memory SET filepath = $1, struct_name = $2, \
99
declared_table_name = $3 WHERE id = $4";
10-
pub const DELETE_FROM_CANYON_MEMORY: &str =
11-
"DELETE FROM canyon_memory WHERE struct_name = $1";
10+
pub const DELETE_FROM_CANYON_MEMORY: &str = "DELETE FROM canyon_memory WHERE struct_name = $1";
1211
}
1312

1413
pub mod postgresql_queries {
@@ -180,8 +179,8 @@ pub mod sqlserver_type {
180179
}
181180

182181
pub mod mocked_data {
183-
use canyon_connection::lazy_static::lazy_static;
184182
use crate::migrations::information_schema::{ColumnMetadata, TableMetadata};
183+
use canyon_connection::lazy_static::lazy_static;
185184

186185
lazy_static! {
187186
pub static ref TABLE_METADATA_LEAGUE_EX: TableMetadata = TableMetadata {

canyon_observer/src/lib.rs

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,4 @@ pub static CANYON_REGISTER_ENTITIES: Mutex<Vec<CanyonRegisterEntity<'static>>> =
2525
lazy_static! {
2626
pub static ref QUERIES_TO_EXECUTE: Mutex<HashMap<&'static str, Vec<String>>> =
2727
Mutex::new(HashMap::new());
28-
pub static ref CM_QUERIES_TO_EXECUTE: Mutex<HashMap<&'static str, Vec<(&'static str, Vec<String>)>>> = // TODO Provisional until we parameterize as well the migration queries
29-
Mutex::new(HashMap::new());
3028
}
31-
32-
// TODO replace the unwraps for the operator ? when the appropiated crate will be added
33-
pub fn add_cm_query_to_execute(stmt: &'static str, datasource_name: &'static str, params: Vec<String>) {
34-
if CM_QUERIES_TO_EXECUTE
35-
.lock()
36-
.unwrap()
37-
.contains_key(datasource_name)
38-
{
39-
CM_QUERIES_TO_EXECUTE
40-
.lock()
41-
.unwrap()
42-
.get_mut(datasource_name)
43-
.unwrap()
44-
.push((stmt, params));
45-
} else {
46-
CM_QUERIES_TO_EXECUTE
47-
.lock()
48-
.unwrap()
49-
.insert(datasource_name, vec![(stmt, params)]);
50-
}
51-
}

canyon_observer/src/migrations/handler.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,25 +58,29 @@ impl Migrations {
5858
let database_tables_schema_info = Self::map_rows(schema_status);
5959
// println!("DB tables: {:?}", &database_tables_schema_info);
6060

61-
6261
// We filter the tables from the schema that aren't Canyon entities
6362
let mut user_database_tables = vec![];
6463
for parsed_table in database_tables_schema_info.iter() {
6564
if canyon_memory
6665
.memory
6766
.iter()
68-
.any(|f|
69-
f.declared_table_name.eq(&parsed_table.table_name)
70-
) || canyon_memory
71-
.renamed_entities
72-
.values()
73-
.any(|f| *f == parsed_table.table_name)
67+
.any(|f| f.declared_table_name.eq(&parsed_table.table_name))
68+
|| canyon_memory
69+
.renamed_entities
70+
.values()
71+
.any(|f| *f == parsed_table.table_name)
7472
{
7573
user_database_tables.append(&mut vec![parsed_table]);
7674
}
7775
}
7876

79-
println!("Tables to process: {:?}", user_database_tables.iter().map(|t| &t.table_name).collect::<Vec<_>>());
77+
println!(
78+
"Tables to process: {:?}",
79+
user_database_tables
80+
.iter()
81+
.map(|t| &t.table_name)
82+
.collect::<Vec<_>>()
83+
);
8084

8185
migrations_processor
8286
.process(

canyon_observer/src/migrations/memory.rs

Lines changed: 52 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
use crate::constants;
12
use canyon_crud::bounds::QueryParameter;
23
use canyon_crud::{bounds::RowOperations, crud::Transaction, DatabaseType, DatasourceConfig};
34
use regex::Regex;
45
use std::collections::HashMap;
56
use std::fs;
67
use walkdir::WalkDir;
7-
use crate::constants;
88

99
use super::register_types::CanyonRegisterEntity;
1010

@@ -59,7 +59,10 @@ impl CanyonMemory {
5959
/// Queries the database to retrieve internal data about the structures
6060
/// tracked by `CanyonSQL`
6161
#[allow(clippy::nonminimal_bool)]
62-
pub async fn remember(datasource: &DatasourceConfig<'static>, canyon_entities: &Vec<CanyonRegisterEntity<'_>>) -> Self {
62+
pub async fn remember(
63+
datasource: &DatasourceConfig<'static>,
64+
canyon_entities: &Vec<CanyonRegisterEntity<'_>>,
65+
) -> Self {
6366
// Creates the memory table if not exists
6467
Self::create_memory(datasource.name, &datasource.properties.db_type).await;
6568

@@ -81,7 +84,7 @@ impl CanyonMemory {
8184
};
8285
db_rows.push(db_row);
8386
}
84-
println!("Data in the canyon_memory table: {db_rows:?}");
87+
println!("Data in the canyon_memory table: {db_rows:?}");
8588

8689
// Parses the source code files looking for the #[canyon_entity] annotated classes
8790
let mut mem = Self {
@@ -100,23 +103,25 @@ impl CanyonMemory {
100103
let already_in_db = db_rows.iter().any(|el| {
101104
(el.filepath == _struct.filepath && el.struct_name == _struct.struct_name)
102105
|| ((el.filepath != _struct.filepath && el.struct_name == _struct.struct_name)
103-
|| (el.filepath == _struct.filepath && el.struct_name != _struct.struct_name))
106+
|| (el.filepath == _struct.filepath
107+
&& el.struct_name != _struct.struct_name))
104108
});
105109
if !already_in_db {
106-
match CanyonMemory::query(
107-
constants::queries::INSERT_INTO_CANYON_MEMORY,
108-
&[
109-
&_struct.filepath as &dyn QueryParameter,
110-
&_struct.struct_name,
111-
&_struct.declared_table_name
112-
],
113-
datasource.name
114-
).await {
115-
Ok(v) => println!("Query insert CM OK: {v:?}"),
116-
Err(e) => println!("Error update CM: {e:?}")
117-
}
110+
match CanyonMemory::query(
111+
constants::queries::INSERT_INTO_CANYON_MEMORY,
112+
[
113+
&_struct.filepath as &dyn QueryParameter,
114+
&_struct.struct_name,
115+
&_struct.declared_table_name,
116+
],
117+
datasource.name,
118+
)
119+
.await
120+
{
121+
Ok(v) => println!("Query insert CM OK: {v:?}"),
122+
Err(e) => println!("Error update CM: {e:?}"),
123+
}
118124
}
119-
120125

121126
// When the struct or the filepath it's already on db but one of the two has been modified
122127
let need_to_update = db_rows.iter().find(|el| {
@@ -130,33 +135,38 @@ impl CanyonMemory {
130135

131136
match CanyonMemory::query(
132137
constants::queries::UPDATE_CANYON_MEMORY,
133-
&[
138+
[
134139
&_struct.filepath as &dyn QueryParameter,
135140
&_struct.struct_name,
136141
&_struct.declared_table_name,
137-
&old.id
142+
&old.id,
138143
],
139-
datasource.name
140-
).await {
144+
datasource.name,
145+
)
146+
.await
147+
{
141148
Ok(v) => println!("Query update CM OK: {v:?}"),
142-
Err(e) => println!("Error update CM: {e:?}")
149+
Err(e) => println!("Error update CM: {e:?}"),
143150
}
144151

145152
// if the updated element is the struct name, we add it to the table_rename Hashmap
146153
let rename_table = old.struct_name != _struct.struct_name;
147154

148155
if rename_table {
149156
mem.renamed_entities.insert(
150-
_struct.struct_name.to_string(), // The new one
151-
old.struct_name.to_string(), // The old one
157+
_struct.struct_name.to_string(), // The new one
158+
old.struct_name.to_string(), // The old one
152159
);
153160
}
154161
}
155162
}
156163

157164
// Deletes the records when a table is dropped on the previous Canyon run
158165
db_rows.into_iter().for_each(|db_row| {
159-
if !mem.memory.iter().any(|entity| entity.struct_name == db_row.struct_name)
166+
if !mem
167+
.memory
168+
.iter()
169+
.any(|entity| entity.struct_name == db_row.struct_name)
160170
&& !updates.contains(&db_row.struct_name)
161171
{
162172
// crate::add_cm_query_to_execute(stmt, datasource.name, &[&db_row.struct_name]);
@@ -167,7 +177,10 @@ impl CanyonMemory {
167177

168178
/// Parses the Rust source code files to find the one who contains Canyon entities
169179
/// ie -> annotated with `#[canyon_entity]`
170-
async fn find_canyon_entity_annotated_structs(&mut self, canyon_entities: &Vec<CanyonRegisterEntity<'_>>) {
180+
async fn find_canyon_entity_annotated_structs(
181+
&mut self,
182+
canyon_entities: &[CanyonRegisterEntity<'_>],
183+
) {
171184
for file in WalkDir::new("./src")
172185
.into_iter()
173186
.filter_map(|file| file.ok())
@@ -185,7 +198,9 @@ impl CanyonMemory {
185198
if line.contains("#[") // separated checks for possible different paths
186199
&& line.contains("canyon_entity")
187200
&& !line.starts_with("//")
188-
{ canyon_entity_macro_counter += 1; }
201+
{
202+
canyon_entity_macro_counter += 1;
203+
}
189204

190205
let re = Regex::new(r#"\bstruct\s+(\w+)"#).unwrap();
191206
if let Some(captures) = re.captures(line) {
@@ -198,15 +213,15 @@ impl CanyonMemory {
198213
match canyon_entity_macro_counter {
199214
0 => (),
200215
1 => {
201-
let canyon_entity = canyon_entities.iter()
216+
let canyon_entity = canyon_entities
217+
.iter()
202218
.find(|ce| ce.entity_name == struct_name);
203219
if let Some(c_entity) = canyon_entity {
204-
self.memory.push(
205-
CanyonMemoryAnalyzer {
206-
filepath: file.path().display().to_string().replace('\\', "/"),
207-
struct_name: struct_name.clone(),
208-
declared_table_name: c_entity.entity_db_table_name.to_string() }
209-
)
220+
self.memory.push(CanyonMemoryAnalyzer {
221+
filepath: file.path().display().to_string().replace('\\', "/"),
222+
struct_name: struct_name.clone(),
223+
declared_table_name: c_entity.entity_db_table_name.to_string(),
224+
})
210225
}
211226
}
212227
_ => panic!(
@@ -224,7 +239,7 @@ impl CanyonMemory {
224239
constants::postgresql_queries::CANYON_MEMORY_TABLE
225240
} else {
226241
constants::mssql_queries::CANYON_MEMORY_TABLE
227-
};
242+
};
228243

229244
Self::query(query, [], datasource_name)
230245
.await
@@ -238,13 +253,13 @@ struct CanyonMemoryRow<'a> {
238253
id: i32,
239254
filepath: &'a str,
240255
struct_name: &'a str,
241-
declared_table_name: &'a str
256+
declared_table_name: &'a str,
242257
}
243258

244259
/// Represents the data that will be serialized in the `canyon_memory` table
245260
#[derive(Debug)]
246261
pub struct CanyonMemoryAnalyzer {
247262
pub filepath: String,
248263
pub struct_name: String,
249-
pub declared_table_name: String
264+
pub declared_table_name: String,
250265
}

0 commit comments

Comments
 (0)