com.gs.obevo.db.impl.platforms.mssql.MsSqlToH2SqlTranslator.java Source code

Java tutorial

Introduction

Here is the source code for com.gs.obevo.db.impl.platforms.mssql.MsSqlToH2SqlTranslator.java

Source

/**
 * Copyright 2017 Goldman Sachs.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.gs.obevo.db.impl.platforms.mssql;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gs.obevo.api.appdata.Change;
import com.gs.obevo.db.impl.platforms.sqltranslator.PostColumnSqlTranslator;
import com.gs.obevo.db.impl.platforms.sqltranslator.PostParsedSqlTranslator;
import com.gs.obevo.db.sqlparser.syntaxparser.CreateTable;
import com.gs.obevo.db.sqlparser.syntaxparser.CreateTableColumn;
import org.apache.commons.lang3.StringUtils;

public class MsSqlToH2SqlTranslator implements PostColumnSqlTranslator, PostParsedSqlTranslator {
    @Override
    public String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table) {
        // only for ASE - need "GENERATED BY DEFAULT AS IDENTITY" as the regular IDENTITY is stored as PK
        sql = sql.replaceAll("(?i)\\bidentity\\s*(\\(.*\\))?", "AUTO_INCREMENT ");

        return sql;
    }

    @Override
    public String handleAnySqlPostTranslation(String string, Change change) {
        /*
         To make "ALTER TABLE some_Table ALTER COLUMN abcCol NOT NULL"  into
             "ALTER TABLE some_Table ALTER COLUMN abcCol SET NOT NULL"
         */
        //if this is "ALTER TABLE XYZ ALTER COLUMN ABC" statement
        Matcher alterTableAlterColumnMatcher = Pattern
                .compile("(?i)(alter\\s+table\\s+\\w+\\s+alter\\s+column\\s+\\w+\\s+)(.+)").matcher(string);
        if (alterTableAlterColumnMatcher.find()) {

            //if this is ALTER TABLE ALTER COLUMN NULL/NOT NULL in Sybase dialect (without "SET" keyword)
            if (!StringUtils.containsIgnoreCase(alterTableAlterColumnMatcher.group(2), "set")
                    && StringUtils.containsIgnoreCase(alterTableAlterColumnMatcher.group(2), "null")) {

                Matcher nullOrNotNull = Pattern.compile("(?i)(NOT\\s+NULL|NULL)(.*)")
                        .matcher(alterTableAlterColumnMatcher.group(2));
                if (nullOrNotNull.matches()) {
                    string = alterTableAlterColumnMatcher.group(1) + "SET " + nullOrNotNull.group(1)
                            + nullOrNotNull.group(2);
                }
            }
        }
        return string;
    }
}