Search in sources :

Example 21 with Column

use of org.jumpmind.db.model.Column in project symmetric-ds by JumpMind.

the class JdbcPersistenceManager method find.

@Override
public <T> List<T> find(Class<T> clazz, Map<String, Object> conditions, String catalogName, String schemaName, String tableName) {
    if (conditions == null || conditions.size() == 0) {
        return find(clazz, catalogName, schemaName, tableName);
    } else {
        try {
            Table table = findTable(catalogName, schemaName, tableName);
            T object = clazz.newInstance();
            LinkedHashMap<String, Column> objectToTableMapping = mapObjectToTable(object, table);
            LinkedHashMap<String, Object> objectValuesByColumnName = new LinkedHashMap<String, Object>();
            Column[] keys = new Column[conditions.size()];
            Set<String> keyPropertyNames = conditions.keySet();
            boolean[] nullKeyValues = new boolean[conditions.size()];
            int index = 0;
            for (String propertyName : keyPropertyNames) {
                Column column = objectToTableMapping.get(propertyName);
                if (column != null) {
                    keys[index] = column;
                    nullKeyValues[index] = conditions.get(propertyName) == null;
                    objectValuesByColumnName.put(column.getName(), conditions.get(propertyName));
                    index++;
                } else {
                    throw new IllegalStateException("Could not find a database column that maps to the " + propertyName + " property on " + clazz.getName() + ".  Make sure the property is defined on the class and " + "the matching column is defined in the database table");
                }
            }
            Column[] columns = objectToTableMapping.values().toArray(new Column[objectToTableMapping.size()]);
            DmlStatement statement = databasePlatform.createDmlStatement(DmlType.SELECT, table.getCatalog(), table.getSchema(), table.getName(), keys, columns, nullKeyValues, null);
            String sql = statement.getSql();
            Object[] values = statement.getValueArray(objectValuesByColumnName);
            int[] types = statement.getTypes();
            List<Row> rows = databasePlatform.getSqlTemplate().query(sql, values, types);
            List<T> objects = new ArrayList<T>();
            for (Row row : rows) {
                object = clazz.newInstance();
                Set<String> propertyNames = objectToTableMapping.keySet();
                for (String propertyName : propertyNames) {
                    Object value = row.get(objectToTableMapping.get(propertyName).getName());
                    BeanUtils.copyProperty(object, propertyName, value);
                }
                objects.add(object);
            }
            return objects;
        } catch (Exception e) {
            throw toRuntimeException(e);
        }
    }
}
Also used : Table(org.jumpmind.db.model.Table) ArrayList(java.util.ArrayList) SqlException(org.jumpmind.db.sql.SqlException) InvocationTargetException(java.lang.reflect.InvocationTargetException) LinkedHashMap(java.util.LinkedHashMap) Column(org.jumpmind.db.model.Column) DmlStatement(org.jumpmind.db.sql.DmlStatement) Row(org.jumpmind.db.sql.Row)

Example 22 with Column

use of org.jumpmind.db.model.Column in project symmetric-ds by JumpMind.

the class AbstractJdbcDdlReader method readColumns.

/*
     * Reads the column definitions for the indicated table.
     * 
     * @param metaData The database meta data
     * 
     * @param tableName The name of the table
     * 
     * @return The columns
     */
protected Collection<Column> readColumns(DatabaseMetaDataWrapper metaData, String tableName) throws SQLException {
    ResultSet columnData = null;
    try {
        Set<String> columnNames = new HashSet<String>();
        columnData = metaData.getColumns(getTableNamePattern(tableName), getDefaultColumnPattern());
        List<Column> columns = new ArrayList<Column>();
        while (columnData.next()) {
            Map<String, Object> values = readMetaData(columnData, getColumnsForColumn());
            Column column = readColumn(metaData, values);
            if (!columnNames.contains(column.getName())) {
                columnNames.add(column.getName());
                columns.add(column);
            }
            genericizeDefaultValuesAndUpdatePlatformColumn(column);
        }
        return columns;
    } finally {
        close(columnData);
    }
}
Also used : Column(org.jumpmind.db.model.Column) IndexColumn(org.jumpmind.db.model.IndexColumn) PlatformColumn(org.jumpmind.db.model.PlatformColumn) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 23 with Column

use of org.jumpmind.db.model.Column in project symmetric-ds by JumpMind.

the class AbstractJdbcDdlReader method readColumn.

/*
     * Extracts a column definition from the result set.
     * 
     * @param metaData The database meta data
     * 
     * @param values The column meta data values as defined by {@link
     * #getColumnsForColumn()}
     * 
     * @return The column
     */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = new Column();
    PlatformColumn platformColumn = new PlatformColumn();
    platformColumn.setName(platform.getName());
    column.setName((String) values.get("COLUMN_NAME"));
    String defaultValue = (String) values.get("COLUMN_DEF");
    if (defaultValue == null) {
        defaultValue = (String) values.get("COLUMN_DEFAULT");
    }
    if (defaultValue != null) {
        defaultValue = defaultValue.trim();
        column.setDefaultValue(defaultValue);
    }
    String typeName = (String) values.get("TYPE_NAME");
    column.setJdbcTypeName(typeName);
    Integer mappedType = mapUnknownJdbcTypeForColumn(values);
    if (mappedType != null) {
        column.setMappedTypeCode(mappedType);
    } else {
        column.setMappedTypeCode((Integer) values.get("DATA_TYPE"));
    }
    column.setJdbcTypeCode((Integer) values.get("DATA_TYPE"));
    column.setPrecisionRadix(((Integer) values.get("NUM_PREC_RADIX")).intValue());
    String columnSize = (String) values.get("COLUMN_SIZE");
    int decimalDigits = ((Integer) values.get("DECIMAL_DIGITS")).intValue();
    try {
        platformColumn.setType(typeName);
        if (isNotBlank(columnSize)) {
            platformColumn.setSize(Integer.parseInt(columnSize));
        }
        platformColumn.setDecimalDigits(decimalDigits);
        column.addPlatformColumn(platformColumn);
    } catch (Exception ex) {
        log.warn("", ex);
    }
    if (columnSize == null) {
        columnSize = (String) _defaultSizes.get(new Integer(column.getMappedTypeCode()));
    }
    // we're setting the size after the precision and radix in case
    // the database prefers to return them in the size value
    column.setSize(columnSize);
    if (decimalDigits != 0) {
        // if there is a scale value, set it after the size (which probably
        // did not contain
        // a scale specification)
        column.setScale(decimalDigits);
    }
    column.setRequired("NO".equalsIgnoreCase(((String) values.get("IS_NULLABLE")).trim()));
    column.setDescription((String) values.get("REMARKS"));
    return column;
}
Also used : Column(org.jumpmind.db.model.Column) IndexColumn(org.jumpmind.db.model.IndexColumn) PlatformColumn(org.jumpmind.db.model.PlatformColumn) SqlException(org.jumpmind.db.sql.SqlException) SQLException(java.sql.SQLException) PlatformColumn(org.jumpmind.db.model.PlatformColumn)

Example 24 with Column

use of org.jumpmind.db.model.Column in project symmetric-ds by JumpMind.

the class RedshiftDdlReader method readColumn.

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    if (column.getJdbcTypeCode() == Types.VARCHAR && column.getSizeAsInt() == 65535) {
        column.setJdbcTypeCode(Types.LONGVARCHAR);
        column.setMappedTypeCode(Types.LONGVARCHAR);
        column.setSize(null);
    }
    String defaultValue = column.getDefaultValue();
    if ((defaultValue != null) && (defaultValue.length() > 0)) {
        // then it is an auto-increment column
        if (defaultValue.startsWith("\"identity\"")) {
            column.setAutoIncrement(true);
            defaultValue = null;
        } else {
            // "'some value'::character varying" or "'2000-01-01'::date"
            switch(column.getMappedTypeCode()) {
                case Types.INTEGER:
                case Types.BIGINT:
                case Types.DECIMAL:
                case Types.NUMERIC:
                    defaultValue = extractUndelimitedDefaultValue(defaultValue);
                    break;
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR:
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                    defaultValue = extractDelimitedDefaultValue(defaultValue);
                    break;
            }
            if (TypeMap.isTextType(column.getMappedTypeCode())) {
                // We assume escaping via double quote (see also the
                // backslash_quote setting:
                // http://www.postgresql.org/docs/7.4/interactive/runtime-config.html#RUNTIME-CONFIG-COMPATIBLE)
                defaultValue = unescape(defaultValue, "'", "''");
            }
        }
        column.setDefaultValue(defaultValue);
    }
    return column;
}
Also used : Column(org.jumpmind.db.model.Column)

Example 25 with Column

use of org.jumpmind.db.model.Column in project symmetric-ds by JumpMind.

the class GreenplumDdlReader method setDistributionKeys.

protected void setDistributionKeys(Connection connection, Table table, String schema) throws SQLException {
    // get the distribution keys for segments
    StringBuilder query = new StringBuilder();
    query.append("select                                        ");
    query.append("   t.relname,                                 ");
    query.append("   a.attname                                  ");
    query.append("from                                          ");
    query.append("   pg_class t,                                ");
    query.append("   pg_namespace n,                            ");
    query.append("   pg_attribute a,                            ");
    query.append("   gp_distribution_policy p                   ");
    query.append("where                                         ");
    query.append("   n.oid = t.relnamespace and                 ");
    query.append("   p.localoid = t.oid and                     ");
    query.append("   a.attrelid = t.oid and                     ");
    query.append("   a.attnum = any(p.attrnums) and             ");
    query.append("   n.nspname = ? and                          ");
    query.append("   t.relname = ?                              ");
    PreparedStatement prepStmt = connection.prepareStatement(query.toString());
    try {
        // set the schema parm in the query
        prepStmt.setString(1, schema);
        prepStmt.setString(2, table.getName());
        ResultSet rs = prepStmt.executeQuery();
        // columns
        while (rs.next()) {
            Column column = table.findColumn(rs.getString(2).trim(), getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn());
            if (column != null) {
                column.setDistributionKey(true);
            }
        }
        rs.close();
    } finally {
        if (prepStmt != null) {
            prepStmt.close();
        }
    }
}
Also used : Column(org.jumpmind.db.model.Column) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

Column (org.jumpmind.db.model.Column)179 Table (org.jumpmind.db.model.Table)78 ArrayList (java.util.ArrayList)34 IndexColumn (org.jumpmind.db.model.IndexColumn)23 PlatformColumn (org.jumpmind.db.model.PlatformColumn)21 Test (org.junit.Test)16 Row (org.jumpmind.db.sql.Row)15 LinkedHashMap (java.util.LinkedHashMap)12 ResultSet (java.sql.ResultSet)11 DmlStatement (org.jumpmind.db.sql.DmlStatement)10 SqlException (org.jumpmind.db.sql.SqlException)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 IIndex (org.jumpmind.db.model.IIndex)9 HashMap (java.util.HashMap)8 ForeignKey (org.jumpmind.db.model.ForeignKey)8 CsvData (org.jumpmind.symmetric.io.data.CsvData)8 PreparedStatement (java.sql.PreparedStatement)7 IOException (java.io.IOException)6 SQLException (java.sql.SQLException)6 Reference (org.jumpmind.db.model.Reference)6