Example usage for java.sql DatabaseMetaData columnNoNulls

List of usage examples for java.sql DatabaseMetaData columnNoNulls

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData columnNoNulls.

Prototype

int columnNoNulls

To view the source code for java.sql DatabaseMetaData columnNoNulls.

Click Source Link

Document

Indicates that the column might not allow NULL values.

Usage

From source file:ca.sqlpower.sqlobject.TestSQLColumn.java

public void testPKAttributes() throws Exception {
    SQLColumn cowCol = table1pk.getColumnByName("cow");
    SQLColumn fooCol = table1pk.getColumnByName("foo");

    // check for PK vs non PK attributes
    assertTrue("table1pk.cow should have been flagged as PK", cowCol.isPrimaryKey());
    assertEquals("table1pk.cow nullability incorrect", cowCol.getNullable(), DatabaseMetaData.columnNoNulls);
    assertFalse("table1pk.cow isDefinitelyNullable incorrect", cowCol.isDefinitelyNullable());

    assertFalse("table1pk.foo should NOT have been flagged as PK", fooCol.isPrimaryKey());
    assertEquals("table1pk.foo nullability incorrect", fooCol.getNullable(), DatabaseMetaData.columnNullable);
    assertTrue("table1pk.foo isDefinitelyNullable incorrect", fooCol.isDefinitelyNullable());
}

From source file:de.erdesignerng.dialect.JDBCReverseEngineeringStrategy.java

/**
 * Reverse engineer an existing table./*w ww .j av  a 2s .  c o  m*/
 *
 * @param aModel     the model
 * @param aOptions     the options
 * @param aNotifier   the notifier
 * @param aTableEntry the table
 * @param aConnection the connection
 * 
 * @return a Map of former ModelProperties of model items in case they have been replaced during reverse engineering into an existing model
 * 
 * @throws SQLException   is thrown in case of an error
 * @throws ReverseEngineeringException is thrown in case of an error
 */
protected final Map<String, ModelProperties> reverseEngineerTable(Model aModel,
        ReverseEngineeringOptions aOptions, ReverseEngineeringNotifier aNotifier, TableEntry aTableEntry,
        Connection aConnection) throws SQLException, ReverseEngineeringException {
    Map<String, ModelProperties> theExistingModelItemProperties = null;
    aNotifier.notifyMessage(ERDesignerBundle.ENGINEERINGTABLE, aTableEntry.getTableName());

    DatabaseMetaData theMetaData = aConnection.getMetaData();

    String theTablePattern = getEscapedPattern(theMetaData, aTableEntry.getTableName());
    String theSchemaPattern = getEscapedPattern(theMetaData, aTableEntry.getSchemaName());

    ResultSet theTablesResultSet = theMetaData.getTables(aTableEntry.getCatalogName(), theSchemaPattern,
            theTablePattern, new String[] { aTableEntry.getTableType().toString() });

    while (theTablesResultSet.next()) {

        String theTableRemarks = theTablesResultSet.getString("REMARKS");

        Table theNewTable = new Table();

        theNewTable.setName(dialect.getCastType().cast(aTableEntry.getTableName()));
        theNewTable.setOriginalName(aTableEntry.getTableName());
        switch (aOptions.getTableNaming()) {
        case INCLUDE_SCHEMA:
            theNewTable.setSchema(aTableEntry.getSchemaName());
            break;
        default:
        }

        if (!StringUtils.isEmpty(theTableRemarks)) {
            theNewTable.setComment(theTableRemarks);
        }

        // Reverse engineer attributes
        ResultSet theColumnsResultSet = theMetaData.getColumns(aTableEntry.getCatalogName(), theSchemaPattern,
                theTablePattern, null);
        while (theColumnsResultSet.next()) {

            String theColumnName = null;
            String theTypeName = null;
            Integer theSize = null;
            Integer theFraction = null;
            int theRadix = 0;
            int theNullable = 0;
            String theDefaultValue = null;
            String theColumnRemarks = null;

            try {
                theColumnName = theColumnsResultSet.getString("COLUMN_NAME");
            } catch (SQLException e) {
            }

            try {
                theTypeName = theColumnsResultSet.getString("TYPE_NAME");
            } catch (SQLException e) {
            }

            try {
                theSize = theColumnsResultSet.getInt("COLUMN_SIZE");
            } catch (SQLException e) {
            }

            try {
                theFraction = theColumnsResultSet.getInt("DECIMAL_DIGITS");
            } catch (SQLException e) {
            }

            try {
                theRadix = theColumnsResultSet.getInt("NUM_PREC_RADIX");
            } catch (SQLException e) {
            }

            try {
                theNullable = theColumnsResultSet.getInt("NULLABLE");
            } catch (SQLException e) {
            }

            try {
                theDefaultValue = theColumnsResultSet.getString("COLUMN_DEF");
                if (!StringUtils.isEmpty(theDefaultValue)) {
                    theDefaultValue = theDefaultValue.trim();
                }
            } catch (SQLException e) {
            }

            try {
                theColumnRemarks = theColumnsResultSet.getString("REMARKS");
            } catch (SQLException e) {
            }

            Attribute<Table> theAttribute = new Attribute<>();

            theAttribute.setName(dialect.getCastType().cast(theColumnName));
            if (!StringUtils.isEmpty(theColumnRemarks)) {
                theAttribute.setComment(theColumnRemarks);
            }

            // Search for the datatype in the domains, the dialect specific and the user defined datatypes
            DataType theDataType = aModel.getAvailableDataTypes()
                    .findByName(dialect.convertTypeNameToRealTypeName(theTypeName));

            if (theDataType == null) {
                throw new ReverseEngineeringException("Unknown data type " + theTypeName + " for "
                        + aTableEntry.getTableName() + "." + theColumnName);
            }

            boolean isNullable = true;

            switch (theNullable) {
            case DatabaseMetaData.columnNoNulls:
                isNullable = false;
                break;
            case DatabaseMetaData.columnNullable:
                isNullable = true;
                break;
            default:
                LOGGER.warn("Unknown nullability : " + theNullable + " for " + theColumnName + " of table "
                        + theNewTable.getName());
            }

            theAttribute.setDatatype(theDataType);
            theAttribute.setSize(theSize);
            theAttribute.setFraction(theFraction);
            theAttribute.setScale(theRadix);
            theAttribute.setDefaultValue(theDefaultValue);
            theAttribute.setNullable(isNullable);

            reverseEngineerAttribute(theAttribute, aTableEntry, aConnection);

            try {
                theNewTable.addAttribute(aModel, theAttribute);
            } catch (ElementAlreadyExistsException | ElementInvalidNameException e) {
                throw new ReverseEngineeringException(e.getMessage(), e);
            }
        }
        theColumnsResultSet.close();

        // Reverse engineer primary keys
        reverseEngineerPrimaryKey(aModel, aTableEntry, theMetaData, theNewTable);

        // Reverse engineer indexes
        try {
            reverseEngineerIndexes(aModel, aTableEntry, theMetaData, theNewTable, aNotifier);
        } catch (SQLException e) {
            // if there is an sql exception, just ignore it
        }

        // We are done here
        try {
            aModel.addTable(theNewTable);
        } catch (ElementAlreadyExistsException e1) {
            //this manages the reverse engineering into an existing model and cares only about the table names of the model that conflict with the new table names from the connection
            //TODO: also care about tables that are no longer part of the connection, but still exist in the local model. E.g. show a dialog and ask the user what to do (delete/keep)
            try {
                //buffer the properties (e.g. position in model) of the existing table and its relations (e.g. the offset of the title) that are going to be replaced
                Table theExistingTable = aModel.getTables().findByName(theNewTable.getName());
                RelationList theExistingRelations = aModel.getRelations().getAllRelataionsOf(theExistingTable);

                if (theExistingModelItemProperties == null) {
                    theExistingModelItemProperties = new HashMap<>();
                }

                //store former layouting data for the table and its relations in the old graph
                theExistingModelItemProperties.put(theExistingTable.getName(),
                        theExistingTable.getProperties());
                for (Relation anExistingRelation : theExistingRelations) {
                    theExistingModelItemProperties.put(anExistingRelation.getName(),
                            anExistingRelation.getProperties());
                }

                //remove old table and its relations
                aModel.removeTable(theExistingTable);

                //add the new table without relations
                aModel.addTable(theNewTable);
            } catch (ElementAlreadyExistsException | ElementInvalidNameException | VetoException e2) {
                throw new ReverseEngineeringException(e2.getMessage());
            }
        } catch (ElementInvalidNameException | VetoException e3) {
            throw new ReverseEngineeringException(e3.getMessage());
        }
    }

    theTablesResultSet.close();

    return theExistingModelItemProperties;
}

From source file:ca.sqlpower.sqlobject.TestSQLTable.java

public void testMoveToPKClearsNullability() throws SQLObjectException {
    SQLTable t = db.getTableByName("REGRESSION_TEST1");
    SQLColumn c = t.getColumnByName("t1_c1");
    assertFalse("Column shouldn't be in PK to begin", c.isPrimaryKey());
    c.setNullable(DatabaseMetaData.columnNullable);

    // Now c is not in the PK and is nullable.  Let's add it to PK
    t.changeColumnIndex(0, 0, true);/* www.j a  v a  2  s  . c  o  m*/

    assertTrue(c.isPrimaryKey());
    assertEquals(DatabaseMetaData.columnNoNulls, c.getNullable());
}

From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java

private boolean isNullable(int nullable) {
    switch (nullable) {
    case DatabaseMetaData.columnNoNulls:
        return false;
    case DatabaseMetaData.columnNullableUnknown:
    case DatabaseMetaData.columnNullable:
    default:/*from w  w w .  j  a v a2 s. c o m*/
        return true;
    }
}

From source file:ca.sqlpower.sqlobject.TestSQLColumn.java

public void testIsDefinitelyNullable() throws Exception {
    SQLColumn tmpCol = new SQLColumn();
    assertEquals(false, tmpCol.isDefinitelyNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNullable);
    assertEquals(true, tmpCol.isDefinitelyNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNoNulls);
    assertEquals(false, tmpCol.isDefinitelyNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNullableUnknown);
    assertEquals(false, tmpCol.isDefinitelyNullable());

    SQLColumn cowCol = table1pk.getColumn(0);

    assertEquals(false, cowCol.isDefinitelyNullable());
    cowCol.setNullable(DatabaseMetaData.columnNullable);
    assertEquals(true, cowCol.isDefinitelyNullable());
    cowCol.setNullable(DatabaseMetaData.columnNoNulls);
    assertEquals(false, cowCol.isDefinitelyNullable());
    cowCol.setNullable(DatabaseMetaData.columnNullableUnknown);
    assertEquals(false, cowCol.isDefinitelyNullable());

}

From source file:com.ccl.jersey.codegen.SimpleMetaDataExporter.java

private void handleColumn(EntityType classModel, String tableName, ResultSet columns) throws SQLException {
    String columnName = normalize(columns.getString("COLUMN_NAME"));
    String normalizedColumnName = namingStrategy.normalizeColumnName(columnName);
    int columnType = columns.getInt("DATA_TYPE");
    String typeName = columns.getString("TYPE_NAME");
    Number columnSize = (Number) columns.getObject("COLUMN_SIZE");
    Number columnDigits = (Number) columns.getObject("DECIMAL_DIGITS");
    int columnIndex = columns.getInt("ORDINAL_POSITION");
    int nullable = columns.getInt("NULLABLE");
    String remarks = columns.getString("REMARKS");
    String defaultValue = columns.getString("COLUMN_DEF");

    String propertyName = namingStrategy.getPropertyName(normalizedColumnName, classModel);

    Map<String, DictType> stringDictTypeMap = registerDictTypes.get(tableName);
    if (null != stringDictTypeMap) {
        DictType dictType = stringDictTypeMap.get(columnName);
        if (null != dictType) {
            String modelClassName = tableModelMapper.get(tableName);
            registerVoDataType(modelClassName, propertyName, dictType.getDictType());
        }//from   www. j av  a  2 s  .c  o m
    }

    Class<?> clazz = configuration.getJavaType(columnType, typeName,
            columnSize != null ? columnSize.intValue() : 0, columnDigits != null ? columnDigits.intValue() : 0,
            tableName, columnName);
    if (clazz == null) {
        throw new IllegalStateException("Found no mapping for " + columnType + " (" + tableName + "."
                + columnName + " " + typeName + ")");
    }

    TypeCategory fieldType = TypeCategory.get(clazz.getName());
    if (Number.class.isAssignableFrom(clazz)) {
        fieldType = TypeCategory.NUMERIC;
    } else if (Enum.class.isAssignableFrom(clazz)) {
        fieldType = TypeCategory.ENUM;
    }
    Type typeModel = new ClassType(fieldType, clazz);
    Property property = createProperty(classModel, normalizedColumnName, propertyName, propertyName, typeModel);
    if (null != defaultValue)
        property.setDefaultValue(DataTypeConvertUtils.convert(defaultValue, clazz));
    ColumnMetadata column = ColumnMetadata.named(normalizedColumnName).ofType(columnType)
            .withIndex(columnIndex);
    if (nullable == DatabaseMetaData.columnNoNulls) {
        column = column.notNull();
    }
    if (columnSize != null) {
        column = column.withSize(columnSize.intValue());
    }
    if (columnDigits != null) {
        column = column.withDigits(columnDigits.intValue());
    }
    property.getData().put("COLUMN", column);

    if (columnAnnotations) {
        property.addAnnotation(new ColumnImpl(normalizedColumnName));
    }
    if (validationAnnotations) {
        if (nullable == DatabaseMetaData.columnNoNulls) {
            NotNullImpl annotation = new NotNullImpl();
            property.addAnnotation(annotation);
        }
        int size = columns.getInt("COLUMN_SIZE");
        if (size > 0 && clazz.equals(String.class)) {
            property.addAnnotation(new SizeImpl(0, size));
        }
    }

    LabelImpl label = new LabelImpl(StringUtils.isBlank(remarks) ? propertyName : remarks);
    property.addAnnotation(label);

    classModel.addProperty(property);
}

From source file:ca.sqlpower.sqlobject.TestSQLColumn.java

public void testGetNullable() throws Exception {
    SQLColumn tmpCol = new SQLColumn();
    assertEquals(DatabaseMetaData.columnNoNulls, tmpCol.getNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNullable);
    assertEquals(DatabaseMetaData.columnNullable, tmpCol.getNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNullableUnknown);
    assertEquals(DatabaseMetaData.columnNullableUnknown, tmpCol.getNullable());
    tmpCol.setNullable(DatabaseMetaData.columnNoNulls);
    assertEquals(DatabaseMetaData.columnNoNulls, tmpCol.getNullable());

    SQLColumn cowCol = table1pk.getColumn(0);
    assertEquals(DatabaseMetaData.columnNoNulls, cowCol.getNullable());
    cowCol.setNullable(DatabaseMetaData.columnNullable);
    assertEquals(DatabaseMetaData.columnNullable, cowCol.getNullable());
    cowCol.setNullable(DatabaseMetaData.columnNullableUnknown);
    assertEquals(DatabaseMetaData.columnNullableUnknown, cowCol.getNullable());
    cowCol.setNullable(DatabaseMetaData.columnNoNulls);
    assertEquals(DatabaseMetaData.columnNoNulls, cowCol.getNullable());
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

/**
 * Dumps the columns of the indicated table.
 * //from   ww w  .  j  a v a 2 s .c o m
 * @param xmlWriter   The xml writer to write to
 * @param metaData    The database metadata
 * @param catalogName The catalog name
 * @param schemaName  The schema name
 * @param tableName   The table name
 */
private void dumpColumns(PrettyPrintingXmlWriter xmlWriter, final DatabaseMetaData metaData,
        final String catalogName, final String schemaName, final String tableName) throws SQLException {
    performResultSetXmlOperation(xmlWriter, null, new ResultSetXmlOperation() {
        public ResultSet getResultSet() throws SQLException {
            return metaData.getColumns(catalogName, schemaName, tableName, _columnPattern);
        }

        public void handleRow(PrettyPrintingXmlWriter xmlWriter, ResultSet result) throws SQLException {
            Set columns = getColumnsInResultSet(result);
            String columnName = result.getString("COLUMN_NAME");

            if ((columnName != null) && (columnName.length() > 0)) {
                xmlWriter.writeElementStart(null, "column");
                xmlWriter.writeAttribute(null, "name", columnName);

                addIntAttribute(xmlWriter, "typeCode", result, columns, "DATA_TYPE");
                addStringAttribute(xmlWriter, "type", result, columns, "TYPE_NAME");
                addIntAttribute(xmlWriter, "size", result, columns, "COLUMN_SIZE");
                addIntAttribute(xmlWriter, "digits", result, columns, "DECIMAL_DIGITS");
                addIntAttribute(xmlWriter, "precision", result, columns, "NUM_PREC_RADIX");
                if (columns.contains("NULLABLE")) {
                    try {
                        switch (result.getInt("NULLABLE")) {
                        case DatabaseMetaData.columnNoNulls:
                            xmlWriter.writeAttribute(null, "nullable", "false");
                            break;
                        case DatabaseMetaData.columnNullable:
                            xmlWriter.writeAttribute(null, "nullable", "true");
                            break;
                        default:
                            xmlWriter.writeAttribute(null, "nullable", "unknown");
                            break;
                        }
                    } catch (SQLException ex) {
                        log("Could not read the NULLABLE value for colum '" + columnName + "' of table '"
                                + tableName + "' from the result set: " + ex.getStackTrace(), Project.MSG_ERR);
                    }
                }
                addStringAttribute(xmlWriter, "remarks", result, columns, "REMARKS");
                addStringAttribute(xmlWriter, "defaultValue", result, columns, "COLUMN_DEF");
                addIntAttribute(xmlWriter, "maxByteLength", result, columns, "CHAR_OCTET_LENGTH");
                addIntAttribute(xmlWriter, "index", result, columns, "ORDINAL_POSITION");
                if (columns.contains("IS_NULLABLE")) {
                    try {
                        String value = result.getString("IS_NULLABLE");

                        if ("no".equalsIgnoreCase(value)) {
                            xmlWriter.writeAttribute(null, "isNullable", "false");
                        } else if ("yes".equalsIgnoreCase(value)) {
                            xmlWriter.writeAttribute(null, "isNullable", "true");
                        } else {
                            xmlWriter.writeAttribute(null, "isNullable", "unknown");
                        }
                    } catch (SQLException ex) {
                        log("Could not read the IS_NULLABLE value for colum '" + columnName + "' of table '"
                                + tableName + "' from the result set: " + ex.getStackTrace(), Project.MSG_ERR);
                    }
                }
                addStringAttribute(xmlWriter, "refCatalog", result, columns, "SCOPE_CATLOG");
                addStringAttribute(xmlWriter, "refSchema", result, columns, "SCOPE_SCHEMA");
                addStringAttribute(xmlWriter, "refTable", result, columns, "SCOPE_TABLE");
                addShortAttribute(xmlWriter, "sourceTypeCode", result, columns, "SOURCE_DATA_TYPE");

                xmlWriter.writeElementEnd();
            }
        }

        public void handleError(SQLException ex) {
            log("Could not read the colums for table '" + tableName + "' from the result set: "
                    + ex.getStackTrace(), Project.MSG_ERR);
        }
    });
}

From source file:org.apache.openjpa.jdbc.schema.Column.java

/**
 * Sets nullability of this receiver by the given flag.
 * @param flag one of the JDBC nullability flag namely
 * <LI> {@link DatabaseMetaData#columnNullableUnknown} : not known if the column can be set to null value
 * <LI> {@link DatabaseMetaData#columnNullable} : the column can be set to null value
 * <LI> {@link DatabaseMetaData#columnNoNulls} : the column can not be set to null value
 *///from  ww  w. ja  va 2 s.  co m
public void setNullability(short flag) {
    switch (flag) {
    case DatabaseMetaData.columnNullableUnknown:
        _notNull = null;
        break;
    case DatabaseMetaData.columnNullable:
        _notNull = false;
        break;
    case DatabaseMetaData.columnNoNulls:
        _notNull = true;
        break;

    }
}

From source file:org.apache.openjpa.jdbc.sql.AzureDictionary.java

/**
 * Create a new column from the information in the schema metadata. Compared to DBDictionary.newColumn(), this will
 * refer to column names reported by sp_columns.
 */// ww  w . ja v  a 2 s.c  o  m
@Override
protected Column newColumn(final ResultSet colMeta) throws SQLException {

    final Column col = new Column();
    col.setSchemaIdentifier(fromDBName(colMeta.getString("TABLE_OWNER"), DBIdentifier.DBIdentifierType.SCHEMA));
    col.setTableIdentifier(fromDBName(colMeta.getString("TABLE_NAME"), DBIdentifier.DBIdentifierType.TABLE));
    col.setIdentifier(fromDBName(colMeta.getString("COLUMN_NAME"), DBIdentifier.DBIdentifierType.COLUMN));
    col.setType(colMeta.getInt("DATA_TYPE"));
    col.setTypeIdentifier(
            fromDBName(colMeta.getString("TYPE_NAME"), DBIdentifier.DBIdentifierType.COLUMN_DEFINITION));
    col.setSize(colMeta.getInt("PRECISION"));
    col.setDecimalDigits(colMeta.getInt("SCALE"));
    col.setNotNull(colMeta.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls);

    final String def = colMeta.getString("COLUMN_DEF");
    if (!StringUtils.isEmpty(def) && !"null".equalsIgnoreCase(def)) {
        col.setDefaultString(def);
    }
    return col;
}