All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jaxio.celerio.configuration.database.h2.MetadataToH2 Maven / Gradle / Ivy

/*
 * Copyright 2015 JAXIO http://www.jaxio.com
 *
 * 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.jaxio.celerio.configuration.database.h2;

import com.jaxio.celerio.configuration.database.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Creates a H2 script from Metadata. Bypasses Celerio to ease its usage.
 */
public class MetadataToH2 {

    Metadata metadata;
    StringBuilder sb = new StringBuilder();

    public MetadataToH2(Metadata metadata) {
        this.metadata = metadata;
    }

    public String getCreateScript() {
        comment("H2 Script generated by Celerio Configuration Module");
        line("DROP ALL objects;");
        createTablesAndPkAndIndexes();
        createConstraints();
        return sb.toString();
    }

    // -- TABLES ---------------------------

    private void createTablesAndPkAndIndexes() {

        for (Table t : metadata.getTables()) {
            comment(" == TABLES [ " + t.getName() + " ] =======================");

            createTable(t);
            createIndexes(t);
            if (t.hasH2IdentityPk()) {
                line("ALTER TABLE ", t.getName(), " ALTER COLUMN ", t.getPrimaryKey(), " IDENTITY;");
            } else if (t.hasPk()) {
                line("CREATE PRIMARY KEY ON ", t.getName(), " (", toCsvString(t.getPrimaryKeys()), ");");
            }
            line("");
        }
    }

    private void createTable(Table table) {
        line("CREATE TABLE ", table.getName(), " (");
        for (Column c : table.getColumns()) {
            line("  ", c.getH2(), ",");
        }
        removeLastChar(); // line feed
        removeLastChar(); // comma

        line("");
        line(");");
        line("");
    }

    // -- INDEXES ---------------------------

    private void createIndexes(Table t) {
        for (String indexName : t.getIndexHoldersByName().keySet()) {
            if (!indexName.startsWith("PRIMARY")) {
                createIndex(t, t.getIndexHolderByName(indexName));
            }
        }
    }

    private void createIndex(Table table, IndexHolder indexHolder) {
        if (table.hasSimplePrimaryKey() && indexHolder.isSimple()) {
            if (indexHolder.getIndex().getColumnName().equalsIgnoreCase(table.getPrimaryKey())) {
                // skip simple pk (ie mysql)
                return;
            }
        }

        line("CREATE ", indexHolder.isUnique() ? "UNIQUE " : "", "INDEX IF NOT EXISTS ", indexHolder.getName(), " ON ", table.getName(), " (",
                toCsvColumnNameString(indexHolder.getIndexes()), ");");
    }

    private String toCsvColumnNameString(List indexes) {
        List asString = new ArrayList();
        for (Index i : indexes) {
            asString.add(i.getColumnName());
        }
        return toCsvString(asString);
    }

    // -- CONSTRAINTS -----------------------------------------

    private void createConstraints() {
        comment(" == CONSTRAINTS =======================");
        comment("");

        for (Table t : metadata.getTables()) {
            createConstraint(t);
        }
    }

    private void createConstraint(Table t) {
        for (String fkName : t.getForeignKeysByName().keySet()) {
            createForeignKey(t, fkName, t.getForeignKeyByName(fkName));
        }
    }

    private void createForeignKey(Table t, String fkName, ForeignKey fk) {
        line("ALTER TABLE ", t.getName());
        line("  ADD CONSTRAINT ", fkName);
        line("  FOREIGN KEY (", toCsvFkColumnNameString(fk.getImportedKeys()), ")");
        line("  REFERENCES ", fk.getPkTableName(), " (", toCsvPkColumnNameString(fk.getImportedKeys()), ");");
        line("");
    }

    private String toCsvFkColumnNameString(List importedKeys) {
        List asString = new ArrayList();
        for (ImportedKey ik : importedKeys) {
            asString.add(ik.getFkColumnName());
        }
        return toCsvString(asString);
    }

    private String toCsvPkColumnNameString(List importedKeys) {
        List asString = new ArrayList();
        for (ImportedKey ik : importedKeys) {
            asString.add(ik.getPkColumnName());
        }
        return toCsvString(asString);
    }

    // -- UTILS -----------------------------------------

    private void comment(String comment) {
        sb.append("-- ").append(comment).append("\n");
    }

    private void removeLastChar(StringBuilder sb) {
        if (sb.length() == 0) {
            return;
        }

        sb.deleteCharAt(sb.length() - 1);
    }

    private void removeLastChar() {
        removeLastChar(sb);
    }

    private void line(CharSequence... str) {
        for (CharSequence s : str) {
            sb.append(s);
        }
        sb.append("\n");
    }

    private String toCsvString(List str) {
        StringBuilder builder = new StringBuilder();
        for (String s : str) {
            builder.append(s).append(",");
        }
        removeLastChar(builder);
        return builder.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy