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   * Trim off the platform quoted identifier quotes like [ ' and ".
060   */
061  public String trimQuotes(String identifier) {
062
063    if (identifier == null) {
064      return "";
065    }
066    // remove quoted identifier characters
067    for (String quotedIdentifier : quotedIdentifiers) {
068      identifier = identifier.replace(quotedIdentifier, "");
069    }
070    return identifier;
071  }
072
073
074}