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

The following examples show how to use org.apache.ddlutils.model.Column#getSize() . 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: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the size specification for the given column. If the column is of a type that has size
 * or precision and scale, and no size is defined for the column itself, then the default size
 * or precision/scale for that type and platform is used instead.
 * 
 * @param column The column
 * @return The size spec
 */
protected String getSizeSpec(Column column)
{
    StringBuilder result   = new StringBuilder();
    Object       sizeSpec = column.getSize();
    
    if (sizeSpec == null)
    {
        sizeSpec = getPlatformInfo().getDefaultSize(column.getTypeCode());
    }
    if (sizeSpec != null)
    {
        if (getPlatformInfo().hasSize(column.getTypeCode()))
        {
            result.append(sizeSpec.toString());
        }
        else if (getPlatformInfo().hasPrecisionAndScale(column.getTypeCode()))
        {
            result.append(column.getSizeAsInt());
            result.append(",");
            result.append(column.getScale());
        }
    }
    return result.toString();
}
 
Example 2
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the size specification for the given column. If the column is of a type that has size
 * or precision and scale, and no size is defined for the column itself, then the default size
 * or precision/scale for that type and platform is used instead.
 * 
 * @param column The column
 * @return The size spec
 */
protected String getSizeSpec(Column column)
{
    StringBuilder result   = new StringBuilder();
    Object       sizeSpec = column.getSize();
    
    if (sizeSpec == null)
    {
        sizeSpec = getPlatformInfo().getDefaultSize(column.getTypeCode());
    }
    if (sizeSpec != null)
    {
        if (getPlatformInfo().hasSize(column.getTypeCode()))
        {
            result.append(sizeSpec.toString());
        }
        else if (getPlatformInfo().hasPrecisionAndScale(column.getTypeCode()))
        {
            result.append(column.getSizeAsInt());
            result.append(",");
            result.append(column.getScale());
        }
    }
    return result.toString();
}
 
Example 3
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Compares the current column in the database with the desired one.
 * Type, nullability, size, scale, default value, and precision radix are
 * the attributes checked.  Currently default values are compared, and
 * null and empty string are considered equal.
 *
 * @param currentColumn The current column as it is in the database
 * @param desiredColumn The desired column
 * @return <code>true</code> if the column specifications differ
 */
protected boolean columnsDiffer(Column currentColumn, Column desiredColumn)
{
    //The createColumn method leaves off the default clause if column.getDefaultValue()
    //is null.  mySQL interprets this as a default of "" or 0, and thus the columns
    //are always different according to this method.  alterDatabase will generate
    //an alter statement for the column, but it will be the exact same definition
    //as before.  In order to avoid this situation I am ignoring the comparison
    //if the desired default is null.  In order to "un-default" a column you'll
    //have to have a default="" or default="0" in the schema xml.
    //If this is bad for other databases, it is recommended that the createColumn
    //method use a "DEFAULT NULL" statement if that is what is needed.
    //A good way to get this would be to require a defaultValue="<NULL>" in the
    //schema xml if you really want null and not just unspecified.

    String  desiredDefault = desiredColumn.getDefaultValue();
    String  currentDefault = currentColumn.getDefaultValue();
    boolean defaultsEqual  = (desiredDefault == null) || desiredDefault.equals(currentDefault);
    boolean sizeMatters    = getPlatformInfo().hasSize(currentColumn.getTypeCode()) &&
                             (desiredColumn.getSize() != null);

    // We're comparing the jdbc type that corresponds to the native type for the
    // desired type, in order to avoid repeated altering of a perfectly valid column
    if ((getPlatformInfo().getTargetJdbcType(desiredColumn.getTypeCode()) != currentColumn.getTypeCode()) ||
        (desiredColumn.isRequired() != currentColumn.isRequired()) ||
        (sizeMatters && !StringUtils.equals(desiredColumn.getSize(), currentColumn.getSize())) ||
        !defaultsEqual)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
Example 4
Source File: DataDtdWriter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the DTD attribute entry for the given column.
 * 
 * @param column The column
 * @param writer The writer to write the attribute entry to
 */
private void writeColumnAttributeEntry(Column column, PrintWriter writer) throws IOException
{
    writer.print("    <!--");
    if (column.isPrimaryKey())
    {
        writer.print(" primary key,");
    }
    if (column.isAutoIncrement())
    {
        writer.print(" auto increment,");
    }
    writer.print(" JDBC type: "+column.getType());
    if ((column.getSize() != null) && (column.getSize().length() > 0))
    {
        writer.print("("+column.getSize()+")");
    }
    writer.println(" -->");
    writer.print("    "+column.getName()+" CDATA ");
    if ((column.getDefaultValue() != null) && (column.getDefaultValue().length() > 0))
    {
        writer.println("\"" + column.getDefaultValue() + "\"");
    }
    else
    {
        writer.println(column.isRequired() ? "#REQUIRED" : "#IMPLIED");
    }
}
 
Example 5
Source File: MSSqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    boolean sizeChanged = ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn);
    boolean typeChanged = ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, targetColumn);

    if (sizeChanged || typeChanged)
    {
        if (TypeMap.isTextType(targetColumn.getTypeCode()) && sizeChanged &&
            (targetColumn.getSize() != null) && (sourceColumn.getSizeAsInt() > targetColumn.getSizeAsInt()))
        {
            print("SUBSTRING(CAST(");
            printIdentifier(getColumnName(sourceColumn));
            print(" AS ");
            print(getNativeType(targetColumn));
            print("),1,");
            print(getSizeSpec(targetColumn));
            print(")");
        }
        else
        {
            print("CAST(");
            printIdentifier(getColumnName(sourceColumn));
            print(" AS ");
            print(getSqlType(targetColumn));
            print(")");
        }
    }
    else
    {
        printIdentifier(getColumnName(sourceColumn));
    }
}
 
Example 6
Source File: MckoiModelReader.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.getSize() != null)
    {
        if (column.getSizeAsInt() <= 0)
        {
            column.setSize(null);
        }
    }

    String defaultValue = column.getDefaultValue();

    if (defaultValue != null)
    {
        if (defaultValue.toLowerCase().startsWith("nextval('") ||
            defaultValue.toLowerCase().startsWith("uniquekey('"))
        {
            column.setDefaultValue(null);
            column.setAutoIncrement(true);
        }
        else if (TypeMap.isTextType(column.getTypeCode()))
        {
            column.setDefaultValue(unescape(column.getDefaultValue(), "'", "\\'"));
        }
    }
    return column;
}
 
Example 7
Source File: Db2Builder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    String sourceNativeType = getBareNativeType(sourceColumn);
    String targetNativeType = getBareNativeType(targetColumn);

    if (sourceNativeType.equals(targetNativeType) &&
        !ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn))
    {
        printIdentifier(getColumnName(sourceColumn));
    }
    else
    {
        String type = getSqlType(targetColumn);

        // DB2 has the limitation that it cannot convert numeric values
        // to VARCHAR, though it can convert them to CHAR
        if (TypeMap.isNumericType(sourceColumn.getTypeCode()) &&
            "VARCHAR".equalsIgnoreCase(targetNativeType))
        {
            Object sizeSpec = targetColumn.getSize();
            
            if (sizeSpec == null)
            {
                sizeSpec = getPlatformInfo().getDefaultSize(targetColumn.getTypeCode());
            }
            type = "CHAR(" + sizeSpec.toString() + ")";
        }

        print("CAST(");
        printIdentifier(getColumnName(sourceColumn));
        print(" AS ");
        print(type);
        print(")");
    }
}
 
Example 8
Source File: FirebirdBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    boolean sizeChanged = ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn);
    boolean typeChanged = ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, targetColumn);

    if (sizeChanged || typeChanged)
    {
        boolean needSubstr = TypeMap.isTextType(targetColumn.getTypeCode()) && sizeChanged &&
                             (targetColumn.getSize() != null) && (sourceColumn.getSizeAsInt() > targetColumn.getSizeAsInt());

        if (needSubstr)
        {
            print("SUBSTRING(");
        }
        // we're not using CAST but instead string construction which does not require us to know the size
        print("(");
        printIdentifier(getColumnName(sourceColumn));
        print(" || '' ");
        if (needSubstr)
        {
            print(") FROM 1 FOR ");
            print(targetColumn.getSize());
            print(")");
        }
        else
        {
            print(")");
        }
    }
    else
    {
        super.writeCastExpression(sourceColumn, targetColumn);
    }
}
 
Example 9
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Compares the current column in the database with the desired one.
 * Type, nullability, size, scale, default value, and precision radix are
 * the attributes checked.  Currently default values are compared, and
 * null and empty string are considered equal.
 *
 * @param currentColumn The current column as it is in the database
 * @param desiredColumn The desired column
 * @return <code>true</code> if the column specifications differ
 */
protected boolean columnsDiffer(Column currentColumn, Column desiredColumn)
{
    //The createColumn method leaves off the default clause if column.getDefaultValue()
    //is null.  mySQL interprets this as a default of "" or 0, and thus the columns
    //are always different according to this method.  alterDatabase will generate
    //an alter statement for the column, but it will be the exact same definition
    //as before.  In order to avoid this situation I am ignoring the comparison
    //if the desired default is null.  In order to "un-default" a column you'll
    //have to have a default="" or default="0" in the schema xml.
    //If this is bad for other databases, it is recommended that the createColumn
    //method use a "DEFAULT NULL" statement if that is what is needed.
    //A good way to get this would be to require a defaultValue="<NULL>" in the
    //schema xml if you really want null and not just unspecified.

    String  desiredDefault = desiredColumn.getDefaultValue();
    String  currentDefault = currentColumn.getDefaultValue();
    boolean defaultsEqual  = (desiredDefault == null) || desiredDefault.equals(currentDefault);
    boolean sizeMatters    = getPlatformInfo().hasSize(currentColumn.getTypeCode()) &&
                             (desiredColumn.getSize() != null);

    // We're comparing the jdbc type that corresponds to the native type for the
    // desired type, in order to avoid repeated altering of a perfectly valid column
    if ((getPlatformInfo().getTargetJdbcType(desiredColumn.getTypeCode()) != currentColumn.getTypeCode()) ||
        (desiredColumn.isRequired() != currentColumn.isRequired()) ||
        (sizeMatters && !StringUtils.equals(desiredColumn.getSize(), currentColumn.getSize())) ||
        !defaultsEqual)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
Example 10
Source File: DataDtdWriter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the DTD attribute entry for the given column.
 * 
 * @param column The column
 * @param writer The writer to write the attribute entry to
 */
private void writeColumnAttributeEntry(Column column, PrintWriter writer) throws IOException
{
    writer.print("    <!--");
    if (column.isPrimaryKey())
    {
        writer.print(" primary key,");
    }
    if (column.isAutoIncrement())
    {
        writer.print(" auto increment,");
    }
    writer.print(" JDBC type: "+column.getType());
    if ((column.getSize() != null) && (column.getSize().length() > 0))
    {
        writer.print("("+column.getSize()+")");
    }
    writer.println(" -->");
    writer.print("    "+column.getName()+" CDATA ");
    if ((column.getDefaultValue() != null) && (column.getDefaultValue().length() > 0))
    {
        writer.println("\"" + column.getDefaultValue() + "\"");
    }
    else
    {
        writer.println(column.isRequired() ? "#REQUIRED" : "#IMPLIED");
    }
}
 
Example 11
Source File: MSSqlBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    boolean sizeChanged = ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn);
    boolean typeChanged = ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, targetColumn);

    if (sizeChanged || typeChanged)
    {
        if (TypeMap.isTextType(targetColumn.getTypeCode()) && sizeChanged &&
            (targetColumn.getSize() != null) && (sourceColumn.getSizeAsInt() > targetColumn.getSizeAsInt()))
        {
            print("SUBSTRING(CAST(");
            printIdentifier(getColumnName(sourceColumn));
            print(" AS ");
            print(getNativeType(targetColumn));
            print("),1,");
            print(getSizeSpec(targetColumn));
            print(")");
        }
        else
        {
            print("CAST(");
            printIdentifier(getColumnName(sourceColumn));
            print(" AS ");
            print(getSqlType(targetColumn));
            print(")");
        }
    }
    else
    {
        printIdentifier(getColumnName(sourceColumn));
    }
}
 
Example 12
Source File: MckoiModelReader.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.getSize() != null)
    {
        if (column.getSizeAsInt() <= 0)
        {
            column.setSize(null);
        }
    }

    String defaultValue = column.getDefaultValue();

    if (defaultValue != null)
    {
        if (defaultValue.toLowerCase().startsWith("nextval('") ||
            defaultValue.toLowerCase().startsWith("uniquekey('"))
        {
            column.setDefaultValue(null);
            column.setAutoIncrement(true);
        }
        else if (TypeMap.isTextType(column.getTypeCode()))
        {
            column.setDefaultValue(unescape(column.getDefaultValue(), "'", "\\'"));
        }
    }
    return column;
}
 
Example 13
Source File: Db2Builder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    String sourceNativeType = getBareNativeType(sourceColumn);
    String targetNativeType = getBareNativeType(targetColumn);

    if (sourceNativeType.equals(targetNativeType) &&
        !ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn))
    {
        printIdentifier(getColumnName(sourceColumn));
    }
    else
    {
        String type = getSqlType(targetColumn);

        // DB2 has the limitation that it cannot convert numeric values
        // to VARCHAR, though it can convert them to CHAR
        if (TypeMap.isNumericType(sourceColumn.getTypeCode()) &&
            "VARCHAR".equalsIgnoreCase(targetNativeType))
        {
            Object sizeSpec = targetColumn.getSize();
            
            if (sizeSpec == null)
            {
                sizeSpec = getPlatformInfo().getDefaultSize(targetColumn.getTypeCode());
            }
            type = "CHAR(" + sizeSpec.toString() + ")";
        }

        print("CAST(");
        printIdentifier(getColumnName(sourceColumn));
        print(" AS ");
        print(type);
        print(")");
    }
}
 
Example 14
Source File: FirebirdBuilder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    boolean sizeChanged = ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn);
    boolean typeChanged = ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, targetColumn);

    if (sizeChanged || typeChanged)
    {
        boolean needSubstr = TypeMap.isTextType(targetColumn.getTypeCode()) && sizeChanged &&
                             (targetColumn.getSize() != null) && (sourceColumn.getSizeAsInt() > targetColumn.getSizeAsInt());

        if (needSubstr)
        {
            print("SUBSTRING(");
        }
        // we're not using CAST but instead string construction which does not require us to know the size
        print("(");
        printIdentifier(getColumnName(sourceColumn));
        print(" || '' ");
        if (needSubstr)
        {
            print(") FROM 1 FOR ");
            print(targetColumn.getSize());
            print(")");
        }
        else
        {
            print(")");
        }
    }
    else
    {
        super.writeCastExpression(sourceColumn, targetColumn);
    }
}
 
Example 15
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 16
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 17
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 18
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;
}