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

The following examples show how to use org.apache.ddlutils.model.Column#getDefaultValue() . 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: 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 3
Source File: DerbyModelReader.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);
    String defaultValue = column.getDefaultValue();

    if (defaultValue != null)
    {
        // we check for these strings
        //   GENERATED_BY_DEFAULT               -> 'GENERATED BY DEFAULT AS IDENTITY'
        //   AUTOINCREMENT: start 1 increment 1 -> 'GENERATED ALWAYS AS IDENTITY'
        if ("GENERATED_BY_DEFAULT".equals(defaultValue) || defaultValue.startsWith("AUTOINCREMENT:"))
        {
            column.setDefaultValue(null);
            column.setAutoIncrement(true);
        }
        else if (TypeMap.isTextType(column.getTypeCode()))
        {
            column.setDefaultValue(unescape(defaultValue, "'", "''"));
        }
    }
    return column;
}
 
Example 4
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 5
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 6
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 7
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 8
Source File: HsqlDbModelReader.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 (TypeMap.isTextType(column.getTypeCode()) &&
        (column.getDefaultValue() != null))
    {
        column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
    }
    return column;
}
 
Example 9
Source File: Oracle8Builder.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected String getNativeDefaultValue(Column column)
{
    if ((column.getTypeCode() == Types.BIT) || (column.getTypeCode() == Types.BOOLEAN))
    {
        return getDefaultValueHelper().convert(column.getDefaultValue(), column.getTypeCode(), Types.SMALLINT);
    }
	// Oracle does not accept ISO formats, so we have to convert an ISO spec if we find one
	// But these are the only formats that we make sure work, every other format has to be database-dependent
	// and thus the user has to ensure that it is correct
    else if (column.getTypeCode() == Types.DATE)
    {
        if (_isoDatePattern.matcher(column.getDefaultValue()).matches())
        {
        	return "TO_DATE('"+column.getDefaultValue()+"', 'YYYY-MM-DD')";
        }
    }
    else if (column.getTypeCode() == Types.TIME)
    {
        if (_isoTimePattern.matcher(column.getDefaultValue()).matches())
        {
        	return "TO_DATE('"+column.getDefaultValue()+"', 'HH24:MI:SS')";
        }
    }
    else if (column.getTypeCode() == Types.TIMESTAMP)
    {
        if (_isoTimestampPattern.matcher(column.getDefaultValue()).matches())
        {
        	return "TO_DATE('"+column.getDefaultValue()+"', 'YYYY-MM-DD HH24:MI:SS')";
        }
    }
    return super.getNativeDefaultValue(column);
}
 
Example 10
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 11
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 12
Source File: HsqlDbModelReader.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 (TypeMap.isTextType(column.getTypeCode()) &&
        (column.getDefaultValue() != null))
    {
        column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
    }
    return column;
}
 
Example 13
Source File: PlatformImplBase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Allows the platform to postprocess the model just read from the database.
 * 
 * @param model The model
 */
protected void postprocessModelFromDatabase(Database model)
{
    // Default values for CHAR/VARCHAR/LONGVARCHAR columns have quotation marks
    // around them which we'll remove now
    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);

            if (TypeMap.isTextType(column.getTypeCode()) ||
                TypeMap.isDateTimeType(column.getTypeCode()))
            {
                String defaultValue = column.getDefaultValue();

                if ((defaultValue != null) && (defaultValue.length() >= 2) &&
                    defaultValue.startsWith("'") && defaultValue.endsWith("'"))
                {
                    defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
                    column.setDefaultValue(defaultValue);
                }
            }
        }
    }
}
 
Example 14
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 15
Source File: SybaseBuilder.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
  * Writes the SQL to change the given column.
  * 
  * @param table     The table
  * @param column    The column to change
  * @param newColumn The new column definition
  */
 public void changeColumn(Table table, Column column, Column newColumn) throws IOException
 {
     Object oldParsedDefault = column.getParsedDefaultValue();
     Object newParsedDefault = newColumn.getParsedDefaultValue();
     String newDefault       = newColumn.getDefaultValue();
     boolean defaultChanges  = ((oldParsedDefault == null) && (newParsedDefault != null)) ||
                               ((oldParsedDefault != null) && !oldParsedDefault.equals(newParsedDefault));

     // Sybase does not like it if there is a default spec in the ALTER TABLE ALTER
     // statement; thus we have to change the default afterwards
     if (defaultChanges)
     {
         // we're first removing the default as it might make problems when the
         // datatype changes
         print("ALTER TABLE ");
         printlnIdentifier(getTableName(table));
         printIndent();
         print("REPLACE ");
         printIdentifier(getColumnName(column));
         print(" DEFAULT NULL");
         printEndOfStatement();
     }
     print("ALTER TABLE ");
     printlnIdentifier(getTableName(table));
     printIndent();
     print("MODIFY ");
     if (newDefault != null)
     {
         newColumn.setDefaultValue(null);
     }
     writeColumn(table, newColumn);
     if (newDefault != null)
     {
         newColumn.setDefaultValue(newDefault);
     }
     printEndOfStatement();
     if (defaultChanges)
     {
         print("ALTER TABLE ");
         printlnIdentifier(getTableName(table));
         printIndent();
         print("REPLACE ");
         printIdentifier(getColumnName(column));
         if (newDefault != null)
         {
             writeColumnDefaultValueStmt(table, newColumn);
         }
         else
         {
             print(" DEFAULT NULL");
         }
         printEndOfStatement();
     }
}
 
Example 16
Source File: SybaseBuilder.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
  * Writes the SQL to change the given column.
  * 
  * @param table     The table
  * @param column    The column to change
  * @param newColumn The new column definition
  */
 public void changeColumn(Table table, Column column, Column newColumn) throws IOException
 {
     Object oldParsedDefault = column.getParsedDefaultValue();
     Object newParsedDefault = newColumn.getParsedDefaultValue();
     String newDefault       = newColumn.getDefaultValue();
     boolean defaultChanges  = ((oldParsedDefault == null) && (newParsedDefault != null)) ||
                               ((oldParsedDefault != null) && !oldParsedDefault.equals(newParsedDefault));

     // Sybase does not like it if there is a default spec in the ALTER TABLE ALTER
     // statement; thus we have to change the default afterwards
     if (defaultChanges)
     {
         // we're first removing the default as it might make problems when the
         // datatype changes
         print("ALTER TABLE ");
         printlnIdentifier(getTableName(table));
         printIndent();
         print("REPLACE ");
         printIdentifier(getColumnName(column));
         print(" DEFAULT NULL");
         printEndOfStatement();
     }
     print("ALTER TABLE ");
     printlnIdentifier(getTableName(table));
     printIndent();
     print("MODIFY ");
     if (newDefault != null)
     {
         newColumn.setDefaultValue(null);
     }
     writeColumn(table, newColumn);
     if (newDefault != null)
     {
         newColumn.setDefaultValue(newDefault);
     }
     printEndOfStatement();
     if (defaultChanges)
     {
         print("ALTER TABLE ");
         printlnIdentifier(getTableName(table));
         printIndent();
         print("REPLACE ");
         printIdentifier(getColumnName(column));
         if (newDefault != null)
         {
             writeColumnDefaultValueStmt(table, newColumn);
         }
         else
         {
             print(" DEFAULT NULL");
         }
         printEndOfStatement();
     }
}
 
Example 17
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 18
Source File: MSSqlBuilder.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the SQL to recreate a column, e.g. using a different type or similar.
 * 
 * @param table     The table
 * @param curColumn The current column definition
 * @param newColumn The new column definition
 */
public void recreateColumn(Table table, Column curColumn, Column newColumn) throws IOException
{
    boolean hasDefault       = curColumn.getParsedDefaultValue() != null;
    boolean shallHaveDefault = newColumn.getParsedDefaultValue() != null;
    String  newDefault       = newColumn.getDefaultValue();

    // Sql Server does not like it if there is a default spec in the ALTER TABLE ALTER COLUMN
    // statement; thus we have to change the default manually
    if (newDefault != null)
    {
        newColumn.setDefaultValue(null);
    }
    if (hasDefault)
    {
        // we're dropping the old default
        writeDropConstraintStatement(table, curColumn, "D");
    }

    print("ALTER TABLE ");
    printlnIdentifier(getTableName(table));
    printIndent();
    print("ALTER COLUMN ");
    writeColumn(table, newColumn);
    printEndOfStatement();

    if (shallHaveDefault)
    {
        newColumn.setDefaultValue(newDefault);

        // if the column shall have a default, then we have to add it as a constraint
        print("ALTER TABLE ");
        printlnIdentifier(getTableName(table));
        printIndent();
        print("ADD CONSTRAINT ");
        printIdentifier(getConstraintName("DF", table, curColumn.getName(), null));
        writeColumnDefaultValueStmt(table, newColumn);
        print(" FOR ");
        printIdentifier(getColumnName(curColumn));
        printEndOfStatement();
    }
}
 
Example 19
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 20
Source File: SqlBuilder.java    From gemfirexd-oss with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the native default value for the column.
 * 
 * @param column The column
 * @return The native default value
 */
protected String getNativeDefaultValue(Column column)
{
    return column.getDefaultValue();
}