Example usage for java.util.regex Matcher end

List of usage examples for java.util.regex Matcher end

Introduction

In this page you can find the example usage for java.util.regex Matcher end.

Prototype

public int end(String name) 

Source Link

Document

Returns the offset after the last character of the subsequence captured by the given named-capturing group during the previous match operation.

Usage

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private String getI18NDetailTableCreateString(Dialect dialect, String sqlCreate, String i18nTblName,
        String i18nFKColName) {/*from w  w w.  ja v a2  s .  c  o m*/
    StringBuilder sql = new StringBuilder();
    Matcher matcher = TBL_PATTERN.matcher(sqlCreate);
    checkTableName(dialect, i18nTblName);

    if (matcher.matches()) {
        sql.append(sqlCreate.substring(0, matcher.start(TBL_PATTERN_IDX_TBLNAME))).append(i18nTblName);

        Matcher colMatcher = COL_PATTERN.matcher(sqlCreate);

        int idx = sqlCreate.indexOf('(', matcher.end(TBL_PATTERN_IDX_TBLNAME)) + 1;
        sql.append(sqlCreate.substring(matcher.end(TBL_PATTERN_IDX_TBLNAME), idx));

        StringBuilder colDef = new StringBuilder();
        while (colMatcher.find(idx)) {
            String colName = TableConfig.getIdentifierForReference(colMatcher.group(COL_PATTERN_IDX_COLNAME));
            if (!colName.toLowerCase().equals(I18N_COLUMN_IS_PERSISTENT)
                    && !colName.toLowerCase().equals(I18N_COLUMN_COMPOSITE_ID)) {
                colDef.append(" ").append(
                        sqlCreate.substring(colMatcher.start(COL_PATTERN_IDX_COLNAME), colMatcher.end()));
            }
            idx = colMatcher.end();
        }
        sql.append(colDef.substring(1));
        sql.append(sqlCreate.substring(idx));

        String tmpSql = sql.toString();
        matcher = TBL_PATTERN.matcher(tmpSql);
        if (matcher.matches()) {
            sql = new StringBuilder(tmpSql.substring(0, matcher.start(TBL_PATTERN_IDX_PK_COLLIST)));
            sql.append(i18nFKColName).append(", language_cd")
                    .append(tmpSql.substring(matcher.end(TBL_PATTERN_IDX_PK_COLLIST)));
        }
    }

    getProfile().duplex(ObjectType.TABLE, i18nTblName, sql.toString());

    return sql.toString();
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table,
        Constraint constraint) {/*  w  w w  .j av a2  s  .com*/
    NamingStrategy namingStrategy = getProfile().getNamingStrategy();
    String newName = namingStrategy.constraintName(constraint,
            getEntityClassName(namingStrategy.tableName(table.getName())));

    if (!name.equals(newName)) {
        String sqlCreate = buf.toString();
        Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate);
        if (matcher.find()) {
            buf = new StringBuffer();
            buf.append(sqlCreate.substring(0, matcher.start(1)));
            buf.append(newName);
            buf.append(sqlCreate.substring(matcher.end(1)));
        }
        name = newName;
    }

    String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase();

    if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) {
        return "-- skipped creation of constraint '" + name + "' for table '" + table.getName()
                + "' as the mapped entity was not chosen to be processed or is a view";
    }

    TableConfig tableConfig = tblNameToConfig.get(tableNameLC);

    String refTblNameLC = null;
    if (constraint instanceof ForeignKey) {
        if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) {
            return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName()
                    + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName();
        }
        refTblNameLC = getProfile().getNamingStrategy()
                .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase();
    }

    checkObjectName(dialect, name);
    String i18nFK = tableConfig.getI18nBaseEntityFkCol();

    if (i18nFK != null) {
        StringBuilder sql = new StringBuilder();
        tableNameLC = getI18NDetailTableName(tableNameLC);
        Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC)
                    .append(buf.substring(matcher.end(1)));
        }
        buf = new StringBuffer(sql.toString());
    }

    if (constraint instanceof ForeignKey) {
        StringBuilder colList = new StringBuilder();
        org.hibernate.mapping.Column singleColumn = null;

        TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC);
        IntervalPartitioning refTblPart = refTableConfig != null
                ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class)
                : null;

        for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint
                .getColumns()) {
            if (colList.length() > 0) {
                colList.append(", ");
            }
            colList.append(column.getName().toLowerCase());
            singleColumn = singleColumn == null ? column : null;
        }

        if (externalViews.contains(refTblNameLC)) {
            buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC
                    + "' since a view will be referenced");
        } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) {
            buf = new StringBuffer();
            buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '")
                    .append(tableNameLC).append("' to table '").append(refTblNameLC)
                    .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ")
                    .append(((ForeignKey) constraint).getReferencedEntityName()).append(")");
        } else {
            if (singleColumn != null) {
                if (tableConfig.getColumnNamesIsCascadeNullable()
                        .contains(singleColumn.getName().toLowerCase())) {
                    buf.append(" on delete set null");
                } else if (tableConfig.getColumnNamesIsCascadeDelete()
                        .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) {
                    buf.append(" on delete cascade");
                }
            }

            Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable();
            Deferrable deferrable;
            if (supportsDeferrable(dialect) && col2Deferrable != null
                    && (deferrable = col2Deferrable.get(colList.toString())) != null) {
                buf.append(" deferrable");
                if (deferrable.initiallyDeferred()) {
                    buf.append(" initially deferred");
                }
            }

            if (getProfile().isDisableFKs()) {
                buf.insert(0,
                        "-- creating FK constraint initially disabled since we do not need it for profile '"
                                + getProfile() + "'\n");
                buf.append(" disable");
            }
        }

        getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString());

        if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) {
            LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC
                    + " and column " + colList.toString());
        } else {
            String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC),
                    tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString()));
            StringBuilder objDdl = new StringBuilder();
            objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (")
                    .append(colList.toString()).append(")");

            if (constraint.getColumnSpan() == 1) {
                tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString());
            }

            buf.append(STATEMENT_SEPARATOR).append(objDdl);

            getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString());
        }
    }

    return buf.toString();
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private String addDefaultValues(String sqlCreate, String nameLC) {
    TableConfig tableConfig = tblNameToConfig.get(nameLC);

    if (tableConfig == null) {
        return sqlCreate;
    }//w w  w.  j  ava2  s.  c o  m

    StringBuilder b = new StringBuilder();
    Matcher matcher = COL_PATTERN.matcher(sqlCreate);
    int idx = 0;

    while (matcher.find(idx)) {
        String colName = TableConfig.getIdentifierForReference(matcher.group(COL_PATTERN_IDX_COLNAME));

        if (matcher.group(COL_PATTERN_IDX_DEFAULT) == null) {
            String defaultExpr = tableConfig.getColNameToDefault().get(colName);

            if (defaultExpr != null) {
                b.append(sqlCreate.substring(idx, matcher.end(COL_PATTERN_IDX_TYPE)));
                b.append(" default ").append(defaultExpr);
                idx = matcher.end(COL_PATTERN_IDX_TYPE);
            }
        }

        b.append(sqlCreate.substring(idx, matcher.end()));
        idx = matcher.end();
    }

    b.append(sqlCreate.substring(idx));

    return b.toString();
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private String processCascadeNullable(Dialect dialect, StringBuffer buf, String tableName, String sqlCreate,
        Set<String> columns) {
    if (columns == null || columns.size() < 1) {
        return sqlCreate;
    }/*from www .ja v  a 2s .  com*/

    Matcher matcher = COL_PATTERN.matcher(sqlCreate);
    int idx = 0;

    StringBuilder sb = new StringBuilder();

    while (matcher.find(idx)) {
        String colName = TableConfig.getIdentifierForReference(matcher.group(COL_PATTERN_IDX_COLNAME));

        if (columns.contains(colName) && matcher.group(COL_PATTERN_IDX_NOT) != null) {
            sb.append(sqlCreate.substring(idx, matcher.start(COL_PATTERN_IDX_NOTNULL)));
            idx = matcher.end(COL_PATTERN_IDX_NOTNULL);
            createCascadeNullableTrigger(dialect, deferredDdl, tableName, colName);
        } else {
            sb.append(sqlCreate.substring(idx, matcher.end()));
            idx = matcher.end();
        }
    }

    sb.append(sqlCreate.substring(idx));

    return sb.toString();
}

From source file:logdruid.ui.table.StatRecordingEditorTable.java

public void FixValues() {
    String patternString = "";
    Matcher matcher;
    PatternCache patternCache = new PatternCache();
    Iterator it = data.iterator();
    Object[] obj;/*ww  w.  ja  v a 2  s .c om*/

    while (it.hasNext()) {
        obj = (Object[]) it.next();
        String stBefore = (String) obj[1];
        String stType = (String) obj[2];
        String stAfter = (String) obj[3];
        logger.info("stType: " + stType);
        if (stType.equals("date") && rep.getDateFormat(recording.getDateFormatID()).getPattern() != null) {
            patternString += stBefore + "(" + rep.getDateFormat(recording.getDateFormatID()).getPattern() + ")"
                    + stAfter;
            logger.info("getTypeString(stType) getPattern -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getPattern());
            logger.info("getTypeString(stType) getDateFormat -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getDateFormat());
        } else {
            patternString += stBefore + "(" + DataMiner.getTypeString(stType) + ")" + stAfter;
            logger.info("getTypeString(stType) -: " + DataMiner.getTypeString(stType));
        }
    }

    try {
        logger.info("theLine: " + examplePane.getText());
        logger.info("patternString: " + patternString);

        Highlighter h = examplePane.getHighlighter();
        h.removeAllHighlights();
        int currIndex = 0;

        String[] lines = examplePane.getText().split(System.getProperty("line.separator"));
        if (lines.length >= 1) {
            for (int i = 0; i < lines.length; i++) {
                matcher = patternCache.getPattern(patternString).matcher(lines[i]);
                if (matcher.find()) {
                    // int currIndex = 0;
                    // doc.insertString(doc.getLength(),line+"\n", null);

                    for (int i2 = 1; i2 <= matcher.groupCount(); i2++) {
                        model.setValueAt(matcher.group(i2), i2 - 1, 5);
                        h.addHighlight(currIndex + matcher.start(i2), +currIndex + matcher.end(i2),
                                new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
                    }

                }
                currIndex += lines[i].length() + 1;
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
        // System.exit(1);
    }

}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private int appendConstraint(StringBuilder b, String sqlCreate, String tableName, String columnName,
        int currIdx, Matcher colMatcher, int groupId, String constraintSuffix) {
    if (colMatcher.group(groupId) != null) {
        String constraintName = getProfile().getNamingStrategy().constraintName(getEntityClassName(tableName),
                tableName, columnName, constraintSuffix);
        b.append(sqlCreate.substring(currIdx, colMatcher.start(groupId)));
        currIdx = colMatcher.start(groupId);
        b.append(" constraint ").append(constraintName);
        b.append(sqlCreate.substring(currIdx, colMatcher.end(groupId)));
        currIdx = colMatcher.end(groupId);
    }//w w  w.  j av a2s  .com

    return currIdx;
}

From source file:logdruid.ui.table.EventRecordingEditorTable.java

public void FixValues() {
    String patternString = "";
    Matcher matcher = null;
    PatternCache patternCache = new PatternCache();
    Iterator it = data.iterator();
    Object[] obj;// w w  w . ja v  a  2s  .  c o  m

    while (it.hasNext()) {
        obj = (Object[]) it.next();
        String stBefore = (String) obj[1];
        String stType = (String) obj[2];
        String stAfter = (String) obj[4];
        logger.info("stType: " + stType);
        if (stType.equals("date") && rep.getDateFormat(recording.getDateFormatID()).getPattern() != null) {
            patternString += stBefore + "(" + rep.getDateFormat(recording.getDateFormatID()).getPattern() + ")"
                    + stAfter;
            logger.info("getTypeString(stType) getPattern -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getPattern());
            logger.info("getTypeString(stType) getDateFormat -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getDateFormat());
        } else {
            patternString += stBefore + "(" + DataMiner.getTypeString(stType) + ")" + stAfter;
            logger.info("getTypeString(stType) -: " + DataMiner.getTypeString(stType));
        }
    }

    try {
        logger.info("theLine: " + examplePane.getText());
        logger.info("patternString: " + patternString);
        Highlighter h = examplePane.getHighlighter();
        h.removeAllHighlights();
        int currIndex = 0;

        String[] lines = examplePane.getText().split(System.getProperty("line.separator"));
        if (lines.length >= 1) {
            for (int i = 0; i < lines.length; i++) {
                matcher = patternCache.getPattern(patternString).matcher(lines[i]);
                if (matcher.find()) {
                    // int currIndex = 0;
                    // doc.insertString(doc.getLength(),line+"\n", null);

                    for (int i2 = 1; i2 <= matcher.groupCount(); i2++) {
                        model.setValueAt(matcher.group(i2), i2 - 1, 6);
                        h.addHighlight(currIndex + matcher.start(i2), +currIndex + matcher.end(i2),
                                new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
                    }
                }
                logger.info("currIndex: " + currIndex + "matcher.end(i2): " + lines[i].length() + ",l: "
                        + lines[i]);
                currIndex += lines[i].length() + 1;
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
        // System.exit(1);
    }

}

From source file:de.uniwue.info6.database.jdbc.ConnectionManager.java

/**
 *
 *
 * @param query//from  ww w  .j  av a  2s .c  o  m
 * @param user
 * @return
 * @throws SQLException
 */
private String addUserPrefix(String query, Scenario scenario, User user) throws SQLException {
    // query = "create table dept_emp, test";
    // String regex_table = "[\\`\\'\"\\s]+([a-zA-Z0-9-_]+?)[\\`\\'\"\\s]+";
    // String regex_table = "[\\s]+([a-zA-Z0-9-_]+)[\\s]*";

    String regex_table = "[\\`\\'\"\\s]+([a-zA-Z0-9-_]+)[\\`\\'\"\\s]*[,]?";
    // String REGEX_FIELD =
    // "(?:create|drop|lock|alter)[\\s]+table[s]?(?:[\\s]*if[\\s]*exists)?" +
    // regex_table;
    String REGEX_FIELD = "(?:create|drop|lock|alter)[\\s]+table[s]?(?:[\\s]*if[\\s]*not?[\\s]*exists)?"
            + regex_table;
    Matcher matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(query);

    ArrayList<String> exclusions = new ArrayList<String>() {
        private static final long serialVersionUID = 1L;
        {
            add("if");
            add("select");
            add("table");
            add("exists");
            add("not exists");
        }
    };

    List<String> tablesToReplace = new ArrayList<String>();
    List<String> tablesToUse = new ArrayList<String>();
    List<Integer> stringStart = new ArrayList<Integer>();
    List<Integer> stringEnd = new ArrayList<Integer>();

    while (matcher.find()) {
        String table = matcher.group(1).trim();
        if (!exclusions.contains(table.toLowerCase())) {
            tablesToReplace.add(table);
            tablesToUse.add(table);
            stringStart.add(matcher.start(1));
            stringEnd.add(matcher.end(1));
        }
    }

    REGEX_FIELD = "(?:insert[\\s]+into|references|constraint)" + regex_table;
    matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(query);
    while (matcher.find()) {
        String table = matcher.group(1).trim();
        if (!exclusions.contains(table.toLowerCase())) {
            tablesToReplace.add(table);
            stringStart.add(matcher.start(1));
            stringEnd.add(matcher.end(1));
        }
    }

    REGEX_FIELD = "(?:insert[\\s]+into|references)" + regex_table;
    matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(query);
    if (matcher.find()) {
        String table = matcher.group(1).trim();
        if (!exclusions.contains(table.toLowerCase())) {
            tablesToUse.add(table);
            stringStart.add(matcher.start(1));
            stringEnd.add(matcher.end(1));
        }
    }

    if (!tablesToReplace.isEmpty()) {
        HashMap<String, String> tablesWithHash = null;
        HashMap<String, String> tableIncrements = null;

        // ------------------------------------------------ //
        if (scenarioTablesWithHash.containsKey(scenario)) {
            tablesWithHash = scenarioTablesWithHash.get(scenario);
        } else {
            tablesWithHash = new HashMap<String, String>();
            scenarioTablesWithHash.put(scenario, tablesWithHash);
        }

        for (int i = tablesToReplace.size() - 1; i >= 0; i--) {
            String foundTable = tablesToReplace.get(i);
            if (user != null) {
                query = query.substring(0, stringStart.get(i)) + user.getId() + "_" + foundTable
                        + query.substring(stringEnd.get(i), query.length());
            }
        }

        if (autoIncrements == null || !autoIncrements.containsKey(scenario)) {
            tableIncrements = new HashMap<String, String>();
            autoIncrements.put(scenario, tableIncrements);
        } else {
            tableIncrements = autoIncrements.get(scenario);
        }

        for (String tableToUse : tablesToUse) {

            // ------------------------------------------------ //

            if (tableIncrements != null) {
                if (!tableIncrements.containsKey(tableToUse)) {
                    String increment = getAutoIncrementFromTable(scenario, tableToUse);
                    if (increment != null) {
                        tableIncrements.put(tableToUse, increment);
                    }
                }
            }
            // ------------------------------------------------ //

            if (!tablesWithHash.containsKey(tableToUse)) {
                String checkSum = getTableChecksum(scenario, user, tableToUse);
                tablesWithHash.put(tableToUse, checkSum);
            }

            // ------------------------------------------------ //

        }

    }
    return query;
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java

/**
 * Takes a URL and then decides if it should be replaced.
 * //w  w w.  j av  a2  s.c  o m
 * @param value
 * @return
 */
private String processUrl(ContentCopyContext context, String value, String contentUrl,
        Map<Long, Long> itemMap) {
    // Need to deal with backticks.
    // - /access/group/{siteId}/
    // - /web/{siteId}/
    // - /dav/{siteId}/
    // http(s)://weblearn.ox.ac.uk/ - needs trimming
    try {
        URI uri = new URI(value);
        uri = uri.normalize();
        if (value.startsWith(ITEMDUMMY)) {
            String num = value.substring(ITEMDUMMYLEN);
            int i = num.indexOf("/");
            if (i >= 0)
                num = num.substring(0, i);
            else
                return value;
            long oldItem = 0;
            try {
                oldItem = Long.parseLong(num);
            } catch (Exception e) {
                return value;
            }
            Long newItem = itemMap.get(oldItem);
            if (newItem == null)
                return value;
            return ITEMDUMMY + newItem + "/";
        } else if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
            if (uri.getHost() != null) {
                // oldserver is the server that this archive is coming from
                // oldserver null means it's a local copy, e.g. duplicate site
                // for null we match URL against all of our server names
                String oldServer = context.getOldServer();
                if (oldServer == null && servers.contains(uri.getHost()) || uri.getHost().equals(oldServer)) {
                    // Drop the protocol and the host.
                    uri = new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment());
                }
            }
        }
        // Only do replacement on our URLs.
        if (uri.getHost() == null && uri.getPath() != null) {
            // Need to attempt todo path replacement now.
            String path = uri.getPath();
            Matcher matcher = pathPattern.matcher(path);

            if (matcher.matches() && context.getOldSiteId().equals(matcher.group(1))) {
                // Need to push the old URL onto the list of resources to
                // process. Except that we can't do that inside Lesson Builder
                //          addPath(context, path);
                String replacementPath = path.substring(0, matcher.start(1)) + context.getNewSiteId()
                        + path.substring(matcher.end(1));
                // Create a new URI with the new path
                uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), replacementPath,
                        uri.getQuery(), uri.getFragment());
            } else if (!path.startsWith("/") && contentUrl != null) {
                // Relative URL.
                try {
                    URI base = new URI(contentUrl);
                    URI link = base.resolve(uri);
                    // sorry, no can do
                    //addPath(context, link.getPath());
                } catch (URISyntaxException e) {
                    System.err.println("Supplied contentUrl isn't valid: " + contentUrl);
                }
            }
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        // Log this so we may get an idea of the things that are breaking
        // the parser.
        System.err.println("Failed to parse URL: " + value + " " + e.getMessage());
    }
    return value;
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private String getHistTableSqlCreateString(Dialect dialect, String sqlCreateString, String histTableName,
        String histColName, Set<String> columns, List<String> pkCols, IntervalPartitioning livePartitioning) {
    checkTableName(dialect, histTableName);

    Matcher matcher = TBL_PATTERN.matcher(sqlCreateString);
    Matcher matchUnique = UNIQUE_PATTERN.matcher(sqlCreateString);

    StringBuilder sql = new StringBuilder();

    // try matching create table sql with PK definition
    if (!matcher.matches()) {
        matcher = TBL_PATTERN_WO_PK.matcher(sqlCreateString);

        // next try without PD definition (e.g. for CollectionTable)
        if (!matcher.matches()) {
            throw new IllegalStateException("cannot find create table in sql: " + sqlCreateString);
        }//from  w  ww. j  av  a2 s  .c om

        sql.append(sqlCreateString.substring(0, matcher.start(TBL_PATTERN_WO_PK_IDX_TBLNAME)))
                .append(histTableName);
        sql.append(sqlCreateString.substring(matcher.end(TBL_PATTERN_WO_PK_IDX_TBLNAME),
                matcher.end(TBL_PATTERN_WO_PK_IDX_BEFORE_COL_DEF)));
        sql.append(formatColumn(dialect, HIST_TABLE_PK_COLUMN_NAME + " ${varcharType} not null",
                Constants.UUID_LEN, null, null)).append(", ");
        sql.append(
                formatColumn(dialect, HIST_OPERATION_COLUMN_NAME + " ${varcharType} not null", 1, null, null))
                .append(", ");

        sql.append(sqlCreateString.substring(matcher.end(TBL_PATTERN_WO_PK_IDX_BEFORE_COL_DEF),
                matcher.start(TBL_PATTERN_WO_PK_IDX_AFTER_COL_DEF)));

        sql.append(", ");

        if (!columns.contains(histColName)) {
            sql.append(formatColumn(dialect, histColName + " ${timestampType} not null", null, null, null))
                    .append(", ");
        }

        sql.append("primary key (");
        sql.append(HIST_TABLE_PK_COLUMN_NAME).append("), ");

        sql.append("unique (");
        for (String columnName : pkCols) {
            sql.append(columnName).append(", ");
        }
        sql.append(histColName);
        sql.append(")");

        sql.append(sqlCreateString.substring(matcher.start(TBL_PATTERN_WO_PK_IDX_AFTER_COL_DEF)));
    } else {
        sql.append(sqlCreateString.substring(0, matcher.start(TBL_PATTERN_IDX_TBLNAME))).append(histTableName);
        sql.append(sqlCreateString.substring(matcher.end(TBL_PATTERN_IDX_TBLNAME),
                matcher.start(TBL_PATTERN_IDX_TBL_DEF)));
        sql.append(formatColumn(dialect, HIST_TABLE_PK_COLUMN_NAME + " ${varcharType} not null",
                Constants.UUID_LEN, null, null)).append(", ");
        sql.append(
                formatColumn(dialect, HIST_OPERATION_COLUMN_NAME + " ${varcharType} not null", 1, null, null))
                .append(", ");

        sql.append(sqlCreateString.substring(matcher.start(TBL_PATTERN_IDX_TBL_DEF),
                matcher.start(TBL_PATTERN_IDX_PK_CLAUSE)));

        if (!columns.contains(histColName)) {
            sql.append(formatColumn(dialect, histColName + " ${timestampType} not null", null, null, null))
                    .append(", ");
        }

        sql.append(sqlCreateString.substring(matcher.start(TBL_PATTERN_IDX_PK_CLAUSE),
                matcher.start(TBL_PATTERN_IDX_PK_COLLIST)));
        sql.append(HIST_TABLE_PK_COLUMN_NAME).append("), ");
        sql.append("unique (");
        sql.append(matcher.group(TBL_PATTERN_IDX_PK_COLLIST));
        sql.append(", ");
        sql.append(histColName);
        sql.append(")");

        int restIdx = matcher.end(TBL_PATTERN_IDX_PK_CLAUSE);
        while (matchUnique.find(restIdx)) {
            restIdx = matchUnique.end(1);
        }

        sql.append(sqlCreateString.substring(restIdx));
    }

    Matcher uniqueColMatcher = COL_PATTERN.matcher(sql.toString());
    int colIdx = 0;
    while (uniqueColMatcher.find(colIdx)) {
        String colName = TableConfig.getIdentifierForReference(uniqueColMatcher.group(COL_PATTERN_IDX_COLNAME));
        //                remove unique constraint from single column
        if (uniqueColMatcher.group(COL_PATTERN_IDX_UNIQUE) != null) {
            sql.delete(uniqueColMatcher.start(COL_PATTERN_IDX_UNIQUE),
                    uniqueColMatcher.end(COL_PATTERN_IDX_UNIQUE));
            colIdx = uniqueColMatcher.start();
            uniqueColMatcher = COL_PATTERN.matcher(sql.toString());
        }
        //                remove not null constraints
        else if (!colName.equals(HIST_OPERATION_COLUMN_NAME) && !colName.equals(histColName)
                && uniqueColMatcher.group(COL_PATTERN_IDX_NOT) != null) {
            sql.delete(uniqueColMatcher.start(COL_PATTERN_IDX_NOTNULL),
                    uniqueColMatcher.end(COL_PATTERN_IDX_NOTNULL));
            colIdx = uniqueColMatcher.start();
            uniqueColMatcher = COL_PATTERN.matcher(sql.toString());
        } else if (colName.equals(histColName)) {
            String addCol = ", " + HIST_INVALID_TIMESTAMP_COLUMN_NAME + " "
                    + uniqueColMatcher.group(COL_PATTERN_IDX_TYPE);
            sql.insert(uniqueColMatcher.end() - 1, addCol);
            colIdx = uniqueColMatcher.end() + addCol.length();
            uniqueColMatcher = COL_PATTERN.matcher(sql.toString());
        } else {
            colIdx = uniqueColMatcher.end();
        }
    }

    StringBuffer additionalObjects = new StringBuffer();

    if (supportsPartitioning(dialect) && livePartitioning != null) {
        sqlCreateString = addPartitioning(additionalObjects, livePartitioning, histTableName, sql.toString(),
                columns, pkCols);
    } else {
        sqlCreateString = sql.toString();
    }

    sqlCreateString = addConstraintsAndNames(dialect, additionalObjects, sqlCreateString,
            histTableName.toLowerCase(), null);
    //        not adding default values to history tables, this will make investigations very hard
    //        sqlCreateString = addDefaultValues(sqlCreateString, histTableName.toLowerCase());

    getProfile().duplex(ObjectType.TABLE, histTableName, sqlCreateString);

    return sqlCreateString + additionalObjects.toString();
}