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

org.jooq.util.derby.DerbyDatabase Maven / Gradle / Ivy

There is a newer version: 3.19.16
Show newest version
/**
 * Copyright (c) 2009-2013, Data Geekery GmbH (http://www.datageekery.com)
 * All rights reserved.
 *
 * This work is dual-licensed
 * - under the Apache Software License 2.0 (the "ASL")
 * - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
 * =============================================================================
 * You may choose which license applies to you:
 *
 * - If you're using this work with Open Source databases, you may choose
 *   either ASL or jOOQ License.
 * - If you're using this work with at least one commercial database, you must
 *   choose jOOQ License
 *
 * For more information, please visit http://www.jooq.org/licenses
 *
 * Apache Software License 2.0:
 * -----------------------------------------------------------------------------
 * 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.
 *
 * jOOQ License and Maintenance Agreement:
 * -----------------------------------------------------------------------------
 * Data Geekery grants the Customer the non-exclusive, timely limited and
 * non-transferable license to install and use the Software under the terms of
 * the jOOQ License and Maintenance Agreement.
 *
 * This library is distributed with a LIMITED WARRANTY. See the jOOQ License
 * and Maintenance Agreement for more details: http://www.jooq.org/licensing
 */

package org.jooq.util.derby;

import static org.jooq.impl.DSL.field;
import static org.jooq.util.derby.sys.tables.Sysconglomerates.SYSCONGLOMERATES;
import static org.jooq.util.derby.sys.tables.Sysconstraints.SYSCONSTRAINTS;
import static org.jooq.util.derby.sys.tables.Syskeys.SYSKEYS;
import static org.jooq.util.derby.sys.tables.Sysschemas.SYSSCHEMAS;
import static org.jooq.util.derby.sys.tables.Syssequences.SYSSEQUENCES;
import static org.jooq.util.derby.sys.tables.Systables.SYSTABLES;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record5;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.util.AbstractDatabase;
import org.jooq.util.ArrayDefinition;
import org.jooq.util.ColumnDefinition;
import org.jooq.util.DataTypeDefinition;
import org.jooq.util.DefaultDataTypeDefinition;
import org.jooq.util.DefaultRelations;
import org.jooq.util.DefaultSequenceDefinition;
import org.jooq.util.EnumDefinition;
import org.jooq.util.PackageDefinition;
import org.jooq.util.RoutineDefinition;
import org.jooq.util.SchemaDefinition;
import org.jooq.util.SequenceDefinition;
import org.jooq.util.TableDefinition;
import org.jooq.util.UDTDefinition;
import org.jooq.util.derby.sys.tables.Sysconglomerates;
import org.jooq.util.derby.sys.tables.Sysconstraints;
import org.jooq.util.derby.sys.tables.Syskeys;
import org.jooq.util.derby.sys.tables.Sysschemas;
import org.jooq.util.derby.sys.tables.Syssequences;
import org.jooq.util.derby.sys.tables.Systables;

/**
 * @author Lukas Eder
 */
public class DerbyDatabase extends AbstractDatabase {

	@Override
	protected void loadPrimaryKeys(DefaultRelations relations) throws SQLException {
	    for (Record record : fetchKeys("P")) {
	        SchemaDefinition schema = getSchema(record.getValue(Sysschemas.SCHEMANAME));
	        String key = record.getValue(Sysconstraints.CONSTRAINTNAME);
            String tableName = record.getValue(Systables.TABLENAME);
            String descriptor = record.getValue(Sysconglomerates.DESCRIPTOR, String.class);

            TableDefinition table = getTable(schema, tableName);
            if (table != null) {
                for (int index : decode(descriptor)) {
                    relations.addPrimaryKey(key, table.getColumn(index));
                }
            }
	    }
	}

    /**
     * {@inheritDoc}
     */
    @Override
    protected void loadUniqueKeys(DefaultRelations relations) throws SQLException {
        for (Record record : fetchKeys("U")) {
            SchemaDefinition schema = getSchema(record.getValue(Sysschemas.SCHEMANAME));
            String key = record.getValue(Sysconstraints.CONSTRAINTNAME);
            String tableName = record.getValue(Systables.TABLENAME);
            String descriptor = record.getValue(Sysconglomerates.DESCRIPTOR, String.class);

            TableDefinition table = getTable(schema, tableName);
            if (table != null) {
                for (int index : decode(descriptor)) {
                    relations.addUniqueKey(key, table.getColumn(index));
                }
            }
        }
    }

    private Result> fetchKeys(String constraintType) {
        return create().select(
                    Sysschemas.SCHEMANAME,
    	            Systables.TABLENAME,
    	            Systables.TABLEID,
    	            Sysconstraints.CONSTRAINTNAME,
    	            Sysconglomerates.DESCRIPTOR)
    	        .from(SYSCONGLOMERATES)
    	        .join(SYSKEYS)
    	        .on(Syskeys.CONGLOMERATEID.equal(Sysconglomerates.CONGLOMERATEID))
    	        .join(SYSCONSTRAINTS)
    	        .on(Sysconstraints.CONSTRAINTID.equal(Syskeys.CONSTRAINTID))
    	        .join(SYSTABLES)
    	        .on(Systables.TABLEID.equal(Sysconglomerates.TABLEID))
    	        .join(SYSSCHEMAS)
    	        .on(Sysschemas.SCHEMAID.equal(Systables.SCHEMAID))
    	        .and(Sysschemas.SCHEMANAME.in(getInputSchemata()))
    	        .where(Sysconstraints.TYPE.equal(constraintType))
    	        .orderBy(
    	            Sysschemas.SCHEMANAME,
    	            Systables.TABLENAME,
    	            Sysconstraints.CONSTRAINTNAME)
    	        .fetch();
    }

	@Override
	protected void loadForeignKeys(DefaultRelations relations) throws SQLException {
        Field fkName = field("fc.constraintname", String.class);
	    Field fkTable = field("ft.tablename", String.class);
	    Field fkSchema = field("fs.schemaname", String.class);
	    Field fkDescriptor = field("fg.descriptor");
	    Field ukName = field("pc.constraintname", String.class);
	    Field ukSchema = field("ps.schemaname", String.class);

	    for (Record record : create().select(
	            fkName,
	            fkTable,
	            fkSchema,
	            fkDescriptor,
	            ukName,
	            ukSchema)
	        .from("sys.sysconstraints   fc")
	        .join("sys.sysforeignkeys   f ").on("f.constraintid = fc.constraintid")
	        .join("sys.sysconglomerates fg").on("fg.conglomerateid = f.conglomerateid")
	        .join("sys.systables        ft").on("ft.tableid = fg.tableid")
	        .join("sys.sysschemas       fs").on("ft.schemaid = fs.schemaid")
	        .join("sys.sysconstraints   pc").on("pc.constraintid = f.keyconstraintid")
	        .join("sys.sysschemas       ps").on("pc.schemaid = ps.schemaid")
	        .where("fc.type = 'F'")
	        .fetch()) {

	        SchemaDefinition foreignKeySchema = getSchema(record.getValue(fkSchema));
	        SchemaDefinition uniqueKeySchema = getSchema(record.getValue(ukSchema));

	        String foreignKeyName = record.getValue(fkName);
            String foreignKeyTableName = record.getValue(fkTable);
            List foreignKeyIndexes = decode(record.getValue(fkDescriptor, String.class));
            String uniqueKeyName = record.getValue(ukName);

	        TableDefinition referencingTable = getTable(foreignKeySchema, foreignKeyTableName);
            if (referencingTable != null) {
                for (int i = 0; i < foreignKeyIndexes.size(); i++) {
                    ColumnDefinition column = referencingTable.getColumn(foreignKeyIndexes.get(i));

                    relations.addForeignKey(foreignKeyName, uniqueKeyName, column, uniqueKeySchema);
                }
            }
	    }
	}

    /*
     * Unfortunately the descriptor interface is not exposed publicly Hence, the
     * toString() method is used and its results are parsed The results are
     * something like UNIQUE BTREE (index1, index2, ... indexN)
     */
    private List decode(String descriptor) {
        List result = new ArrayList();

        Pattern p = Pattern.compile(".*?\\((.*?)\\)");
        Matcher m = p.matcher(descriptor);

        while (m.find()) {
            String[] split = m.group(1).split(",");

            if (split != null) {
                for (String index : split) {
                    result.add(Integer.valueOf(index.trim()) - 1);
                }
            }
        }

        return result;
    }

    @Override
    protected void loadCheckConstraints(DefaultRelations r) throws SQLException {
        // Currently not supported
    }

    @Override
    protected List getSchemata0() throws SQLException {
        List result = new ArrayList();

        for (String name : create()
                .select(Sysschemas.SCHEMANAME)
                .from(SYSSCHEMAS)
                .fetch(Sysschemas.SCHEMANAME)) {

            result.add(new SchemaDefinition(this, name, ""));
        }

        return result;
    }

    @Override
    protected List getSequences0() throws SQLException {
        List result = new ArrayList();

        for (Record record : create().select(
                    Sysschemas.SCHEMANAME,
                    Syssequences.SEQUENCENAME,
                    Syssequences.SEQUENCEDATATYPE)
                .from(SYSSEQUENCES)
                .join(SYSSCHEMAS)
                .on(Sysschemas.SCHEMAID.equal(Syssequences.SCHEMAID))
                .where(Sysschemas.SCHEMANAME.in(getInputSchemata()))
                .orderBy(
                    Sysschemas.SCHEMANAME,
                    Syssequences.SEQUENCENAME)
                .fetch()) {

            SchemaDefinition schema = getSchema(record.getValue(Sysschemas.SCHEMANAME));

            DataTypeDefinition type = new DefaultDataTypeDefinition(
                this,
                schema,
                record.getValue(Syssequences.SEQUENCEDATATYPE)
            );

            result.add(new DefaultSequenceDefinition(
                schema,
                record.getValue(Syssequences.SEQUENCENAME, String.class),
                type));
        }

        return result;
    }

	@Override
	protected List getTables0() throws SQLException {
		List result = new ArrayList();

		for (Record record : create().select(
		            Sysschemas.SCHEMANAME,
		            Systables.TABLENAME,
		            Systables.TABLEID)
                .from(SYSTABLES)
                .join(SYSSCHEMAS)
                .on(Systables.SCHEMAID.equal(Sysschemas.SCHEMAID))
                .where(Sysschemas.SCHEMANAME.in(getInputSchemata()))
                .orderBy(
                    Sysschemas.SCHEMANAME,
                    Systables.TABLENAME)
    	        .fetch()) {

		    SchemaDefinition schema = getSchema(record.getValue(Sysschemas.SCHEMANAME));
		    String name = record.getValue(Systables.TABLENAME);
		    String id = record.getValue(Systables.TABLEID);

		    DerbyTableDefinition table = new DerbyTableDefinition(schema, name, id);
            result.add(table);
		}

		return result;
	}

    @Override
    protected List getEnums0() throws SQLException {
        List result = new ArrayList();
        return result;
    }

    @Override
    protected List getUDTs0() throws SQLException {
        List result = new ArrayList();
        return result;
    }

    @Override
    protected List getArrays0() throws SQLException {
        List result = new ArrayList();
        return result;
    }

    @Override
    protected List getRoutines0() throws SQLException {
        List result = new ArrayList();
        return result;
    }

    @Override
    protected List getPackages0() throws SQLException {
        List result = new ArrayList();
        return result;
    }

    @Override
    protected DSLContext create0() {
        return DSL.using(getConnection(), SQLDialect.DERBY);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy