001package io.ebean.config; 002 003/** 004 * Used to normalise table and column names which means stripping out 005 * quoted identifier characters and any catalog or schema prefix. 006 */ 007public class DbConstraintNormalise { 008 009 protected final String[] quotedIdentifiers; 010 011 protected final boolean lowerCaseTables; 012 013 protected final boolean lowerCaseColumns; 014 015 public DbConstraintNormalise() { 016 this(true, true); 017 } 018 019 public DbConstraintNormalise(boolean lowerCaseTables, boolean lowerCaseColumns) { 020 this.lowerCaseTables = lowerCaseTables; 021 this.lowerCaseColumns = lowerCaseColumns; 022 this.quotedIdentifiers = new String[]{"\"", "'", "[", "]", "`"}; 023 } 024 025 /** 026 * Normalise the table name by trimming catalog and schema and removing any 027 * quoted identifier characters (",',[,] etc). 028 */ 029 public String normaliseTable(String tableName) { 030 031 tableName = trimQuotes(tableName); 032 int lastPeriod = tableName.lastIndexOf('.'); 033 if (lastPeriod > -1) { 034 // trim off catalog and schema prefix 035 tableName = tableName.substring(lastPeriod + 1); 036 } 037 if (lowerCaseTables) { 038 tableName = tableName.toLowerCase(); 039 } 040 return tableName; 041 } 042 043 /** 044 * Normalise the column name by removing any quoted identifier characters and formula brackets. 045 */ 046 public String normaliseColumn(String columnName) { 047 columnName = trimBrackets(trimQuotes(columnName)); 048 if (lowerCaseColumns) { 049 columnName = columnName.toLowerCase(); 050 } 051 return columnName; 052 } 053 054 private String trimBrackets(String value) { 055 return value.replace("(","").replace(")",""); 056 } 057 058 /** 059 * Lower case the table name checking for quoted identifiers. 060 */ 061 public String lowerTableName(String tableName) { 062 if (lowerCaseTables && notQuoted(tableName)) { 063 return tableName.toLowerCase(); 064 } 065 return tableName; 066 } 067 068 /** 069 * Lower case the column name checking for quoted identifiers. 070 */ 071 public String lowerColumnName(String name) { 072 if (lowerCaseColumns && notQuoted(name)) { 073 return name.toLowerCase(); 074 } 075 return name; 076 } 077 078 /** 079 * Trim off the platform quoted identifier quotes like [ ' and ". 080 */ 081 public boolean notQuoted(String tableName) { 082 083 // remove quoted identifier characters 084 for (String quotedIdentifier : quotedIdentifiers) { 085 if (tableName.contains(quotedIdentifier)) { 086 return false; 087 } 088 } 089 return true; 090 } 091 092 /** 093 * Trim off the platform quoted identifier quotes like [ ' and ". 094 */ 095 public String trimQuotes(String tableName) { 096 097 if (tableName == null) { 098 return ""; 099 } 100 // remove quoted identifier characters 101 for (String quotedIdentifier : quotedIdentifiers) { 102 tableName = tableName.replace(quotedIdentifier, ""); 103 } 104 return tableName; 105 } 106 107 108}