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. 045 */ 046 public String normaliseColumn(String columnName) { 047 048 columnName = trimQuotes(columnName); 049 if (lowerCaseColumns) { 050 columnName = columnName.toLowerCase(); 051 } 052 return columnName; 053 } 054 055 /** 056 * Lower case the table name checking for quoted identifiers. 057 */ 058 public String lowerTableName(String tableName) { 059 if (lowerCaseTables && notQuoted(tableName)) { 060 return tableName.toLowerCase(); 061 } 062 return tableName; 063 } 064 065 /** 066 * Lower case the column name checking for quoted identifiers. 067 */ 068 public String lowerColumnName(String name) { 069 if (lowerCaseColumns && notQuoted(name)) { 070 return name.toLowerCase(); 071 } 072 return name; 073 } 074 075 /** 076 * Trim off the platform quoted identifier quotes like [ ' and ". 077 */ 078 public boolean notQuoted(String tableName) { 079 080 // remove quoted identifier characters 081 for (String quotedIdentifier : quotedIdentifiers) { 082 if (tableName.contains(quotedIdentifier)) { 083 return false; 084 } 085 } 086 return true; 087 } 088 089 /** 090 * Trim off the platform quoted identifier quotes like [ ' and ". 091 */ 092 public String trimQuotes(String tableName) { 093 094 if (tableName == null) { 095 return ""; 096 } 097 // remove quoted identifier characters 098 for (String quotedIdentifier : quotedIdentifiers) { 099 tableName = tableName.replace(quotedIdentifier, ""); 100 } 101 return tableName; 102 } 103 104 105}