1616
1717import java .lang .reflect .Field ;
1818import java .lang .reflect .Modifier ;
19+ import java .util .ArrayList ;
20+ import java .util .List ;
1921import java .util .Objects ;
2022
2123/**
@@ -51,7 +53,10 @@ public TableSchema buildTableSchema() {
5153
5254 debug ("Building defs from type class: " + typeClass .getName ());
5355
56+ boolean multiplePK = getPKCount () > 1 ;
57+
5458 ColumnDefinition [] defs = new ColumnDefinition [0 ];
59+ List <String > pks = new ArrayList <>();
5560 for (Field field : typeClass .getDeclaredFields ()) {
5661 debug ("Building def for field: " + field .getName () + " (" + field .getType ().getName () + ")" );
5762 if (Modifier .isTransient (field .getModifiers ())) {
@@ -60,7 +65,7 @@ public TableSchema buildTableSchema() {
6065 }
6166
6267 String colName = namingStrategy .fieldNameToColumn (field .getName ());
63- String colType = recognizeFieldTypeToDbType (field );
68+ String colType = recognizeFieldTypeToDbType (field , multiplePK );
6469
6570 if (colType != null && !colType .contains ("NOT NULL" ) && field .isAnnotationPresent (NullableField .class )) {
6671 if (!field .getAnnotation (NullableField .class ).nullable ()) {
@@ -75,17 +80,35 @@ public TableSchema buildTableSchema() {
7580 colType += " DEFAULT " + defaultValue ;
7681 }
7782
83+ if (field .isAnnotationPresent (PrimaryKey .class )) {
84+ pks .add (colName );
85+ }
86+
7887 defs = Arrays .add (defs , new ColumnDefinition (colName , colType ));
7988
8089 debug ("Added def: " + colName + " " + colType );
8190 }
8291
92+ if (multiplePK ) {
93+ defs = Arrays .add (defs , new ColumnDefinition ("PRIMARY KEY" , String .format ("(%s)" , String .join (", " , pks ))));
94+ }
95+
8396 debug ("Built defs: " + java .util .Arrays .toString (defs ));
8497
8598 return new TableSchema (tableName , defs );
8699 }
87100
88- private String recognizeFieldTypeToDbType (Field field ) {
101+ private int getPKCount () {
102+ int count = 0 ;
103+ for (Field field : typeClass .getDeclaredFields ()) {
104+ if (field .isAnnotationPresent (PrimaryKey .class )) {
105+ count ++;
106+ }
107+ }
108+ return count ;
109+ }
110+
111+ private String recognizeFieldTypeToDbType (Field field , boolean multiplePK ) {
89112 Class <?> fieldType = Primitives .wrap (field .getType ());
90113 boolean isSupported = isSupported (fieldType );
91114
@@ -111,8 +134,9 @@ private String recognizeFieldTypeToDbType(Field field) {
111134 dbType = "FLOAT" ;
112135 }
113136
114- if (field .isAnnotationPresent (PrimaryKey .class ))
137+ if (field .isAnnotationPresent (PrimaryKey .class ) && ! multiplePK ) {
115138 dbType += " PRIMARY KEY" ;
139+ }
116140
117141 if (Validator .validateAutoIncrement (field ))
118142 dbType += " " + (isSQLite () ? "AUTOINCREMENT" : "AUTO_INCREMENT" );
0 commit comments