View Javadoc

1   /*
2    * Copyright 2006 Outsource Cafe, Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the 'License')
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *    http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an 'AS IS' BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.javagen.agile.db.visitor;
17  
18  import java.util.EnumSet;
19  import java.util.Set;
20  
21  import org.javagen.agile.core.util.StringUtil;
22  import org.javagen.agile.db.model.DbType;
23  import org.javagen.agile.db.model.PkColumn;
24  import org.javagen.agile.db.model.Table;
25  
26  /***
27   * Sets all non-composite, unique primary keys matching the SQL types specified 
28   * by the targetAutoPkTypes Set<String> to auto-incrament primary keys.
29   * 
30   * Wire this class into the code generation pipeline after database model creation, but before
31   * Java conversion.
32   * 
33   * @author Richard Easterling
34   */
35  public class AutoIncrementFinderVisitor extends DefaultDatabaseVisitor {
36  
37      public final static EnumSet<DbType> DEFAULT_AUTO_PK_TYPES = EnumSet.of(DbType.INTEGER, DbType.BIGINT);
38      
39      public final static Set<String> ITINERARY = StringUtil.toStringSet(new String[] {PkColumn.DEFAULT_MODEL_TYPE});
40  
41      private EnumSet<DbType> targetAutoPkTypes = DEFAULT_AUTO_PK_TYPES;
42      
43      public EnumSet<DbType> getTargetAutoPkTypes() {
44          return targetAutoPkTypes;
45      }
46  
47      /*** set to null to match all unique primary keys */
48      public void setTargetAutoPkTypes(EnumSet<DbType> targetAutoPkTypes) {
49          this.targetAutoPkTypes = targetAutoPkTypes;
50      }
51  
52      public Set<String> itinerary() { return ITINERARY; }
53  
54      /***
55       * Identify and set auto-increment primary keys using specified pattern.
56       */
57      public void visit(PkColumn pkColumn) {
58          Table table = pkColumn.getParentTable();
59          if ( ! Boolean.TRUE.equals(pkColumn.getAutoIncrement()) 
60               && ! table.hasCompositeKey()
61               && Boolean.TRUE.equals(pkColumn.getUnique())
62               && (targetAutoPkTypes==null || targetAutoPkTypes.contains(pkColumn.getDbType()))
63             )
64          {
65              pkColumn.setAutoIncrement(Boolean.TRUE);
66          }
67      }
68  
69  
70  }