Java Code Examples for org.apache.ddlutils.model.Column#setTypeCode()

The following examples show how to use org.apache.ddlutils.model.Column#setTypeCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SapDbModelReader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
   {
	Column column = super.readColumn(metaData, values);

	if (column.getDefaultValue() != null)
	{
		// SapDb pads the default value with spaces
		column.setDefaultValue(column.getDefaultValue().trim());
		// SapDb uses the default value for the auto-increment specification
		if (column.getDefaultValue().startsWith("DEFAULT SERIAL"))
		{
			column.setAutoIncrement(true);
			column.setDefaultValue(null);
		}
	}
	if (column.getTypeCode() == Types.DECIMAL)
	{
		// We also perform back-mapping to BIGINT
		if ((column.getSizeAsInt() == 38) && (column.getScale() == 0))
		{
			column.setTypeCode(Types.BIGINT);
		}
	}
	return column;
}
 
Example 2
Source File: ModelComparator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Compares the two columns and returns the change necessary to create the second
 * column from the first one if they differe.
 *  
 * @param sourceTable  The source table which contains the source column
 * @param sourceColumn The source column
 * @param targetTable  The target table which contains the target column
 * @param targetColumn The target column
 * @return The change or <code>null</code> if the columns are the same
 */
protected ColumnDefinitionChange compareColumns(Table  sourceTable,
                                                Column sourceColumn,
                                                Table  targetTable,
                                                Column targetColumn)
{
    if (ColumnDefinitionChange.isChanged(getPlatformInfo(), sourceColumn, targetColumn))
    {
        Column  newColumnDef   = _cloneHelper.clone(sourceColumn, true);
        int     targetTypeCode = _platformInfo.getTargetJdbcType(targetColumn.getTypeCode());
        boolean sizeMatters    = _platformInfo.hasSize(targetTypeCode);
        boolean scaleMatters   = _platformInfo.hasPrecisionAndScale(targetTypeCode);

        newColumnDef.setTypeCode(targetColumn.getTypeCode());
        newColumnDef.setSize(sizeMatters || scaleMatters ? targetColumn.getSize() : null);
        newColumnDef.setAutoIncrement(targetColumn.isAutoIncrement());
        newColumnDef.setRequired(targetColumn.isRequired());
        newColumnDef.setDescription(targetColumn.getDescription());
        newColumnDef.setDefaultValue(targetColumn.getDefaultValue());
        return new ColumnDefinitionChange(sourceTable.getQualifiedName(), sourceColumn.getName(), newColumnDef);
    }
    else
    {
        return null;
    }
}
 
Example 3
Source File: SapDbModelReader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
   {
	Column column = super.readColumn(metaData, values);

	if (column.getDefaultValue() != null)
	{
		// SapDb pads the default value with spaces
		column.setDefaultValue(column.getDefaultValue().trim());
		// SapDb uses the default value for the auto-increment specification
		if (column.getDefaultValue().startsWith("DEFAULT SERIAL"))
		{
			column.setAutoIncrement(true);
			column.setDefaultValue(null);
		}
	}
	if (column.getTypeCode() == Types.DECIMAL)
	{
		// We also perform back-mapping to BIGINT
		if ((column.getSizeAsInt() == 38) && (column.getScale() == 0))
		{
			column.setTypeCode(Types.BIGINT);
		}
	}
	return column;
}
 
Example 4
Source File: ModelComparator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Compares the two columns and returns the change necessary to create the second
 * column from the first one if they differe.
 *  
 * @param sourceTable  The source table which contains the source column
 * @param sourceColumn The source column
 * @param targetTable  The target table which contains the target column
 * @param targetColumn The target column
 * @return The change or <code>null</code> if the columns are the same
 */
protected ColumnDefinitionChange compareColumns(Table  sourceTable,
                                                Column sourceColumn,
                                                Table  targetTable,
                                                Column targetColumn)
{
    if (ColumnDefinitionChange.isChanged(getPlatformInfo(), sourceColumn, targetColumn))
    {
        Column  newColumnDef   = _cloneHelper.clone(sourceColumn, true);
        int     targetTypeCode = _platformInfo.getTargetJdbcType(targetColumn.getTypeCode());
        boolean sizeMatters    = _platformInfo.hasSize(targetTypeCode);
        boolean scaleMatters   = _platformInfo.hasPrecisionAndScale(targetTypeCode);

        newColumnDef.setTypeCode(targetColumn.getTypeCode());
        newColumnDef.setSize(sizeMatters || scaleMatters ? targetColumn.getSize() : null);
        newColumnDef.setAutoIncrement(targetColumn.isAutoIncrement());
        newColumnDef.setRequired(targetColumn.isRequired());
        newColumnDef.setDescription(targetColumn.getDescription());
        newColumnDef.setDefaultValue(targetColumn.getDefaultValue());
        return new ColumnDefinitionChange(sourceTable.getQualifiedName(), sourceColumn.getName(), newColumnDef);
    }
    else
    {
        return null;
    }
}
 
Example 5
Source File: JdbcSchemaManager.java    From eagle with Apache License 2.0 5 votes vote down vote up
private void buildTable(Table table) {
    Column id = new Column();
    id.setName("id");
    id.setPrimaryKey(true);
    id.setRequired(true);
    id.setTypeCode(Types.VARCHAR);
    id.setSize("50");
    table.addColumn(id);

    Column value = new Column();
    value.setName("value");
    value.setTypeCode(Types.CLOB);
    table.addColumn(value);
}
 
Example 6
Source File: ColumnDefinitionChange.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void apply(Database model, boolean caseSensitive)
{
    Column column = findChangedColumn(model, caseSensitive);

    column.setTypeCode(_newColumnDef.getTypeCode());
    column.setSize(_newColumnDef.getSize());
    column.setAutoIncrement(_newColumnDef.isAutoIncrement());
    column.setRequired(_newColumnDef.isRequired());
    column.setDescription(_newColumnDef.getDescription());
    column.setDefaultValue(_newColumnDef.getDefaultValue());
}
 
Example 7
Source File: FirebirdModelReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
	Column column = super.readColumn(metaData, values);

	if (column.getTypeCode() == Types.FLOAT)
	{
		column.setTypeCode(Types.REAL);
	}
       else if (TypeMap.isTextType(column.getTypeCode()))
       {
           column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
       }
	return column;
}
 
Example 8
Source File: MaxDbModelReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
    Column column = super.readColumn(metaData, values);

    if (column.getDefaultValue() != null)
    {
        // SapDb pads the default value with spaces
        column.setDefaultValue(column.getDefaultValue().trim());
        // SapDb uses the default value for the auto-increment specification
        if (column.getDefaultValue().startsWith("DEFAULT SERIAL"))
        {
            column.setAutoIncrement(true);
            column.setDefaultValue(null);
        }
    }
    if (column.getTypeCode() == Types.DECIMAL)
    {
        // need to use COLUMN_SIZE for precision instead of NUM_PREC_RADIX
        column.setPrecisionRadix(column.getSizeAsInt());

        // We also perform back-mapping to BIGINT
        if ((column.getSizeAsInt() == 38) && (column.getScale() == 0))
        {
            column.setTypeCode(Types.BIGINT);
        }
    }
    return column;
}
 
Example 9
Source File: ColumnDefinitionChange.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void apply(Database model, boolean caseSensitive)
{
    Column column = findChangedColumn(model, caseSensitive);

    column.setTypeCode(_newColumnDef.getTypeCode());
    column.setSize(_newColumnDef.getSize());
    column.setAutoIncrement(_newColumnDef.isAutoIncrement());
    column.setRequired(_newColumnDef.isRequired());
    column.setDescription(_newColumnDef.getDescription());
    column.setDefaultValue(_newColumnDef.getDefaultValue());
}
 
Example 10
Source File: FirebirdModelReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
	Column column = super.readColumn(metaData, values);

	if (column.getTypeCode() == Types.FLOAT)
	{
		column.setTypeCode(Types.REAL);
	}
       else if (TypeMap.isTextType(column.getTypeCode()))
       {
           column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
       }
	return column;
}
 
Example 11
Source File: MaxDbModelReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
    Column column = super.readColumn(metaData, values);

    if (column.getDefaultValue() != null)
    {
        // SapDb pads the default value with spaces
        column.setDefaultValue(column.getDefaultValue().trim());
        // SapDb uses the default value for the auto-increment specification
        if (column.getDefaultValue().startsWith("DEFAULT SERIAL"))
        {
            column.setAutoIncrement(true);
            column.setDefaultValue(null);
        }
    }
    if (column.getTypeCode() == Types.DECIMAL)
    {
        // need to use COLUMN_SIZE for precision instead of NUM_PREC_RADIX
        column.setPrecisionRadix(column.getSizeAsInt());

        // We also perform back-mapping to BIGINT
        if ((column.getSizeAsInt() == 38) && (column.getScale() == 0))
        {
            column.setTypeCode(Types.BIGINT);
        }
    }
    return column;
}
 
Example 12
Source File: TestAgainstLiveDatabaseBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a copy of the given model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * 
 * @param sourceModel The source model
 * @return The adjusted model
 */
protected Database adjustModel(Database sourceModel)
{
    Database model = new CloneHelper().clone(sourceModel);

    for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++)
    {
        Table table = model.getTable(tableIdx);

        for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++)
        {
            Column column     = table.getColumn(columnIdx);
            int    origType   = column.getTypeCode();
            int    targetType = getPlatformInfo().getTargetJdbcType(origType);

            // we adjust the column types if the native type would back-map to a
            // different jdbc type
            if (targetType != origType)
            {
                column.setTypeCode(targetType);
                // we should also adapt the default value
                if (column.getDefaultValue() != null)
                {
                    DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                    column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                }
            }
            // we also promote the default size if the column has no size
            // spec of its own
            if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType))
            {
                Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                if (defaultSize != null)
                {
                    column.setSize(defaultSize.toString());
                }
            }
            // finally the platform might return a synthetic default value if the column
            // is a primary key column
            if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned() &&
                (column.getDefaultValue() == null) && column.isRequired() && !column.isAutoIncrement())
            {
                switch (column.getTypeCode())
                {
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                        column.setDefaultValue("0");
                        break;
                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        column.setDefaultValue("0.0");
                        break;
                    case Types.BIT:
                        column.setDefaultValue("false");
                        break;
                    default:
                        column.setDefaultValue("");
                        break;
                }
            }
            if (column.isPrimaryKey() && getPlatformInfo().isPrimaryKeyColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
            if (column.isAutoIncrement() && getPlatformInfo().isIdentityColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
        }
        // we also add the default names to foreign keys that are initially unnamed
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey fk = table.getForeignKey(fkIdx);

            if (fk.getName() == null)
            {
                fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
            }
        }
    }
    return model;
}
 
Example 13
Source File: InterbaseModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method that determines extra column info from the system tables: default value, precision, scale.
 *
 * @param table The table
 */
protected void determineExtraColumnInfo(Table table) throws SQLException
{
    final String query =
        "SELECT a.RDB$FIELD_NAME, a.RDB$DEFAULT_SOURCE, b.RDB$FIELD_PRECISION, b.RDB$FIELD_SCALE," +
        " b.RDB$FIELD_TYPE, b.RDB$FIELD_SUB_TYPE FROM RDB$RELATION_FIELDS a, RDB$FIELDS b" +
        " WHERE a.RDB$RELATION_NAME=? AND a.RDB$FIELD_SOURCE=b.RDB$FIELD_NAME";

    PreparedStatement prepStmt = null;

    try
    {
        prepStmt = getConnection().prepareStatement(query);
        prepStmt.setString(1, getPlatform().isDelimitedIdentifierModeOn() ? table.getName() : table.getName().toUpperCase());

        ResultSet rs = prepStmt.executeQuery();

        while (rs.next())
        {
            String columnName = rs.getString(1).trim();
            Column column     = table.findColumn(columnName, getPlatform().isDelimitedIdentifierModeOn());

            if (column != null)
            {
                String defaultValue = rs.getString(2);

                if (!rs.wasNull() && (defaultValue != null))
                {
                    defaultValue = defaultValue.trim();
                    if (defaultValue.startsWith("DEFAULT "))
                    {
                        defaultValue = defaultValue.substring("DEFAULT ".length());
                    }
                    column.setDefaultValue(defaultValue);
                }
                
                short   precision          = rs.getShort(3);
                boolean precisionSpecified = !rs.wasNull();
                short   scale              = rs.getShort(4);
                boolean scaleSpecified     = !rs.wasNull();

                if (precisionSpecified)
                {
                    // for some reason, Interbase stores the negative scale
                    column.setSizeAndScale(precision, scaleSpecified ? -scale : 0);
                }

                short dbType      = rs.getShort(5);
                short blobSubType = rs.getShort(6);

                // CLOBs are returned by the driver as VARCHAR
                if (!rs.wasNull() && (dbType == 261) && (blobSubType == 1))
                {
                    column.setTypeCode(Types.CLOB);
                }
            }
        }
    }
    finally
    {
        closeStatement(prepStmt);
    }
}
 
Example 14
Source File: JdbcModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * 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 values) throws SQLException
{
    Column column = new Column();

    column.setName((String)values.get("COLUMN_NAME"));
    column.setDefaultValue((String)values.get("COLUMN_DEF"));
    column.setTypeCode(((Integer)values.get("DATA_TYPE")).intValue());

    Integer precision = (Integer)values.get("NUM_PREC_RADIX");

    if (precision != null)
    {
        column.setPrecisionRadix(precision.intValue());
    }

    String size = (String)values.get("COLUMN_SIZE");

    if (size == null)
    {
        size = (String)_defaultSizes.get(Integer.valueOf(column.getTypeCode()));
    }
    // we're setting the size after the precision and radix in case
    // the database prefers to return them in the size value
    column.setSize(size);

    Integer scale = (Integer)values.get("DECIMAL_DIGITS");

    if (scale != null)
    {
        // if there is a scale value, set it after the size (which probably did not contain
        // a scale specification)
        column.setScale(scale.intValue());
    }
    column.setRequired("NO".equalsIgnoreCase(((String)values.get("IS_NULLABLE")).trim()));

    String description = (String)values.get("REMARKS");

    if (!org.apache.ddlutils.util.StringUtilsExt.isEmpty(description))
    {
        column.setDescription(description);
    }
    return column;
}
 
Example 15
Source File: PostgreSqlModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
    Column column = super.readColumn(metaData, values);

    if (column.getSize() != null)
    {
        if (column.getSizeAsInt() <= 0)
        {
            column.setSize(null);
            // PostgreSQL reports BYTEA and TEXT as BINARY(-1) and VARCHAR(-1) respectively
            // Since we cannot currently use the Blob/Clob interface with BYTEA, we instead
            // map them to LONGVARBINARY/LONGVARCHAR
            if (column.getTypeCode() == Types.BINARY)
            {
                column.setTypeCode(Types.LONGVARBINARY);
            }
            else if (column.getTypeCode() == Types.VARCHAR)
            {
                column.setTypeCode(Types.LONGVARCHAR);
            }
        }
        // fix issue DDLUTILS-165 as postgresql-8.2-504-jdbc3.jar seems to return Integer.MAX_VALUE
        // on columns defined as TEXT.
        else if (column.getSizeAsInt() == Integer.MAX_VALUE)
        {
            column.setSize(null);
            if (column.getTypeCode() == Types.VARCHAR)
            {
                column.setTypeCode(Types.LONGVARCHAR);
            }
            else if (column.getTypeCode() == Types.BINARY)
            {
                column.setTypeCode(Types.LONGVARBINARY);
            }
        }
    }

    String defaultValue = column.getDefaultValue();

    if ((defaultValue != null) && (defaultValue.length() > 0))
    {
        // If the default value looks like "nextval('ROUNDTRIP_VALUE_seq'::text)"
        // then it is an auto-increment column
        if (defaultValue.startsWith("nextval("))
        {
            column.setAutoIncrement(true);
            defaultValue = null;
        }
        else
        {
            // PostgreSQL returns default values in the forms "-9000000000000000000::bigint" or
            // "'some value'::character varying" or "'2000-01-01'::date"
            switch (column.getTypeCode())
            {
                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.getTypeCode()))
            {
                // 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;
}
 
Example 16
Source File: JdbcModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * 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 values) throws SQLException
{
    Column column = new Column();

    column.setName((String)values.get("COLUMN_NAME"));
    column.setDefaultValue((String)values.get("COLUMN_DEF"));
    column.setTypeCode(((Integer)values.get("DATA_TYPE")).intValue());

    Integer precision = (Integer)values.get("NUM_PREC_RADIX");

    if (precision != null)
    {
        column.setPrecisionRadix(precision.intValue());
    }

    String size = (String)values.get("COLUMN_SIZE");

    if (size == null)
    {
        size = (String)_defaultSizes.get(Integer.valueOf(column.getTypeCode()));
    }
    // we're setting the size after the precision and radix in case
    // the database prefers to return them in the size value
    column.setSize(size);

    Integer scale = (Integer)values.get("DECIMAL_DIGITS");

    if (scale != null)
    {
        // if there is a scale value, set it after the size (which probably did not contain
        // a scale specification)
        column.setScale(scale.intValue());
    }
    column.setRequired("NO".equalsIgnoreCase(((String)values.get("IS_NULLABLE")).trim()));

    String description = (String)values.get("REMARKS");

    if (!org.apache.ddlutils.util.StringUtilsExt.isEmpty(description))
    {
        column.setDescription(description);
    }
    return column;
}
 
Example 17
Source File: InterbaseModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method that determines extra column info from the system tables: default value, precision, scale.
 *
 * @param table The table
 */
protected void determineExtraColumnInfo(Table table) throws SQLException
{
    final String query =
        "SELECT a.RDB$FIELD_NAME, a.RDB$DEFAULT_SOURCE, b.RDB$FIELD_PRECISION, b.RDB$FIELD_SCALE," +
        " b.RDB$FIELD_TYPE, b.RDB$FIELD_SUB_TYPE FROM RDB$RELATION_FIELDS a, RDB$FIELDS b" +
        " WHERE a.RDB$RELATION_NAME=? AND a.RDB$FIELD_SOURCE=b.RDB$FIELD_NAME";

    PreparedStatement prepStmt = null;

    try
    {
        prepStmt = getConnection().prepareStatement(query);
        prepStmt.setString(1, getPlatform().isDelimitedIdentifierModeOn() ? table.getName() : table.getName().toUpperCase());

        ResultSet rs = prepStmt.executeQuery();

        while (rs.next())
        {
            String columnName = rs.getString(1).trim();
            Column column     = table.findColumn(columnName, getPlatform().isDelimitedIdentifierModeOn());

            if (column != null)
            {
                String defaultValue = rs.getString(2);

                if (!rs.wasNull() && (defaultValue != null))
                {
                    defaultValue = defaultValue.trim();
                    if (defaultValue.startsWith("DEFAULT "))
                    {
                        defaultValue = defaultValue.substring("DEFAULT ".length());
                    }
                    column.setDefaultValue(defaultValue);
                }
                
                short   precision          = rs.getShort(3);
                boolean precisionSpecified = !rs.wasNull();
                short   scale              = rs.getShort(4);
                boolean scaleSpecified     = !rs.wasNull();

                if (precisionSpecified)
                {
                    // for some reason, Interbase stores the negative scale
                    column.setSizeAndScale(precision, scaleSpecified ? -scale : 0);
                }

                short dbType      = rs.getShort(5);
                short blobSubType = rs.getShort(6);

                // CLOBs are returned by the driver as VARCHAR
                if (!rs.wasNull() && (dbType == 261) && (blobSubType == 1))
                {
                    column.setTypeCode(Types.CLOB);
                }
            }
        }
    }
    finally
    {
        closeStatement(prepStmt);
    }
}
 
Example 18
Source File: PostgreSqlModelReader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
{
    Column column = super.readColumn(metaData, values);

    if (column.getSize() != null)
    {
        if (column.getSizeAsInt() <= 0)
        {
            column.setSize(null);
            // PostgreSQL reports BYTEA and TEXT as BINARY(-1) and VARCHAR(-1) respectively
            // Since we cannot currently use the Blob/Clob interface with BYTEA, we instead
            // map them to LONGVARBINARY/LONGVARCHAR
            if (column.getTypeCode() == Types.BINARY)
            {
                column.setTypeCode(Types.LONGVARBINARY);
            }
            else if (column.getTypeCode() == Types.VARCHAR)
            {
                column.setTypeCode(Types.LONGVARCHAR);
            }
        }
        // fix issue DDLUTILS-165 as postgresql-8.2-504-jdbc3.jar seems to return Integer.MAX_VALUE
        // on columns defined as TEXT.
        else if (column.getSizeAsInt() == Integer.MAX_VALUE)
        {
            column.setSize(null);
            if (column.getTypeCode() == Types.VARCHAR)
            {
                column.setTypeCode(Types.LONGVARCHAR);
            }
            else if (column.getTypeCode() == Types.BINARY)
            {
                column.setTypeCode(Types.LONGVARBINARY);
            }
        }
    }

    String defaultValue = column.getDefaultValue();

    if ((defaultValue != null) && (defaultValue.length() > 0))
    {
        // If the default value looks like "nextval('ROUNDTRIP_VALUE_seq'::text)"
        // then it is an auto-increment column
        if (defaultValue.startsWith("nextval("))
        {
            column.setAutoIncrement(true);
            defaultValue = null;
        }
        else
        {
            // PostgreSQL returns default values in the forms "-9000000000000000000::bigint" or
            // "'some value'::character varying" or "'2000-01-01'::date"
            switch (column.getTypeCode())
            {
                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.getTypeCode()))
            {
                // 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;
}
 
Example 19
Source File: TestAgainstLiveDatabaseBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a copy of the given model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * 
 * @param sourceModel The source model
 * @return The adjusted model
 */
protected Database adjustModel(Database sourceModel)
{
    Database model = new CloneHelper().clone(sourceModel);

    for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++)
    {
        Table table = model.getTable(tableIdx);

        for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++)
        {
            Column column     = table.getColumn(columnIdx);
            int    origType   = column.getTypeCode();
            int    targetType = getPlatformInfo().getTargetJdbcType(origType);

            // we adjust the column types if the native type would back-map to a
            // different jdbc type
            if (targetType != origType)
            {
                column.setTypeCode(targetType);
                // we should also adapt the default value
                if (column.getDefaultValue() != null)
                {
                    DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                    column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                }
            }
            // we also promote the default size if the column has no size
            // spec of its own
            if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType))
            {
                Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                if (defaultSize != null)
                {
                    column.setSize(defaultSize.toString());
                }
            }
            // finally the platform might return a synthetic default value if the column
            // is a primary key column
            if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned() &&
                (column.getDefaultValue() == null) && column.isRequired() && !column.isAutoIncrement())
            {
                switch (column.getTypeCode())
                {
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                        column.setDefaultValue("0");
                        break;
                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        column.setDefaultValue("0.0");
                        break;
                    case Types.BIT:
                        column.setDefaultValue("false");
                        break;
                    default:
                        column.setDefaultValue("");
                        break;
                }
            }
            if (column.isPrimaryKey() && getPlatformInfo().isPrimaryKeyColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
            if (column.isAutoIncrement() && getPlatformInfo().isIdentityColumnAutomaticallyRequired())
            {
                column.setRequired(true);
            }
        }
        // we also add the default names to foreign keys that are initially unnamed
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
        {
            ForeignKey fk = table.getForeignKey(fkIdx);

            if (fk.getName() == null)
            {
                fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
            }
        }
    }
    return model;
}