/
hasrelationships.hpp
1635 lines (1347 loc) · 66.6 KB
/
hasrelationships.hpp
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
#pragma once
#ifndef ORM_TINY_CONCERNS_HASRELATIONSHIPS_HPP
#define ORM_TINY_CONCERNS_HASRELATIONSHIPS_HPP
#include "orm/macros/systemheader.hpp"
TINY_SYSTEM_HEADER
#include <range/v3/algorithm/contains.hpp>
#include "orm/exceptions/invalidtemplateargumenterror.hpp"
#include "orm/tiny/concerns/hasrelationstore.hpp"
#include "orm/tiny/exceptions/relationmappingnotfounderror.hpp"
#include "orm/tiny/exceptions/relationnotloadederror.hpp"
#include "orm/tiny/macros/crtpmodelwithbase.hpp"
#include "orm/tiny/relations/belongsto.hpp"
#include "orm/tiny/relations/belongstomany.hpp"
#include "orm/tiny/relations/hasmany.hpp"
#include "orm/tiny/relations/hasone.hpp"
#include "orm/utils/string.hpp"
TINYORM_BEGIN_COMMON_NAMESPACE
namespace Orm::Tiny
{
namespace Relations
{
class IsPivotModel;
}
namespace Concerns
{
/*! Model relationships. */
template<typename Derived, AllRelationsConcept ...AllRelations>
class HasRelationships :
private Concerns::HasRelationStore<Derived, AllRelations...>
{
/* Using starts in the BaseRelationStore::visit() and is used to access private
visited methods. */
friend Concerns::HasRelationStore<Derived, AllRelations...>;
// To access private queriesRelationshipsWithVisitor()
friend Concerns::QueriesRelationships<Derived>;
// To access XyzVisitor()-s, replaceRelations() and few other private methods
friend Model<Derived, AllRelations...>;
// To access private pushVisited()
friend Support::Stores::PushRelationStore<Derived, AllRelations...>;
// To access private touchOwnersVisited()
friend Support::Stores::TouchOwnersRelationStore<Derived, AllRelations...>;
// To access private serializeRelationVisited()
template<SerializedAttributes C, typename Derived_,
AllRelationsConcept ...AllRelations_>
friend class Support::Stores::SerializeRelationStore;
// To access eagerLoadRelationWithVisitor()
friend TinyBuilder<Derived>;
/*! Alias for the attribute utils. */
using AttributeUtils = Orm::Tiny::Utils::Attribute;
/*! Alias for the string utils. */
using StringUtils = Orm::Utils::String;
/*! Alias for the type utils. */
using TypeUtils = Orm::Utils::Type;
public:
/*! Alias for the RelationsContainer. */
using RelationsContainerType = RelationsContainer<AllRelations...>;
/* HasRelationships related */
/*! Get a relationship for Many types relation (load a relationship lazily if
not loaded). */
template<typename Related,
template<typename> typename Container = ModelsCollection>
const Container<Related *>
getRelationValue(const QString &relation);
/*! Get a relationship for a One type relation (load a relationship lazily if
not loaded). */
template<typename Related, typename Tag> requires std::same_as<Tag, One>
Related *
getRelationValue(const QString &relation);
/*! Get a specified relationship (throw if a relationship is not loaded). */
template<typename Related,
template<typename> typename Container = ModelsCollection>
const Container<Related *>
getRelation(const QString &relation);
/*! Get a specified relationship as Related type, for use with HasOne and
BelongsTo relation types (throw if a relationship is not loaded). */
template<typename Related, typename Tag> requires std::same_as<Tag, One>
Related *getRelation(const QString &relation);
/*! Determine if the given relation is loaded. */
bool relationLoaded(const QString &relation) const;
/*! Set the given relationship on the model. */
template<typename Related>
Derived &setRelation(const QString &relation,
const ModelsCollection<Related> &models);
/*! Set the given relationship on the model. */
template<typename Related>
Derived &setRelation(const QString &relation,
ModelsCollection<Related> &&models);
/*! Set the given relationship on the model. */
template<typename Related>
Derived &setRelation(const QString &relation,
const std::optional<Related> &model);
/*! Set the given relationship on the model. */
template<typename Related>
Derived &setRelation(const QString &relation, std::optional<Related> &&model);
/*! Set the given relationship on the model. */
template<typename Related>
requires std::is_base_of_v<Relations::IsPivotModel, Related>
Derived &setRelation(const QString &relation,
const std::optional<Related> &model);
/*! Set the given relationship on the model. */
template<typename Related>
requires std::is_base_of_v<Relations::IsPivotModel, Related>
Derived &setRelation(const QString &relation, std::optional<Related> &&model);
/*! Get all the loaded relations for the instance. */
inline const RelationsContainer<AllRelations...> &getRelations() const noexcept;
/*! Get all the loaded relations for the instance. */
inline RelationsContainer<AllRelations...> &getRelations() noexcept;
/*! Unset all the loaded relations for the instance. */
Derived &unsetRelations();
/*! Unset a loaded relationship. */
Derived &unsetRelation(const QString &relation);
/* Relationships factory methods */
/*! Define a one-to-one relationship. */
template<typename Related>
std::unique_ptr<Relations::HasOne<Derived, Related>>
hasOne(QString foreignKey = "", QString localKey = "");
/*! Define an inverse one-to-one or many relationship. */
template<typename Related>
std::unique_ptr<Relations::BelongsTo<Derived, Related>>
belongsTo(QString foreignKey = "", QString ownerKey = "", QString relation = "");
/*! Define a one-to-many relationship. */
template<typename Related>
std::unique_ptr<Relations::HasMany<Derived, Related>>
hasMany(QString foreignKey = "", QString localKey = "");
/*! Define a many-to-many relationship. */
template<typename Related, typename PivotType = Relations::Pivot>
std::unique_ptr<Relations::BelongsToMany<Derived, Related, PivotType>>
belongsToMany(QString table = "", QString foreignPivotKey = "",
QString relatedPivotKey = "", QString parentKey = "",
QString relatedKey = "", QString relation = "");
/* Touching timestamps */
/*! Touch the owning relations of the model. */
void touchOwners() const;
/*! Get the relationships that are touched on save. */
inline const QStringList &getTouchedRelations() const;
/*! Add one relationship that is touched on save. */
inline Derived &addTouch(const QString &touch);
/*! Add one relationship that is touched on save. */
inline Derived &addTouch(QString &&touch);
/*! Add one relationship that is touched on save. */
inline Derived &addTouches(const QStringList &touches);
/*! Add one relationship that is touched on save. */
inline Derived &addTouches(QStringList &&touches);
/*! Set the relationships that are touched on save. */
inline Derived &setTouchedRelations(const QStringList &touches);
/*! Set the relationships that are touched on save. */
inline Derived &setTouchedRelations(QStringList &&touches);
/*! Determine if the model touches a given relation. */
inline bool touches(const QString &relation) const;
/*! Clear the u_touches for the model. */
inline Derived &clearTouches();
/* Serialization - Relations */
/*! Convert the model's relationships to the map or vector. */
template<SerializedAttributes C, typename PivotType = void>
C serializeRelations() const;
/* Others */
/*! Equality comparison operator for the HasRelationships concern. */
bool operator==(const HasRelationships &right) const;
/*! Determine whether the current model contains a pivot relation alternative
in the m_relations std::variant. */
constexpr static bool hasPivotRelation() noexcept;
protected:
/*! Relation visitor lambda type. */
using RelationVisitor = std::function<void(
typename Concerns::HasRelationStore<Derived, AllRelations...>
::BaseRelationStore &)>;
/*! Get a relationship value from a method. */
template<class Related,
template<typename> typename Container = ModelsCollection>
Container<Related *>
getRelationshipFromMethod(const QString &relation);
/*! Get a relationship value from a method. */
template<class Related, typename Tag> requires std::same_as<Tag, One>
Related *
getRelationshipFromMethod(const QString &relation);
/*! Set the entire relations hash on the model. */
Derived &setRelations(const RelationsContainer<AllRelations...> &relations);
/*! Set the entire relations hash on the model. */
Derived &setRelations(RelationsContainer<AllRelations...> &&relations);
/* Relationships factory methods */
/*! Instantiate a new HasOne relationship. */
template<typename Related>
inline std::unique_ptr<Relations::HasOne<Derived, Related>>
newHasOne(std::unique_ptr<Related> &&related, Derived &parent,
const QString &foreignKey, const QString &localKey) const;
/*! Instantiate a new BelongsTo relationship. */
template<typename Related>
inline std::unique_ptr<Relations::BelongsTo<Derived, Related>>
newBelongsTo(std::unique_ptr<Related> &&related,
Derived &child, const QString &foreignKey,
const QString &ownerKey, const QString &relation) const;
/*! Instantiate a new HasMany relationship. */
template<typename Related>
inline std::unique_ptr<Relations::HasMany<Derived, Related>>
newHasMany(std::unique_ptr<Related> &&related, Derived &parent,
const QString &foreignKey, const QString &localKey) const;
/*! Instantiate a new BelongsToMany relationship. */
template<typename Related, typename PivotType>
inline std::unique_ptr<Relations::BelongsToMany<Derived, Related, PivotType>>
newBelongsToMany(std::unique_ptr<Related> &&related, Derived &parent,
const QString &table, const QString &foreignPivotKey,
const QString &relatedPivotKey, const QString &parentKey,
const QString &relatedKey, const QString &relation) const;
/*! Create a new model instance for a related model. */
template<typename Related>
std::unique_ptr<Related> newRelatedInstance() const;
/*! Guess the "belongs to" relationship name. */
template<typename Related>
QString guessBelongsToRelation() const;
/*! Guess the "belongs to many" relationship name. */
template<typename Related>
QString guessBelongsToManyRelation() const;
/*! Get the joining table name for a many-to-many relation. */
template<typename Related>
QString pivotTableName() const;
/* Serialization - Relations */
/*! Get a map of all serializable relations (visible/hidden). */
RelationsContainer<AllRelations...> getSerializableRelations() const;
/* Others */
/*! Compare the u_relations hash (size and keys only). */
static bool compareURelations(
const QHash<QString, RelationVisitor> &left,
const QHash<QString, RelationVisitor> &right);
/* Data members */
/*! Map of relation names to methods. */
QHash<QString, RelationVisitor> u_relations;
/* The libstdc++ shipped with the GCC <12.1 doesn't allow an incomplete
mapped_type (value) in the std::unordered_map. */
/*! The loaded relationships for the model. */
RelationsContainer<AllRelations...> m_relations;
/*! The relationships that should be touched on save. */
QStringList u_touches;
// CUR1 use sets instead of QStringList where appropriate silverqx
/*! Currently loaded Pivot relation names. */
std::unordered_set<QString> m_pivots;
private:
/*! Alias for the enum struct RelationMappingNotFoundError::From. */
using RelationFrom = Tiny::Exceptions::RelationMappingNotFoundError::From;
/*! Throw exception if a relation is not defined. */
void validateUserRelation(const QString &name,
RelationFrom from = RelationFrom::UNDEFINED) const;
/*! Obtain related models from "relationships" data member hash
without any checks. */
template<class Related,
template<typename> typename Container = ModelsCollection>
Container<Related *>
getRelationFromHash(const QString &relation);
/*! Obtain related models from "relationships" data member hash
without any checks. */
template<class Related, typename Tag> requires std::same_as<Tag, One>
Related *
getRelationFromHash(const QString &relation);
/*! Create lazy store and obtain a relationship from defined method. */
template<typename Related, typename Result>
Result getRelationshipFromMethodWithVisitor(const QString &relation) const;
/*! Throw exception if correct getRelation/Value() method was not used, to avoid
std::bad_variant_access. */
template<typename Result, typename Related, typename T>
void checkRelationType(const T &relationVariant, const QString &relation,
const QString &source) const;
/*! Guess the relationship name for belongsTo/belongsToMany. */
template<typename Related>
QString guessBelongsToRelationInternal() const;
/* Eager load relation store related */
/*! Obtain a relationship instance for eager loading. */
template<SameDerivedCollectionModel<Derived> CollectionModel>
void eagerLoadRelationWithVisitor(
const WithItem &relation, const TinyBuilder<Derived> &builder,
ModelsCollection<CollectionModel> &models) const;
/* Get related table for belongs-to-many relation store related */
/*! Get Related model table name if the relation is BelongsToMany, otherwise
return empty std::optional. */
std::optional<QString>
getRelatedTableForBelongsToManyWithVisitor(const QString &relation) const;
/* Push relation store related */
/*! Create push store and call push for every model. */
bool pushWithVisitor(const QString &relation,
RelationsType<AllRelations...> &models) const;
/*! On the base of alternative held by m_relations decide, which
pushVisitied() to execute. */
template<typename Related>
void pushVisited() const;
/*! Push for Many relation types. */
template<typename Related, typename Tag> requires std::same_as<Tag, Many>
void pushVisited() const;
/*! Push for One relation type. */
template<typename Related, typename Tag> requires std::same_as<Tag, One>
void pushVisited() const;
/* Touch owners store related */
/*! Create 'touch owners relation store' and touch all related models. */
void touchOwnersWithVisitor(const QString &relation) const;
/*! On the base of alternative held by m_relations decide, which
touchOwnersVisited() to execute. */
template<typename Related, typename Relation>
void touchOwnersVisited(Relation &&relation, const QString &relationName);
/* QueriesRelationships store related */
/*! Create 'QueriesRelationships relation store' to obtain relation instance. */
template<typename Related = void>
void queriesRelationshipsWithVisitor(
const QString &relation, Concerns::QueriesRelationships<Derived> &origin,
const QString &comparison, qint64 count, const QString &condition,
const std::function<void(
Concerns::QueriesRelationshipsCallback<Related> &)> &callback,
std::optional<std::reference_wrapper<
QStringList>> relations = std::nullopt) const;
/* Operations on a Model instance */
/*! Obtain all loaded relation names except pivot relations. */
QVector<WithItem> getLoadedRelationsWithoutPivot() const;
/*! Replace relations in the m_relation. */
void replaceRelations(RelationsContainer<AllRelations...> &relations,
const QVector<WithItem> &onlyRelations);
/* Serialization - Relations */
/*! Create and visit the serialize relation store. */
template<SerializedAttributes C>
void serializeRelationWithVisitor(
const QString &relation, const RelationsType<AllRelations...> &models,
C &attributes) const;
/*! On the base of alternative held by m_relations decide, which
serializeRelation() to execute. */
template<typename Related, SerializedAttributes C, typename PivotType>
void serializeRelationVisited(
QString relation, const RelationsType<AllRelations...> &models,
C &attributes) const;
/*! Serialize for Many relation types. */
template<typename Related, bool isMap, typename PivotType>
inline static void serializeRelation(QVariant &relationSerialized, // don't remove inline
const ModelsCollection<Related> &models);
/*! Serialize for One relation type. */
template<typename Related, bool isMap>
inline static void serializeRelation(QVariant &relationSerialized, // don't remove inline
const std::optional<Related> &model);
/*! Insert the serialized relation attributes to the final attributes map. */
inline static void
insertSerializedRelation(QVariantMap &attributes, const QString &relation,
const QVariant &relationSerialized);
/*! Emplace the serialized relation attributes to the final attributes vector. */
inline static void
insertSerializedRelation(QVector<AttributeItem> &attributes, QString &&relation,
QVariant &&relationSerialized);
/* Serialization - HidesAttributes */
/*! Get a relations map of visible serializable relations. */
static RelationsContainer<AllRelations...>
getSerializableVisibleRelations(
const RelationsContainer<AllRelations...> &relations,
const std::set<QString> &visible);
/*! Get a relations map without hidden relation attributes. */
static RelationsContainer<AllRelations...>
removeSerializableHiddenRelations(
RelationsContainer<AllRelations...> &&relations,
const std::set<QString> &hidden);
/* Static cast this to a child's instance type (CRTP) */
TINY_CRTP_MODEL_WITH_BASE_DECLARATIONS
};
/* public */
/* HasRelationships related */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, template<typename> typename Container>
const Container<Related *> // NOLINT(readability-const-return-type)
HasRelationships<Derived, AllRelations...>::getRelationValue(const QString &relation)
{
/*! If the key already exists in the relationships hash, it just means the
relationship has already been loaded, so we'll just return it out of
here because there is no need to query within the relations twice. */
if (this->relationLoaded(relation))
return getRelationFromHash<Related, Container>(relation);
/*! If the relation is defined on the model, then lazy load and return results
from the query and hydrate the relationship's value on the "relationships"
data member m_relations. */
if (basemodel().getUserRelations().contains(relation))
return getRelationshipFromMethod<Related, Container>(relation);
return {};
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, typename Tag> requires std::same_as<Tag, One>
Related *
HasRelationships<Derived, AllRelations...>::getRelationValue(const QString &relation)
{
/*! If the key already exists in the relationships hash, it just means the
relationship has already been loaded, so we'll just return it out of
here because there is no need to query within the relations twice. */
if (this->relationLoaded(relation))
return getRelationFromHash<Related, Tag>(relation);
/*! If the relation is defined on the model, then lazy load and return results
from the query and hydrate the relationship's value on the "relationships"
data member m_relations. */
if (basemodel().getUserRelations().contains(relation))
return getRelationshipFromMethod<Related, Tag>(relation);
return nullptr;
}
// TODO make getRelation() Container argument compatible with STL containers API silverqx
// TODO solve different behavior like Eloquent getRelation() silverqx
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, template<typename> typename Container>
const Container<Related *> // NOLINT(readability-const-return-type)
HasRelationships<Derived, AllRelations...>::getRelation(const QString &relation)
{
if (!relationLoaded(relation))
throw Exceptions::RelationNotLoadedError(
TypeUtils::classPureBasename<Derived>(), relation);
return getRelationFromHash<Related, Container>(relation);
}
/* Returning shared_ptr for getRelation()-related methods would be unperformant,
imagine 100 models with 2 relations and every relation would have another 100
models, it's houndreds of shared_ptr-s which would have to be counted. */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, typename Tag> requires std::same_as<Tag, One>
Related *
HasRelationships<Derived, AllRelations...>::getRelation(const QString &relation)
{
if (!relationLoaded(relation))
throw Exceptions::RelationNotLoadedError(
TypeUtils::classPureBasename<Derived>(), relation);
return getRelationFromHash<Related, Tag>(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
bool
HasRelationships<Derived, AllRelations...>::relationLoaded(
const QString &relation) const
{
return m_relations.contains(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, const ModelsCollection<Related> &models)
{
m_relations[relation] = models;
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, ModelsCollection<Related> &&models)
{
m_relations[relation] = std::move(models);
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, const std::optional<Related> &model)
{
m_relations[relation] = model;
return this->model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, std::optional<Related> &&model)
{
m_relations[relation] = std::move(model);
return this->model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
requires std::is_base_of_v<Relations::IsPivotModel, Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, const std::optional<Related> &model)
{
m_pivots.insert(relation);
m_relations[relation] = model;
return this->model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
requires std::is_base_of_v<Relations::IsPivotModel, Related>
Derived &
HasRelationships<Derived, AllRelations...>::setRelation(
const QString &relation, std::optional<Related> &&model)
{
m_pivots.insert(relation);
m_relations[relation] = std::move(model);
return this->model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
const RelationsContainer<AllRelations...> &
HasRelationships<Derived, AllRelations...>::getRelations() const noexcept
{
return m_relations;
}
template<typename Derived, AllRelationsConcept ...AllRelations>
RelationsContainer<AllRelations...> &
HasRelationships<Derived, AllRelations...>::getRelations() noexcept
{
return m_relations;
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &HasRelationships<Derived, AllRelations...>::unsetRelations()
{
m_relations.clear();
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::unsetRelation(const QString &relation)
{
m_relations.erase(relation);
return model();
}
/* Relationships factory methods */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::HasOne<Derived, Related>>
HasRelationships<Derived, AllRelations...>::hasOne(
QString foreignKey, QString localKey)
{
auto &model = this->model();
auto instance = newRelatedInstance<Related>();
if (foreignKey.isEmpty())
foreignKey = model.getForeignKey(); // model() needed as it's overriden in the BasePivot
if (localKey.isEmpty())
localKey = basemodel().getKeyName();
return newHasOne<Related>(std::move(instance), model,
DOT_IN.arg(instance->getTable(), foreignKey),
localKey);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::BelongsTo<Derived, Related>>
HasRelationships<Derived, AllRelations...>::belongsTo(
QString foreignKey, QString ownerKey, QString relation)
{
/* If no relation name was given, we will use the Related class type to extract
the name and use that as the relationship name as most of the time this
will be what we desire to use for the belongsTo relationships. */
if (relation.isEmpty())
relation = guessBelongsToRelation<Related>();
auto instance = newRelatedInstance<Related>();
const auto &relatedKeyName = instance->getKeyName();
/* If no foreign key was supplied, we can guess the proper foreign key name
by using the snake_case name of the relationship, which when combined
with an "_id" should conventionally match the columns. */
if (foreignKey.isEmpty())
foreignKey = QStringLiteral("%1_%2").arg(relation, relatedKeyName);
/* Once we have the foreign key names, we return the relationship instance,
which will actually be responsible for retrieving and hydrating every
relations. */
if (ownerKey.isEmpty())
ownerKey = relatedKeyName;
return newBelongsTo<Related>(std::move(instance), model(),
foreignKey, ownerKey, relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::HasMany<Derived, Related>>
HasRelationships<Derived, AllRelations...>::hasMany(
QString foreignKey, QString localKey)
{
auto &model = this->model();
auto instance = newRelatedInstance<Related>();
if (foreignKey.isEmpty())
foreignKey = model.getForeignKey(); // model() needed as it's overriden in the BasePivot
if (localKey.isEmpty())
localKey = basemodel().getKeyName();
return newHasMany<Related>(std::move(instance), model,
DOT_IN.arg(instance->getTable(), foreignKey),
localKey);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, typename PivotType>
std::unique_ptr<Relations::BelongsToMany<Derived, Related, PivotType>>
HasRelationships<Derived, AllRelations...>::belongsToMany(
QString table, QString foreignPivotKey, QString relatedPivotKey,
QString parentKey, QString relatedKey, QString relation)
{
/* If no relation name was given, we will use the Related class type to extract
the name, suffix it with 's' and use that as the relationship name, as most
of the time this will be what we desire to use for the belongsToMany
relationships. */
if (relation.isEmpty())
relation = guessBelongsToManyRelation<Related>();
auto &model = this->model();
/* First, we'll need to determine the foreign key and "other key"
for the relationship. Once we have determined the keys, we'll make
the relationship instance we need for this. */
auto instance = newRelatedInstance<Related>();
if (foreignPivotKey.isEmpty())
foreignPivotKey = model.getForeignKey(); // model() needed as it's overriden in the BasePivot
if (relatedPivotKey.isEmpty())
relatedPivotKey = instance->getForeignKey();
/* If no table name was provided, we can guess it by concatenating the two
models using underscores in alphabetical order. The two model names
are transformed to snake_case from their default StudlyCase also. */
if (table.isEmpty())
table = pivotTableName<Related>();
if (parentKey.isEmpty())
parentKey = basemodel().getKeyName();
if (relatedKey.isEmpty())
relatedKey = instance->getKeyName();
return newBelongsToMany<Related, PivotType>(
std::move(instance), model, table, foreignPivotKey,
relatedPivotKey, parentKey, relatedKey, relation);
}
/* Touching timestamps */
template<typename Derived, AllRelationsConcept ...AllRelations>
void HasRelationships<Derived, AllRelations...>::touchOwners() const
{
for (const auto &relation : getTouchedRelations())
touchOwnersWithVisitor(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
const QStringList &
HasRelationships<Derived, AllRelations...>::getTouchedRelations() const
{
return basemodel().getUserTouches();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::addTouch(const QString &touch)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
basemodel().getUserTouches().emplaceBack(touch);
#else
basemodel().getUserTouches().append(touch);
#endif
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::addTouch(QString &&touch)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
basemodel().getUserTouches().emplaceBack(std::move(touch));
#else
basemodel().getUserTouches().append(std::move(touch));
#endif
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::addTouches(const QStringList &touches)
{
basemodel().getUserTouches().append(touches);
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::addTouches(QStringList &&touches)
{
basemodel().getUserTouches().append(std::move(touches));
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::setTouchedRelations(
const QStringList &touches)
{
basemodel().getUserTouches() = touches;
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::setTouchedRelations(
QStringList &&touches)
{
basemodel().getUserTouches() = std::move(touches);
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
bool
HasRelationships<Derived, AllRelations...>::touches(const QString &relation) const
{
return getTouchedRelations().contains(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::clearTouches()
{
basemodel().getUserTouches().clear();
return model();
}
/* Serialization - Relations */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<SerializedAttributes C, typename PivotType>
C HasRelationships<Derived, AllRelations...>::serializeRelations() const
{
const auto serializableRelations = getSerializableRelations();
C attributes;
if constexpr (HasReserveMethod<C>)
attributes.reserve(static_cast<QVector<AttributeItem>::size_type>(
serializableRelations.size()));
for (const auto &[relation, models] : serializableRelations) {
Q_ASSERT(!models.valueless_by_exception());
// Serialize belongs-to-many relation or the pivot model
if constexpr (hasPivotRelation() && !std::is_void_v<PivotType>) {
// Pivot model, skipping the relation store, call the visited directly
if (m_pivots.contains(relation))
serializeRelationVisited<PivotType, C, void>(relation, models,
attributes);
// belongs-to-many relation
else
serializeRelationWithVisitor(relation, models, attributes);
}
// Serialize has-one, has-many, and belongs-to relations
else
serializeRelationWithVisitor(relation, models, attributes);
}
return attributes;
}
/* Others */
template<typename Derived, AllRelationsConcept ...AllRelations>
bool HasRelationships<Derived, AllRelations...>::operator==(
const HasRelationships &right) const
{
// u_relations == right.u_relations
/* It compares only the size and keys and doesn't compare hash values because
the std::function doesn't have a full/complete operator==() (it only compares
for the nullptr). */
if (!compareURelations(u_relations, right.u_relations))
return false;
return m_relations == right.m_relations &&
u_touches == right.u_touches &&
m_pivots == right.m_pivots;
}
template<typename Derived, AllRelationsConcept ...AllRelations>
constexpr bool
HasRelationships<Derived, AllRelations...>::hasPivotRelation() noexcept
{
return std::disjunction_v<
std::is_base_of<Relations::IsPivotModel, AllRelations>...>;
}
/* protected */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<class Related, template<typename> typename Container>
Container<Related *>
HasRelationships<Derived, AllRelations...>::getRelationshipFromMethod(
const QString &relation)
{
// Obtain related models
auto relatedModels =
getRelationshipFromMethodWithVisitor<Related,
ModelsCollection<Related>>(relation);
setRelation(relation, std::move(relatedModels));
return getRelationFromHash<Related, Container>(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<class Related, typename Tag> requires std::same_as<Tag, One>
Related *
HasRelationships<Derived, AllRelations...>::getRelationshipFromMethod(
const QString &relation)
{
// Obtain related model
auto relatedModel =
getRelationshipFromMethodWithVisitor<Related,
std::optional<Related>>(relation);
setRelation(relation, std::move(relatedModel));
return getRelationFromHash<Related, Tag>(relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::setRelations(
const RelationsContainer<AllRelations...> &relations)
{
m_relations = relations;
return model();
}
template<typename Derived, AllRelationsConcept ...AllRelations>
Derived &
HasRelationships<Derived, AllRelations...>::setRelations(
RelationsContainer<AllRelations...> &&relations)
{
m_relations = std::move(relations);
return model();
}
/* Relationships factory methods */
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::HasOne<Derived, Related>>
HasRelationships<Derived, AllRelations...>::newHasOne(
std::unique_ptr<Related> &&related, Derived &parent,
const QString &foreignKey, const QString &localKey) const
{
return Relations::HasOne<Derived, Related>::instance(
std::move(related), parent, foreignKey, localKey);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::BelongsTo<Derived, Related>>
HasRelationships<Derived, AllRelations...>::newBelongsTo(
std::unique_ptr<Related> &&related, Derived &child,
const QString &foreignKey, const QString &ownerKey,
const QString &relation) const
{
return Relations::BelongsTo<Derived, Related>::instance(
std::move(related), child, foreignKey, ownerKey, relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Relations::HasMany<Derived, Related>>
HasRelationships<Derived, AllRelations...>::newHasMany(
std::unique_ptr<Related> &&related, Derived &parent,
const QString &foreignKey, const QString &localKey) const
{
return Relations::HasMany<Derived, Related>::instance(
std::move(related), parent, foreignKey, localKey);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related, typename PivotType>
std::unique_ptr<Relations::BelongsToMany<Derived, Related, PivotType>>
HasRelationships<Derived, AllRelations...>::newBelongsToMany(
std::unique_ptr<Related> &&related, Derived &parent, const QString &table,
const QString &foreignPivotKey, const QString &relatedPivotKey,
const QString &parentKey, const QString &relatedKey,
const QString &relation) const
{
return Relations::BelongsToMany<Derived, Related, PivotType>::instance(
std::move(related), parent, table, foreignPivotKey,
relatedPivotKey, parentKey, relatedKey, relation);
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
std::unique_ptr<Related>
HasRelationships<Derived, AllRelations...>::newRelatedInstance() const
{
auto instance = Related::instanceHeap();
if (instance->getConnectionName().isEmpty())
instance->setConnection(basemodel().getConnectionName());
return instance;
}
template<typename Derived, AllRelationsConcept ...AllRelations>
template<typename Related>
QString
HasRelationships<Derived, AllRelations...>::guessBelongsToRelation() const
{
static const QString relation = guessBelongsToRelationInternal<Related>();
/* validateUserRelation() method call can not be cached, has to be called
every time, to correctly inform the user about invalid relation name. */
// Validate if the guessed relation name exists in the u_relations