-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
JavaGenerator.java
5630 lines (4358 loc) · 214 KB
/
JavaGenerator.java
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
/*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.util;
import static java.util.Arrays.asList;
import static org.jooq.SQLDialect.MYSQL;
import static org.jooq.SQLDialect.POSTGRES;
import static org.jooq.impl.DSL.name;
import static org.jooq.tools.StringUtils.defaultIfBlank;
import static org.jooq.tools.StringUtils.defaultString;
import static org.jooq.util.AbstractGenerator.Language.JAVA;
import static org.jooq.util.AbstractGenerator.Language.SCALA;
import static org.jooq.util.GenerationUtil.convertToIdentifier;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Modifier;
import java.lang.reflect.TypeVariable;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.DatatypeConverter;
import org.jooq.AggregateFunction;
import org.jooq.Catalog;
import org.jooq.Configuration;
import org.jooq.Constants;
import org.jooq.DataType;
import org.jooq.EnumType;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
// ...
import org.jooq.Name;
import org.jooq.Package;
import org.jooq.Parameter;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.Row;
import org.jooq.Schema;
import org.jooq.Sequence;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UDT;
import org.jooq.UDTField;
import org.jooq.UniqueKey;
import org.jooq.exception.SQLDialectNotSupportedException;
import org.jooq.impl.AbstractKeys;
import org.jooq.impl.AbstractRoutine;
// ...
import org.jooq.impl.CatalogImpl;
import org.jooq.impl.DAOImpl;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultDataType;
import org.jooq.impl.PackageImpl;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.SchemaImpl;
import org.jooq.impl.SequenceImpl;
import org.jooq.impl.TableImpl;
import org.jooq.impl.TableRecordImpl;
import org.jooq.impl.UDTImpl;
import org.jooq.impl.UDTRecordImpl;
import org.jooq.impl.UpdatableRecordImpl;
import org.jooq.tools.JooqLogger;
import org.jooq.tools.StopWatch;
import org.jooq.tools.StringUtils;
import org.jooq.tools.reflect.Reflect;
import org.jooq.tools.reflect.ReflectException;
import org.jooq.util.GeneratorStrategy.Mode;
// ...
// ...
// ...
// ...
// ...
// ...
import org.jooq.util.postgres.PostgresDatabase;
/**
* A default implementation for code generation.
* <p>
* Replace this code with your own logic, if you need your database schema
* represented in a different way.
* <p>
* Note that you can also extend this class to generate POJO's or other stuff
* entirely independent of jOOQ.
*
* @author Lukas Eder
*/
public class JavaGenerator extends AbstractGenerator {
private static final JooqLogger log = JooqLogger.getLogger(JavaGenerator.class);
/**
* The Javadoc to be used for private constructors
*/
private static final String NO_FURTHER_INSTANCES_ALLOWED = "No further instances allowed";
/**
* [#1459] Prevent large static initialisers by splitting nested classes
*/
private static final int INITIALISER_SIZE = 500;
/**
* [#4429] A map providing access to SQLDataType member literals
*/
private static final Map<DataType<?>, String> SQLDATATYPE_LITERAL_LOOKUP;
/**
* An overall stop watch to measure the speed of source code generation
*/
private final StopWatch watch = new StopWatch();
/**
* The underlying database of this generator
*/
private Database database;
/**
* The code generation date, if needed.
*/
private String isoDate;
/**
* The cached schema version numbers.
*/
private Map<SchemaDefinition, String> schemaVersions;
/**
* The cached catalog version numbers.
*/
private Map<CatalogDefinition, String> catalogVersions;
/**
* All files modified by this generator.
*/
private Set<File> files = new LinkedHashSet<File>();
/**
* These directories were not modified by this generator, but flagged as not
* for removal (e.g. because of {@link #schemaVersions} or
* {@link #catalogVersions}).
*/
private Set<File> directoriesNotForRemoval = new LinkedHashSet<File>();
private final boolean scala;
private final String tokenVoid;
static {
SQLDATATYPE_LITERAL_LOOKUP = new IdentityHashMap<DataType<?>, String>();
try {
for (java.lang.reflect.Field f : SQLDataType.class.getFields()) {
if (Modifier.isPublic(f.getModifiers()) &&
Modifier.isStatic(f.getModifiers()) &&
Modifier.isFinal(f.getModifiers()))
SQLDATATYPE_LITERAL_LOOKUP.put((DataType<?>) f.get(SQLDataType.class), f.getName());
}
}
catch (Exception e) {
log.warn(e);
}
}
public JavaGenerator() {
this(JAVA);
}
JavaGenerator(Language language) {
super(language);
this.scala = (language == SCALA);
this.tokenVoid = (scala ? "Unit" : "void");
}
@Override
public final void generate(Database db) {
this.isoDate = DatatypeConverter.printDateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
this.schemaVersions = new LinkedHashMap<SchemaDefinition, String>();
this.catalogVersions = new LinkedHashMap<CatalogDefinition, String>();
this.database = db;
this.database.addFilter(new AvoidAmbiguousClassesFilter());
this.database.setIncludeRelations(generateRelations());
this.database.setTableValuedFunctions(generateTableValuedFunctions());
logDatabaseParameters(db);
log.info("");
log.info("JavaGenerator parameters");
log.info("----------------------------------------------------------");
log.info(" strategy", strategy.delegate.getClass());
log.info(" deprecated", generateDeprecated());
log.info(" generated annotation", generateGeneratedAnnotation()
+ ((!generateGeneratedAnnotation && (useSchemaVersionProvider || useCatalogVersionProvider)) ?
" (forced to true because of <schemaVersionProvider/> or <catalogVersionProvider/>)" : ""));
log.info(" JPA annotations", generateJPAAnnotations());
log.info(" validation annotations", generateValidationAnnotations());
log.info(" instance fields", generateInstanceFields());
log.info(" sequences", generateSequences());
log.info(" udts", generateUDTs());
log.info(" routines", generateRoutines());
log.info(" tables", generateTables()
+ ((!generateTables && generateRecords) ? " (forced to true because of <records/>)" :
((!generateTables && generateDaos) ? " (forced to true because of <daos/>)" : "")));
log.info(" records", generateRecords()
+ ((!generateRecords && generateDaos) ? " (forced to true because of <daos/>)" : ""));
log.info(" pojos", generatePojos()
+ ((!generatePojos && generateDaos) ? " (forced to true because of <daos/>)" :
((!generatePojos && generateImmutablePojos) ? " (forced to true because of <immutablePojos/>)" : "")));
log.info(" immutable pojos", generateImmutablePojos());
log.info(" interfaces", generateInterfaces()
+ ((!generateInterfaces && generateImmutableInterfaces) ? " (forced to true because of <immutableInterfaces/>)" : ""));
log.info(" immutable interfaces", generateInterfaces());
log.info(" daos", generateDaos());
log.info(" relations", generateRelations()
+ ((!generateRelations && generateTables) ? " (forced to true because of <tables/>)" :
((!generateRelations && generateDaos) ? " (forced to true because of <daos/>)" : "")));
log.info(" table-valued functions", generateTableValuedFunctions());
log.info(" global references", generateGlobalObjectReferences());
log.info("----------------------------------------------------------");
if (!generateInstanceFields()) {
log.warn("");
log.warn("Deprecation warnings");
log.warn("----------------------------------------------------------");
log.warn(" <generateInstanceFields/> = false is deprecated! Please adapt your configuration.");
}
log.info("");
logGenerationRemarks(db);
log.info("");
log.info("----------------------------------------------------------");
// ----------------------------------------------------------------------
// XXX Generating catalogs
// ----------------------------------------------------------------------
log.info("Generating catalogs", "Total: " + database.getCatalogs().size());
for (CatalogDefinition catalog : database.getCatalogs()) {
try {
if (generateCatalogIfEmpty(catalog))
generate(catalog);
else
log.info("Excluding empty catalog", catalog);
}
catch (Exception e) {
throw new GeneratorException("Error generating code for catalog " + catalog, e);
}
}
// [#5556] Clean up common parent directory
log.info("Removing excess files");
empty(getStrategy().getFileRoot(), (scala ? ".scala" : ".java"), files, directoriesNotForRemoval);
directoriesNotForRemoval.clear();
files.clear();
}
private boolean generateCatalogIfEmpty(CatalogDefinition catalog) {
if (generateEmptyCatalogs())
return true;
List<SchemaDefinition> schemas = catalog.getSchemata();
if (schemas.isEmpty())
return false;
for (SchemaDefinition schema : schemas)
if (generateSchemaIfEmpty(schema))
return true;
return false;
}
private final boolean generateSchemaIfEmpty(SchemaDefinition schema) {
if (generateEmptySchemas())
return true;
if (database.getArrays(schema).isEmpty()
&& database.getEnums(schema).isEmpty()
&& database.getPackages(schema).isEmpty()
&& database.getRoutines(schema).isEmpty()
&& database.getTables(schema).isEmpty()
&& database.getUDTs(schema).isEmpty())
return false;
return true;
}
private void generate(CatalogDefinition catalog) {
String newVersion = catalog.getDatabase().getCatalogVersionProvider().version(catalog);
if (StringUtils.isBlank(newVersion)) {
log.info("No schema version is applied for catalog " + catalog.getInputName() + ". Regenerating.");
}
else {
catalogVersions.put(catalog, newVersion);
String oldVersion = readVersion(getFile(catalog), "catalog");
if (StringUtils.isBlank(oldVersion)) {
log.info("No previous version available for catalog " + catalog.getInputName() + ". Regenerating.");
}
else if (!oldVersion.equals(newVersion)) {
log.info("Existing version " + oldVersion + " is not up to date with " + newVersion + " for catalog " + catalog.getInputName() + ". Regenerating.");
}
else {
log.info("Existing version " + oldVersion + " is up to date with " + newVersion + " for catalog " + catalog.getInputName() + ". Ignoring catalog.");
// [#5614] If a catalog is not regenerated, we must flag it as "not for removal", because its contents
// will not be listed in the files directory.
directoriesNotForRemoval.add(getFile(catalog).getParentFile());
return;
}
}
generateCatalog(catalog);
log.info("Generating schemata", "Total: " + catalog.getSchemata().size());
for (SchemaDefinition schema : catalog.getSchemata()) {
try {
if (generateSchemaIfEmpty(schema))
generate(schema);
else
log.info("Excluding empty schema", schema);
}
catch (Exception e) {
throw new GeneratorException("Error generating code for schema " + schema, e);
}
}
}
private void generate(SchemaDefinition schema) {
String newVersion = schema.getDatabase().getSchemaVersionProvider().version(schema);
if (StringUtils.isBlank(newVersion)) {
log.info("No schema version is applied for schema " + schema.getInputName() + ". Regenerating.");
}
else {
schemaVersions.put(schema, newVersion);
String oldVersion = readVersion(getFile(schema), "schema");
if (StringUtils.isBlank(oldVersion)) {
log.info("No previous version available for schema " + schema.getInputName() + ". Regenerating.");
}
else if (!oldVersion.equals(newVersion)) {
log.info("Existing version " + oldVersion + " is not up to date with " + newVersion + " for schema " + schema.getInputName() + ". Regenerating.");
}
else {
log.info("Existing version " + oldVersion + " is up to date with " + newVersion + " for schema " + schema.getInputName() + ". Ignoring schema.");
// [#5614] If a schema is not regenerated, we must flag it as "not for removal", because its contents
// will not be listed in the files directory.
directoriesNotForRemoval.add(getFile(schema).getParentFile());
return;
}
}
// ----------------------------------------------------------------------
// XXX Initialising
// ----------------------------------------------------------------------
generateSchema(schema);
if (generateGlobalSequenceReferences() && database.getSequences(schema).size() > 0) {
generateSequences(schema);
}
if (generateTables() && database.getTables(schema).size() > 0) {
generateTables(schema);
}
if (generatePojos() && database.getTables(schema).size() > 0) {
generatePojos(schema);
}
if (generateDaos() && database.getTables(schema).size() > 0) {
generateDaos(schema);
}
if (generateGlobalTableReferences() && database.getTables(schema).size() > 0) {
generateTableReferences(schema);
}
if (generateRelations() && database.getTables(schema).size() > 0) {
generateRelations(schema);
}
if (generateRecords() && database.getTables(schema).size() > 0) {
generateRecords(schema);
}
if (generateInterfaces() && database.getTables(schema).size() > 0) {
generateInterfaces(schema);
}
if (generateUDTs() && database.getUDTs(schema).size() > 0) {
generateUDTs(schema);
}
if (generatePojos() && database.getUDTs(schema).size() > 0) {
generateUDTPojos(schema);
}
if (generateUDTs() && generateRecords() && database.getUDTs(schema).size() > 0) {
generateUDTRecords(schema);
}
if (generateInterfaces() && database.getUDTs(schema).size() > 0) {
generateUDTInterfaces(schema);
}
if (generateUDTs() && generateRoutines() && database.getUDTs(schema).size() > 0) {
generateUDTRoutines(schema);
}
if (generateGlobalUDTReferences() && database.getUDTs(schema).size() > 0) {
generateUDTReferences(schema);
}
if (generateUDTs() && database.getArrays(schema).size() > 0) {
generateArrays(schema);
}
if (generateUDTs() && database.getEnums(schema).size() > 0) {
generateEnums(schema);
}
if (generateUDTs() && database.getDomains(schema).size() > 0) {
generateDomains(schema);
}
if (generateRoutines() && (database.getRoutines(schema).size() > 0 || hasTableValuedFunctions(schema))) {
generateRoutines(schema);
}
// XXX [#651] Refactoring-cursor
watch.splitInfo("Generation finished: " + schema.getQualifiedName());
log.info("");
}
private class AvoidAmbiguousClassesFilter implements Database.Filter {
private Map<String, String> included = new HashMap<String, String>();
@Override
public boolean exclude(Definition definition) {
// These definitions don't generate types of their own.
if ( definition instanceof ColumnDefinition
|| definition instanceof AttributeDefinition
|| definition instanceof ParameterDefinition)
return false;
// Check if we've previously encountered a Java type of the same case-insensitive, fully-qualified name.
String name = getStrategy().getFullJavaClassName(definition);
String nameLC = name.toLowerCase();
String existing = included.put(nameLC, name);
if (existing == null)
return false;
log.warn("Ambiguous type name", "The object " + definition.getQualifiedOutputName() + " generates a type " + name + " which conflicts with the existing type " + existing + " on some operating systems. Use a custom generator strategy to disambiguate the types.");
return true;
}
}
private boolean hasTableValuedFunctions(SchemaDefinition schema) {
for (TableDefinition table : database.getTables(schema)) {
if (table.isTableValuedFunction()) {
return true;
}
}
return false;
}
protected void generateRelations(SchemaDefinition schema) {
log.info("Generating Keys");
JavaWriter out = newJavaWriter(new File(getFile(schema).getParentFile(), "Keys.java"));
printPackage(out, schema);
printClassJavadoc(out,
"A class modelling foreign key relationships between tables of the <code>" + schema.getOutputName() + "</code> schema");
printClassAnnotations(out, schema);
if (scala)
out.println("object Keys {");
else
out.println("public class Keys {");
out.tab(1).header("IDENTITY definitions");
out.println();
List<IdentityDefinition> allIdentities = new ArrayList<IdentityDefinition>();
List<UniqueKeyDefinition> allUniqueKeys = new ArrayList<UniqueKeyDefinition>();
List<ForeignKeyDefinition> allForeignKeys = new ArrayList<ForeignKeyDefinition>();
for (TableDefinition table : database.getTables(schema)) {
try {
IdentityDefinition identity = table.getIdentity();
if (identity != null) {
final String identityType = out.ref(getStrategy().getFullJavaClassName(identity.getColumn().getContainer(), Mode.RECORD));
final String columnType = out.ref(getJavaType(identity.getColumn().getType()));
final String identityId = getStrategy().getJavaIdentifier(identity.getColumn().getContainer());
final int block = allIdentities.size() / INITIALISER_SIZE;
if (scala)
out.tab(1).println("val IDENTITY_%s = Identities%s.IDENTITY_%s",
identityId, block, identityId);
else
out.tab(1).println("public static final %s<%s, %s> IDENTITY_%s = Identities%s.IDENTITY_%s;",
Identity.class, identityType, columnType, identityId, block, identityId);
allIdentities.add(identity);
}
}
catch (Exception e) {
log.error("Error while generating table " + table, e);
}
}
// Unique keys
out.tab(1).header("UNIQUE and PRIMARY KEY definitions");
out.println();
for (TableDefinition table : database.getTables(schema)) {
try {
List<UniqueKeyDefinition> uniqueKeys = table.getUniqueKeys();
for (UniqueKeyDefinition uniqueKey : uniqueKeys) {
final String keyType = out.ref(getStrategy().getFullJavaClassName(uniqueKey.getTable(), Mode.RECORD));
final String keyId = getStrategy().getJavaIdentifier(uniqueKey);
final int block = allUniqueKeys.size() / INITIALISER_SIZE;
if (scala)
out.tab(1).println("val %s = UniqueKeys%s.%s", keyId, block, keyId);
else
out.tab(1).println("public static final %s<%s> %s = UniqueKeys%s.%s;", UniqueKey.class, keyType, keyId, block, keyId);
allUniqueKeys.add(uniqueKey);
}
}
catch (Exception e) {
log.error("Error while generating table " + table, e);
}
}
// Foreign keys
out.tab(1).header("FOREIGN KEY definitions");
out.println();
for (TableDefinition table : database.getTables(schema)) {
try {
List<ForeignKeyDefinition> foreignKeys = table.getForeignKeys();
for (ForeignKeyDefinition foreignKey : foreignKeys) {
final String keyType = out.ref(getStrategy().getFullJavaClassName(foreignKey.getKeyTable(), Mode.RECORD));
final String referencedType = out.ref(getStrategy().getFullJavaClassName(foreignKey.getReferencedTable(), Mode.RECORD));
final String keyId = getStrategy().getJavaIdentifier(foreignKey);
final int block = allForeignKeys.size() / INITIALISER_SIZE;
if (scala)
out.tab(1).println("val %s = ForeignKeys%s.%s", keyId, block, keyId);
else
out.tab(1).println("public static final %s<%s, %s> %s = ForeignKeys%s.%s;", ForeignKey.class, keyType, referencedType, keyId, block, keyId);
allForeignKeys.add(foreignKey);
}
}
catch (Exception e) {
log.error("Error while generating reference " + table, e);
}
}
// [#1459] Print nested classes for actual static field initialisations
// keeping top-level initialiser small
int identityCounter = 0;
int uniqueKeyCounter = 0;
int foreignKeyCounter = 0;
out.tab(1).header("[#1459] distribute members to avoid static initialisers > 64kb");
// Identities
// ----------
for (IdentityDefinition identity : allIdentities) {
printIdentity(out, identityCounter, identity);
identityCounter++;
}
if (identityCounter > 0) {
out.tab(1).println("}");
}
// UniqueKeys
// ----------
for (UniqueKeyDefinition uniqueKey : allUniqueKeys) {
printUniqueKey(out, uniqueKeyCounter, uniqueKey);
uniqueKeyCounter++;
}
if (uniqueKeyCounter > 0) {
out.tab(1).println("}");
}
// ForeignKeys
// -----------
for (ForeignKeyDefinition foreignKey : allForeignKeys) {
printForeignKey(out, foreignKeyCounter, foreignKey);
foreignKeyCounter++;
}
if (foreignKeyCounter > 0) {
out.tab(1).println("}");
}
out.println("}");
closeJavaWriter(out);
watch.splitInfo("Keys generated");
}
protected void printIdentity(JavaWriter out, int identityCounter, IdentityDefinition identity) {
final int block = identityCounter / INITIALISER_SIZE;
// Print new nested class
if (identityCounter % INITIALISER_SIZE == 0) {
if (identityCounter > 0) {
out.tab(1).println("}");
}
out.println();
if (scala)
out.tab(1).println("private object Identities%s extends %s {", block, AbstractKeys.class);
else
out.tab(1).println("private static class Identities%s extends %s {", block, AbstractKeys.class);
}
if (scala)
out.tab(2).println("val %s : %s[%s, %s] = %s.createIdentity(%s, %s)",
getStrategy().getJavaIdentifier(identity),
Identity.class,
out.ref(getStrategy().getFullJavaClassName(identity.getTable(), Mode.RECORD)),
out.ref(getJavaType(identity.getColumn().getType())),
AbstractKeys.class,
out.ref(getStrategy().getFullJavaIdentifier(identity.getColumn().getContainer()), 2),
out.ref(getStrategy().getFullJavaIdentifier(identity.getColumn()), colRefSegments(identity.getColumn())));
else
out.tab(2).println("public static %s<%s, %s> %s = createIdentity(%s, %s);",
Identity.class,
out.ref(getStrategy().getFullJavaClassName(identity.getTable(), Mode.RECORD)),
out.ref(getJavaType(identity.getColumn().getType())),
getStrategy().getJavaIdentifier(identity),
out.ref(getStrategy().getFullJavaIdentifier(identity.getColumn().getContainer()), 2),
out.ref(getStrategy().getFullJavaIdentifier(identity.getColumn()), colRefSegments(identity.getColumn())));
}
protected void printUniqueKey(JavaWriter out, int uniqueKeyCounter, UniqueKeyDefinition uniqueKey) {
final int block = uniqueKeyCounter / INITIALISER_SIZE;
// Print new nested class
if (uniqueKeyCounter % INITIALISER_SIZE == 0) {
if (uniqueKeyCounter > 0) {
out.tab(1).println("}");
}
out.println();
if (scala)
out.tab(1).println("private object UniqueKeys%s extends %s {", block, AbstractKeys.class);
else
out.tab(1).println("private static class UniqueKeys%s extends %s {", block, AbstractKeys.class);
}
if (scala)
out.tab(2).println("val %s : %s[%s] = %s.createUniqueKey(%s, \"%s\", [[%s]])",
getStrategy().getJavaIdentifier(uniqueKey),
UniqueKey.class,
out.ref(getStrategy().getFullJavaClassName(uniqueKey.getTable(), Mode.RECORD)),
AbstractKeys.class,
out.ref(getStrategy().getFullJavaIdentifier(uniqueKey.getTable()), 2),
escapeString(uniqueKey.getOutputName()),
out.ref(getStrategy().getFullJavaIdentifiers(uniqueKey.getKeyColumns()), colRefSegments(null)));
else
out.tab(2).println("public static final %s<%s> %s = createUniqueKey(%s, \"%s\", [[%s]]);",
UniqueKey.class,
out.ref(getStrategy().getFullJavaClassName(uniqueKey.getTable(), Mode.RECORD)),
getStrategy().getJavaIdentifier(uniqueKey),
out.ref(getStrategy().getFullJavaIdentifier(uniqueKey.getTable()), 2),
escapeString(uniqueKey.getOutputName()),
out.ref(getStrategy().getFullJavaIdentifiers(uniqueKey.getKeyColumns()), colRefSegments(null)));
}
protected void printForeignKey(JavaWriter out, int foreignKeyCounter, ForeignKeyDefinition foreignKey) {
final int block = foreignKeyCounter / INITIALISER_SIZE;
// Print new nested class
if (foreignKeyCounter % INITIALISER_SIZE == 0) {
if (foreignKeyCounter > 0) {
out.tab(1).println("}");
}
out.println();
if (scala)
out.tab(1).println("private object ForeignKeys%s extends %s {", block, AbstractKeys.class);
else
out.tab(1).println("private static class ForeignKeys%s extends %s {", block, AbstractKeys.class);
}
if (scala)
out.tab(2).println("val %s : %s[%s, %s] = %s.createForeignKey(%s, %s, \"%s\", [[%s]])",
getStrategy().getJavaIdentifier(foreignKey),
ForeignKey.class,
out.ref(getStrategy().getFullJavaClassName(foreignKey.getKeyTable(), Mode.RECORD)),
out.ref(getStrategy().getFullJavaClassName(foreignKey.getReferencedTable(), Mode.RECORD)),
AbstractKeys.class,
out.ref(getStrategy().getFullJavaIdentifier(foreignKey.getReferencedKey()), 2),
out.ref(getStrategy().getFullJavaIdentifier(foreignKey.getKeyTable()), 2),
escapeString(foreignKey.getOutputName()),
out.ref(getStrategy().getFullJavaIdentifiers(foreignKey.getKeyColumns()), colRefSegments(null)));
else
out.tab(2).println("public static final %s<%s, %s> %s = createForeignKey(%s, %s, \"%s\", [[%s]]);",
ForeignKey.class,
out.ref(getStrategy().getFullJavaClassName(foreignKey.getKeyTable(), Mode.RECORD)),
out.ref(getStrategy().getFullJavaClassName(foreignKey.getReferencedTable(), Mode.RECORD)),
getStrategy().getJavaIdentifier(foreignKey),
out.ref(getStrategy().getFullJavaIdentifier(foreignKey.getReferencedKey()), 2),
out.ref(getStrategy().getFullJavaIdentifier(foreignKey.getKeyTable()), 2),
escapeString(foreignKey.getOutputName()),
out.ref(getStrategy().getFullJavaIdentifiers(foreignKey.getKeyColumns()), colRefSegments(null)));
}
protected void generateRecords(SchemaDefinition schema) {
log.info("Generating table records");
for (TableDefinition table : database.getTables(schema)) {
try {
generateRecord(table);
} catch (Exception e) {
log.error("Error while generating table record " + table, e);
}
}
watch.splitInfo("Table records generated");
}
protected void generateRecord(TableDefinition table) {
JavaWriter out = newJavaWriter(getFile(table, Mode.RECORD));
log.info("Generating record", out.file().getName());
generateRecord(table, out);
closeJavaWriter(out);
}
protected void generateUDTRecord(UDTDefinition udt) {
JavaWriter out = newJavaWriter(getFile(udt, Mode.RECORD));
log.info("Generating record", out.file().getName());
generateRecord0(udt, out);
closeJavaWriter(out);
}
protected void generateRecord(TableDefinition table, JavaWriter out) {
generateRecord0(table, out);
}
protected void generateUDTRecord(UDTDefinition udt, JavaWriter out) {
generateRecord0(udt, out);
}
private final void generateRecord0(Definition tableOrUdt, JavaWriter out) {
final UniqueKeyDefinition key = (tableOrUdt instanceof TableDefinition)
? ((TableDefinition) tableOrUdt).getPrimaryKey()
: null;
final String className = getStrategy().getJavaClassName(tableOrUdt, Mode.RECORD);
final String tableIdentifier = out.ref(getStrategy().getFullJavaIdentifier(tableOrUdt), 2);
final List<String> interfaces = out.ref(getStrategy().getJavaClassImplements(tableOrUdt, Mode.RECORD));
final List<? extends TypedElementDefinition<?>> columns = getTypedElements(tableOrUdt);
printPackage(out, tableOrUdt, Mode.RECORD);
if (tableOrUdt instanceof TableDefinition)
generateRecordClassJavadoc((TableDefinition) tableOrUdt, out);
else
generateUDTRecordClassJavadoc((UDTDefinition) tableOrUdt, out);
printClassAnnotations(out, tableOrUdt.getSchema());
if (tableOrUdt instanceof TableDefinition)
printTableJPAAnnotation(out, (TableDefinition) tableOrUdt);
Class<?> baseClass;
if (tableOrUdt instanceof UDTDefinition)
baseClass = UDTRecordImpl.class;
else if (generateRelations() && key != null)
baseClass = UpdatableRecordImpl.class;
else
baseClass = TableRecordImpl.class;
int degree = columns.size();
String rowType = null;
String rowTypeRecord = null;
// [#3130] Invalid UDTs may have a degree of 0
if (degree > 0 && degree <= Constants.MAX_ROW_DEGREE) {
rowType = refRowType(out, columns);
if (scala)
rowTypeRecord = out.ref(Record.class.getName() + degree) + "[" + rowType + "]";
else
rowTypeRecord = out.ref(Record.class.getName() + degree) + "<" + rowType + ">";
interfaces.add(rowTypeRecord);
}
if (generateInterfaces()) {
interfaces.add(out.ref(getStrategy().getFullJavaClassName(tableOrUdt, Mode.INTERFACE)));
}
if (scala)
out.println("class %s extends %s[%s](%s)[[before= with ][separator= with ][%s]] {", className, baseClass, className, tableIdentifier, interfaces);
else
out.println("public class %s extends %s<%s>[[before= implements ][%s]] {", className, baseClass, className, interfaces);
out.printSerial();
for (int i = 0; i < degree; i++) {
TypedElementDefinition<?> column = columns.get(i);
if (tableOrUdt instanceof TableDefinition) {
generateRecordSetter(column, i, out);
generateRecordGetter(column, i, out);
}
else {
generateUDTRecordSetter(column, i, out);
generateUDTRecordGetter(column, i, out);
}
}
if (generateRelations() && key != null) {
int keyDegree = key.getKeyColumns().size();
if (keyDegree <= Constants.MAX_ROW_DEGREE) {
String keyType = refRowType(out, key.getKeyColumns());
out.tab(1).header("Primary key information");
if (scala) {
out.tab(1).println("override def key : %s[%s] = {", out.ref(Record.class.getName() + keyDegree), keyType);
out.tab(2).println("return super.key.asInstanceOf[ %s[%s] ]", out.ref(Record.class.getName() + keyDegree), keyType);
out.tab(1).println("}");
}
else {
out.tab(1).overrideInherit();
out.tab(1).println("public %s<%s> key() {", out.ref(Record.class.getName() + keyDegree), keyType);