-
-
Notifications
You must be signed in to change notification settings - Fork 421
Expand file tree
/
Copy pathrelationship.cpp
More file actions
3165 lines (2678 loc) · 94.8 KB
/
relationship.cpp
File metadata and controls
3165 lines (2678 loc) · 94.8 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
/*
# PostgreSQL Database Modeler (pgModeler)
#
# Copyright 2006-2025 - Raphael Araújo e Silva <raphael@pgmodeler.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# The complete text of GPLv3 is at LICENSE file on source code root directory.
# Also, you can get the complete GNU General Public License at <http://www.gnu.org/licenses/>
*/
#include "relationship.h"
#include "coreutilsns.h"
#include "tablespace.h"
#include <QApplication>
const QString Relationship::SuffixSeparator {"_"};
const QString Relationship::SrcTabToken {"{st}"};
const QString Relationship::DstTabToken {"{dt}"};
const QString Relationship::GenTabToken {"{gt}"};
const QString Relationship::SrcColToken {"{sc}"};
Relationship::Relationship(Relationship *rel) : BaseRelationship(rel)
{
if(!rel)
throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);
(*(this))=(*rel);
}
Relationship::Relationship(BaseRelationship::RelType rel_type, PhysicalTable *src_tab,
PhysicalTable *dst_tab, bool src_mdtry, bool dst_mdtry,
bool identifier) :
BaseRelationship(rel_type, src_tab, dst_tab, src_mdtry, dst_mdtry)
{
try
{
obj_type = ObjectType::Relationship;
QString str_aux;
/* Raises an error if the user tries to create a relationship (1-1, 1-n, n-n or copy)
* if any involved table is a foreign table. Foreign tables can participate only
* inheritance and partitioning relationships */
if((rel_type!=RelationshipGen && rel_type!=RelationshipPart && rel_type!=RelationshipDep) &&
(src_tab->getObjectType() == ObjectType::ForeignTable ||
dst_tab->getObjectType() == ObjectType::ForeignTable))
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvRelTypeForeignTable)
.arg(obj_name, src_tab->getName(true), dst_tab->getName(true)),
ErrorCode::InvRelTypeForeignTable,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
/* Raises an error if the user tries to create a copy relation in which the receiver table
* is a foreign table. In case of creating a copy relationship between a table and a foreign table
* the receiver must be a table and the reference a foreign table */
if(rel_type == RelationshipDep && src_tab->getObjectType() == ObjectType::ForeignTable)
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvCopyRelForeignTable)
.arg(obj_name, src_tab->getName(true), dst_tab->getName(true)),
ErrorCode::InvCopyRelForeignTable,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
/* Raises an error if the user tries to create a relationship which some
table doesn't has a primary key */
if(((rel_type==Relationship11 || rel_type==Relationship1n) &&
!this->getReferenceTable()->getPrimaryKey()) ||
(rel_type==RelationshipNn && (!src_tab->getPrimaryKey() || !dst_tab->getPrimaryKey())))
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvLinkTablesNoPrimaryKey)
.arg(obj_name, src_tab->getName(true), dst_tab->getName(true)),
ErrorCode::InvLinkTablesNoPrimaryKey,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
// Raises an error if the user tries to create another copy relationship if the table already copies another table
if(rel_type==RelationshipDep && src_tab->getCopyTable())
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvCopyRelTableDefined)
.arg(src_tab->getName(true), dst_tab->getName(true),
dynamic_cast<PhysicalTable *>(src_tab)->getCopyTable()->getName(true)),
ErrorCode::InvCopyRelTableDefined,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
/* If the relationship is partitioning the destination table (partitioned) shoud have
* a partitioning type defined otherwise and error is raised */
if(rel_type == RelationshipPart && !dst_tab->isPartitioned())
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvPartitioningTypePartRel)
.arg(src_tab->getSignature(), dst_tab->getSignature()),
ErrorCode::InvPartitioningTypePartRel, __PRETTY_FUNCTION__,__FILE__,__LINE__);
}
// Raises an error if the user tries to create a partitioning relationship where one of the tables are already a partition table
if(rel_type==RelationshipPart && src_tab->getPartitionedTable())
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvPartRelPartitionedDefined)
.arg(src_tab->getName(true), dst_tab->getName(true),
src_tab->getPartitionedTable()->getName(true)),
ErrorCode::InvPartRelPartitionedDefined,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
/* Raises an error if the user tries to create a generalization or copy relationship in
* which one of the tables is part of a partitioning hierarchy, or if the relationship is 1-1, 1-n, n-n and
* one of the tables is a partition. */
if(((rel_type == RelationshipGen || rel_type == RelationshipDep) &&
(src_tab->isPartition() || src_tab->isPartitioned() ||
dst_tab->isPartition() || dst_tab->isPartitioned())) ||
((rel_type == Relationship11 || rel_type == Relationship1n || rel_type == RelationshipNn) &&
(src_tab->isPartition() || dst_tab->isPartition())))
{
throw Exception(Exception::getErrorMessage(ErrorCode::InvRelTypeForPatitionTables)
.arg(src_tab->getName(true), dst_tab->getName(true),
src_tab->isPartitioned() || src_tab->isPartition() ?
src_tab->getName(true) : dst_tab->getName(true)),
ErrorCode::InvRelTypeForPatitionTables,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
fk_index = nullptr;
fk_idx_type = IndexingType::Null;
table_relnn = nullptr;
fk_rel1n = pk_relident = pk_special = nullptr;
uq_rel11 = pk_original = nullptr;
deferrable = false;
deferral_type = DeferralType::Null;
del_action = ActionType::Null;
upd_action = ActionType::Null;
invalidated = true;
single_pk_column = false;
if(rel_type == Relationship11)
str_aux = qApp->translate("Relationship","%1_has_one_%2","");
else if(rel_type == Relationship1n)
str_aux = qApp->translate("Relationship","%1_has_many_%2","");
else if(rel_type == RelationshipNn)
str_aux = qApp->translate("Relationship","many_%1_has_many_%2","");
else if(rel_type == RelationshipGen)
str_aux = qApp->translate("Relationship","%1_inherits_%2","");
else if(rel_type == RelationshipPart)
str_aux = qApp->translate("Relationship","%1_is_partition_of_%2","");
else
str_aux = qApp->translate("Relationship","%1_copies_%2","");
if(rel_type == RelationshipNn)
str_aux = str_aux.arg(this->src_table->getName(), this->dst_table->getName());
else if(rel_type == Relationship1n)
str_aux = str_aux.arg(this->getReferenceTable()->getName(), this->getReceiverTable()->getName());
else
str_aux = str_aux.arg(this->getReceiverTable()->getName(), this->getReferenceTable()->getName());
if(str_aux.size() > BaseObject::ObjectNameMaxLength)
str_aux.resize(BaseObject::ObjectNameMaxLength);
setName(str_aux);
if(rel_type == RelationshipNn)
{
tab_name_relnn = this->obj_name;
if(tab_name_relnn.size() > BaseObject::ObjectNameMaxLength)
tab_name_relnn.resize(BaseObject::ObjectNameMaxLength);
setNamePattern(PkPattern, GenTabToken + SuffixSeparator + "pk");
setNamePattern(SrcFkPattern, SrcTabToken + SuffixSeparator + "fk");
setNamePattern(DstFkPattern, DstTabToken + SuffixSeparator + "fk");
setNamePattern(UqPattern, GenTabToken + SuffixSeparator + "uq");
setNamePattern(SrcColPattern, SrcColToken + SuffixSeparator + SrcTabToken);
setNamePattern(DstColPattern, SrcColToken + SuffixSeparator + DstTabToken);
setNamePattern(PkColPattern, "id");
setNamePattern(FkIdxPattern, GenTabToken + SuffixSeparator + "idx");
}
else if(rel_type == RelationshipDep || rel_type == RelationshipGen)
setNamePattern(PkPattern, DstTabToken + SuffixSeparator + "pk");
else
{
setNamePattern(PkPattern, DstTabToken + SuffixSeparator + "pk");
setNamePattern(SrcFkPattern, SrcTabToken + SuffixSeparator + "fk");
setNamePattern(UqPattern, DstTabToken + SuffixSeparator + "uq");
setNamePattern(SrcColPattern, SrcColToken + SuffixSeparator + SrcTabToken);
setNamePattern(FkIdxPattern, SrcTabToken + SuffixSeparator + "idx");
}
rejected_col_count = 0;
setIdentifier(identifier);
}
catch(Exception &e)
{
throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
}
}
void Relationship::setNamePattern(PatternId pat_id, const QString &pattern)
{
if(pattern.isEmpty())
return;
static const QString token { "tk" };
QString aux_name = pattern;
QStringList pat_tokens { SrcTabToken, DstTabToken,
GenTabToken, SrcColToken };
/* Replacing the pattern ids by a placeholder text
* so the resulting name can be validated */
for(auto &patt : pat_tokens)
aux_name.replace(patt, token);
if(pat_id > FkIdxPattern)
{
throw Exception(Exception::getErrorMessage(ErrorCode::RefInvalidNamePatternId)
.arg(this->getName()),__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
else if(!BaseObject::isValidName(aux_name))
{
throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidNamePattern)
.arg(this->getName()),__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
invalidated = name_patterns[pat_id] != pattern;
name_patterns[pat_id] = pattern;
}
QString Relationship::getNamePattern(PatternId pat_id)
{
if(pat_id > FkIdxPattern)
throw Exception(ErrorCode::RefInvalidNamePatternId,__PRETTY_FUNCTION__,__FILE__,__LINE__);
return name_patterns[pat_id];
}
QString Relationship::generateObjectName(PatternId pat_id, Column *id_col, bool use_alias)
{
QString name, aux_name;
name=name_patterns[pat_id];
name.replace(GenTabToken, (rel_type == RelationshipNn ? tab_name_relnn : ""));
if(rel_type == RelationshipNn)
{
aux_name = use_alias && !src_table->getAlias().isEmpty() ? src_table->getAlias() : src_table->getName();
name.replace(SrcTabToken, aux_name);
aux_name = use_alias && !dst_table->getAlias().isEmpty() ? dst_table->getAlias() : dst_table->getName();
name.replace(DstTabToken, aux_name);
}
else
{
aux_name = use_alias && !getReferenceTable()->getAlias().isEmpty() ? getReferenceTable()->getAlias() : getReferenceTable()->getName();
name.replace(SrcTabToken, aux_name);
aux_name = use_alias && !getReceiverTable()->getAlias().isEmpty() ? getReceiverTable()->getAlias() : getReceiverTable()->getName();
name.replace(DstTabToken, aux_name);
}
aux_name.clear();
if(id_col)
aux_name = use_alias && !id_col->getAlias().isEmpty() ? id_col->getAlias() : id_col->getName();
name.replace(SrcColToken, aux_name);
if(name.size() > BaseObject::ObjectNameMaxLength)
name.remove(BaseObject::ObjectNameMaxLength, name.size());
return name;
}
void Relationship::setOriginalPrimaryKey(Constraint *pk)
{
pk_original = pk;
}
void Relationship::setMandatoryTable(TableId table_id, bool value)
{
BaseRelationship::setMandatoryTable(table_id, value);
this->invalidated = true;
}
void Relationship::setDeferrable(bool value)
{
deferrable = value;
this->invalidated = true;
}
void Relationship::setIdentifier(bool value)
{
/* Raises an error if the user try to set an self relationship, n-n relationship,
generalization or copy as identifier. Only 1-1, 1-n relationships can be
set as identifier. */
if(value &&
(src_table==dst_table ||
(rel_type==RelationshipNn ||
rel_type==RelationshipGen ||
rel_type==RelationshipDep)))
throw Exception(ErrorCode::InvIdentifierRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__);
invalidated = identifier != value;
identifier = value;
}
void Relationship::setSpecialPrimaryKeyCols(std::vector<unsigned> &cols)
{
/* Raises an error if the user try to set columns for special primary key when the
relationship type is identifier or self relationship */
if(!cols.empty() && (isSelfRelationship() || isIdentifier()))
throw Exception(Exception::getErrorMessage(ErrorCode::InvUseSpecialPrimaryKey)
.arg(this->getName()),
ErrorCode::InvUseSpecialPrimaryKey,__PRETTY_FUNCTION__,__FILE__,__LINE__);
this->column_ids_pk_rel=cols;
}
std::vector<unsigned> Relationship::getSpecialPrimaryKeyCols()
{
return this->column_ids_pk_rel;
}
void Relationship::addGeneratedColsToSpecialPk()
{
if(!pk_special)
return;
auto gen_cols = gen_columns;
for(auto &attrib : rel_attributes)
gen_cols.push_back(dynamic_cast<Column *>(attrib));
//Adds the columns to the primary key
for(auto &col_idx : column_ids_pk_rel)
{
if(col_idx < gen_cols.size() &&
!pk_special->isColumnExists(gen_cols[col_idx], Constraint::SourceCols))
pk_special->addColumn(gen_cols[col_idx], Constraint::SourceCols);
}
}
void Relationship::createSpecialPrimaryKey()
{
if(!column_ids_pk_rel.empty())
{
unsigned i = 0;
std::vector<Column *> gen_cols;
PhysicalTable *table = getReceiverTable();
// First we need to remove the original primary key in order to use the special pk
if(table->getPrimaryKey())
{
pk_original = table->getPrimaryKey();
table->removeObject(pk_original);
}
/* Allocates the primary key with the following feature:
1) Protected and included by linking in order to be easily identified
on internal operations of the relationship
2) Use the same tablespace as the receiver table */
//pk_special=new Constraint;
pk_special = createObject<Constraint>();
pk_special->setName(generateObjectName(PkPattern));
pk_special->setAlias(generateObjectName(PkPattern, nullptr, true));
pk_special->setConstraintType(ConstraintType::PrimaryKey);
pk_special->setAddedByLinking(true);
pk_special->setParentRelationship(this);
pk_special->setProtected(true);
pk_special->setTablespace(dynamic_cast<Tablespace *>(getReceiverTable()->getTablespace()));
//For generalization relationships generates the primary key in form of ALTER command
pk_special->setDeclaredInTable(this->getRelationshipType()!=RelationshipGen);
// Adding the columns of the original primary key to the special one
for(i=0; pk_original && i < pk_original->getColumnCount(Constraint::SourceCols); i++)
pk_special->addColumn(pk_original->getColumn(i, Constraint::SourceCols), Constraint::SourceCols);
//Adding generated columns and relationship attributes to the special primary key
addGeneratedColsToSpecialPk();
try
{
this->addObject(pk_special);
}
catch(Exception &)
{
//Case some error is raised deletes the special primary key
//delete pk_special;
discardObject(pk_special);
pk_special=nullptr;
}
}
}
void Relationship::setTableNameRelNN(const QString &name)
{
if(rel_type==RelationshipNn)
{
if(!BaseObject::isValidName(name))
throw Exception(ErrorCode::AsgInvalidNameTableRelNN, __PRETTY_FUNCTION__,__FILE__,__LINE__);
invalidated = tab_name_relnn != name;
tab_name_relnn = name;
tab_name_relnn.remove('"');
}
}
QString Relationship::getTableNameRelNN()
{
return tab_name_relnn;
}
void Relationship::setPartitionBoundingExpr(const QString &part_bound_expr)
{
part_bounding_expr = (part_bound_expr.toLower() == Attributes::Default.toLower() ? "" : part_bound_expr);
this->invalidated = true;
}
QString Relationship::getPartitionBoundingExpr()
{
return part_bounding_expr;
}
bool Relationship::isDeferrable()
{
return deferrable;
}
void Relationship::setDeferralType(DeferralType defer_type)
{
invalidated = deferral_type != defer_type;
deferral_type = defer_type;
}
DeferralType Relationship::getDeferralType()
{
return deferral_type;
}
void Relationship::setFKIndexType(IndexingType idx_type)
{
invalidated = fk_idx_type != idx_type;
fk_idx_type = idx_type;
}
void Relationship::setActionType(ActionType act_type, Constraint::ActionEvent act_id)
{
if(act_id == Constraint::DeleteAction)
{
invalidated = del_action != act_type;
del_action = act_type;
}
else
{
invalidated = upd_action != act_type;
upd_action = act_type;
}
}
ActionType Relationship::getActionType(unsigned act_id)
{
if(act_id == Constraint::DeleteAction)
return del_action;
return upd_action;
}
int Relationship::getObjectIndex(TableObject *object)
{
std::vector<TableObject *>::iterator itr, itr_end;
std::vector<TableObject *> *list=nullptr;
TableObject *obj_aux=nullptr;
ObjectType obj_type;
bool found=false;
//Raises an error if the object is not allocated
if(!object)
throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);
//Selecting the correct list using the object type
obj_type=object->getObjectType();
if(obj_type==ObjectType::Column)
list=&rel_attributes;
else if(obj_type==ObjectType::Constraint)
list=&rel_constraints;
else
//Raises an error if the object type isn't valid (not a column or constraint)
throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__);
itr=list->begin();
itr_end=list->end();
while(itr!=itr_end && !found)
{
obj_aux=(*itr);
found=(obj_aux==object || obj_aux->getName()==object->getName());
itr++;
}
if(found)
return ((itr-list->begin())-1);
else
return -1;
}
/* template<class Class>
Class *Relationship::createObject()
{
if constexpr (std::is_same_v<Class, Column>)
{
Column *new_col = nullptr;
if(cols_stack.empty())
new_col = new Column;
else
{
new_col = cols_stack.top();
cols_stack.pop();
}
return new_col;
}
if constexpr (std::is_same_v<Class, Constraint>)
{
Constraint *new_constr = nullptr;
if(constrs_stack.empty())
new_constr = new Constraint;
else
{
new_constr = constrs_stack.top();
constrs_stack.pop();
}
return new_constr;
}
if constexpr (std::is_same_v<Class, Index>)
{
Index *new_index = nullptr;
if(indexes_stack.empty())
new_index = new Index;
else
{
new_index = indexes_stack.top();
indexes_stack.pop();
}
return new_index;
}
return nullptr;
} */
template<class Class>
Class *Relationship::createObject()
{
std::stack<Class *> *obj_stack = nullptr;
if constexpr (std::is_same_v<Class, Column>)
obj_stack = &cols_stack;
else if constexpr (std::is_same_v<Class, Constraint>)
obj_stack = &constrs_stack;
else if constexpr (std::is_same_v<Class, Index>)
obj_stack = &indexes_stack;
else
return nullptr;
Class *new_obj = nullptr;
if(obj_stack->empty())
new_obj = new Class;
else
{
new_obj = obj_stack->top();
obj_stack->pop();
}
return new_obj;
}
void Relationship::discardObject(TableObject* object)
{
if(!object)
throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);
ObjectType obj_type = object->getObjectType();
if(obj_type == ObjectType::Column)
cols_stack.push(dynamic_cast<Column *>(object));
else if(obj_type == ObjectType::Constraint)
{
Constraint *constr = dynamic_cast<Constraint *>(object);
constr->removeColumns();
constrs_stack.push(constr);
}
else if(obj_type == ObjectType::Index)
{
Index *index = dynamic_cast<Index *>(object);
index->removeIndexElements();
indexes_stack.push(index);
}
}
bool Relationship::isColumnExists(Column *column)
{
std::vector<Column *>::iterator itr, itr_end;
Column *col_aux=nullptr;
bool found=false;
//Raises an error if the column is not allocated
if(!column)
throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);
itr=gen_columns.begin();
itr_end=gen_columns.end();
while(itr!=itr_end && !found)
{
col_aux=(*itr);
found=(col_aux==column || col_aux->getName()==column->getName());
itr++;
}
return found;
}
void Relationship::addObject(TableObject *tab_obj, int obj_idx)
{
ObjectType obj_type;
std::vector<TableObject *> *obj_list=nullptr;
/* Raises an error if the user try to add manually a special primary key on
the relationship and the relationship type is not generalization or copy */
if((rel_type==RelationshipGen ||
rel_type==RelationshipDep ||
rel_type==RelationshipPart) &&
!(tab_obj->isAddedByRelationship() &&
tab_obj->isProtected() &&
tab_obj->getObjectType()==ObjectType::Constraint))
throw Exception(ErrorCode::AsgObjectInvalidRelationshipType,__PRETTY_FUNCTION__,__FILE__,__LINE__);
try
{
//Checks if the object isn't exists on the relationshi and doesn't belongs to a table
if(tab_obj->getParentTable() || getObjectIndex(tab_obj) >= 0)
{
throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject)
.arg(tab_obj->getName(true))
.arg(tab_obj->getTypeName())
.arg(this->getName(true))
.arg(this->getTypeName()),
ErrorCode::AsgDuplicatedObject, __PRETTY_FUNCTION__,__FILE__,__LINE__);
}
//Gets the object list according the object type
obj_type=tab_obj->getObjectType();
if(obj_type==ObjectType::Column)
obj_list=&rel_attributes;
else if(obj_type==ObjectType::Constraint)
obj_list=&rel_constraints;
else
//Raises an error if the object type isn't valid (not a column or constraint)
throw Exception(ErrorCode::AsgObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__);
//Defines the parent table for the object only for validation
tab_obj->setParentTable(src_table);
tab_obj->setParentRelationship(this);
//Generates the code for the object only for validation
if(obj_type==ObjectType::Column)
dynamic_cast<Column *>(tab_obj)->getSourceCode(SchemaParser::SqlCode);
else
{
Constraint *rest=nullptr;
rest=dynamic_cast<Constraint *>(tab_obj);
//Raises an error if the user try to add as foreign key to relationship
if(rest->getConstraintType()==ConstraintType::ForeignKey)
throw Exception(ErrorCode::AsgForeignKeyRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__);
rest->getSourceCode(SchemaParser::SqlCode);
}
//Switch back to null the object parent
tab_obj->setParentTable(nullptr);
if(obj_idx < 0 || obj_idx >= static_cast<int>(obj_list->size()))
obj_list->push_back(tab_obj);
else
{
if(obj_list->size() > 0)
obj_list->insert((obj_list->begin() + obj_idx), tab_obj);
else
obj_list->push_back(tab_obj);
}
tab_obj->setAddedByLinking(true);
this->invalidated=true;
}
catch(Exception &e)
{
if(e.getErrorCode()==ErrorCode::UndefinedAttributeValue)
throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition)
.arg(tab_obj->getName())
.arg(tab_obj->getTypeName()),
ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
else
throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
}
}
void Relationship::destroyObjects()
{
while(!rel_constraints.empty())
{
delete rel_constraints.back();
rel_constraints.pop_back();
}
while(!rel_attributes.empty())
{
delete rel_attributes.back();
rel_attributes.pop_back();
}
while(!cols_stack.empty())
{
delete cols_stack.top();
cols_stack.pop();
}
while(!constrs_stack.empty())
{
delete constrs_stack.top();
constrs_stack.pop();
}
while(!indexes_stack.empty())
{
delete indexes_stack.top();
indexes_stack.pop();
}
}
void Relationship::removeObject(unsigned obj_id, ObjectType obj_type)
{
std::vector<TableObject *> *obj_list=nullptr;
TableObject *tab_obj=nullptr;
PhysicalTable *recv_table=nullptr;
if(obj_type==ObjectType::Column)
obj_list=&rel_attributes;
else if(obj_type==ObjectType::Constraint)
obj_list=&rel_constraints;
else
throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__);
//Raises an error if the object index is out of bound
if(obj_id >= obj_list->size())
throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__);
tab_obj=obj_list->at(obj_id);
recv_table=this->getReceiverTable();
if(obj_type==ObjectType::Column)
{
Column *col=nullptr;
Constraint *constr=nullptr;
std::vector<TableObject *>::iterator itr, itr_end;
std::vector<unsigned>::iterator sp_pk_itr;
bool refer=false;
int col_idx=0;
itr=rel_constraints.begin();
itr_end=rel_constraints.end();
col=dynamic_cast<Column *>(tab_obj);
while(itr!=itr_end && !refer)
{
constr=dynamic_cast<Constraint *>(*itr);
//Check is the column is referenced by one relationship constraints
refer=(constr->getColumn(col->getName(), Constraint::SourceCols) ||
constr->getColumn(col->getName(), Constraint::ReferencedCols));
itr++;
}
//Raises an error if the column to be removed is referenced by a relationship constraint
if(refer)
throw Exception(Exception::getErrorMessage(ErrorCode::RemInderectReference)
.arg(col->getName())
.arg(col->getTypeName())
.arg(constr->getName())
.arg(constr->getTypeName())
.arg(this->getName(true))
.arg(this->getTypeName()),
ErrorCode::RemInderectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__);
//Generating the column index inside the special pk column list
col_idx=getObjectIndex(col) + gen_columns.size();
sp_pk_itr=find(column_ids_pk_rel.begin(), column_ids_pk_rel.end(), col_idx);
//Remove the attribute from the special pk column id list
if(sp_pk_itr!=column_ids_pk_rel.end())
column_ids_pk_rel.erase(sp_pk_itr);
removeColumnFromTablePK(dynamic_cast<PhysicalTable *>(col->getParentTable()), col);
}
//Removing the object from the receiver table
if(recv_table && tab_obj->getParentTable()==recv_table)
{
recv_table->removeObject(tab_obj);
tab_obj->setParentTable(nullptr);
}
//Removes the column
obj_list->erase(obj_list->begin() + obj_id);
this->invalidated=true;
}
void Relationship::removeObject(TableObject *object)
{
if(!object)
throw Exception(ErrorCode::RemNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);
removeObject(getObjectIndex(object),object->getObjectType());
}
void Relationship::removeAttribute(unsigned attrib_idx)
{
removeObject(attrib_idx, ObjectType::Column);
}
void Relationship::removeConstraint(unsigned constr_idx)
{
removeObject(constr_idx, ObjectType::Constraint);
}
std::vector<Column *> Relationship::getGeneratedColumns()
{
return gen_columns;
}
Table *Relationship::getGeneratedTable()
{
return table_relnn;
}
std::vector<Constraint *> Relationship::getGeneratedConstraints()
{
std::vector<Constraint *> vect;
if(fk_rel1n)
vect.push_back(fk_rel1n);
if(uq_rel11)
vect.push_back(uq_rel11);
if(pk_relident)
vect.push_back(pk_relident);
return vect;
}
Index *Relationship::getGeneratedIndex()
{
return fk_index;
}
void Relationship::configureSearchAttributes()
{
BaseRelationship::configureSearchAttributes();
search_attribs[Attributes::RelatedForeignKey] = fk_rel1n ? fk_rel1n->getSignature(true) : "";
}
TableObject *Relationship::getObject(unsigned obj_idx, ObjectType obj_type)
{
std::vector<TableObject *> *list=nullptr;
if(obj_type==ObjectType::Column)
list=&rel_attributes;
else if(obj_type==ObjectType::Constraint)
list=&rel_constraints;
else
throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__);
if(obj_idx >= list->size())
throw Exception(ErrorCode::RefObjectInvalidIndex, __PRETTY_FUNCTION__,__FILE__,__LINE__);
return list->at(obj_idx);
}
TableObject *Relationship::getObject(const QString &name, ObjectType obj_type)
{
std::vector<TableObject *>::iterator itr, itr_end;
std::vector<TableObject *> *list=nullptr;
TableObject *obj_aux=nullptr;
bool found=false;
if(obj_type==ObjectType::Column)
list=&rel_attributes;
else if(obj_type==ObjectType::Constraint)
list=&rel_constraints;
else
throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__);
itr=list->begin();
itr_end=list->end();
while(itr!=itr_end && !found)
{
obj_aux=(*itr);
found=(obj_aux->getName()==name);
itr++;
}
if(found)
return obj_aux;
else
return nullptr;
}
Column *Relationship::getAttribute(unsigned attrib_idx)
{
//Raises an error if the attribute index is out of bound
if(attrib_idx >= rel_attributes.size())
throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__);
return dynamic_cast<Column *>(rel_attributes[attrib_idx]);
}
Column *Relationship::getAttribute(const QString &name)
{
return dynamic_cast<Column *>(getObject(name,ObjectType::Column));
}
std::vector<TableObject *> Relationship::getAttributes()
{
return rel_attributes;
}
Constraint *Relationship::getConstraint(unsigned constr_idx)
{
//Raises an error if the constraint index is out of bound
if(constr_idx >= rel_constraints.size())
throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__);
return dynamic_cast<Constraint *>(rel_constraints[constr_idx]);
}
Constraint *Relationship::getConstraint(const QString &name)
{
return dynamic_cast<Constraint *>(getObject(name,ObjectType::Constraint));
}
std::vector<TableObject *> Relationship::getConstraints()
{
return rel_constraints;
}
unsigned Relationship::getAttributeCount()
{
return rel_attributes.size();
}
unsigned Relationship::getConstraintCount()
{
return rel_constraints.size();
}
unsigned Relationship::getObjectCount(ObjectType obj_type)
{
if(obj_type==ObjectType::Column)
return rel_attributes.size();
else if(obj_type==ObjectType::Constraint)
return rel_constraints.size();
else
throw Exception(ErrorCode::RefObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__);
}
void Relationship::addConstraints(PhysicalTable *recv_tab)
{
Constraint *constr=nullptr, *pk=nullptr;
unsigned constr_id, constr_cnt, i, count;
try
{
constr_cnt=rel_constraints.size();
for(constr_id=0; constr_id < constr_cnt; constr_id++)
{
constr=dynamic_cast<Constraint *>(rel_constraints[constr_id]);
constr->setAddedByLinking(true);
constr->setParentRelationship(this);
//Breaks the iteration if the constraist has a parent
if(constr->getParentTable())