-
Notifications
You must be signed in to change notification settings - Fork 31
/
metadata.d
executable file
·3938 lines (3663 loc) · 177 KB
/
metadata.d
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
/**
* HibernateD - Object-Relation Mapping for D programming language, with interface similar to Hibernate.
*
* Hibernate documentation can be found here:
* $(LINK http://hibernate.org/docs)$(BR)
*
* Source file hibernated/metadata.d.
*
* This module contains implementation of Annotations parsing and ORM model metadata holder classes.
*
* Copyright: Copyright 2013
* License: $(LINK www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Author: Vadim Lopatin
*/
module hibernated.metadata;
import std.ascii;
import std.conv;
import std.datetime;
import std.exception;
//import std.stdio : writeln;
import std.string;
import std.traits;
import std.typecons;
import std.typetuple;
import std.variant;
import std.uuid;
import ddbc.core;
import ddbc.common;
import hibernated.annotations;
import hibernated.core;
import hibernated.type;
import hibernated.session;
import hibernated.dialect;
import hibernated.dialects.mysqldialect;
// For backwards compatibily
// 'enforceEx' will be removed with 2.089
static if(__VERSION__ < 2080) {
alias enforceHelper = enforceEx;
} else {
alias enforceHelper = enforce;
}
// For backwards compatibily (since D 2.101, logger is no longer in std.experimental)
static if (__traits(compiles, (){ import std.logger; } )) {
import std.logger : trace, warning;
} else {
import std.experimental.logger : trace, warning;
}
abstract class EntityMetaData {
@property size_t length();
const(EntityInfo) opIndex(int index) const;
const(EntityInfo) opIndex(string entityName) const;
const(PropertyInfo) opIndex(string entityName, string propertyName) const;
public string getEntityName(TypeInfo_Class type) const {
return getClassMap()[type].name;
}
public string getEntityNameForClass(T)() const {
return getClassMap()[T.classinfo].name;
}
int opApply(int delegate(ref const EntityInfo) dg) const;
public const(EntityInfo[]) getEntities() const;
public const(EntityInfo[string]) getEntityMap() const;
public const(EntityInfo[TypeInfo_Class]) getClassMap() const;
public const(EntityInfo) findEntity(string entityName) const;
public const(EntityInfo) findEntity(TypeInfo_Class entityClass) const;
public const(EntityInfo) findEntityForObject(Object obj) const;
public const(EntityInfo) getEntity(int entityIndex) const;
public int getEntityCount() const;
/// Entity factory
public Object createEntity(string entityName) const;
/// Fills all properties of entity instance from dataset
public int readAllColumns(Object obj, DataSetReader r, int startColumn) const;
/// Puts all properties of entity instance to dataset
public int writeAllColumns(Object obj, DataSetWriter w, int startColumn, bool exceptKey = false) const;
public string generateFindAllForEntity(Dialect dialect, string entityName) const;
public int getFieldCount(const EntityInfo ei, bool exceptKey) const;
public string getAllFieldList(Dialect dialect, const EntityInfo ei, bool exceptKey = false) const;
public string getAllFieldList(Dialect dialect, string entityName, bool exceptKey = false) const;
public string generateFindByPkForEntity(Dialect dialect, const EntityInfo ei) const;
public string generateFindByPkForEntity(Dialect dialect, string entityName) const;
public string generateInsertAllFieldsForEntity(Dialect dialect, const EntityInfo ei) const;
public string generateInsertAllFieldsForEntity(Dialect dialect, string entityName) const;
public string generateInsertNoKeyForEntity(Dialect dialect, const EntityInfo ei) const;
public string generateUpdateForEntity(Dialect dialect, const EntityInfo ei) const;
public Variant getPropertyValue(Object obj, string propertyName) const;
public void setPropertyValue(Object obj, string propertyName, Variant value) const;
}
enum RelationType {
None,
Embedded,
OneToOne,
OneToMany,
ManyToOne,
ManyToMany,
}
/// Metadata of entity property
class PropertyInfo {
public:
/// reads simple property value from data set to object
alias ReaderFunc = void function(Object, DataSetReader, int index);
/// writes simple property value to data set from object
alias WriterFunc = void function(Object, DataSetWriter, int index);
/// copy property from second passed object to first
alias CopyFunc = void function(Object, Object);
/// returns simple property as Variant
alias GetVariantFunc = Variant function(Object);
/// sets simple property from Variant
alias SetVariantFunc = void function(Object, Variant value);
/// returns true if property value of object is not null
alias IsNullFunc = bool function(Object);
/// returns true if key property of object is set (similar to IsNullFunc but returns true if non-nullable number is 0.
alias KeyIsSetFunc = bool function(Object);
/// returns OneToOne, ManyToOne or Embedded property as Object
alias GetObjectFunc = Object function(Object);
/// sets OneToOne, ManyToOne or Embedded property as Object
alias SetObjectFunc = void function(Object, Object);
/// sets lazy loader delegate for OneToOne, or ManyToOne property if it's Lazy! template instance
alias SetObjectDelegateFunc = void function(Object, Object delegate());
/// sets lazy loader delegate for OneToMany, or ManyToMany property if it's LazyCollection! template instance
alias SetCollectionDelegateFunc = void function(Object, Object[] delegate());
/// returns OneToMany or ManyToMany property value as object array
alias GetCollectionFunc = Object[] function(Object);
/// sets OneToMany or ManyToMany property value from object array
alias SetCollectionFunc = void function(Object, Object[]);
/// returns true if Lazy! or LazyCollection! property is loaded (no loader delegate set).
alias IsLoadedFunc = bool function(Object);
/// returns new generated primary key for property
alias GeneratorFunc = Variant function(Connection conn, const PropertyInfo prop);
package EntityInfo _entity;
@property const(EntityInfo) entity() const { return _entity; }
@property const(EntityMetaData) metadata() const { return _entity._metadata; }
immutable string propertyName;
immutable string columnName;
immutable Type columnType;
immutable int length;
immutable bool key;
immutable bool generated;
immutable bool nullable;
immutable string uniqueIndex;
immutable RelationType relation;
immutable bool lazyLoad;
immutable bool collection;
immutable string referencedEntityName; // for @Embedded, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany holds name of entity
package EntityInfo _referencedEntity; // for @Embedded, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany holds entity info reference, filled in runtime
@property const(EntityInfo) referencedEntity() const { return _referencedEntity; }
immutable string referencedPropertyName; // for @OneToOne, @OneToMany, @ManyToOne
package PropertyInfo _referencedProperty;
@property const(PropertyInfo) referencedProperty() const { return _referencedProperty; }
package int _columnOffset; // offset from first column of this entity in selects
@property int columnOffset() const { return _columnOffset; } // offset from first column of this entity in selects
package JoinTableInfo _joinTable;
@property const (JoinTableInfo) joinTable() const { return _joinTable; }
immutable ReaderFunc readFunc;
immutable WriterFunc writeFunc;
immutable GetVariantFunc getFunc;
immutable SetVariantFunc setFunc;
immutable KeyIsSetFunc keyIsSetFunc;
immutable IsNullFunc isNullFunc;
immutable GetObjectFunc getObjectFunc;
immutable SetObjectFunc setObjectFunc;
immutable CopyFunc copyFieldFunc;
immutable GetCollectionFunc getCollectionFunc;
immutable SetCollectionFunc setCollectionFunc;
immutable SetObjectDelegateFunc setObjectDelegateFunc;
immutable SetCollectionDelegateFunc setCollectionDelegateFunc;
immutable IsLoadedFunc isLoadedFunc;
immutable GeneratorFunc generatorFunc;
@property bool simple() const { return relation == RelationType.None; };
@property bool embedded() const { return relation == RelationType.Embedded; };
@property bool oneToOne() const { return relation == RelationType.OneToOne; };
@property bool oneToMany() const { return relation == RelationType.OneToMany; };
@property bool manyToOne() const { return relation == RelationType.ManyToOne; };
@property bool manyToMany() const { return relation == RelationType.ManyToMany; };
this(string propertyName, string columnName, Type columnType, int length, bool key, bool generated, bool nullable, string uniqueIndex, RelationType relation, string referencedEntityName, string referencedPropertyName, ReaderFunc reader, WriterFunc writer, GetVariantFunc getFunc, SetVariantFunc setFunc, KeyIsSetFunc keyIsSetFunc, IsNullFunc isNullFunc,
CopyFunc copyFieldFunc,
GeneratorFunc generatorFunc = null,
GetObjectFunc getObjectFunc = null,
SetObjectFunc setObjectFunc = null,
GetCollectionFunc getCollectionFunc = null,
SetCollectionFunc setCollectionFunc = null,
SetObjectDelegateFunc setObjectDelegateFunc = null,
SetCollectionDelegateFunc setCollectionDelegateFunc = null,
IsLoadedFunc isLoadedFunc = null,
bool lazyLoad = false, bool collection = false,
JoinTableInfo joinTable = null) {
this.propertyName = propertyName;
this.columnName = columnName;
this.columnType = cast(immutable Type)columnType;
this.length = length;
this.key = key;
this.generated = generated;
this.nullable = nullable;
this.relation = relation;
this.referencedEntityName =referencedEntityName;
this.referencedPropertyName = referencedPropertyName;
this.readFunc = reader;
this.writeFunc = writer;
this.getFunc = getFunc;
this.setFunc = setFunc;
this.keyIsSetFunc = keyIsSetFunc;
this.isNullFunc = isNullFunc;
this.getObjectFunc = getObjectFunc;
this.setObjectFunc = setObjectFunc;
this.copyFieldFunc = copyFieldFunc;
this.generatorFunc = generatorFunc;
this.lazyLoad = lazyLoad;
this.collection = collection;
this.setObjectDelegateFunc = setObjectDelegateFunc;
this.setCollectionDelegateFunc = setCollectionDelegateFunc;
this.getCollectionFunc = getCollectionFunc;
this.setCollectionFunc = setCollectionFunc;
this.isLoadedFunc = isLoadedFunc;
this._joinTable = joinTable;
this.uniqueIndex = uniqueIndex;
}
package void updateJoinTable() {
assert(relation == RelationType.ManyToMany);
assert(_joinTable !is null);
_joinTable.setEntities(entity, referencedEntity);
}
hash_t opHash() const {
return (cast(hash_t)(cast(void*)this)) * 31;
}
bool opEquals(ref const PropertyInfo s) const {
return this == s;
}
int opCmp(ref const PropertyInfo s) const {
return this == s ? 0 : (opHash() > s.opHash() ? 1 : -1);
}
Variant[] getCollectionIds(Object obj) const {
assert(oneToMany || manyToMany);
Variant[] res;
Object[] list = getCollectionFunc(obj);
if (list is null)
return res;
foreach(item; list) {
res ~= referencedEntity.getKey(item);
}
return res;
}
}
/// Metadata of single entity
class EntityInfo {
package EntityMetaData _metadata;
@property const(EntityMetaData) metadata() const { return _metadata; }
immutable string name;
immutable string tableName;
private PropertyInfo[] _properties;
@property const(PropertyInfo[]) properties() const { return _properties; }
package PropertyInfo [string] _propertyMap;
immutable TypeInfo_Class classInfo;
private int _keyIndex;
@property int keyIndex() const { return _keyIndex; }
private PropertyInfo _keyProperty;
@property const(PropertyInfo) keyProperty() const { return _keyProperty; }
immutable bool embeddable;
int opApply(int delegate(ref const PropertyInfo) dg) const {
int result = 0;
for (int i = 0; i < _properties.length; i++) {
result = dg(_properties[i]);
if (result) break;
}
return result;
}
public this(string name, string tableName, bool embeddable, PropertyInfo [] properties, TypeInfo_Class classInfo) {
this.name = name;
this.tableName = tableName;
this.embeddable = embeddable;
this._properties = properties;
this.classInfo = cast(immutable TypeInfo_Class)classInfo;
PropertyInfo[string] map;
foreach(i, p; properties) {
p._entity = this;
map[p.propertyName] = p;
if (p.key) {
_keyIndex = cast(int)i;
_keyProperty = p;
}
}
this._propertyMap = map;
enforceHelper!MappingException(keyProperty !is null || embeddable, "No key specified for non-embeddable entity " ~ name);
}
/// returns key value as Variant from entity instance
Variant getKey(Object obj) const { return keyProperty.getFunc(obj); }
/// returns key value as Variant from data set
Variant getKey(DataSetReader r, int startColumn) const { return r.getVariant(startColumn + keyProperty.columnOffset); }
/// sets key value from Variant
void setKey(Object obj, Variant value) const { keyProperty.setFunc(obj, value); }
/// returns property info for key property
const(PropertyInfo) getKeyProperty() const { return keyProperty; }
/// checks if primary key is set (for non-nullable member types like int or long, 0 is considered as non-set)
bool isKeySet(Object obj) const { return keyProperty.keyIsSetFunc(obj); }
/// checks if primary key is set (for non-nullable member types like int or long, 0 is considered as non-set)
bool isKeyNull(DataSetReader r, int startColumn) const { return r.isNull(startColumn + keyProperty.columnOffset); }
/// checks if property value is null
bool isNull(Object obj) const { return keyProperty.isNullFunc(obj); }
/// returns property value as Variant
Variant getPropertyValue(Object obj, string propertyName) const { return findProperty(propertyName).getFunc(obj); }
/// sets property value from Variant
void setPropertyValue(Object obj, string propertyName, Variant value) const { return findProperty(propertyName).setFunc(obj, value); }
/// returns all properties as array
const (PropertyInfo[]) getProperties() const { return properties; }
/// returns map of property name to property metadata
const (PropertyInfo[string]) getPropertyMap() const { return _propertyMap; }
/// returns number of properties
ulong getPropertyCount() const { return properties.length; }
/// returns number of properties
ulong getPropertyCountExceptKey() const { return properties.length - 1; }
@property size_t length() const { return properties.length; }
const(PropertyInfo) opIndex(int index) const {
return properties[index];
}
const(PropertyInfo) opIndex(string propertyName) const {
return findProperty(propertyName);
}
/// returns property by index
const(PropertyInfo) getProperty(int propertyIndex) const { return properties[propertyIndex]; }
/// returns property by name, throws exception if not found
const(PropertyInfo) findProperty(string propertyName) const { try { return _propertyMap[propertyName]; } catch (Throwable e) { throw new MappingException("No property " ~ propertyName ~ " found in entity " ~ name); } }
/// create instance of entity object (using default constructor)
Object createEntity() const { return Object.factory(classInfo.name); }
void copyAllProperties(Object to, Object from) const {
foreach(pi; this)
pi.copyFieldFunc(to, from);
}
}
class JoinTableInfo {
package string _tableName;
@property string tableName() const { return _tableName; }
package string _column1;
@property string column1() const { return _column1; }
package string _column2;
@property string column2() const { return _column2; }
package EntityInfo _thisEntity;
@property const (EntityInfo) thisEntity() const { return _thisEntity; }
package EntityInfo _otherEntity;
@property const (EntityInfo) otherEntity() const { return _otherEntity; }
this(string tableName, string column1, string column2) {
this._tableName = tableName;
this._column1 = column1;
this._column2 = column2;
}
/// set entities, and replace missing parameters with default generated values
package void setEntities(const EntityInfo thisEntity, const EntityInfo otherEntity) {
assert(thisEntity !is null);
assert(otherEntity !is null);
this._thisEntity = cast(EntityInfo)thisEntity;
this._otherEntity = cast(EntityInfo)otherEntity;
// table name is constructed from names of two entities delimited with underscore, sorted in alphabetical order, with appended suffix 's': entity1_entity2s
// (to get same table name on two sides)
string entity1 = camelCaseToUnderscoreDelimited(thisEntity.name < otherEntity.name ? thisEntity.name : otherEntity.name);
string entity2 = camelCaseToUnderscoreDelimited(thisEntity.name < otherEntity.name ? otherEntity.name : thisEntity.name);
_tableName = _tableName !is null ? _tableName : entity1 ~ "_" ~ entity2 ~ "s";
// columns are entity name (CamelCase to camel_case
_column1 = _column1 !is null ? _column1 : camelCaseToUnderscoreDelimited(thisEntity.name) ~ "_fk";
_column2 = _column2 !is null ? _column2 : camelCaseToUnderscoreDelimited(otherEntity.name) ~ "_fk";
}
static string generateJoinTableCode(string table, string column1, string column2) {
return "new JoinTableInfo(" ~ quoteString(table) ~ ", " ~ quoteString(column1) ~ ", " ~ quoteString(column2) ~ ")";
}
string getInsertSQL(const Dialect dialect) const {
return "INSERT INTO " ~ dialect.quoteIfNeeded(_tableName) ~ "(" ~ dialect.quoteIfNeeded(_column1) ~ ", " ~ dialect.quoteIfNeeded(column2) ~ ") VALUES ";
}
string getOtherKeySelectSQL(const Dialect dialect, string thisKeySQL) const {
return "SELECT " ~ dialect.quoteIfNeeded(column2) ~ " FROM " ~ dialect.quoteIfNeeded(_tableName) ~ " WHERE " ~ dialect.quoteIfNeeded(_column1) ~ "=" ~ thisKeySQL;
}
string getInsertSQL(const Dialect dialect, string thisKeySQL, string[] otherKeysSQL) const {
string list;
foreach(otherKeySQL; otherKeysSQL) {
if (list.length > 0)
list ~= ", ";
list ~= "(" ~ thisKeySQL ~ ", " ~ otherKeySQL ~ ")";
}
return getInsertSQL(dialect) ~ list;
}
string getDeleteSQL(const Dialect dialect, string thisKeySQL, string[] otherKeysSQL) const {
string sql = "DELETE FROM " ~ dialect.quoteIfNeeded(_tableName) ~ " WHERE " ~ dialect.quoteIfNeeded(_column1) ~ "=" ~ thisKeySQL ~ " AND " ~ dialect.quoteIfNeeded(_column2) ~ " IN ";
string list;
foreach(otherKeySQL; otherKeysSQL) {
if (list.length > 0)
list ~= ", ";
list ~= otherKeySQL;
}
return sql ~ "(" ~ list ~ ")";
}
}
string quoteString(string s) {
return s is null ? "null" : "\"" ~ s ~ "\"";
}
string quoteBool(bool b) {
return b ? "true" : "false";
}
string capitalizeFieldName(immutable string name) {
if (name[0] == '_')
return toUpper(name[1..2]) ~ name[2..$];
else
return toUpper(name[0..1]) ~ name[1..$];
}
/// lowercases first letter
string classNameToPropertyName(immutable string name) {
return toLower(name[0..1]) ~ name[1..$];
}
string getterNameToFieldName(immutable string name) {
if (name[0..3] == "get")
return toLower(name[3..4]) ~ name[4..$];
if (name[0..2] == "is")
return toLower(name[2..3]) ~ name[3..$];
return "_" ~ name;
}
string getterNameToSetterName(immutable string name) {
if (name[0..3] == "get")
return "set" ~ name[3..$]; // e.g. getValue() -> setValue()
if (name[0..2] == "is")
return "set" ~ toUpper(name[0..1]) ~ name[1..$]; // e.g. isDefault()->setIsDefault()
return "_" ~ name;
}
/// converts camel case MyEntityName to my_entity_name
string camelCaseToUnderscoreDelimited(immutable string s) {
string res;
bool lastLower = false;
foreach(ch; s) {
if (ch >= 'A' && ch <= 'Z') {
if (lastLower) {
lastLower = false;
res ~= "_";
}
res ~= std.ascii.toLower(ch);
} else if (ch >= 'a' && ch <= 'z') {
lastLower = true;
res ~= ch;
} else {
res ~= ch;
}
}
return res;
}
unittest {
static assert(camelCaseToUnderscoreDelimited("User") == "user");
static assert(camelCaseToUnderscoreDelimited("MegaTableName") == "mega_table_name");
}
/// returns true if class member has at least one known property level annotation (@Column, @Id, @Generated)
template hasHibernatedPropertyAnnotation(T, string m) {
enum bool hasHibernatedPropertyAnnotation = hasOneOfMemberAnnotations!(T, m, Id, Column, OneToOne, ManyToOne, ManyToMany, OneToMany, Generated, Generator);
}
bool hasHibernatedClassOrPropertyAnnotation(T)() {
static if (hasOneOfAnnotations!(T, Entity, Embeddable, Table)) {
return true;
} else {
auto hasAnnotation = false;
foreach (m; __traits(allMembers, T)) {
static if (__traits(compiles, (typeof(__traits(getMember, T, m))))){
static if (__traits(getProtection, __traits(getMember, T, m)) == "public") {
static if (hasHibernatedPropertyAnnotation!(T, m)) {
hasAnnotation = true;
break;
}
}
}
}
return hasAnnotation;
}
}
bool hasAnyKeyPropertyAnnotation(T)() {
auto hasAny = false;
foreach (m; __traits(allMembers, T)) {
static if (__traits(compiles, (typeof(__traits(getMember, T, m))))){
static if (__traits(getProtection, __traits(getMember, T, m)) == "public") {
static if (hasOneOfMemberAnnotations!(T, m, Id, Generated, Generator))
hasAny = true;
break;
}
}
}
return hasAny;
}
/// returns true if class has one of specified anotations
bool hasOneOfAnnotations(T : Object, A...)() {
auto hasOne = false;
foreach(a; A) {
static if (hasAnnotation!(T, a)) {
hasOne = true;
break;
}
}
return hasOne;
}
/// returns true if class member has one of specified anotations
bool hasOneOfMemberAnnotations(T : Object, string m, A...)() {
bool res = false;
foreach(a; A) {
static if (hasMemberAnnotation!(T, m, a)) {
res = true;
break;
}
}
return res;
}
/// returns true if class has specified anotations
bool hasAnnotation(T, A)() {
bool res = false;
foreach(a; __traits(getAttributes, T)) {
static if (is(typeof(a) == A) || a.stringof == A.stringof) {
res = true;
break;
}
}
return res;
}
bool isGetterFunction(alias overload, string methodName)() {
//pragma(msg, "isGetterFunction " ~ methodName ~ " " ~ typeof(overload).stringof);
static if (is(typeof(overload) == function)) {
//pragma(msg, "is function " ~ methodName ~ " " ~ typeof(overload).stringof);
static if (ParameterTypeTuple!(overload).length == 0) {
//pragma(msg, "no params " ~ methodName ~ " " ~ typeof(overload).stringof);
static if (functionAttributes!overload & FunctionAttribute.property) {
//pragma(msg, "is property");
//writeln("is property or starts with get or is");
return true;
} else if (methodName.startsWith("get") || methodName.startsWith("get")) {
//pragma(msg, "is getter");
//writeln("is property or starts with get or is");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
/// returns true if class member has specified anotations
bool hasMemberAnnotation(T, string m, A)() {
bool res = false;
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == A) || a.stringof == A.stringof) {
res = true;
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == A) || a.stringof == A.stringof) {
res = true;
break;
}
}
}
return res;
}
/// returns entity name for class type
string getEntityName(T : Object)() {
// foreach (a; __traits(getAttributes, T)) {
// static if (is(typeof(a) == Entity)) {
// return a.name;
// }
// static if (a.stringof == Entity.stringof) {
// return T.stringof;
// }
// }
return T.stringof;
}
/// returns table name for class type
string getTableName(T : Object)() {
string name = camelCaseToUnderscoreDelimited(T.stringof);
foreach (a; __traits(getAttributes, T)) {
static if (is(typeof(a) == Table)) {
name = a.name;
break;
}
}
return name;
}
string applyDefault(string s, string defaultValue) {
return s != null && s.length > 0 ? s : defaultValue;
}
string getColumnName(T, string m)() {
immutable string defValue = camelCaseToUnderscoreDelimited(getPropertyName!(T,m));
string name = defValue;
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == Column)) {
name = applyDefault(a.name, defValue);
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == Column)) {
name = applyDefault(a.name, defValue);
break;
}
}
}
return name;
}
string getGeneratorCode(T, string m)() {
string code = null;
foreach (a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == Generator)) {
static assert(a.code != null && a.code != "", "@Generator doesn't have code specified");
code = a.code;
break;
}
static if (a.stringof == Generator.stringof) {
static assert(false, "@Generator doesn't have code specified");
}
}
return code;
}
string getJoinColumnName(T, string m)() {
string name = null;
immutable string defValue = camelCaseToUnderscoreDelimited(getPropertyName!(T,m)()) ~ "_fk";
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == JoinColumn)) {
name = applyDefault(a.name, defValue);
break Louter;
} else static if (a.stringof == JoinColumn.stringof) {
name = defValue;
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == JoinColumn)) {
name = applyDefault(a.name, defValue);
break;
} else static if (a.stringof == JoinColumn.stringof) {
name = defValue;
break;
}
}
}
return name;
}
string getUniqueIndexName(T, string m)() {
string name = null;
immutable string defValue = camelCaseToUnderscoreDelimited(getEntityName!T) ~ "_" ~ camelCaseToUnderscoreDelimited(getPropertyName!(T,m)()) ~ "_index";
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == UniqueKey)) {
name = applyDefault(a.name, defValue);
break Louter;
} else static if (a.stringof == UniqueKey.stringof) {
name = defValue;
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == UniqueKey)) {
name = applyDefault(a.name, defValue);
break;
} else static if (a.stringof == UniqueKey.stringof) {
name = defValue;
break;
}
}
}
return name;
}
string getJoinTableName(T, string m)() {
string name = null;
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == JoinTable)) {
name = emptyStringToNull(a.joinTableName);
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == JoinTable)) {
name = emptyStringToNull(a.joinTableName);
break;
}
}
}
return name;
}
string getJoinTableColumn1(T, string m)() {
string column = null;
foreach (a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == JoinTable)) {
column = emptyStringToNull(a.joinColumn1);
break;
}
}
return column;
}
string getJoinTableColumn2(T, string m)() {
string column = null;
foreach (a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == JoinTable)) {
column = emptyStringToNull(a.joinColumn2);
break;
}
}
return column;
}
string emptyStringToNull(string s) {
return (s is null || s.length == 0) ? null : s;
}
string getOneToOneReferencedPropertyName(T, string m)() {
string propertyName = null;
foreach (a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == OneToOne)) {
propertyName = emptyStringToNull(a.name);
break;
}
static if (a.stringof == OneToOne.stringof) {
propertyName = null;
break;
}
}
return propertyName;
}
/**
T is class/entity
m is member of T eg T.m; m is a collection/array. The ElementType of the collection/array has a ref to T.
Try to figure out the field name in the type of m which is of type T.
When m has a attribute of OneToMany with a name, the atribute.name is used.
*/
string getOneToManyReferencedPropertyName(T, string m)() {
// first check there is a attribute @OneToMany with a non null name, if so use it!
foreach( a; __traits( getAttributes, __traits( getMember, T, m ) ) ) {
static if( is( typeof(a) == OneToMany ) && a.name != null && a.name.length != 0 ) {
return a.name;
}
}
// No attrib or no name, try to deduce the field name from the type of T's field m
alias memberFieldType = typeof(__traits(getMember, T, m));
static if( is( memberFieldType == LazyCollection!TAL, TAL ))
{
alias refererType = TAL;
}
else
{
import std.range : ElementType;
alias refererType = ElementType!memberFieldType;
}
// test T has single occurance in refererType
static if (__VERSION__ < 2074) {
import std.traits : FieldTypeTuple, Filter; // Filter used to be in std.traits
} else {
import std.traits : FieldTypeTuple;
import std.meta : Filter;
}
alias refererFields = FieldTypeTuple!refererType;
enum bool isSameType(U) = is( T == U ) || is ( Lazy!T == U );
alias refererFieldsofTypeT = Filter!( isSameType, refererFields );
// assert there is exactly one field with type T in refererFields
// when there is more than one use explicit attributes for each field eg: OneToMany( "field name first referer" ).. OneToMany( "field name second referer" )..
static assert( refererFieldsofTypeT.length == 1, "auto deduction of OneToMany referencedPropertyName for " ~ T.stringof ~ "." ~ m ~ " failed: ElementType of " ~ refererType.stringof ~ "[] has " ~ refererFieldsofTypeT.length.stringof ~ " of fields " ~ T.stringof ~ ". (Use explicit OneToMany( fieldname in " ~ refererType.stringof ~ " ) annotations for multiple referers.)" );
string res = null;
foreach( mf; __traits( allMembers, refererType ) ) {
static if( is( typeof(__traits(getMember, refererType, mf)) == T ) ) {
res = mf;
break;
}
}
return res;
}
int getColumnLength(T, string m)() {
auto length = 0;
static if (is(typeof(__traits(getMember, T, m)) == function)) {
// function: check overloads
Louter:
foreach(overload; MemberFunctionsTuple!(T, m)) {
static if (isGetterFunction!(overload, m)) {
foreach(a; __traits(getAttributes, overload)) {
static if (is(typeof(a) == Column)) {
length = a.length;
break Louter;
}
}
}
}
} else {
foreach(a; __traits(getAttributes, __traits(getMember,T,m))) {
static if (is(typeof(a) == Column)) {
length = a.length;
break;
}
}
}
return length;
}
string getPropertyName(T, string m)() {
alias ti = typeof(__traits(getMember, T, m));
static if (is(ti == function)) {
return getterNameToFieldName(m);
} else
return m;
}
enum PropertyMemberKind : int {
FIELD_MEMBER, // int field;
GETTER_MEMBER, // getField() + setField() or isField() and setField()
PROPERTY_MEMBER, // @property T field() { ... } + @property xxx field(T value) { ... }
LAZY_MEMBER, // Lazy!Object field;
UNSUPPORTED_MEMBER,//
}
bool hasPercentSign(immutable string str) {
foreach(ch; str) {
if (ch == '%')
return true;
}
return false;
}
int percentSignCount(immutable string str) {
string res;
foreach(ch; str) {
if (ch == '%')
res ~= "%";
}
return cast(int)res.length;
}
string substituteParam(immutable string fmt, immutable string value) {
if (hasPercentSign(fmt))
return format(fmt, value);
else
return fmt;
}
//string substituteIntParam(immutable string fmt, immutable int value) {
// int percentPos = -1;
// for (int i=0; i<fmt.length; i++) {
// if (fmt[i] == '%') {
// percentPos = i;
// }
//
// }
// if (percentPos < 0)
// return fmt;
// return fmt[0 .. percentPos] ~ "1024" ~ fmt[percentPos + 2 .. $]; //to!string(value)
//// string res;
//// bool skipNext = false;
////
//// foreach(ch; fmt) {
//// if (ch == '%') {
//// res ~= "1024"; //to!string(value);
//// skipNext = true;
//// } else if (!skipNext) {
//// res ~= ch;
//// skipNext = false;
//// }
//// }
//// return res;
// // following code causes error in DMD
//// if (hasPercentSign(fmt))
//// return format(fmt, value);
//// else
//// return fmt;
//}
string substituteParamTwice(immutable string fmt, immutable string value) {
immutable int paramCount = cast(int)percentSignCount(fmt);
if (paramCount == 1)
return format(fmt, value);
else if (paramCount == 2)
return format(fmt, value, value);
else
return fmt;
}
static immutable string[] PropertyMemberKind_ReadCode =
[
"entity.%s",
"entity.%s()",
"entity.%s",
"entity.%s()",
"dummy"
];
PropertyMemberKind getPropertyMemberKind(T : Object, string m)() {
auto memberKind = PropertyMemberKind.UNSUPPORTED_MEMBER;
alias ti = typeof(__traits(getMember, T, m));
static if (is(ti == function)) {
// interate through all overloads
//return checkGetterOverload!(T, m);