@SuppressWarnings("rawtypes")
 public void testUniqueConstraintGeneration() {
   DefaultGrailsDomainConfiguration config = getDomainConfig(UNIQUE_PROPERTIES);
   assertEquals("Tables created", 1, getTableCount(config));
   List expectedKeyColumns1 =
       Arrays.asList(
           new Column[] {new Column("camel_cased"), new Column("group"), new Column("login")});
   List expectedKeyColumns2 =
       Arrays.asList(new Column[] {new Column("camel_cased"), new Column("group")});
   Table mapping = (Table) config.getTableMappings().next();
   int cnt = 0;
   boolean found1 = false, found2 = false;
   for (Iterator<?> i = mapping.getUniqueKeyIterator(); i.hasNext(); ) {
     UniqueKey key = (UniqueKey) i.next();
     List keyColumns = key.getColumns();
     if (keyColumns.equals(expectedKeyColumns1)) {
       found1 = true;
     }
     if (keyColumns.equals(expectedKeyColumns2)) {
       found2 = true;
     }
     cnt++;
   }
   assertEquals(2, cnt);
   assertEquals(true, mapping.getColumn(new Column("employeeID")).isUnique());
   assertEquals(true, found1);
   assertEquals(true, found2);
 }
예제 #2
0
 private boolean isSameAsPrimaryKeyColumns(UniqueKey uniqueKey) {
   if (primaryKey == null || !primaryKey.columnIterator().hasNext()) {
     // happens for many-to-many tables
     return false;
   }
   return primaryKey.getColumns().containsAll(uniqueKey.getColumns())
       && uniqueKey.getColumns().containsAll(primaryKey.getColumns());
 }
예제 #3
0
파일: Table.java 프로젝트: raedle/univis
 public UniqueKey addUniqueKey(UniqueKey uniqueKey) {
   UniqueKey current = (UniqueKey) uniqueKeys.get(uniqueKey.getName());
   if (current != null) {
     throw new MappingException("UniqueKey " + uniqueKey.getName() + " already exists!");
   }
   uniqueKeys.put(uniqueKey.getName(), uniqueKey);
   return uniqueKey;
 }
예제 #4
0
파일: Table.java 프로젝트: raedle/univis
  public UniqueKey getOrCreateUniqueKey(String keyName) {
    UniqueKey uk = (UniqueKey) uniqueKeys.get(keyName);

    if (uk == null) {
      uk = new UniqueKey();
      uk.setName(keyName);
      uk.setTable(this);
      uniqueKeys.put(keyName, uk);
    }
    return uk;
  }
예제 #5
0
  private void cleanseUniqueKeyMap() {
    // We need to account for a few conditions here...
    // 	1) If there are multiple unique keys contained in the uniqueKeys Map, we need to deduplicate
    // 		any sharing the same columns as other defined unique keys; this is needed for the
    // annotation
    // 		processor since it creates unique constraints automagically for the user
    //	2) Remove any unique keys that share the same columns as the primary key; again, this is
    //		needed for the annotation processor to handle @Id @OneToOne cases.  In such cases the
    //		unique key is unnecessary because a primary key is already unique by definition.  We handle
    //		this case specifically because some databases fail if you try to apply a unique key to
    //		the primary key columns which causes schema export to fail in these cases.
    if (uniqueKeys.isEmpty()) {
      // nothing to do
      return;
    } else if (uniqueKeys.size() == 1) {
      // we have to worry about condition 2 above, but not condition 1
      final Map.Entry<String, UniqueKey> uniqueKeyEntry = uniqueKeys.entrySet().iterator().next();
      if (isSameAsPrimaryKeyColumns(uniqueKeyEntry.getValue())) {
        uniqueKeys.remove(uniqueKeyEntry.getKey());
      }
    } else {
      // we have to check both conditions 1 and 2
      final Iterator<Map.Entry<String, UniqueKey>> uniqueKeyEntries =
          uniqueKeys.entrySet().iterator();
      while (uniqueKeyEntries.hasNext()) {
        final Map.Entry<String, UniqueKey> uniqueKeyEntry = uniqueKeyEntries.next();
        final UniqueKey uniqueKey = uniqueKeyEntry.getValue();
        boolean removeIt = false;

        // condition 1 : check against other unique keys
        for (UniqueKey otherUniqueKey : uniqueKeys.values()) {
          // make sure its not the same unique key
          if (uniqueKeyEntry.getValue() == otherUniqueKey) {
            continue;
          }
          if (otherUniqueKey.getColumns().containsAll(uniqueKey.getColumns())
              && uniqueKey.getColumns().containsAll(otherUniqueKey.getColumns())) {
            removeIt = true;
            break;
          }
        }

        // condition 2 : check against pk
        if (isSameAsPrimaryKeyColumns(uniqueKeyEntry.getValue())) {
          removeIt = true;
        }

        if (removeIt) {
          // uniqueKeys.remove( uniqueKeyEntry.getKey() );
          uniqueKeyEntries.remove();
        }
      }
    }
  }
예제 #6
0
파일: Table.java 프로젝트: raedle/univis
 public UniqueKey createUniqueKey(List keyColumns) {
   String keyName = "UK" + uniqueColumnString(keyColumns.iterator());
   UniqueKey uk = getOrCreateUniqueKey(keyName);
   uk.addColumns(keyColumns.iterator());
   return uk;
 }
예제 #7
0
파일: Table.java 프로젝트: raedle/univis
  public String sqlCreateString(
      Dialect dialect, Mapping p, String defaultCatalog, String defaultSchema)
      throws HibernateException {
    StringBuffer buf =
        new StringBuffer("create table ")
            .append(getQualifiedName(dialect, defaultCatalog, defaultSchema))
            .append(" (");

    boolean identityColumn = idValue != null && idValue.isIdentityColumn(dialect);

    // Try to find out the name of the primary key to create it as identity if the IdentityGenerator
    // is used
    String pkname = null;
    if (hasPrimaryKey() && identityColumn) {
      pkname = ((Column) getPrimaryKey().getColumnIterator().next()).getQuotedName(dialect);
    }

    Iterator iter = getColumnIterator();
    while (iter.hasNext()) {
      Column col = (Column) iter.next();

      buf.append(col.getQuotedName(dialect)).append(' ');

      if (identityColumn && col.getQuotedName(dialect).equals(pkname)) {
        // to support dialects that have their own identity data type
        if (dialect.hasDataTypeInIdentityColumn()) {
          buf.append(col.getSqlType(dialect, p));
        }
        buf.append(' ').append(dialect.getIdentityColumnString(col.getSqlTypeCode(p)));
      } else {

        buf.append(col.getSqlType(dialect, p));

        String defaultValue = col.getDefaultValue();
        if (defaultValue != null) {
          buf.append(" default ").append(defaultValue);
        }

        if (col.isNullable()) {
          buf.append(dialect.getNullColumnString());
        } else {
          buf.append(" not null");
        }
      }

      boolean useUniqueConstraint =
          col.isUnique() && (!col.isNullable() || dialect.supportsNotNullUnique());
      if (useUniqueConstraint) {
        if (dialect.supportsUnique()) {
          buf.append(" unique");
        } else {
          UniqueKey uk = getOrCreateUniqueKey(col.getQuotedName(dialect) + '_');
          uk.addColumn(col);
        }
      }

      if (col.hasCheckConstraint() && dialect.supportsColumnCheck()) {
        buf.append(" check (").append(col.getCheckConstraint()).append(")");
      }

      String columnComment = col.getComment();
      if (columnComment != null) {
        buf.append(dialect.getColumnComment(columnComment));
      }

      if (iter.hasNext()) buf.append(", ");
    }
    if (hasPrimaryKey()) {
      buf.append(", ").append(getPrimaryKey().sqlConstraintString(dialect));
    }

    if (dialect.supportsUniqueConstraintInCreateAlterTable()) {
      Iterator ukiter = getUniqueKeyIterator();
      while (ukiter.hasNext()) {
        UniqueKey uk = (UniqueKey) ukiter.next();
        buf.append(", ").append(uk.sqlConstraintString(dialect));
      }
    }
    /*Iterator idxiter = getIndexIterator();
    while ( idxiter.hasNext() ) {
    	Index idx = (Index) idxiter.next();
    	buf.append(',').append( idx.sqlConstraintString(dialect) );
    }*/

    if (dialect.supportsTableCheck()) {
      Iterator chiter = checkConstraints.iterator();
      while (chiter.hasNext()) {
        buf.append(", check (").append(chiter.next()).append(')');
      }
    }

    buf.append(')');

    if (comment != null) buf.append(dialect.getTableComment(comment));

    return buf.append(dialect.getTableTypeString()).toString();
  }
예제 #8
0
 public UniqueKey createUniqueKey(List keyColumns) {
   String keyName = Constraint.generateName("UK_", this, keyColumns);
   UniqueKey uk = getOrCreateUniqueKey(keyName);
   uk.addColumns(keyColumns.iterator());
   return uk;
 }
예제 #9
0
  public String sqlCreateString(
      Dialect dialect, Mapping p, String defaultCatalog, String defaultSchema) {
    StringBuilder buf =
        new StringBuilder(
                hasPrimaryKey()
                    ? dialect.getCreateTableString()
                    : dialect.getCreateMultisetTableString())
            .append(' ')
            .append(getQualifiedName(dialect, defaultCatalog, defaultSchema))
            .append(" (");

    boolean identityColumn =
        idValue != null && idValue.isIdentityColumn(p.getIdentifierGeneratorFactory(), dialect);

    // Try to find out the name of the primary key to create it as identity if the IdentityGenerator
    // is used
    String pkname = null;
    if (hasPrimaryKey() && identityColumn) {
      pkname = ((Column) getPrimaryKey().getColumnIterator().next()).getQuotedName(dialect);
    }

    Iterator iter = getColumnIterator();
    while (iter.hasNext()) {
      Column col = (Column) iter.next();

      buf.append(col.getQuotedName(dialect)).append(' ');

      if (identityColumn && col.getQuotedName(dialect).equals(pkname)) {
        // to support dialects that have their own identity data type
        if (dialect.getIdentityColumnSupport().hasDataTypeInIdentityColumn()) {
          buf.append(col.getSqlType(dialect, p));
        }
        buf.append(' ')
            .append(
                dialect.getIdentityColumnSupport().getIdentityColumnString(col.getSqlTypeCode(p)));
      } else {

        buf.append(col.getSqlType(dialect, p));

        String defaultValue = col.getDefaultValue();
        if (defaultValue != null) {
          buf.append(" default ").append(defaultValue);
        }

        if (col.isNullable()) {
          buf.append(dialect.getNullColumnString());
        } else {
          buf.append(" not null");
        }
      }

      if (col.isUnique()) {
        String keyName = Constraint.generateName("UK_", this, col);
        UniqueKey uk = getOrCreateUniqueKey(keyName);
        uk.addColumn(col);
        buf.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(col));
      }

      if (col.hasCheckConstraint() && dialect.supportsColumnCheck()) {
        buf.append(" check (").append(col.getCheckConstraint()).append(")");
      }

      String columnComment = col.getComment();
      if (columnComment != null) {
        buf.append(dialect.getColumnComment(columnComment));
      }

      if (iter.hasNext()) {
        buf.append(", ");
      }
    }
    if (hasPrimaryKey()) {
      buf.append(", ").append(getPrimaryKey().sqlConstraintString(dialect));
    }

    buf.append(dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment(this));

    if (dialect.supportsTableCheck()) {
      for (String checkConstraint : checkConstraints) {
        buf.append(", check (").append(checkConstraint).append(')');
      }
    }

    buf.append(')');

    if (comment != null) {
      buf.append(dialect.getTableComment(comment));
    }

    return buf.append(dialect.getTableTypeString()).toString();
  }
예제 #10
0
  public Iterator sqlAlterStrings(
      Dialect dialect,
      Mapping p,
      TableInformation tableInfo,
      String defaultCatalog,
      String defaultSchema)
      throws HibernateException {

    StringBuilder root =
        new StringBuilder("alter table ")
            .append(getQualifiedName(dialect, defaultCatalog, defaultSchema))
            .append(' ')
            .append(dialect.getAddColumnString());

    Iterator iter = getColumnIterator();
    List results = new ArrayList();

    while (iter.hasNext()) {
      final Column column = (Column) iter.next();
      final ColumnInformation columnInfo =
          tableInfo.getColumn(Identifier.toIdentifier(column.getName(), column.isQuoted()));

      if (columnInfo == null) {
        // the column doesnt exist at all.
        StringBuilder alter =
            new StringBuilder(root.toString())
                .append(' ')
                .append(column.getQuotedName(dialect))
                .append(' ')
                .append(column.getSqlType(dialect, p));

        String defaultValue = column.getDefaultValue();
        if (defaultValue != null) {
          alter.append(" default ").append(defaultValue);
        }

        if (column.isNullable()) {
          alter.append(dialect.getNullColumnString());
        } else {
          alter.append(" not null");
        }

        if (column.isUnique()) {
          String keyName = Constraint.generateName("UK_", this, column);
          UniqueKey uk = getOrCreateUniqueKey(keyName);
          uk.addColumn(column);
          alter.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(column));
        }

        if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
          alter.append(" check(").append(column.getCheckConstraint()).append(")");
        }

        String columnComment = column.getComment();
        if (columnComment != null) {
          alter.append(dialect.getColumnComment(columnComment));
        }

        alter.append(dialect.getAddColumnSuffixString());

        results.add(alter.toString());
      }
    }

    if (results.isEmpty()) {
      Logger.getLogger(SchemaUpdate.class)
          .debugf("No alter strings for table : %s", getQuotedName());
    }

    return results.iterator();
  }