Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package net.java.ao.schema.helper;
  
  import java.sql.ResultSet;
  import java.sql.Types;
  import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 import static com.google.common.collect.Lists.newLinkedList;
 import static com.google.common.collect.Maps.newHashMap;
 import static com.google.common.collect.Sets.newHashSet;
 import static net.java.ao.sql.SqlUtils.closeQuietly;
 import static net.java.ao.types.TypeQualifiers.qualifiers;
 
 {
     private static final Pattern STRING_VALUE = Pattern.compile("\"(.*)\"");
 
     private final DatabaseProvider databaseProvider;
     private final NameConverters nameConverters;
     private final SchemaConfiguration schemaConfiguration;
 
     public DatabaseMetaDataReaderImpl(DatabaseProvider databaseProviderNameConverters nameConvertersSchemaConfiguration schemaConfiguration)
     {
         this. = databaseProvider;
         this. = nameConverters;
         this. = schemaConfiguration;
     }
 
     public Iterable<StringgetTableNames(DatabaseMetaData metaData)
     {
         ResultSet rs = null;
         try
         {
             rs = .getTables(metaData.getConnection());
 
             final List<StringtableNames = newLinkedList();
             while (rs.next())
             {
                 final String tableName = parseStringValue(rs"TABLE_NAME");
                 if (.shouldManageTable(tableName.isCaseSensitive()))
                 {
                     tableNames.add(tableName);
                 }
             }
             return tableNames;
         }
         catch (SQLException e)
         {
             throw new RuntimeException(e);
         }
         finally
         {
             closeQuietly(rs);
         }
     }
 
     public Iterable<? extends FieldgetFields(DatabaseMetaData databaseMetaDataString tableName)
     {
         final TypeManager manager = .getTypeManager();
         final List<StringsequenceNames = getSequenceNames(databaseMetaData);
         final Set<StringuniqueFields = getUniqueFields(databaseMetaDatatableName);
 
         final Map<StringFieldImplfields = newHashMap();
 
         CloseableResultSetMetaData rsmd = null;
         try
         {
             rsmd = getResultSetMetaData(databaseMetaDatatableName);
             for (int i = 1; i < rsmd.getColumnCount() + 1; i++)
             {
                 final String fieldName = rsmd.getColumnName(i);
                 final TypeQualifiers qualifiers = getTypeQualifiers(rsmdi);
                 final int jdbcType = rsmd.getColumnType(i);
                 final TypeInfo<?> databaseType = manager.getTypeFromSchema(jdbcTypequalifiers);
                 if (databaseType == null)
                 {
                     StringBuilder buf = new StringBuilder();
                     buf.append("TABLE: " + tableName + ": ");
                     for (int j = 1; j <= rsmd.getColumnCount(); j++) {
                         buf.append(rsmd.getColumnName(j)).append(" - ");
                     }
                    buf.append("can't find type " + jdbcType + " " + qualifiers + " in field " + fieldName);
                    throw new IllegalStateException(buf.toString());
                }
                final boolean autoIncrement = isAutoIncrement(rsmdisequenceNamestableNamefieldName);
                final boolean notNull = isNotNull(rsmdi);
                final boolean isUnique = isUnique(uniqueFieldsfieldName);
                fields.put(fieldNamenewField(fieldNamedatabaseTypejdbcTypeautoIncrementnotNullisUnique));
            }
            ResultSet rs = null;
            try
            {
                rs = databaseMetaData.getColumns(nullnulltableNamenull);
                while (rs.next())
                {
                    final String columnName = parseStringValue(rs"COLUMN_NAME");
                    final FieldImpl current = fields.get(columnName);
                    if (current == null)
                    {
                        throw new IllegalStateException("Could not find column '" + columnName + "' in previously parsed query!");
                    }
                    current.setDefaultValue(.parseValue(current.getJdbcType(), parseStringValue(rs"COLUMN_DEF")));
                    current.setNotNull(current.isNotNull() || parseStringValue(rs"IS_NULLABLE").equals("NO"));
                }
            }
            finally
            {
                closeQuietly(rs);
            }
            try
            {
                rs = databaseMetaData.getPrimaryKeys(null.getSchema(), tableName);
                while (rs.next())
                {
                    final String fieldName = parseStringValue(rs"COLUMN_NAME");
                    final FieldImpl field = fields.get(fieldName);
                    field.setPrimaryKey(true);
                    field.setUnique(false); // MSSQL server 2005 tells us that the primary key is a unique key, this isn't what we want, we want real 'added' by hand unique keys.
                }
            }
            finally
            {
                closeQuietly(rs);
            }
            return fields.values();
        }
        catch (SQLException e)
        {
            throw new RuntimeException("Could not read fields for table " + tableNamee);
        }
        finally
        {
            if (rsmd != null)
            {
                rsmd.close();
            }
        }
    }
    @Override
    public Iterable<? extends IndexgetIndexes(DatabaseMetaData databaseMetaDataString tableName)
    {
        ResultSet resultSet = null;
        try
        {
            final List<Indexindexes = newLinkedList();
            resultSet = .getIndexes(databaseMetaData.getConnection(), tableName);
            while (resultSet.next())
            {
                boolean nonUnique = resultSet.getBoolean("NON_UNIQUE");
                if (nonUnique)
                {
                    indexes.add(newIndex(resultSettableName));
                }
            }
            return indexes;
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            closeQuietly(resultSet);
        }
    }
    private Set<StringgetUniqueFields(DatabaseMetaData metaDataString tableName)
    {
        ResultSet rs = null;
        try
        {
            rs = .getIndexes(metaData.getConnection(), tableName);
            final Set<Stringfields = newHashSet();
            while (rs.next())
            {
                boolean nonUnique = rs.getBoolean("NON_UNIQUE");
                if (!nonUnique)
                {
                    fields.add(parseStringValue(rs"COLUMN_NAME"));
                }
            }
            return fields;
        }
        catch (SQLException e)
        {
            throw new RuntimeException("Could not get unique fields for table '" + tableName + "'"e);
        }
        finally
        {
            closeQuietly(rs);
        }
    }
    private List<StringgetSequenceNames(DatabaseMetaData metaData)
    {
        ResultSet rs = null;
        try
        {
            rs = .getSequences(metaData.getConnection());
            final List<StringsequenceNames = newLinkedList();
            while (rs.next())
            {
                sequenceNames.add(.processID(parseStringValue(rs"TABLE_NAME")));
            }
            return sequenceNames;
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            closeQuietly(rs);
        }
    }
    private boolean isAutoIncrement(ResultSetMetaData rsmdint iList<StringsequenceNamesString tableNameString fieldNamethrows SQLException
    {
        boolean autoIncrement = rsmd.isAutoIncrement(i);
        if (!autoIncrement)
        {
            autoIncrement = isUsingSequence(sequenceNamestableNamefieldName);
        }
        return autoIncrement;
    }
    private boolean isUsingSequence(List<StringsequenceNamesString tableNameString fieldName)
    {
        return sequenceNames.contains(.processID(.getSequenceNameConverter().getName(tableNamefieldName)));
    }
    private boolean isUnique(Set<StringuniqueFieldsString fieldNamethrows SQLException
    {
        return uniqueFields.contains(fieldName);
    }
    private FieldImpl newField(String fieldNameTypeInfo<?> databaseTypeint jdbcTypeboolean autoIncrementboolean notNullboolean isUnique)
    {
        return new FieldImpl(fieldNamedatabaseTypejdbcTypeautoIncrementnotNullisUnique);
    }
    private boolean isNotNull(ResultSetMetaData resultSetMetaDataint fieldIndexthrows SQLException
    {
        return resultSetMetaData.isNullable(fieldIndex) == .;
    }
    private TypeQualifiers getTypeQualifiers(ResultSetMetaData rsmdint fieldIndexthrows SQLException
    {
        TypeQualifiers ret = qualifiers();
        if (rsmd.getColumnType(fieldIndex) == .) {
            int length = rsmd.getColumnDisplaySize(fieldIndex);
            if (length > 0) {
                ret = ret.stringLength(length);
            }
        }
        else {
            int precision = rsmd.getPrecision(fieldIndex);
            int scale = rsmd.getScale(fieldIndex);
            if (precision > 0) {
                ret = ret.precision(precision);
            }
            if (scale > 0) {
                ret = ret.scale(scale);
            }
        }
        return ret;
    }
    {
        final Query query = Query.select("*").from(tableName).limit(1);
        final PreparedStatement stmt = metaData.getConnection().prepareStatement(.renderQuery(querynullfalse));
        .setQueryStatementProperties(stmtquery);
        final ResultSet rs = stmt.executeQuery();
        return new AbstractCloseableResultSetMetaData(rs.getMetaData())
        {
            public void close()
            {
                closeQuietly(rs);
                closeQuietly(stmt);
            }
        };
    }
    public Iterable<ForeignKeygetForeignKeys(DatabaseMetaData metaDataString tableName)
    {
        ResultSet resultSet = null;
        try
        {
            final List<ForeignKeykeys = newLinkedList();
            resultSet = getImportedKeys(metaDatatableName);
            while (resultSet.next())
            {
                keys.add(newForeignKey(resultSettableName));
            }
            return keys;
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            closeQuietly(resultSet);
        }
    }
    private ResultSet getImportedKeys(DatabaseMetaData metaDataString tableNamethrows SQLException
    {
        return .getImportedKeys(metaData.getConnection(), tableName);
    }
    private ForeignKey newForeignKey(ResultSet rsString localTableNamethrows SQLException
    {
        final String localFieldName = parseStringValue(rs"FKCOLUMN_NAME");
        final String foreignFieldName = parseStringValue(rs"PKCOLUMN_NAME");
        final String foreignTableName = parseStringValue(rs"PKTABLE_NAME");
        return new ForeignKeyImpl(localTableNamelocalFieldNameforeignTableNameforeignFieldName);
    }
    private Index newIndex(ResultSet rsString tableNamethrows SQLException
    {
        return new IndexImpl(tableNameparseStringValue(rs"COLUMN_NAME"), parseStringValue(rs"INDEX_NAME"));
    }
    private String parseStringValue(ResultSet rsString columnNamethrows SQLException
    {
        final String value = rs.getString(columnName);
        if (StringUtils.isBlank(value))
        {
            return value;
        }
        final Matcher m = .matcher(value);
        return m.find() ? m.group(1) : value;
    }
    private static final class FieldImpl implements Field
    {
        private final String name;
        private final TypeInfo<?> databaseType;
        private final int jdbcType;
        private final boolean autoIncrement;
        private boolean notNull;
        private Object defaultValue;
        private boolean primaryKey;
        private boolean isUnique;
        public FieldImpl(String nameTypeInfo<?> databaseTypeint jdbcTypeboolean autoIncrementboolean notNullboolean isUnique)
        {
            this. = name;
            this. = databaseType;
            this. = jdbcType;
            this. = autoIncrement;
            this. = notNull;
            this. = isUnique;
        }
        @Override
        public String getName()
        {
            return ;
        }
        @Override
        public TypeInfo<?> getDatabaseType()
        {
            return ;
        }
        @Override
        public int getJdbcType()
        {
            return ;
        }
        @Override
        public boolean isAutoIncrement()
        {
            return ;
        }
        @Override
        public boolean isNotNull()
        {
            return ;
        }
        public void setNotNull(boolean notNull)
        {
            this. = notNull;
        }
        @Override
        public Object getDefaultValue()
        {
            return ;
        }
        public void setDefaultValue(Object defaultValue)
        {
            this. = defaultValue;
        }
        @Override
        public boolean isPrimaryKey()
        {
            return ;
        }
        public void setPrimaryKey(boolean primaryKey)
        {
            this. = primaryKey;
        }
        @Override
        public boolean isUnique()
        {
            return ;
        }
        public void setUnique(boolean unique)
        {
             = unique;
        }
    }
    private static final class ForeignKeyImpl implements ForeignKey
    {
        public ForeignKeyImpl(String localTableNameString localFieldNameString foreignTableNameString foreignFieldName)
        {
            this. = localTableName;
            this. = localFieldName;
            this. = foreignTableName;
            this. = foreignFieldName;
        }
        public String getLocalTableName()
        {
            return ;
        }
        public String getLocalFieldName()
        {
            return ;
        }
        public String getForeignTableName()
        {
            return ;
        }
        public String getForeignFieldName()
        {
            return ;
        }
    }
    private static final class IndexImpl implements Index
    {
        private final String tableNamefieldNameindexName;
        public IndexImpl(String tableNameString fieldNameString indexName)
        {
            this. = tableName;
            this. = fieldName;
            this. = indexName;
        }
        public String getTableName()
        {
            return ;
        }
        public String getFieldName()
        {
            return ;
        }
        @Override
        public String getIndexName()
        {
            return ;
        }
    }
New to GrepCode? Check out our FAQ X