Package org.apache.ddlutils.model

Examples of org.apache.ddlutils.model.Column


      String[] columns = ClassInfo.getColumnNames(field);
      boolean notNull = field.getAnnotation(NotNull.class) != null;
     
      Class<?> type = field.getType();
      if(!ClassInfo.isModel(type) || (ClassInfo.isModel(type) && ClassInfo.isEmbedded(field))) {
        Column column = createColumn(clazz, field, columns[0]);
       
        if(notNull || type.isPrimitive()) {
          column.setRequired(true);
         
          if(type.isPrimitive() && !ClassInfo.isId(field)) { // TODO: add also Boolean, Long, Double,... ?
            if(type == Boolean.TYPE) {
              column.setDefaultValue("false");
            } else {
              column.setDefaultValue("0");
            }
          }
        }
       
        Id id = field.getAnnotation(Id.class);
        if(id != null) {
          column.setPrimaryKey(true);
          column.setRequired(true);
         
          // auto_increments managed ONLY for long
          if(id.value() == Generator.AUTO_INCREMENT
              && (Long.TYPE == type || Long.class.isAssignableFrom(type)))
            column.setAutoIncrement(true);
         
          // adds index on primary key
          /*UniqueIndex i = uniques.get(columns[0]);
          if(i == null) {
            i = new UniqueIndex();
            i.setName(columns[0]);
            uniques.put(columns[0], i);
            table.addIndex(i);
          }
          fillIndex(i, field);*/
        }
       
        table.addColumn(column);
      } else {
        List<Field> keys = ClassInfo.getClassInfo(type).keys;
       
        for (int i = 0; i < columns.length; i++) {
          Field f = keys.get(i);
          Column column = createColumn(clazz, f, columns[i]);

          if(notNull)
            column.setRequired(true);
         
          table.addColumn(column);
        }
      }
    }
View Full Code Here


    }
  }
 
  private Column createColumn(Class<?> clazz, Field field, String col) {
    Class<?> type = field.getType();
    Column column = new Column();
    column.setName(col);

    int columnType;
   
    if(type == Byte.class         || type == Byte.TYPE)    columnType = Types.TINYINT;
    else if(type == Short.class   || type == Short.TYPE)   columnType = Types.SMALLINT;
    else if(type == Integer.class || type == Integer.TYPE) columnType = Types.INTEGER;
    else if(type == Long.class    || type == Long.TYPE)    columnType = Types.BIGINT;
    else if(type == Float.class   || type == Float.TYPE)   columnType = Types.FLOAT; // TODO verify
    else if(type == Double.class  || type == Double.TYPEcolumnType = Types.DOUBLE; // TODO verify
    else if(type == String.class) {
      if(field.getAnnotation(Text.class) != null) {
        columnType = Types.LONGVARCHAR;
      } else {
        columnType = Types.VARCHAR;
       
        Max max = field.getAnnotation(Max.class);
        if(max == null){
          //throw new SienaRestrictedApiException(DB, "createColumn", "Field "+field.getName()+" in class "
          //    +clazz.getName()+" doesn't have a @Max annotation");
          // default is 255 chars as in hibernate
          column.setSize("255");
        }
        else column.setSize(""+max.value());
      }
    }
    else if(type == Boolean.class || type == Boolean.TYPE) columnType = Types.BOOLEAN;
    else if(type == Date.class) {
      if(field.getAnnotation(DateTime.class) != null)
        columnType = Types.TIMESTAMP;
      else if(field.getAnnotation(Time.class) != null)
        columnType = Types.TIME;
      else if(field.getAnnotation(SimpleDate.class) != null)
        columnType = Types.DATE;
      else
        columnType = Types.TIMESTAMP;
    } else if(type == Json.class) {
      columnType = Types.LONGVARCHAR;
    } else if(type == byte[].class){
      columnType = Types.BLOB;
    } else if(Enum.class.isAssignableFrom(type)){
      // enums are stored as string
      columnType = Types.VARCHAR;
      Max max = field.getAnnotation(Max.class);
      if(max == null)
        column.setSize(""+255); // fixes by default to this value in order to prevent alter tables every time
      else column.setSize(""+max.value());
    } else if(type == BigDecimal.class){           
      DecimalPrecision an = field.getAnnotation(DecimalPrecision.class);
      if(an == null) {
        columnType = Types.DECIMAL;
        column.setSizeAndScale(19, 2);
      }
      else {
        if(an.storageType() == DecimalPrecision.StorageType.NATIVE){
          columnType = Types.DECIMAL;
          column.setSizeAndScale(an.size(), an.scale());
        }else if(an.storageType() == DecimalPrecision.StorageType.STRING) {
          columnType = Types.VARCHAR;
          // should be an.size+"."+sign
          column.setSize((an.size()+2)+"");
        }else if(an.storageType() == DecimalPrecision.StorageType.DOUBLE) {
          columnType = Types.DOUBLE;         
        }else {
          columnType = Types.DECIMAL;
          column.setSizeAndScale(19, 2);
        }
      }
    }
    else {
      Embedded embedded = field.getAnnotation(Embedded.class);
      if(embedded != null) {
        if("h2".equals(DB)){
          columnType = Types.CLOB;
        }
        else {
          columnType = Types.LONGVARCHAR;
        }
      } else if(field.isAnnotationPresent(Polymorphic.class)){
            columnType = Types.BLOB;
        }else {       
        throw new SienaRestrictedApiException(DB, "createColumn", "Unsupported type for field "
            +clazz.getName()+"."+field.getName());
      }
    }

    column.setTypeCode(columnType);
    return column;
  }
View Full Code Here

        Table curTable = currentModel.findTable(change.getChangedTable().getName(), getPlatform().isDelimitedIdentifierModeOn());

        if (!change.isAtEnd())
        {
            Column prevColumn = change.getPreviousColumn();

            if (prevColumn != null)
            {
              // we need the corresponding column object from the current table
              prevColumn = curTable.findColumn(prevColumn.getName(), getPlatform().isDelimitedIdentifierModeOn());
            }
            // Even though Firebird can only add columns, we can move them later on
            print("ALTER TABLE ");
            printlnIdentifier(getTableName(change.getChangedTable()));
            printIndent();
View Full Code Here

    /**
   * {@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;
  }
View Full Code Here

            ResultSet rs = stmt.executeQuery("SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS");

            while (rs.next())
            {
                String generatorName = rs.getString(1).trim();
                Column column        = (Column)names.get(generatorName);

                if (column != null)
                {
                    column.setAutoIncrement(true);
                }
            }
        rs.close();
      }
        finally
View Full Code Here

                    uniquesByName.put(index.getName(), index);
                }
            }
            for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++)
            {
                Column column = table.getColumn(columnIdx);
                if (column.isAutoIncrement() && !column.isPrimaryKey())
                {
                    String indexName = table.getName() + "_" + column.getName() + "_key";
   
                    if (uniquesByName.containsKey(indexName))
                    {
                        table.removeIndex((Index)uniquesByName.get(indexName));
                        uniquesByName.remove(indexName);
View Full Code Here

    /**
     * {@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;
    }
View Full Code Here

     * {@inheritDoc}
     */
    public void apply(Database database, boolean caseSensitive)
    {
        Table  table  = database.findTable(getChangedTable().getName(), caseSensitive);
        Column column = table.findColumn(_column.getName(), caseSensitive);

        column.setTypeCode(_newTypeCode);
    }
View Full Code Here

        Table     table      = database.findTable(getChangedTable().getName(), caseSensitive);
        ArrayList newColumns = new ArrayList(table.getColumnCount());

        for (int idx = 0; idx < table.getColumnCount(); idx++)
        {
            Column column = table.getColumn(idx);
            int    newPos = getNewPosition(column);

            newColumns.set(newPos < 0 ? idx : newPos, column);
        }
        for (int idx = 0; idx < table.getColumnCount(); idx++)
View Full Code Here

        HashMap addColumnChanges = new HashMap();

        for (int columnIdx = 0; columnIdx < targetTable.getColumnCount(); columnIdx++)
        {
            Column targetColumn = targetTable.getColumn(columnIdx);
            Column sourceColumn = sourceTable.findColumn(targetColumn.getName(), _caseSensitive);

            if (sourceColumn == null)
            {
                if (_log.isInfoEnabled())
                {
                    _log.info("Column " + targetColumn.getName() + " needs to be created for table " + sourceTable.getName());
                }

                AddColumnChange change = new AddColumnChange(sourceTable,
                                                             targetColumn,
                                                             columnIdx > 0 ? targetTable.getColumn(columnIdx - 1) : null,
                                                             columnIdx < targetTable.getColumnCount() - 1 ? targetTable.getColumn(columnIdx + 1) : null);

                changes.add(change);
                addColumnChanges.put(targetColumn, change);
            }
            else
            {
                changes.addAll(compareColumns(sourceTable, sourceColumn, targetTable, targetColumn));
            }
        }
        // if the last columns in the target table are added, then we note this at the changes
        for (int columnIdx = targetTable.getColumnCount() - 1; columnIdx >= 0; columnIdx--)
        {
            Column          targetColumn = targetTable.getColumn(columnIdx);
            AddColumnChange change       = (AddColumnChange)addColumnChanges.get(targetColumn);

            if (change == null)
            {
                // column was not added, so we can ignore any columns before it that were added
                break;
            }
            else
            {
                change.setAtEnd(true);
            }
        }

        Column[] sourcePK = sourceTable.getPrimaryKeyColumns();
        Column[] targetPK = targetTable.getPrimaryKeyColumns();

        if ((sourcePK.length == 0) && (targetPK.length > 0))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("A primary key needs to be added to the table " + sourceTable.getName());
            }
            // we have to use the target table here because the primary key might
            // reference a new column
            changes.add(new AddPrimaryKeyChange(targetTable, targetPK));
        }
        else if ((targetPK.length == 0) && (sourcePK.length > 0))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("The primary key needs to be removed from the table " + sourceTable.getName());
            }
            changes.add(new RemovePrimaryKeyChange(sourceTable, sourcePK));
        }
        else if ((sourcePK.length > 0) && (targetPK.length > 0))
        {
            boolean changePK = false;

            if (sourcePK.length != targetPK.length)
            {
                changePK = true;
            }
            else
            {
                for (int pkColumnIdx = 0; (pkColumnIdx < sourcePK.length) && !changePK; pkColumnIdx++)
                {
                    if ((_caseSensitive  && !sourcePK[pkColumnIdx].getName().equals(targetPK[pkColumnIdx].getName())) ||
                        (!_caseSensitive && !sourcePK[pkColumnIdx].getName().equalsIgnoreCase(targetPK[pkColumnIdx].getName())))
                    {
                        changePK = true;
                    }
                }
            }
            if (changePK)
            {
                if (_log.isInfoEnabled())
                {
                    _log.info("The primary key of table " + sourceTable.getName() + " needs to be changed");
                }
                changes.add(new PrimaryKeyChange(sourceTable, sourcePK, targetPK));
            }
        }
       
        HashMap columnPosChanges = new HashMap();

        for (int columnIdx = 0; columnIdx < sourceTable.getColumnCount(); columnIdx++)
        {
            Column sourceColumn = sourceTable.getColumn(columnIdx);
            Column targetColumn = targetTable.findColumn(sourceColumn.getName(), _caseSensitive);

            if (targetColumn == null)
            {
                if (_log.isInfoEnabled())
                {
View Full Code Here

TOP

Related Classes of org.apache.ddlutils.model.Column

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.