/
GrailsDomainBinderTests.groovy
1275 lines (1108 loc) · 48.2 KB
/
GrailsDomainBinderTests.groovy
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
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.grails.orm.hibernate.cfg
import grails.core.DefaultGrailsApplication
import grails.core.GrailsDomainClass
import grails.util.Holders
import org.grails.core.DefaultGrailsDomainClass
import org.grails.datastore.mapping.model.PersistentEntity
import org.grails.datastore.mapping.model.PersistentProperty
import org.grails.plugins.MockGrailsPluginManager
import org.grails.validation.TestClass
import org.hibernate.cfg.ImprovedNamingStrategy
import org.hibernate.mapping.*
import org.hibernate.mapping.Table
import org.springframework.context.support.GenericApplicationContext
/**
* @author Jason Rudolph
* @author Sergey Nebolsin
* @since 0.4
*/
class GrailsDomainBinderTests extends GroovyTestCase {
private static final String CACHED_MAP = '''
class Area {
Long id
Long version
Map names
static mapping = {
names cache: true
}
}
'''
private static final String ONE_TO_ONE_CLASSES_DEFINITION = '''
class Species {
Long id
Long version
String name
}
class Pet {
Long id
Long version
Species species
}'''
private static final String ONE_TO_MANY_CLASSES_DEFINITION = '''
class Visit {
Long id
Long version
String description
}
class Pet {
Long id
Long version
Set visits
static hasMany = [visits:Visit]
static mapping = { visits joinTable:false, nullable:false }
}
'''
private static final String BAG_ONE_TO_MANY_CLASSES_DEFINITION = '''
class Bagged {
Long id
Long version
String description
}
class Bagger {
Long id
Long version
Collection bagged
static hasMany = [bagged: Bagged]
}'''
private static final String MANY_TO_MANY_CLASSES_DEFINITION = '''
class Specialty {
Long id
Long version
String name
Set vets
static hasMany = [vets:Vet]
static belongsTo = Vet
}
class Vet {
Long id
Long version
Set specialities
static hasMany = [specialities:Specialty]
}
'''
private static final String BAG_MANY_TO_MANY_CLASSES_DEFINITION = '''
class ManyBagged {
Long id
Long version
String name
Collection baggers
static hasMany = [baggers: ManyBagger]
static belongsTo = ManyBagger
}
class ManyBagger {
Long id
Long version
Collection bagged
static hasMany = [bagged: ManyBagged]
}'''
private static final String MULTI_COLUMN_USER_TYPE_DEFINITION = '''
import org.grails.orm.hibernate.cfg.*
class Item {
Long id
Long version
String name
MyType other
MonetaryAmount price
static mapping = {
name column: 's_name', sqlType: 'text'
other type: MyUserType, sqlType: 'wrapper-characters', params:[param1: 'myParam1', param2: 'myParam2']
price type: MonetaryAmountUserType, {
column name: 'value'
column name: 'currency_code', sqlType: 'text'
}
}
}
'''
private static final String UNIQUE_PROPERTIES = '''
class UniquePropertiesUser {
Long id
Long version
String login
String group
String camelCased
String employeeID
static constraints = {
employeeID(unique:true)
group(unique:'camelCased')
login(unique:['group','camelCased'])
}
}'''
private static final String TABLE_PER_HIERARCHY = '''
class TablePerHierarchySuperclass {
Long id
Long version
String stringProperty
String optionalStringProperty
ProductStatus someProductStatus
ProductStatus someOptionalProductStatus
static constraints = {
optionalStringProperty nullable: true
someOptionalProductStatus nullable: true
}
}
enum ProductStatus {
GOOD, BAD
}
class TablePerHierarchySubclass extends TablePerHierarchySuperclass {
Long id
Long version
ProductStatus productStatus
String productName
Integer productCount
ProductStatus optionalProductStatus
String optionalProductName
Integer optionalProductCount
static constraints = {
optionalProductName nullable: true
optionalProductCount nullable: true
optionalProductStatus nullable: true
}
}
'''
private static final String TABLE_PER_SUBCLASS = '''
class TablePerSubclassSuperclass {
Long id
Long version
String stringProperty
String optionalStringProperty
ProductStatus someProductStatus
ProductStatus someOptionalProductStatus
static constraints = {
optionalStringProperty nullable: true
someOptionalProductStatus nullable: true
}
static mapping = {
tablePerHierarchy false
}
}
enum ProductStatus {
GOOD, BAD
}
class TablePerSubclassSubclass extends TablePerSubclassSuperclass {
Long id
Long version
ProductStatus productStatus
String productName
Integer productCount
ProductStatus optionalProductStatus
String optionalProductName
Integer optionalProductCount
static constraints = {
optionalProductName nullable: true
optionalProductCount nullable: true
optionalProductStatus nullable: true
}
}
'''
private GroovyClassLoader cl = new GroovyClassLoader()
private GrailsDomainBinder grailsDomainBinder = new GrailsDomainBinder()
private Class previousNamingStrategyClass
@Override
protected void setUp() {
super.setUp()
ExpandoMetaClass.enableGlobally()
MockGrailsPluginManager pluginManager = new MockGrailsPluginManager()
Holders.setPluginManager(pluginManager)
previousNamingStrategyClass = grailsDomainBinder.NAMING_STRATEGIES[Mapping.DEFAULT_DATA_SOURCE].getClass()
}
@Override
protected void tearDown() {
super.tearDown()
grailsDomainBinder.NAMING_STRATEGIES.clear()
grailsDomainBinder.NAMING_STRATEGIES.put(
Mapping.DEFAULT_DATA_SOURCE, ImprovedNamingStrategy.INSTANCE)
Holders.setPluginManager(null)
grailsDomainBinder.configureNamingStrategy previousNamingStrategyClass
}
/**
* Test for GRAILS-4200
*/
void testEmbeddedComponentMapping() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class Widget {
Long id
Long version
EmbeddedWidget ew
static embedded = ['ew']
}
class EmbeddedWidget {
String ew
static mapping = {
ew column: 'widget_name'
}
}''')
Table tableMapping = getTableMapping("widget", config)
Column embeddedComponentMappedColumn = tableMapping.getColumn(new Column("widget_name"))
assertNotNull(embeddedComponentMappedColumn)
assertEquals("widget_name", embeddedComponentMappedColumn.name)
}
void testLengthProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class Widget {
Long id
Long version
String name
String description
static mapping = {
name column: 's_name', sqlType: 'text', length: 42
description column: 's_description', sqlType: 'text'
}
}''')
Table tableMapping = getTableMapping("widget", config)
Column nameColumn = tableMapping.getColumn(new Column("s_name"))
Column descriptionColumn = tableMapping.getColumn(new Column("s_description"))
assertEquals(42, nameColumn.length)
assertEquals(Column.DEFAULT_LENGTH, descriptionColumn.length)
}
void testUniqueProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class Widget {
Long id
Long version
String name
String description
static mapping = {
name unique: true
}
}''')
Table tableMapping = getTableMapping("widget", config)
Column nameColumn = tableMapping.getColumn(new Column("name"))
Column descriptionColumn = tableMapping.getColumn(new Column("description"))
assertTrue nameColumn.isUnique()
assertFalse descriptionColumn.isUnique()
}
void testGroupUniqueProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class CompositeUnique1 {
Long id
Long version
String name
String surname
static constraints = {
name unique:'surname'
}
}
class CompositeUnique2 {
Long id
Long version
String name
String surname
static constraints = {
name unique:'surname'
}
}
''')
Table tableMapping = getTableMapping("composite_unique1", config)
UniqueKey key = tableMapping.getUniqueKey('unique_composite_unique1_name')
assertNotNull(key)
Table tableMapping2 = getTableMapping("composite_unique2", config)
UniqueKey key2 = tableMapping2.getUniqueKey('unique_composite_unique2_name')
assertNotNull(key2)
assertTrue(key.name != key2.name)
}
void testPrecisionProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class Widget {
Long id
Long version
Float width
Float height
static mapping = {
width precision: 3
}
}''')
Table tableMapping = getTableMapping("widget", config)
Column heightColumn = tableMapping.getColumn(new Column("height"))
Column widthColumn = tableMapping.getColumn(new Column("width"))
assertEquals(3, widthColumn.precision)
assertEquals(Column.DEFAULT_PRECISION, heightColumn.precision)
}
void testScaleProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig('''
class Widget {
Long id
Long version
Float width
Float height
static mapping = {
width scale: 7
}
}''')
Table tableMapping = getTableMapping("widget", config)
Column heightColumn = tableMapping.getColumn(new Column("height"))
Column widthColumn = tableMapping.getColumn(new Column("width"))
assertEquals(7, widthColumn.scale)
assertEquals(Column.DEFAULT_SCALE, heightColumn.scale)
}
void testCachedMapProperty() {
DefaultGrailsDomainConfiguration config = getDomainConfig(CACHED_MAP)
Table table = getTableMapping("area_names", config)
assertEquals(255, table.getColumn(new Column("names_elt")).length)
}
void testColumnNullabilityWithTablePerHierarchy() {
DefaultGrailsDomainConfiguration config = getDomainConfig(TABLE_PER_HIERARCHY)
// with tablePerHierarchy all columns related to properties defined in subclasses must
// be nullable to allow instances of other classes in the hierarchy to be persisted
assertColumnNullable("table_per_hierarchy_superclass", "product_status", config)
assertColumnNullable("table_per_hierarchy_superclass", "product_name", config)
assertColumnNullable("table_per_hierarchy_superclass", "product_count", config)
assertColumnNullable("table_per_hierarchy_superclass", "optional_product_status", config)
assertColumnNullable("table_per_hierarchy_superclass", "optional_product_name", config)
assertColumnNullable("table_per_hierarchy_superclass", "optional_product_count", config)
// columns related to required properties in the root class should not be nullable
assertColumnNotNullable("table_per_hierarchy_superclass", "string_property", config)
assertColumnNotNullable("table_per_hierarchy_superclass", "some_product_status", config)
// columns related to optional properties in the root class should be nullable
assertColumnNullable("table_per_hierarchy_superclass", "optional_string_property", config)
assertColumnNullable("table_per_hierarchy_superclass", "some_optional_product_status", config)
}
void testColumnNullabilityWithTablePerSubclass() {
DefaultGrailsDomainConfiguration config = getDomainConfig(TABLE_PER_SUBCLASS)
// with tablePerSubclass columns related to required properties defined in subclasses
// should not be nullable
assertColumnNotNullable("table_per_subclass_subclass", "product_status", config)
assertColumnNotNullable("table_per_subclass_subclass", "product_name", config)
assertColumnNotNullable("table_per_subclass_subclass", "product_count", config)
// with tablePerSubclass columns related to optional properties defined in subclasses
// should be nullable
assertColumnNullable("table_per_subclass_subclass", "optional_product_status", config)
assertColumnNullable("table_per_subclass_subclass", "optional_product_name", config)
assertColumnNullable("table_per_subclass_subclass", "optional_product_count", config)
// columns related to required properties in the root class should not be nullable
assertColumnNotNullable("table_per_subclass_superclass", "string_property", config)
assertColumnNotNullable("table_per_subclass_superclass", "some_product_status", config)
// columns related to optional properties in the root class should be nullable
assertColumnNullable("table_per_subclass_superclass", "optional_string_property", config)
assertColumnNullable("table_per_subclass_superclass", "some_optional_product_status", config)
}
//
// void testUniqueConstraintGeneration() {
// DefaultGrailsDomainConfiguration config = getDomainConfig(UNIQUE_PROPERTIES)
// assertEquals("Tables created", 1, getTableCount(config))
// List expectedKeyColumns1 = [new Column("camel_cased"), new Column("group"), new Column("login")]
// List expectedKeyColumns2 = [new Column("camel_cased"), new Column("group")]
// Table mapping = config.tableMappings.next()
// int cnt = 0
// boolean found1 = false, found2 = false
// for (UniqueKey key in mapping.uniqueKeyIterator) {
// List keyColumns = key.columns
// if (keyColumns.equals(expectedKeyColumns1)) {
// found1 = true
// }
// if (keyColumns.equals(expectedKeyColumns2)) {
// found2 = true
// }
// cnt++
// }
// assertEquals(2, cnt)
// assertTrue mapping.getColumn(new Column("employeeID")).isUnique()
// assertTrue found1
// assertTrue found2
// }
//
// void testInsertableHibernateMapping() {
// GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
// cl.parseClass('''
//class TestInsertableDomain {
// Long id
// Long version
// String testString1
// String testString2
//
// static mapping = {
// testString1 insertable:false
// testString2 insertable:true
// }
//}'''))
//
// DefaultGrailsDomainConfiguration config = getDomainConfig(cl, [domainClass.clazz])
// Field privateDomainClasses = DefaultGrailsDomainConfiguration.getDeclaredField("domainClasses")
// privateDomainClasses.setAccessible(true)
//
// PersistentClass persistentClass = config.getClassMapping("TestInsertableDomain")
//
// assertFalse persistentClass.getProperty("testString1").isInsertable()
// assertTrue persistentClass.getProperty("testString2").isInsertable()
// }
void testUpdateableHibernateMapping() {
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestInsertableDomain {
Long id
Long version
String testString1
String testString2
static mapping = {
testString1 updateable:false
testString2 updateable:true
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl, [domainClass.clazz])
PersistentClass persistentClass = config.getClassMapping("TestInsertableDomain")
assertFalse persistentClass.getProperty("testString1").isUpdateable()
assertTrue persistentClass.getProperty("testString2").isUpdateable()
}
void testInsertableUpdateableHibernateMapping() {
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestInsertableUpdateableDomain {
Long id
Long version
String testString1
String testString2
static mapping = {
testString1 insertable:false, updateable:false
testString2 updateable:false, insertable:false
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl, [domainClass.clazz])
PersistentClass persistentClass = config.getClassMapping("TestInsertableUpdateableDomain")
Property property1 = persistentClass.getProperty("testString1")
assertFalse property1.isInsertable()
assertFalse property1.isUpdateable()
Property property2 = persistentClass.getProperty("testString2")
assertFalse property2.isUpdateable()
assertFalse property2.isInsertable()
}
void testOneToOneBindingTables() {
assertEquals("Tables created", 2, getTableCount(getDomainConfig(ONE_TO_ONE_CLASSES_DEFINITION)))
}
void testOneToOneBindingFk() {
assertForeignKey("species", "pet", getDomainConfig(ONE_TO_ONE_CLASSES_DEFINITION))
}
void testOneToOneBindingFkColumn() {
assertColumnNotNullable("pet", "species_id", getDomainConfig(ONE_TO_ONE_CLASSES_DEFINITION))
}
void testOneToManyBindingTables() {
assertEquals("Tables created", 2, getTableCount(getDomainConfig(ONE_TO_MANY_CLASSES_DEFINITION)))
}
void testOneToManyBindingFk() {
assertForeignKey("pet", "visit", getDomainConfig(ONE_TO_MANY_CLASSES_DEFINITION))
}
/* void testOneToManyBindingFkColumn() {
DefaultGrailsDomainConfiguration config = getDomainConfig(ONE_TO_MANY_CLASSES_DEFINITION)
assertColumnNotNullable("visit", "pet_visits_id", config)
}*/
void testManyToManyBindingTables() {
assertEquals("Tables created", 3, getTableCount(getDomainConfig(MANY_TO_MANY_CLASSES_DEFINITION)))
}
void testManyToManyBindingPk() {
Table table = getTableMapping("vet_specialities", getDomainConfig(MANY_TO_MANY_CLASSES_DEFINITION))
assertNotNull("VET_SPECIALTY table has a PK", table.primaryKey)
assertEquals("VET_SPECIALTY table has a 2 column PK", 2, table.primaryKey.columns.size())
}
void testManyToManyBindingFk() {
DefaultGrailsDomainConfiguration config = getDomainConfig(MANY_TO_MANY_CLASSES_DEFINITION)
assertForeignKey("specialty", "vet_specialities", config)
assertForeignKey("vet", "vet_specialities", config)
}
void testManyToManyBindingFkColumn() {
DefaultGrailsDomainConfiguration config = getDomainConfig(MANY_TO_MANY_CLASSES_DEFINITION)
assertColumnNotNullable("vet_specialities", "vet_id", config)
assertColumnNotNullable("vet_specialities", "specialty_id", config)
}
/**
* Tests that single- and multi-column user type mappings work
* correctly. Also Checks that the "sqlType" property is honoured.
*/
void testUserTypeMappings() {
DefaultGrailsDomainConfiguration config = getDomainConfig(MULTI_COLUMN_USER_TYPE_DEFINITION)
PersistentClass persistentClass = config.getClassMapping("Item")
// First check the "name" property and its associated column.
Property nameProperty = persistentClass.getProperty("name")
assertEquals(1, nameProperty.columnSpan)
assertEquals("name", nameProperty.name)
Column column = nameProperty.columnIterator.next()
assertEquals("s_name", column.name)
assertEquals("text", column.sqlType)
// Next the "other" property.
Property otherProperty = persistentClass.getProperty("other")
assertEquals(1, otherProperty.columnSpan)
assertEquals("other", otherProperty.name)
column = otherProperty.columnIterator.next()
assertEquals("other", column.name)
assertEquals("wrapper-characters", column.sqlType)
assertEquals(MyUserType.name, column.value.type.name)
assertTrue(column.value instanceof SimpleValue)
SimpleValue v = column.value
assertEquals("myParam1", v.typeParameters.get("param1"))
assertEquals("myParam2", v.typeParameters.get("param2"))
// And now for the "price" property, which should have two columns.
Property priceProperty = persistentClass.getProperty("price")
assertEquals(2, priceProperty.columnSpan)
assertEquals("price", priceProperty.name)
Iterator<?> colIter = priceProperty.columnIterator
column = colIter.next()
assertEquals("value", column.name)
assertNull("SQL type should have been 'null' for 'value' column.", column.sqlType)
column = colIter.next()
assertEquals("currency_code", column.name)
assertEquals("text", column.sqlType)
}
void testDomainClassBinding() {
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class BinderTestClass {
Long id
Long version
String firstName
String lastName
String comment
Integer age
boolean active = true
static constraints = {
firstName(nullable:true,size:4..15)
lastName(nullable:false)
age(nullable:true)
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl, cl.loadedClasses)
// Test database mappings
PersistentClass persistentClass = config.getClassMapping("BinderTestClass")
assertTrue("Property [firstName] must be optional in db mapping", persistentClass.getProperty("firstName").isOptional())
assertFalse("Property [lastName] must be required in db mapping", persistentClass.getProperty("lastName").isOptional())
// Property must be required by default
assertFalse("Property [comment] must be required in db mapping", persistentClass.getProperty("comment").isOptional())
// Test properties
assertTrue("Property [firstName] must be optional", domainClass.getPropertyByName("firstName").isOptional())
assertFalse("Property [lastName] must be optional", domainClass.getPropertyByName("lastName").isOptional())
assertFalse("Property [comment] must be required", domainClass.getPropertyByName("comment").isOptional())
assertTrue("Property [age] must be optional", domainClass.getPropertyByName("age").isOptional())
}
void testForeignKeyColumnBinding() {
GrailsDomainClass oneClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestOneSide {
Long id
Long version
String name
String description
}'''))
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestManySide {
Long id
Long version
String name
TestOneSide testOneSide
static mapping = {
columns {
testOneSide column:'EXPECTED_COLUMN_NAME'
}
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl,
[oneClass.clazz, domainClass.clazz])
PersistentClass persistentClass = config.getClassMapping("TestManySide")
Column column = persistentClass.getProperty("testOneSide").columnIterator.next()
assertEquals("EXPECTED_COLUMN_NAME", column.name)
}
/**
* @see org.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder#bindStringColumnConstraints(Column, PersistentProperty)
*/
void testBindStringColumnConstraints() {
// Verify that the correct length is set when a maxSize constraint is applied
PersistentProperty constrainedProperty = getConstrainedStringProperty()
constrainedProperty.mapping.mappedForm.maxSize = 30
assertColumnLength(constrainedProperty, 30)
// Verify that the correct length is set when a size constraint is applied
constrainedProperty = getConstrainedStringProperty()
constrainedProperty.mapping.mappedForm.size = new IntRange(6, 32768)
assertColumnLength(constrainedProperty, 32768)
// Verify that the default length remains intact when no size-related constraints are applied
constrainedProperty = getConstrainedStringProperty()
assertColumnLength(constrainedProperty, Column.DEFAULT_LENGTH)
// Verify that the correct length is set when an inList constraint is applied
constrainedProperty = getConstrainedStringProperty()
constrainedProperty.mapping.mappedForm.inList = ["Groovy", "Java", "C++"]
assertColumnLength(constrainedProperty, 6)
// Verify that the correct length is set when a maxSize constraint *and* an inList constraint are *both* applied
constrainedProperty = getConstrainedStringProperty()
constrainedProperty.mapping.mappedForm.inList = ["Groovy", "Java", "C++"]
constrainedProperty.mapping.mappedForm.maxSize = 30
assertColumnLength(constrainedProperty, 30)
}
/**
* @see org.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder#bindNumericColumnConstraints(Column, PersistentProperty, ColumnConfig)
*/
void testBindNumericColumnConstraints() {
PersistentProperty constrainedProperty = getConstrainedBigDecimalProperty()
// maxSize and minSize constraint has the number with the most digits
constrainedProperty.mapping.mappedForm.maxSize = 123
constrainedProperty.mapping.mappedForm.minSize = 0
assertColumnPrecisionAndScale(constrainedProperty, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE)
// Verify that the correct precision is set when the max constraint has the number with the most digits
constrainedProperty = getConstrainedBigDecimalProperty()
// maxSize and minSize constraint has the number with the most digits
constrainedProperty.mapping.mappedForm.max = new BigDecimal("123.45")
constrainedProperty.mapping.mappedForm.min = new BigDecimal("0")
assertColumnPrecisionAndScale(constrainedProperty, 5, Column.DEFAULT_SCALE)
// Verify that the correct precision is set when the minSize constraint has the number with the most digits
constrainedProperty = getConstrainedBigDecimalProperty()
// maxSize and minSize constraint has the number with the most digits
constrainedProperty.mapping.mappedForm.max = new BigDecimal("123.45")
constrainedProperty.mapping.mappedForm.min = new BigDecimal("-123.45")
assertColumnPrecisionAndScale(constrainedProperty, 5, Column.DEFAULT_SCALE)
// Verify that the correct precision is set when the high value of a floating point range constraint has the number with the most digits
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.range = new ObjectRange(new BigDecimal("0"), new BigDecimal("123.45"))
assertColumnPrecisionAndScale(constrainedProperty, 5, Column.DEFAULT_SCALE)
// Verify that the correct precision is set when the low value of a floating point range constraint has the number with the most digits
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.range = new ObjectRange(new BigDecimal("-123.45"), new BigDecimal("123.45"))
assertColumnPrecisionAndScale(constrainedProperty, 5, Column.DEFAULT_SCALE)
// Verify that the correct scale is set when the scale constraint is specified in isolation
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.scale = 4
assertColumnPrecisionAndScale(constrainedProperty, Column.DEFAULT_PRECISION, 4)
// Verify that the precision is set correctly for a floating point number with a min/max constraint and a scale...
// 1) where the min/max constraint includes fewer decimal places than the scale constraint
constrainedProperty = getConstrainedBigDecimalProperty()
// maxSize and minSize constraint has the number with the most digits
constrainedProperty.mapping.mappedForm.max = new BigDecimal("123.45")
constrainedProperty.mapping.mappedForm.min = new BigDecimal("0")
constrainedProperty.mapping.mappedForm.scale = 3
assertColumnPrecisionAndScale(constrainedProperty, 6, 3) // precision (6) = number of integer digits in max constraint ("123.45") + scale (3)
// 2) where the min/max constraint includes more decimal places than the scale constraint
constrainedProperty = getConstrainedBigDecimalProperty()
// maxSize and minSize constraint has the number with the most digits
constrainedProperty.mapping.mappedForm.max = new BigDecimal("123.4567")
constrainedProperty.mapping.mappedForm.min = new BigDecimal("0")
constrainedProperty.mapping.mappedForm.scale = 3
assertColumnPrecisionAndScale(constrainedProperty, 7, 3) // precision (7) = number of digits in max constraint ("123.4567")
// Verify that the correct precision is set when the only one of 'min' and 'max' constraint specified
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.max = new BigDecimal("123.4567")
assertColumnPrecisionAndScale(constrainedProperty, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE)
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.max = new BigDecimal("12345678901234567890.4567")
assertColumnPrecisionAndScale(constrainedProperty, 24, Column.DEFAULT_SCALE)
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.min = new BigDecimal("-123.4567")
assertColumnPrecisionAndScale(constrainedProperty, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE)
constrainedProperty = getConstrainedBigDecimalProperty()
constrainedProperty.mapping.mappedForm.min = new BigDecimal("-12345678901234567890.4567")
assertColumnPrecisionAndScale(constrainedProperty, 24, Column.DEFAULT_SCALE)
}
void testDefaultNamingStrategy() {
GrailsDomainClass oneClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestOneSide {
Long id
Long version
String fooName
String barDescriPtion
}'''))
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestManySide {
Long id
Long version
TestOneSide testOneSide
static mapping = {
columns {
testOneSide column:'EXPECTED_COLUMN_NAME'
}
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl,
[oneClass.clazz, domainClass.clazz])
PersistentClass persistentClass = config.getClassMapping("TestOneSide")
assertEquals("test_one_side", persistentClass.table.name)
Column column = persistentClass.getProperty("id").columnIterator.next()
assertEquals("id", column.name)
column = persistentClass.getProperty("version").columnIterator.next()
assertEquals("version", column.name)
column = persistentClass.getProperty("fooName").columnIterator.next()
assertEquals("foo_name", column.name)
column = persistentClass.getProperty("barDescriPtion").columnIterator.next()
assertEquals("bar_descri_ption", column.name)
persistentClass = config.getClassMapping("TestManySide")
assertEquals("test_many_side", persistentClass.table.name)
column = persistentClass.getProperty("id").columnIterator.next()
assertEquals("id", column.name)
column = persistentClass.getProperty("version").columnIterator.next()
assertEquals("version", column.name)
column = persistentClass.getProperty("testOneSide").columnIterator.next()
assertEquals("EXPECTED_COLUMN_NAME", column.name)
}
// void testTableNamePrefixing() {
// def widgetClass = new DefaultGrailsDomainClass(
// cl.parseClass('''
//class WidgetClass {
// Long id
// Long version
//}'''))
// def personClass = new DefaultGrailsDomainClass(
// cl.parseClass('''
//class MyPluginPersonClass {
// Long id
// Long version
//}'''))
//
// def gadgetClass = new DefaultGrailsDomainClass(
// cl.parseClass('''
//class GadgetClass {
// Long id
// Long version
//}'''))
//
// def authorClass = new DefaultGrailsDomainClass(
// cl.parseClass('''
//class AuthorClass {
// Long id
// Long version
//}'''))
//
// def grailsApplication = new DefaultGrailsApplication([widgetClass.clazz, gadgetClass.clazz, personClass.clazz, authorClass.clazz] as Class[], cl)
//
// def myPluginMap = [:]
// myPluginMap.getName = { -> 'MyPlugin' }
// def myPlugin = myPluginMap as GrailsPlugin
//
// def publisherPluginMap = [:]
// publisherPluginMap.getName = { -> 'Publisher' }
// def publisherPlugin = publisherPluginMap as GrailsPlugin
//
// def pluginManagerMap = [setApplicationContext: { }]
// def myPluginDomainClassNames = ['GadgetClass', 'MyPluginPersonClass']
// def publisherPluginDomainClassNames = ['AuthorClass']
// pluginManagerMap.getPluginForClass = { Class clz ->
// if (myPluginDomainClassNames.contains(clz?.name)) {
// return myPlugin
// }
// if (publisherPluginDomainClassNames.contains(clz?.name)) {
// return publisherPlugin
// }
// return null
// }
// def pluginManager = pluginManagerMap as GrailsPluginManager
//
// def config = getDomainConfig(grailsApplication, pluginManager)
// def persistentClass = config.getClassMapping("WidgetClass")
// assertEquals("widget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("GadgetClass")
// assertEquals("gadget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("MyPluginPersonClass")
// assertEquals("my_plugin_person_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("AuthorClass")
// assertEquals("author_class", persistentClass.table.name)
//
// grailsApplication.config['grails.gorm.table.prefix.enabled'] = true
// config = getDomainConfig(grailsApplication, pluginManager)
// persistentClass = config.getClassMapping("WidgetClass")
// assertEquals("widget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("GadgetClass")
// assertEquals("my_plugin_gadget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("MyPluginPersonClass")
// assertEquals("my_plugin_person_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("AuthorClass")
// assertEquals("publisher_author_class", persistentClass.table.name)
//
// grailsApplication.config['grails.gorm.table.prefix.enabled'] = false
// config = getDomainConfig(grailsApplication, pluginManager)
// persistentClass = config.getClassMapping("WidgetClass")
// assertEquals("widget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("GadgetClass")
// assertEquals("gadget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("MyPluginPersonClass")
// assertEquals("my_plugin_person_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("AuthorClass")
// assertEquals("author_class", persistentClass.table.name)
//
// grailsApplication.config['grails.gorm.publisher.table.prefix.enabled'] = true
// config = getDomainConfig(grailsApplication, pluginManager)
// persistentClass = config.getClassMapping("WidgetClass")
// assertEquals("widget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("GadgetClass")
// assertEquals("gadget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("MyPluginPersonClass")
// assertEquals("my_plugin_person_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("AuthorClass")
// assertEquals("publisher_author_class", persistentClass.table.name)
//
// grailsApplication.config['grails.gorm.table.prefix.enabled'] = true
// grailsApplication.config['grails.gorm.myPlugin.table.prefix.enabled'] = false
// config = getDomainConfig(grailsApplication, pluginManager)
// persistentClass = config.getClassMapping("WidgetClass")
// assertEquals("widget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("GadgetClass")
// assertEquals("gadget_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("MyPluginPersonClass")
// assertEquals("my_plugin_person_class", persistentClass.table.name)
// persistentClass = config.getClassMapping("AuthorClass")
// assertEquals("publisher_author_class", persistentClass.table.name)
// }
void testCustomNamingStrategy() {
// somewhat artificial in that it doesn't test that setting the property
// in DataSource.groovy works, but that's handled in DataSourceConfigurationTests
grailsDomainBinder.configureNamingStrategy(CustomNamingStrategy)
GrailsDomainClass oneClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestOneSide {
Long id
Long version
String fooName
String barDescriPtion
}'''))
GrailsDomainClass domainClass = new DefaultGrailsDomainClass(
cl.parseClass('''
class TestManySide {
Long id
Long version
TestOneSide testOneSide
static mapping = {
columns {
testOneSide column:'EXPECTED_COLUMN_NAME'
}
}
}'''))
DefaultGrailsDomainConfiguration config = getDomainConfig(cl,
[oneClass.clazz, domainClass.clazz])
PersistentClass persistentClass = config.getClassMapping("TestOneSide")
assertEquals("table_TestOneSide", persistentClass.table.name)
Column column = persistentClass.getProperty("id").columnIterator.next()
assertEquals("col_id", column.name)
column = persistentClass.getProperty("version").columnIterator.next()
assertEquals("col_version", column.name)
column = persistentClass.getProperty("fooName").columnIterator.next()