forked from zerodaycode/Canyon-SQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor.rs
More file actions
1600 lines (1423 loc) · 66.9 KB
/
Copy pathprocessor.rs
File metadata and controls
1600 lines (1423 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///! File that contains all the datatypes and logic to perform the migrations
///! over a target database
use async_trait::async_trait;
use canyon_crud::DatabaseType;
use regex::Regex;
use std::fmt::Debug;
use std::{ops::Not, sync::MutexGuard};
use crate::constants::regex_patterns;
use crate::memory::CanyonMemory;
use crate::QUERIES_TO_EXECUTE;
use canyon_crud::crud::Transaction;
use super::information_schema::{TableMetadata, ColumnMetadata};
use super::register_types::{CanyonRegisterEntity, CanyonRegisterEntityField};
/// Responsible of generating the queries to sync the database status with the
/// Rust source code managed by Canyon, for succesfully make the migrations
#[derive(Debug, Default)]
pub struct MigrationsProcessor {
operations: Vec<Box<dyn DatabaseOperation>>,
set_primary_key_operations: Vec<Box<dyn DatabaseOperation>>,
drop_primary_key_operations: Vec<Box<dyn DatabaseOperation>>,
constraints_operations: Vec<Box<dyn DatabaseOperation>>,
}
impl Transaction<Self> for MigrationsProcessor {}
impl MigrationsProcessor {
pub async fn process<'a>(
&'a mut self,
canyon_memory: CanyonMemory,
canyon_entities: Vec<CanyonRegisterEntity<'a>>,
database_tables: Vec<&'a TableMetadata>,
_datasource_name: &'a str,
db_type: DatabaseType
) {
println!("Database tables to play with: {:?}", &database_tables.len());
println!("Entities in canyon entity to play with: {:?}", &canyon_entities.iter().map(|cr| cr.entity_name.to_string()).collect::<Vec<String>>());
// For each entity (table) on the register (Rust structs)
for canyon_register_entity in canyon_entities {
let entity_name = canyon_register_entity.entity_name.to_lowercase();
// 1st operation ->
self.create_or_rename_tables(
&canyon_memory,
entity_name.as_str(),
canyon_register_entity.entity_fields.clone(),
&database_tables
);
let current_table_metadata = MigrationsHelper::get_current_table_metadata(
&canyon_memory,
entity_name.as_str(),
&database_tables
);
self.delete_fields(
entity_name.as_str(),
canyon_register_entity.entity_fields.clone(),
current_table_metadata,
db_type
);
// For each field (column) on the this canyon register entity
for canyon_register_field in canyon_register_entity.entity_fields {
let current_column_metadata = MigrationsHelper::get_current_column_metadata(
canyon_register_field.field_name.clone(),
current_table_metadata
);
// We only create or modify (right now only datatype)
// the column when the database already contains the table,
// if not, the columns are already create in the previous operation (create table)
if current_table_metadata.is_some(){
self.create_or_modify_field (
entity_name.as_str(),
db_type,
canyon_register_field.clone(),
current_column_metadata
)
}
// Time to check annotations for the current column
// Case when we only need to add contrains
if (current_table_metadata.is_none() && &(&canyon_register_field.annotations).len() > &0)
|| (current_table_metadata.is_some() && current_column_metadata.is_none()) {
self.add_constraints(
entity_name.as_str(),
canyon_register_field.clone()
)
}
// Case when we need to compare the entity with the database contain
if current_table_metadata.is_some() && current_column_metadata.is_some(){
self.add_modify_or_remove_constraints(
entity_name.as_str(),
canyon_register_field,
current_column_metadata.unwrap()
)
}
}
}
// Self::operations_executor().await;
for operation in &self.operations {
println!("Operation query: {:?}", &operation);
operation.execute(db_type).await; // This should be moved again to runtime
}
for operation in &self.drop_primary_key_operations {
println!("Operation query: {:?}", &operation);
operation.execute(db_type).await; // This should be moved again to runtime
}
for operation in &self.set_primary_key_operations {
println!("Operation query: {:?}", &operation);
operation.execute(db_type).await; // This should be moved again to runtime
}
for operation in &self.constraints_operations {
println!("Operation query: {:?}", &operation);
operation.execute(db_type).await; // This should be moved again to runtime
}
// Self::from_query_register(datasource_name).await;
}
/// TODO
fn create_or_rename_tables<'a>(
&mut self,
canyon_memory: &'_ CanyonMemory,
entity_name: &'a str,
entity_fields: Vec<CanyonRegisterEntityField>,
database_tables: &'a [&'a TableMetadata]
) {
println!("Table with name {} already on DB ? {}",entity_name,MigrationsHelper::entity_already_on_database(entity_name, database_tables) );
// 1st operation -> Check if the current entity is already on the target database.
// If isn't present (this if case), we
if !MigrationsHelper::entity_already_on_database(entity_name, database_tables) {
// [`CanyonMemory`] holds a HashMap with the tables who changed their name in
// the Rust side. If this table name is present, we don't create a new table,
// just rename the already known one
println!("Check if {} its a new name for an old table name",entity_name);
if canyon_memory.renamed_entities.contains_key(entity_name) {
self.table_rename(
canyon_memory
.renamed_entities
.get(entity_name) // Get the old entity name (the value)
.unwrap()
.to_owned(),
entity_name.to_string() // Set the new table name
)
} else {
println!("Create table with name {}",entity_name);
self.create_table(entity_name.to_string(), entity_fields)
}
// else {
// todo!()
// Return some control flag to indicate that we must begin to
// parse inner elements (columns, constraints...) with the data
// Also, we must indicate a relation between the old table name
// and the new one, because the parsing are against the legacy
// table name, but the queries must be generated against the new
// table name
// }
}
}
/// Generates a database agnostic query to change the name of a table
fn create_table(&mut self, table_name: String, entity_fields: Vec<CanyonRegisterEntityField>) {
self.operations
.push(Box::new(TableOperation::CreateTable(table_name, entity_fields)));
}
/// Generates a database agnostic query to change the name of a table
fn table_rename(&mut self, old_table_name: String, new_table_name: String) {
self.operations
.push(Box::new(TableOperation::AlterTableName(old_table_name, new_table_name)));
}
// Creates or modify (currently only datatype) a column for a given canyon register entity field
fn delete_fields<'a > (
&mut self,
entity_name: &'a str,
entity_fields: Vec<CanyonRegisterEntityField>,
current_table_metadata: Option<&'a TableMetadata>,
db_type: DatabaseType
) {
if current_table_metadata.is_some() {
let columns_name_to_delete : Vec<&ColumnMetadata> = current_table_metadata
.unwrap()
.columns
.iter()
.filter(|db_column| {
entity_fields
.iter()
.map(|canyon_field| canyon_field.field_name.to_string())
.any (|canyon_field| canyon_field == db_column.column_name)
.not()
})
.collect();
for column_metadata in columns_name_to_delete {
if db_type == DatabaseType::SqlServer && !column_metadata.is_nullable {
self.drop_column_not_null(
entity_name,
column_metadata.column_name.clone(),
MigrationsHelper::get_datatype_from_column_metadata(
column_metadata
)
)
}
self.delete_column(entity_name, column_metadata.column_name.clone());
}
}
}
// Creates or modify (currently only datatype) a column for a given canyon register entity field
fn create_or_modify_field<'a > (
&mut self,
entity_name: &'a str,
db_type: DatabaseType,
canyon_register_entity_field: CanyonRegisterEntityField,
current_column_metadata: Option<&ColumnMetadata>,
) {
// If we do not retrieve data for this database column, it does not exist yet
// and therefore has to be created
if current_column_metadata.is_none() {
self.create_column(entity_name.to_string(), canyon_register_entity_field)
}
else if !MigrationsHelper::is_same_datatype(
db_type,
&canyon_register_entity_field,
current_column_metadata.unwrap()
){
self.change_column_datatype(entity_name.to_string(), canyon_register_entity_field)
}
}
fn delete_column(&mut self, table_name: &str, column_name: String) {
self.operations
.push(Box::new(ColumnOperation::DeleteColumn(table_name.to_string(), column_name)));
}
fn drop_column_not_null(&mut self, table_name: &str, column_name: String, column_datatype: String) {
self.operations
.push(Box::new(ColumnOperation::DropNotNullBeforeDropColumn(table_name.to_string(), column_name, column_datatype)));
}
fn create_column(&mut self, table_name: String, field: CanyonRegisterEntityField) {
self.operations
.push(Box::new(ColumnOperation::CreateColumn(table_name, field)));
}
fn change_column_datatype(&mut self, table_name: String, field: CanyonRegisterEntityField) {
self.operations
.push(Box::new(ColumnOperation::AlterColumnType(table_name, field)));
}
fn add_constraints(
&mut self,
entity_name: &str,
canyon_register_entity_field: CanyonRegisterEntityField,
) {
for attr in &canyon_register_entity_field.annotations {
if attr.starts_with("Annotation: ForeignKey") {
let annotation_data = MigrationsHelper::extract_foreign_key_annotation(
&canyon_register_entity_field.annotations
);
let table_to_reference = annotation_data.0;
let column_to_reference = annotation_data.1;
let foreign_key_name = format!("{entity_name}_{}_fkey", &canyon_register_entity_field.field_name);
Self::add_foreign_key(
self,
entity_name,
foreign_key_name,
table_to_reference,
column_to_reference,
&canyon_register_entity_field
);
}
if attr.starts_with("Annotation: PrimaryKey") {
Self::add_primary_key(self, entity_name, canyon_register_entity_field.clone());
if canyon_register_entity_field.is_autoincremental() {
Self::add_identity(self, entity_name, canyon_register_entity_field.clone());
}
}
}
}
fn add_foreign_key(
&mut self,
entity_name: &'_ str,
foreign_key_name: String,
table_to_reference: String,
column_to_reference: String,
canyon_register_entity_field: &CanyonRegisterEntityField,
) {
self.operations
.push(Box::new(TableOperation::AddTableForeignKey(
entity_name.to_string(), foreign_key_name, canyon_register_entity_field.field_name.clone(), table_to_reference, column_to_reference
)));
}
fn add_primary_key(&mut self, entity_name: &str, canyon_register_entity_field: CanyonRegisterEntityField)
{
self.set_primary_key_operations
.push(Box::new(
TableOperation::AddTablePrimaryKey(entity_name.to_string(), canyon_register_entity_field),
));
}
fn add_identity(&mut self, entity_name: &str, field: CanyonRegisterEntityField)
{
self.constraints_operations
.push(Box::new(ColumnOperation::AlterColumnAddIdentity(
entity_name.to_string(),
field.clone(),
)));
self.constraints_operations
.push(Box::new(SequenceOperation::ModifySequence(
entity_name.to_string(), field,
)));
}
fn add_modify_or_remove_constraints<'a>(
&mut self,
entity_name: &'a str,
canyon_register_entity_field: CanyonRegisterEntityField,
current_column_metadata: &ColumnMetadata)
{
let field_is_primary_key = canyon_register_entity_field
.annotations
.iter()
.any(|anno| anno.starts_with("Annotation: PrimaryKey"));
let field_is_foreign_key = canyon_register_entity_field
.annotations
.iter()
.any(|anno| anno.starts_with("Annotation: ForeignKey"));
// ----------- PRIMARY KEY ---------------
println!("Column -> {}. Is primary key Rust ? {}, Is primary key DB ? {}",
canyon_register_entity_field.field_name,field_is_primary_key,
current_column_metadata.primary_key_info.is_some());
// Case when field contains a primary key annotation, and it's not already on database, add it to constrains_operations
if field_is_primary_key && current_column_metadata.primary_key_info.is_none() {
Self::add_primary_key(self, entity_name, canyon_register_entity_field.clone());
if canyon_register_entity_field.is_autoincremental() {
Self::add_identity(self, entity_name, canyon_register_entity_field.clone());
}
}
// Case when field don't contains a primary key annotation, but there is already one in the database column
else if !field_is_primary_key && current_column_metadata.primary_key_info.is_some()
{
println!("Column to remove PK -> {}",canyon_register_entity_field.field_name);
Self::drop_primary_key(
self,
entity_name,
current_column_metadata
.primary_key_name
.as_ref()
.expect("PrimaryKey constrain name not found")
.to_string(),
);
if current_column_metadata.is_identity {
Self::drop_identity(self, entity_name, canyon_register_entity_field.clone());
}
}
// -------- FOREIGN KEY CASE ----------------------------
println!("Column -> {}. Is foreign key Rust ? {}, Is foreign key DB ? {}",
canyon_register_entity_field.field_name, field_is_foreign_key,
current_column_metadata.foreign_key_name.is_some());
println!("Column -> {}. Should we delete FK ? {}",
canyon_register_entity_field.field_name,
!field_is_foreign_key && current_column_metadata.foreign_key_name.is_some());
// Case when field contains a foreign key annotation, and it's not already on database, add it to constraints_operations
if field_is_foreign_key && current_column_metadata.foreign_key_name.is_none() {
if current_column_metadata.foreign_key_name.is_none() {
let annotation_data = MigrationsHelper::extract_foreign_key_annotation(
&canyon_register_entity_field.annotations
);
let table_to_reference = annotation_data.0;
let column_to_reference = annotation_data.1;
let foreign_key_name = format!("{entity_name}_{}_fkey", &canyon_register_entity_field.field_name);
Self::add_foreign_key(
self,
entity_name,
foreign_key_name,
table_to_reference,
column_to_reference,
&canyon_register_entity_field,
);
}
}
// Case when field contains a foreign key annotation, and there is already one in the database
else if field_is_foreign_key && current_column_metadata.foreign_key_name.is_some()
{
// Will contain the table name (on index 0) and column name (on index 1) pointed to by the foreign key
let annotation_data = MigrationsHelper::extract_foreign_key_annotation(
&canyon_register_entity_field.annotations
);
let foreign_key_name = format!("{entity_name}_{}_fkey", &canyon_register_entity_field.field_name);
// Example of information in foreign_key_info: FOREIGN KEY (league) REFERENCES leagues(id)
let references_regex = Regex::new(regex_patterns::EXTRACT_FOREIGN_KEY_INFO).unwrap();
let captures_references = references_regex
.captures(
current_column_metadata
.foreign_key_info
.as_ref()
.expect("Regex - foreign key info"),
)
.expect("Regex - foreign key info not found");
let current_column = captures_references
.name("current_column")
.expect("Regex - Current column not found")
.as_str()
.to_string();
let ref_table = captures_references
.name("ref_table")
.expect("Regex - Ref tablenot found")
.as_str()
.to_string();
let ref_column = captures_references
.name("ref_column")
.expect("Regex - Ref column not found")
.as_str()
.to_string();
// If entity foreign key is not equal to the one on database, a constrains_operations is added to delete it and add a new one.
if canyon_register_entity_field.field_name != current_column
|| annotation_data.0 != ref_table
|| annotation_data.1 != ref_column
{
Self::delete_foreign_key(
self,
entity_name,
current_column_metadata
.foreign_key_name
.as_ref()
.expect("Annotation foreign key constrain name not found")
.to_string(),
);
Self::add_foreign_key(
self,
entity_name,
foreign_key_name,
annotation_data.0,
annotation_data.1,
&canyon_register_entity_field)
}
}
// Case when field don't contains a foreign key annotation, but there is already one in the database column
else if !field_is_foreign_key && current_column_metadata.foreign_key_name.is_some()
{
println!("Removing FK on column {}", &canyon_register_entity_field.field_name);
Self::delete_foreign_key(
self,
entity_name,
current_column_metadata
.foreign_key_name
.as_ref()
.expect("ForeignKey constrain name not found")
.to_string(),
);
} else {
println!("Column {} going somewhere it shouldn't", &canyon_register_entity_field.field_name);
}
}
fn drop_primary_key(&mut self, entity_name: &str, primary_key_name: String)
{
self.drop_primary_key_operations
.push(Box::new(TableOperation::DeleteTablePrimaryKey(entity_name.to_string(), primary_key_name)));
}
fn drop_identity(&mut self, entity_name: &str, canyon_register_entity_field: CanyonRegisterEntityField)
{
self.constraints_operations
.push(Box::new(ColumnOperation::AlterColumnDropIdentity(
entity_name.to_string(), canyon_register_entity_field,
)));
}
fn delete_foreign_key(
&mut self,
entity_name: &str,
constrain_name: String,
)
{
self.constraints_operations
.push(Box::new(TableOperation::DeleteTableForeignKey(
// table_with_foreign_key,constrain_name
entity_name.to_string(),
constrain_name,
)));
}
/// Make the detected migrations for the next Canyon-SQL run
#[allow(clippy::await_holding_lock)]
pub async fn from_query_register(datasource_name: &str) {
let queries: &MutexGuard<Vec<String>> = &QUERIES_TO_EXECUTE.lock().unwrap();
if queries.len() > 0 {
for i in 0..queries.len() - 1 {
let query_to_execute = queries.get(i).unwrap_or_else(|| {
panic!("Failed to retrieve query from the register at index: {i}")
});
let res = Self::query(query_to_execute, [], datasource_name).await;
match res {
Ok(_) =>
println!("[OK] - Query: {:?}", queries.get(i).unwrap()),
Err(e) =>
println!("[ERR] - Query: {:?}\nCause: {:?}", queries.get(i).unwrap(), e),
}
// TODO Ask for user input?
}
} else {
println!("No migrations queries found to apply")
}
}
}
/// Contains helper methods to parse and process the external and internal input data
/// for the migrations
struct MigrationsHelper;
impl MigrationsHelper {
/// Checks if a tracked Canyon entity is already present in the database
fn entity_already_on_database<'a>(
entity_name: &'a str,
database_tables: &'a [&'_ TableMetadata],
) -> bool {
println!("Looking for entity: {:?}", entity_name);
database_tables.iter().any( |v|
v.table_name.to_lowercase() == entity_name.to_lowercase()
)
}
// Get the table metadata for a given entity name or his old entity name if the table was renamed.
fn get_current_table_metadata<'a> (
canyon_memory: &'_ CanyonMemory,
entity_name: &'a str,
database_tables: &'a [&'_ TableMetadata],
) -> Option<&'a TableMetadata> {
let correct_entity_name = canyon_memory.renamed_entities
.get(&entity_name.to_lowercase())
.map(|e| e.to_owned())
.unwrap_or(entity_name.to_string());
database_tables.iter()
.find(|table_metadata| table_metadata.table_name.to_lowercase() == *correct_entity_name.to_lowercase())
.map(|e| e.to_owned().clone())
}
// Get the column metadata for a given column name
fn get_current_column_metadata(
column_name: String,
current_table_metadata: Option<&TableMetadata>,
) -> Option<&ColumnMetadata> {
if current_table_metadata.is_none() {
None
} else {
current_table_metadata.expect("Cant unwrap the current Table Metadata").columns.iter()
.find(|column| column.column_name == column_name)
.map(|e| e.to_owned().clone())
}
}
fn get_datatype_from_column_metadata(
current_column_metadata: &ColumnMetadata,
) -> String {
// TODO Add all SQL Server text datatypes
if vec!["nvarchar","varchar"].contains(¤t_column_metadata.postgres_datatype.to_lowercase().as_str()) {
let varchar_len = match ¤t_column_metadata.character_maximum_length {
Some(v) => v.to_string(),
None => "max".to_string()
};
format!("{}({})", current_column_metadata.postgres_datatype, varchar_len)
} else {
format!("{}", current_column_metadata.postgres_datatype)
}
}
fn is_same_datatype(
db_type: DatabaseType,
canyon_register_entity_field: &CanyonRegisterEntityField,
current_column_metadata: &ColumnMetadata
) -> bool {
if db_type == DatabaseType::PostgreSql {
canyon_register_entity_field.to_postgres_syntax() != current_column_metadata.postgres_datatype
} else if db_type == DatabaseType::SqlServer {
// TODO Search a better way to get the datatype without useless info (like "VARCHAR(MAX)")
canyon_register_entity_field.to_sqlserver_syntax() != current_column_metadata.postgres_datatype
} else {
todo!()
}
}
fn extract_foreign_key_annotation(field_annotations: &[String]) -> (String, String) {
let opt_fk_annotation = field_annotations
.iter()
.find(|anno| anno.starts_with("Annotation: ForeignKey"));
if let Some(fk_annotation) = opt_fk_annotation {
let annotation_data = fk_annotation
.split(',')
.filter(|x| !x.contains("Annotation: ForeignKey")) // After here, we only have the "table" and the "column" attribute values
.map(|x| {
x.split(':')
.collect::<Vec<&str>>()
.get(1)
.expect("Error. Unable to split annotations")
.trim()
.to_string()
})
.collect::<Vec<String>>();
let table_to_reference = annotation_data
.get(0)
.expect("Error extracting table ref from FK annotation")
.to_string();
let column_to_reference = annotation_data
.get(1)
.expect("Error extracting column ref from FK annotation")
.to_string();
(table_to_reference, column_to_reference)
} else {
panic!("Detected a Foreign Key attribute when does not exists on the user's code");
}
}
}
#[cfg(test)]
mod migrations_helper_tests {
use crate::constants;
use super::*;
const MOCKED_ENTITY_NAME: &str = "League";
#[test]
fn test_entity_already_on_database() {
let parse_result_empty_db_tables = MigrationsHelper::entity_already_on_database(
MOCKED_ENTITY_NAME, &[]
);
// Always should be false
assert_eq!(parse_result_empty_db_tables, false);
// Rust has a League entity. Database has a `league` entity. Case should be normalized
// and a match must raise
let mocked_league_entity_on_database = MigrationsHelper::entity_already_on_database(
MOCKED_ENTITY_NAME, &[&constants::mocked_data::TABLE_METADATA_LEAGUE_EX]
);
assert!(mocked_league_entity_on_database);
let mocked_league_entity_on_database = MigrationsHelper::entity_already_on_database(
MOCKED_ENTITY_NAME, &[&constants::mocked_data::NON_MATCHING_TABLE_METADATA]
);
assert_eq!(mocked_league_entity_on_database, false)
}
}
// /// Responsible of generating the queries to sync the database status with the
// /// Rust source code managed by Canyon, for succesfully make the migrations
// #[derive(Debug, Default)]
// pub struct DatabaseSyncOperations {
// operations: Vec<Box<dyn DatabaseOperation>>,
// drop_primary_key_operations: Vec<Box<dyn DatabaseOperation>>,
// set_primary_key_operations: Vec<Box<dyn DatabaseOperation>>,
// constrains_operations: Vec<Box<dyn DatabaseOperation>>,
// }
// impl Transaction<Self> for DatabaseSyncOperations {}
// impl DatabaseSyncOperations {
// pub async fn fill_operations<'a>(
// &mut self,
// canyon_memory: CanyonMemory,
// canyon_tables: Vec<CanyonRegisterEntity<'static>>,
// database_tables: Vec<TableMetadata>,
// ) {
// // For each entity (table) on the register (Rust structs)
// for canyon_register_entity in canyon_tables {
// let table_name = canyon_register_entity.entity_name;
// // true if this table on the register is already on the database
// let table_on_database = Self::check_table_on_database(table_name, &database_tables);
// // If the table isn't on the database we push a new operation to the collection,
// // either to create a new table or to rename an existing one.
// if !table_on_database {
// let table_renamed = canyon_memory.renamed_entities.contains_key(table_name);
// // canyon_memory holds a hashmap of the tables who must changed their name.
// // If this table name is present, we dont create a new one, just rename
// if table_renamed {
// // let old_table_name = data.canyon_memory.table_rename.to_owned().get(&table_name.to_owned());
// let otn = canyon_memory
// .renamed_entities
// .get(table_name)
// .unwrap()
// .to_owned()
// .clone();
// Self::push_table_rename::<String, &str>(self, otn, table_name);
// // TODO Change foreign_key constrain name on database
// continue;
// }
// // If not, we push an operation to create a new one
// else {
// Self::add_new_table::<&str>(
// self,
// table_name,
// canyon_register_entity.entity_fields.clone(),
// );
// }
// let cloned_fields = canyon_register_entity.entity_fields.clone();
// // We iterate over the fields/columns seeking for constrains to add
// for field in cloned_fields
// .iter()
// .filter(|column| !column.annotations.is_empty())
// {
// field.annotations.iter().for_each(|attr| {
// if attr.starts_with("Annotation: ForeignKey") {
// Self::add_foreign_key_with_annotation::<&str, &String>(
// self,
// &field.annotations,
// table_name,
// &field.field_name,
// );
// }
// if attr.starts_with("Annotation: PrimaryKey") {
// Self::add_primary_key::<&str>(self, table_name, field.clone());
// Self::add_identity::<&str>(self, table_name, field.clone());
// }
// });
// }
// } else {
// // We check if each of the columns in this table of the register is in the database table.
// // We get the names and add them to a vector of strings
// let columns_in_table = Self::columns_in_table(
// canyon_register_entity.entity_fields.clone(),
// &database_tables,
// table_name,
// );
// // For each field (name, type) in this table of the register
// for field in canyon_register_entity.entity_fields.clone() {
// // Case when the column doesn't exist on the database
// // We push a new column operation to the collection for each one
// if !columns_in_table.contains(&field.field_name) {
// Self::add_column_to_table::<&str>(self, table_name, field.clone());
// // We added the founded constraints on the field attributes
// for attr in &field.annotations {
// if attr.starts_with("Annotation: ForeignKey") {
// Self::add_foreign_key_with_annotation::<&str, &String>(
// self,
// &field.annotations,
// table_name,
// &field.field_name,
// );
// }
// if attr.starts_with("Annotation: PrimaryKey") {
// Self::add_primary_key::<&str>(self, table_name, field.clone());
// Self::add_identity::<&str>(self, table_name, field.clone());
// }
// }
// }
// // Case when the column exist on the database
// else {
// let database_table = database_tables
// .iter()
// .find(|x| x.table_name == table_name)
// .unwrap();
// let database_field = database_table
// .columns
// .iter()
// .find(|x| x.column_name == field.field_name)
// .expect("Field annt exists");
// let mut database_field_postgres_type: String = String::new();
// match database_field.postgres_datatype.as_str() {
// "integer" => {
// database_field_postgres_type.push_str("i32");
// }
// "bigint" => {
// database_field_postgres_type.push_str("i64");
// }
// "text" | "character varying" => {
// database_field_postgres_type.push_str("String");
// }
// "date" => {
// database_field_postgres_type.push_str("NaiveDate");
// }
// _ => {}
// }
// if database_field.is_nullable {
// database_field_postgres_type =
// format!("Option<{database_field_postgres_type}>");
// }
// if field.field_type != database_field_postgres_type {
// if field.field_type.starts_with("Option") {
// self.constrains_operations.push(Box::new(
// ColumnOperation::AlterColumnDropNotNull(
// table_name,
// field.clone(),
// ),
// ));
// } else {
// self.constrains_operations.push(Box::new(
// ColumnOperation::AlterColumnSetNotNull(
// table_name,
// field.clone(),
// ),
// ));
// }
// Self::change_column_type(self, table_name, field.clone());
// }
// let field_is_primary_key = field
// .annotations
// .iter()
// .any(|anno| anno.starts_with("Annotation: PrimaryKey"));
// let field_is_foreign_key = field
// .annotations
// .iter()
// .any(|anno| anno.starts_with("Annotation: ForeignKey"));
// // TODO Checking Foreign Key attrs. Refactor to a database rust attributes matcher
// // TODO Evaluate changing the name of the primary key if it already exists in the database
// // -------- PRIMARY KEY CASE ----------------------------
// // Case when field contains a primary key annotation, and it's not already on database, add it to constrains_operations
// if field_is_primary_key && database_field.primary_key_info.is_none() {
// Self::add_primary_key::<&str>(self, table_name, field.clone());
// Self::add_identity::<&str>(self, table_name, field.clone());
// }
// // Case when field don't contains a primary key annotation, but there is already one in the database column
// else if !field_is_primary_key && database_field.primary_key_info.is_some()
// {
// Self::drop_primary_key::<String>(
// self,
// table_name.to_string(),
// database_field
// .primary_key_name
// .as_ref()
// .expect("PrimaryKey constrain name not found")
// .to_string(),
// );
// if database_field.is_identity {
// Self::drop_identity::<&str>(self, table_name, field.clone());
// }
// }
// // -------- FOREIGN KEY CASE ----------------------------
// // Case when field contains a foreign key annotation, and it's not already on database, add it to constrains_operations
// if field_is_foreign_key && database_field.foreign_key_name.is_none() {
// if database_field.foreign_key_name.is_none() {
// Self::add_foreign_key_with_annotation::<&str, &String>(
// self,
// &field.annotations,
// table_name,
// &field.field_name,
// )
// }
// }
// // Case when field contains a foreign key annotation, and there is already one in the database
// else if field_is_foreign_key && database_field.foreign_key_name.is_some()
// {
// // Will contain the table name (on index 0) and column name (on index 1) pointed to by the foreign key
// let annotation_data =
// Self::extract_foreign_key_annotation(&field.annotations);
// // Example of information in foreign_key_info: FOREIGN KEY (league) REFERENCES leagues(id)
// let references_regex = Regex::new(r"\w+\s\w+\s\((?P<current_column>\w+)\)\s\w+\s(?P<ref_table>\w+)\((?P<ref_column>\w+)\)").unwrap();
// let captures_references = references_regex
// .captures(
// database_field
// .foreign_key_info
// .as_ref()
// .expect("Regex - foreign key info"),
// )
// .expect("Regex - foreign key info not found");
// let current_column = captures_references
// .name("current_column")
// .expect("Regex - Current column not found")
// .as_str()
// .to_string();
// let ref_table = captures_references
// .name("ref_table")
// .expect("Regex - Ref tablenot found")
// .as_str()
// .to_string();
// let ref_column = captures_references
// .name("ref_column")
// .expect("Regex - Ref column not found")
// .as_str()
// .to_string();
// // If entity foreign key is not equal to the one on database, a constrains_operations is added to delete it and add a new one.
// if field.field_name != current_column
// || annotation_data.0 != ref_table
// || annotation_data.1 != ref_column
// {
// Self::delete_foreign_key_with_references::<String>(
// self,
// table_name.to_string(),
// database_field
// .foreign_key_name
// .as_ref()
// .expect("Annotation foreign key constrain name not found")
// .to_string(),
// );
// Self::add_foreign_key_with_references(
// self,
// annotation_data.0,
// annotation_data.1,
// table_name,
// field.field_name.clone(),
// )
// }
// }
// // Case when field don't contains a foreign key annotation, but there is already one in the database column
// else if !field_is_foreign_key && database_field.foreign_key_name.is_some()
// {
// Self::delete_foreign_key_with_references::<String>(
// self,
// table_name.to_string(),
// database_field
// .foreign_key_name
// .as_ref()add_foreign_key_with_annotation
// .expect("ForeignKey constrain name not found")
// .to_string(),
// );
// }
// }
// }
// // Filter the list of columns in the corresponding table of the database for the current table of the register,
// // and look for columns that don't exist in the table of the register
// let columns_to_remove: Vec<String> = Self::columns_to_remove(
// &database_tables,
// canyon_register_entity.entity_fields.clone(),
// table_name,
// );