001package gu.sql2java.generator; 002 003import java.util.ArrayList; 004import java.util.Collections; 005import java.util.HashMap; 006import java.util.List; 007import java.util.Map; 008 009import gu.sql2java.generator.Column; 010import gu.sql2java.generator.IndexColumn; 011import gu.sql2java.generator.Table; 012 013public class Index { 014 private Table table; 015 private String name; 016 private boolean unique; 017 private Map<String,Column> columns; 018 019 public Index() { 020 this(""); 021 } 022 023 public Index(String name) { 024 this(name, null); 025 } 026 027 public Index(String name, Table table) { 028 this(name, table, new HashMap<String,Column>()); 029 } 030 031 public Index(String name, Table table, Map<String,Column> columns) { 032 this.name = name; 033 this.table = table; 034 this.columns = columns; 035 if (null != this.table) { 036 this.table.addIndex(this); 037 } 038 } 039 040 public void addIndexColumn(IndexColumn column) { 041 if (null != column) { 042 this.columns.put(column.getName().toLowerCase(), column); 043 } 044 } 045 046 public void removeIndexColumn(Column column) { 047 if (null != column) { 048 this.columns.remove(column.getName().toLowerCase()); 049 } 050 } 051 052 public Table getTable() { 053 return this.table; 054 } 055 056 public String getName() { 057 return this.name; 058 } 059 060 public boolean isUnique() { 061 return this.unique; 062 } 063 064 public Map<String,Column> getIndexColumns() { 065 return this.columns; 066 } 067 068 public List<Column> getIndexColumnsList() { 069 ArrayList<Column> list = new ArrayList<Column>(); 070 list.addAll(this.columns.values()); 071 Collections.sort(list); 072 return list; 073 } 074 public Column getIndexColumn() { 075 if (this.columns.size() != 1) { 076 throw new RuntimeException("the index "+this.getName() + "of Table " + this.getTable().getName() + " is a composite key"); 077 } 078 return getIndexColumnsList().get(0); 079 } 080 public void setName(String name) { 081 this.name = name; 082 } 083 084 public void setUnique(boolean unique) { 085 this.unique = unique; 086 } 087 088 public void setTable(Table table) { 089 this.table = table; 090 } 091 092 public String asIndexName(){ 093 StringBuilder buf=new StringBuilder("index"); 094 List<Column> list = getIndexColumnsList(); 095 for(int i=0;i<list.size();++i){ 096 buf.append('_').append(list.get(i).getName()); 097 } 098 return buf.toString(); 099 } 100 101 public String asCamelCaseName(){ 102 return StringUtilities.convertName(this.asIndexName(),false); 103 } 104 public String asConstName(){ 105 return (this.table.getName() + "_" +this.asIndexName()).toUpperCase(); 106 } 107 public String asIndexVar(){ 108 return StringUtilities.convertName(this.asIndexName(),true); 109 } 110}