001package io.ebeaninternal.dbmigration.ddlgeneration.platform; 002 003import io.ebean.annotation.IdentityGenerated; 004import io.ebean.config.dbplatform.IdType; 005import io.ebeaninternal.server.deploy.IdentityMode; 006 007public class DdlIdentity { 008 009 public static final DdlIdentity NONE = new DdlIdentity(); 010 011 private final IdType idType; 012 private final IdentityMode identityMode; 013 private final String sequenceName; 014 015 public DdlIdentity(IdType idType, IdentityMode identityMode, String sequenceName) { 016 this.idType = idType; 017 this.identityMode = identityMode; 018 this.sequenceName = sequenceName; 019 } 020 021 private DdlIdentity() { 022 this.idType = null; 023 this.identityMode = null; 024 this.sequenceName = null; 025 } 026 027 public boolean useSequence() { 028 return idType == IdType.SEQUENCE; 029 } 030 031 public boolean useIdentity() { 032 return idType == IdType.IDENTITY; 033 } 034 035 public String getSequenceName() { 036 return sequenceName; 037 } 038 039 private String generatedBy() { 040 return isAlways() ? "always" : "by default"; 041 } 042 043 private boolean isAlways() { 044 return IdentityGenerated.ALWAYS == identityMode.getGenerated(); 045 } 046 047 public String optionGenerated() { 048 return " generated " + generatedBy() +" as identity"; 049 } 050 051 public String identityOptions(String startWith, String incrementBy, String cache) { 052 return options(true, startWith, incrementBy, cache); 053 } 054 055 public String sequenceOptions(String startWith, String incrementBy, String cache) { 056 return options(false, startWith, incrementBy, cache); 057 } 058 059 private String options(boolean brackets, String startWith, String incrementBy, String cache) { 060 if (!identityMode.hasOptions()) { 061 return ""; 062 } 063 StringBuilder sb = new StringBuilder(40); 064 if (brackets) { 065 sb.append(" ("); 066 } else { 067 sb.append(" "); 068 } 069 optionFor(sb, startWith, identityMode.getStart()); 070 optionFor(sb, incrementBy, identityMode.getIncrement()); 071 optionFor(sb, cache, identityMode.getCache()); 072 if (brackets) { 073 sb.append(")"); 074 } 075 return sb.toString(); 076 } 077 078 private void optionFor(StringBuilder sb, String prefix, int val) { 079 if (val > 0 && prefix != null) { 080 if (sb.length() > 2) { 081 sb.append(" "); 082 } 083 sb.append(prefix).append(" ").append(val); 084 } 085 } 086 087 public int getStart() { 088 return identityMode.getStart(); 089 } 090 091 public int getIncrement() { 092 return identityMode.getIncrement(); 093 } 094 095 public int getCache() { 096 return identityMode.getCache(); 097 } 098}