Example usage for java.sql ResultSetMetaData getColumnDisplaySize

List of usage examples for java.sql ResultSetMetaData getColumnDisplaySize

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnDisplaySize.

Prototype

int getColumnDisplaySize(int column) throws SQLException;

Source Link

Document

Indicates the designated column's normal maximum width in characters.

Usage

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

/**
 * Validate the Metadata for the result set of a metadata getColumns call.
 *///from  w  ww .  j a  v a  2 s.  co m
public void testMetaDataGetColumnsMetaData() throws SQLException {
    ResultSet rs = con.getMetaData().getColumns(null, null, "testhivejdbcdriver\\_table", null);

    ResultSetMetaData rsmd = rs.getMetaData();

    assertEquals("TABLE_CAT", rsmd.getColumnName(1));
    assertEquals(Types.VARCHAR, rsmd.getColumnType(1));
    assertEquals(Integer.MAX_VALUE, rsmd.getColumnDisplaySize(1));

    assertEquals("ORDINAL_POSITION", rsmd.getColumnName(17));
    assertEquals(Types.INTEGER, rsmd.getColumnType(17));
    assertEquals(11, rsmd.getColumnDisplaySize(17));
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaData(String sql) throws Exception {
    Exception error = null;/* www.  j a v  a  2s  .  c  o m*/

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            String columnType = rsmd.getColumnTypeName(i);
            int columnSqlType = rsmd.getColumnType(i);
            int columnLength = rsmd.getColumnDisplaySize(i);
            int columnPrecision = rsmd.getPrecision(i);

            ColumnVO column = new ColumnVO();
            column.setNameOnTable(columnName);
            column.setType(columnType);
            column.setSqlType(columnSqlType);
            column.setLength(columnLength);
            column.setPrecision(columnPrecision);
            column.setInTable(true);

            tableColumns.add(column);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param correctedSql/*from  www  . j  a v a 2s. c o m*/
 * @param sqlRequest
 * @return
 * @throws Exception
 */
private SQLResponse execute(String correctedSql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    Boolean isPushDown = false;

    List<List<String>> results = Lists.newArrayList();
    List<SelectedColumnMeta> columnMetas = Lists.newArrayList();

    try {
        conn = cacheService.getOLAPDataSource(sqlRequest.getProject()).getConnection();

        // special case for prepare query. 
        if (BackdoorToggles.getPrepareOnly()) {
            return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas);
        }

        stat = conn.createStatement();
        processStatementAttr(stat, sqlRequest);
        resultSet = stat.executeQuery(correctedSql);

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // Fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i),
                    metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i),
                    metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i),
                    metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i),
                    metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i),
                    metaData.isWritable(i), metaData.isDefinitelyWritable(i)));
        }

        // fill in results
        while (resultSet.next()) {
            List<String> oneRow = Lists.newArrayListWithCapacity(columnCount);
            for (int i = 0; i < columnCount; i++) {
                oneRow.add((resultSet.getString(i + 1)));
            }

            results.add(oneRow);
        }
    } catch (SQLException sqlException) {
        isPushDown = PushDownUtil.doPushDownQuery(sqlRequest.getProject(), correctedSql, results, columnMetas,
                sqlException);
    } finally {
        close(resultSet, stat, conn);
    }

    return getSqlResponse(isPushDown, results, columnMetas);
}

From source file:com.netspective.axiom.sql.QueryResultSet.java

public void fillReportFromMetaData(TabularReport report) throws SQLException {
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int numColumns = rsmd.getColumnCount();

    TabularReportColumns columns = report.getColumns();
    columns.clear();/* www . j a v a2  s.  c om*/

    for (int c = 1; c <= numColumns; c++) {
        TabularReportColumn column = null;

        int dataType = rsmd.getColumnType(c);
        switch (dataType) {
        case Types.INTEGER:
        case Types.SMALLINT:
        case Types.BIGINT:
        case Types.TINYINT:
        case Types.BIT:
            column = new NumericColumn();
            break;

        case Types.FLOAT:
        case Types.REAL:
            column = new DecimalColumn();
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
            if (rsmd.getScale(c) > 0)
                column = new DecimalColumn();
            else
                column = new NumericColumn();
            break;

        default:
            column = new GeneralColumn();
            break;
        }

        column.setColIndex(c - 1);
        column.setHeading(new StaticValueSource(
                TextUtils.getInstance().sqlIdentifierToText(rsmd.getColumnLabel(c), true)));
        column.setDataType(dataType);
        column.setWidth(rsmd.getColumnDisplaySize(c));

        columns.add(column);
    }

    report.finalizeContents();
}

From source file:org.geoserver.taskmanager.tasks.CopyTableTaskTypeImpl.java

@Override
public TaskResult run(TaskContext ctx) throws TaskException {
    // TODO: check for ctx.isInterruptMe() in loops and cancel task

    final DbSource sourcedb = (DbSource) ctx.getParameterValues().get(PARAM_SOURCE_DB_NAME);
    final DbSource targetdb = (DbSource) ctx.getParameterValues().get(PARAM_TARGET_DB_NAME);
    final DbTable table = (DbTable) ctx.getBatchContext().get(ctx.getParameterValues().get(PARAM_TABLE_NAME));

    final DbTable targetTable = ctx.getParameterValues().containsKey(PARAM_TARGET_TABLE_NAME)
            ? (DbTable) ctx.getParameterValues().get(PARAM_TARGET_TABLE_NAME)
            : new DbTableImpl(targetdb, table.getTableName());
    final String tempTableName = SqlUtil.qualified(SqlUtil.schema(targetTable.getTableName()),
            "_temp_" + UUID.randomUUID().toString().replace('-', '_'));
    ctx.getBatchContext().put(targetTable, new DbTableImpl(targetdb, tempTableName));

    try (Connection sourceConn = sourcedb.getDataSource().getConnection()) {
        sourceConn.setAutoCommit(false);
        try (Connection destConn = targetdb.getDataSource().getConnection()) {
            try (Statement stmt = sourceConn.createStatement()) {
                stmt.setFetchSize(BATCH_SIZE);
                try (ResultSet rs = stmt
                        .executeQuery("SELECT * FROM " + sourcedb.getDialect().quote(table.getTableName()))) {

                    ResultSetMetaData rsmd = rs.getMetaData();

                    String tempSchema = SqlUtil.schema(tempTableName);
                    String sqlCreateSchemaIfNotExists = tempSchema == null ? ""
                            : targetdb.getDialect().createSchema(destConn,
                                    targetdb.getDialect().quote(tempSchema));

                    // create the temp table structure
                    StringBuilder sb = new StringBuilder(sqlCreateSchemaIfNotExists);
                    sb.append("CREATE TABLE ").append(targetdb.getDialect().quote(tempTableName)).append(" ( ");
                    int columnCount = rsmd.getColumnCount();

                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = targetdb.getDialect().quote(rsmd.getColumnLabel(i));
                        String typeName = rsmd.getColumnTypeName(i);
                        sb.append(columnName).append(" ").append(typeName);
                        if (("char".equals(typeName) || "varchar".equals(typeName))
                                && rsmd.getColumnDisplaySize(i) > 0
                                && rsmd.getColumnDisplaySize(i) < Integer.MAX_VALUE) {
                            sb.append(" (").append(rsmd.getColumnDisplaySize(i)).append(" ) ");
                        }//from   w w w. j  a va 2s . c om
                        switch (sourcedb.getDialect().isNullable(rsmd.isNullable(i))) {
                        case ResultSetMetaData.columnNoNulls:
                            sb.append(" NOT NULL");
                            break;
                        case ResultSetMetaData.columnNullable:
                            sb.append(" NULL");
                            break;
                        }
                        sb.append(", ");
                    }
                    String primaryKey = getPrimaryKey(sourceConn, table.getTableName());
                    boolean hasPrimaryKeyColumn = !primaryKey.isEmpty();
                    if (!hasPrimaryKeyColumn) {
                        // create a Primary key column if none exist.
                        sb.append(GENERATE_ID_COLUMN_NAME + " int PRIMARY KEY, ");
                        columnCount++;
                    }

                    sb.setLength(sb.length() - 2);
                    sb.append(" ); ");

                    // creating indexes
                    Map<String, Set<String>> indexAndColumnMap = getIndexesColumns(sourceConn,
                            table.getTableName());
                    Set<String> uniqueIndexes = getUniqueIndexes(sourceConn, table.getTableName());
                    Set<String> spatialColumns = sourcedb.getDialect().getSpatialColumns(sourceConn,
                            table.getTableName(), sourcedb.getSchema());

                    for (String indexName : indexAndColumnMap.keySet()) {
                        Set<String> columnNames = indexAndColumnMap.get(indexName);
                        boolean isSpatialIndex = columnNames.size() == 1
                                && spatialColumns.contains(columnNames.iterator().next());

                        sb.append(targetdb.getDialect().createIndex(tempTableName, columnNames, isSpatialIndex,
                                uniqueIndexes.contains(indexName)));
                    }
                    // we are copying a view and need to create the spatial index.
                    if (indexAndColumnMap.isEmpty() && !spatialColumns.isEmpty()) {
                        sb.append(
                                targetdb.getDialect().createIndex(tempTableName, spatialColumns, true, false));
                    }

                    String dump = sb.toString();
                    LOGGER.log(Level.FINE, "creating temporary table: " + dump);

                    try (Statement stmt2 = destConn.createStatement()) {
                        stmt2.executeUpdate(dump);
                    }

                    // copy the data
                    sb = new StringBuilder("INSERT INTO ").append(targetdb.getDialect().quote(tempTableName))
                            .append(" VALUES (");
                    for (int i = 0; i < columnCount; i++) {
                        if (i > 0) {
                            sb.append(",");
                        }
                        sb.append("?");
                    }
                    sb.append(")");

                    LOGGER.log(Level.FINE, "inserting records: " + sb.toString());

                    try (PreparedStatement pstmt = destConn.prepareStatement(sb.toString())) {
                        int batchSize = 0;
                        int primaryKeyValue = 0;
                        while (rs.next()) {
                            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                                pstmt.setObject(i, rs.getObject(i));
                            }
                            // generate the primary key value
                            if (!hasPrimaryKeyColumn) {
                                pstmt.setObject(columnCount, primaryKeyValue);
                            }
                            pstmt.addBatch();
                            batchSize++;
                            if (batchSize >= BATCH_SIZE) {
                                pstmt.executeBatch();
                                batchSize = 0;
                            }
                            primaryKeyValue++;
                        }
                        if (batchSize > 0) {
                            pstmt.executeBatch();
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        // clean-up if necessary
        try (Connection conn = targetdb.getDataSource().getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate("DROP TABLE IF EXISTS " + targetdb.getDialect().quote(tempTableName));
            }
        } catch (SQLException e2) {
        }

        throw new TaskException(e);
    }

    return new TaskResult() {
        @Override
        public void commit() throws TaskException {
            try (Connection conn = targetdb.getDataSource().getConnection()) {
                try (Statement stmt = conn.createStatement()) {
                    stmt.executeUpdate(
                            "DROP TABLE IF EXISTS " + targetdb.getDialect().quote(targetTable.getTableName()));
                    stmt.executeUpdate("ALTER TABLE " + targetdb.getDialect().quote(tempTableName)
                            + " RENAME TO "
                            + targetdb.getDialect().quote(SqlUtil.notQualified(targetTable.getTableName())));
                }

                ctx.getBatchContext().delete(targetTable);
            } catch (SQLException e) {
                throw new TaskException(e);
            }
        }

        @Override
        public void rollback() throws TaskException {
            try (Connection conn = targetdb.getDataSource().getConnection()) {
                try (Statement stmt = conn.createStatement()) {
                    stmt.executeUpdate("DROP TABLE " + targetdb.getDialect().quote(tempTableName) + "");
                }
            } catch (SQLException e) {
                throw new TaskException(e);
            }
        }
    };
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java

/**
 * No longer used./*www.ja va 2s  .c  o  m*/
 *
 * @param rsmd
 * @param metaData
 * @param column
 */
@Deprecated
public static void updateMetaData(final ResultSetMetaData rsmd, final DefaultTableMetaData metaData,
        final int column) {
    try {
        if (rsmd.isCurrency(column + 1)) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                    MetaAttributeNames.Numeric.CURRENCY, Boolean.TRUE);
        } else {
            metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                    MetaAttributeNames.Numeric.CURRENCY, Boolean.FALSE);
        }

        if (rsmd.isSigned(column + 1)) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                    MetaAttributeNames.Numeric.SIGNED, Boolean.TRUE);
        } else {
            metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                    MetaAttributeNames.Numeric.SIGNED, Boolean.FALSE);
        }

        final String tableName = rsmd.getTableName(column + 1);
        if (tableName != null) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE,
                    MetaAttributeNames.Database.TABLE, tableName);
        }
        final String schemaName = rsmd.getSchemaName(column + 1);
        if (schemaName != null) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE,
                    MetaAttributeNames.Database.SCHEMA, schemaName);
        }
        final String catalogName = rsmd.getCatalogName(column + 1);
        if (catalogName != null) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Database.NAMESPACE,
                    MetaAttributeNames.Database.CATALOG, catalogName);
        }
        final String label = rsmd.getColumnLabel(column + 1);
        if (label != null) {
            metaData.setColumnAttribute(column, MetaAttributeNames.Formatting.NAMESPACE,
                    MetaAttributeNames.Formatting.LABEL, label);
        }
        final int displaySize = rsmd.getColumnDisplaySize(column + 1);
        metaData.setColumnAttribute(column, MetaAttributeNames.Formatting.NAMESPACE,
                MetaAttributeNames.Formatting.DISPLAY_SIZE, IntegerCache.getInteger(displaySize));

        final int precision = rsmd.getPrecision(column + 1);
        metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                MetaAttributeNames.Numeric.PRECISION, IntegerCache.getInteger(precision));
        final int scale = rsmd.getScale(column + 1);
        metaData.setColumnAttribute(column, MetaAttributeNames.Numeric.NAMESPACE,
                MetaAttributeNames.Numeric.SCALE, IntegerCache.getInteger(scale));
    } catch (SQLException sqle) {
        // It is non-fatal if the meta-data cannot be read from the result set. Drivers are
        // buggy all the time ..
    }
}

From source file:DbMetaServlet.java

private void printMeta(ResultSetMetaData metaData, String type, java.io.PrintWriter out, int colCount)
        throws SQLException {

    if (metaData == null || type == null || out == null)
        throw new IllegalArgumentException("Illegal args passed to printMeta()");

    out.println("<tr>");

    if (type.equals("table")) {

        out.println("<td><strong>Table name</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getTableName(i) + "</td>");
        }//w w w  . java  2  s. c o m

    } else if (type.equals("name")) {

        out.println("<td><strong>Column name</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnName(i) + "</td>");
        }

    } else if (type.equals("index")) {

        out.println("<td><strong>Column index</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + i + "</td>");
        }

    } else if (type.equals("column type")) {

        out.println("<td><strong>Column type</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnTypeName(i) + "</td>");
        }

    } else if (type.equals("column display")) {

        out.println("<td><strong>Column display size</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnDisplaySize(i) + "</td>");
        }
    }

    out.println("</tr>");

}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaDataExceptGeom(String sql, String geometryName) throws Exception {
    Exception error = null;// ww  w . j a  va 2 s  .  c  o m

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        String geometryFieldName = geometryName;
        if (StringUtils.isEmpty(geometryFieldName)) {
            geometryFieldName = "the_geom";
        }
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            if (!columnName.equals(geometryFieldName)) {
                String columnType = rsmd.getColumnTypeName(i);
                int columnSqlType = rsmd.getColumnType(i);
                int columnLength = rsmd.getColumnDisplaySize(i);
                int columnPrecision = rsmd.getPrecision(i);

                ColumnVO column = new ColumnVO();
                column.setNameOnTable(columnName);
                column.setType(columnType);
                column.setSqlType(columnSqlType);
                column.setLength(columnLength);
                column.setPrecision(columnPrecision);
                column.setInTable(true);

                tableColumns.add(column);
            }

        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

public void testResultSetMetaData() throws SQLException {
    Statement stmt = con.createStatement();

    ResultSet res = stmt.executeQuery("select c1, c2, c3, c4, c5 as a, c6, c7, c8, c9, c10, c11, c12, "
            + "c1*2, sentences(null, null, null) as b, c17, c18, c20 from " + dataTypeTableName + " limit 1");
    ResultSetMetaData meta = res.getMetaData();

    ResultSet colRS = con.getMetaData().getColumns(null, null, dataTypeTableName.toLowerCase(), null);

    assertEquals(17, meta.getColumnCount());

    assertTrue(colRS.next());//from  ww w. ja  va2 s . c o m

    assertEquals("c1", meta.getColumnName(1));
    assertEquals(Types.INTEGER, meta.getColumnType(1));
    assertEquals("int", meta.getColumnTypeName(1));
    assertEquals(11, meta.getColumnDisplaySize(1));
    assertEquals(10, meta.getPrecision(1));
    assertEquals(0, meta.getScale(1));

    assertEquals("c1", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.INTEGER, colRS.getInt("DATA_TYPE"));
    assertEquals("int", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(1), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(1), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c2", meta.getColumnName(2));
    assertEquals("boolean", meta.getColumnTypeName(2));
    assertEquals(Types.BOOLEAN, meta.getColumnType(2));
    assertEquals(1, meta.getColumnDisplaySize(2));
    assertEquals(1, meta.getPrecision(2));
    assertEquals(0, meta.getScale(2));

    assertEquals("c2", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.BOOLEAN, colRS.getInt("DATA_TYPE"));
    assertEquals("boolean", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(2), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(2), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c3", meta.getColumnName(3));
    assertEquals(Types.DOUBLE, meta.getColumnType(3));
    assertEquals("double", meta.getColumnTypeName(3));
    assertEquals(25, meta.getColumnDisplaySize(3));
    assertEquals(15, meta.getPrecision(3));
    assertEquals(15, meta.getScale(3));

    assertEquals("c3", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.DOUBLE, colRS.getInt("DATA_TYPE"));
    assertEquals("double", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(3), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(3), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c4", meta.getColumnName(4));
    assertEquals(Types.VARCHAR, meta.getColumnType(4));
    assertEquals("string", meta.getColumnTypeName(4));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(4));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(4));
    assertEquals(0, meta.getScale(4));

    assertEquals("c4", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("string", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(4), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(4), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("a", meta.getColumnName(5));
    assertEquals(Types.VARCHAR, meta.getColumnType(5));
    assertEquals("string", meta.getColumnTypeName(5));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(5));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(5));
    assertEquals(0, meta.getScale(5));

    assertEquals("c5", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("array<int>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(5), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(5), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c6", meta.getColumnName(6));
    assertEquals(Types.VARCHAR, meta.getColumnType(6));
    assertEquals("string", meta.getColumnTypeName(6));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(6));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(6));
    assertEquals(0, meta.getScale(6));

    assertEquals("c6", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("map<int,string>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(6), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(6), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c7", meta.getColumnName(7));
    assertEquals(Types.VARCHAR, meta.getColumnType(7));
    assertEquals("string", meta.getColumnTypeName(7));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(7));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(7));
    assertEquals(0, meta.getScale(7));

    assertEquals("c7", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("map<string,string>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(7), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(7), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c8", meta.getColumnName(8));
    assertEquals(Types.VARCHAR, meta.getColumnType(8));
    assertEquals("string", meta.getColumnTypeName(8));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(8));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(8));
    assertEquals(0, meta.getScale(8));

    assertEquals("c8", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("struct<r:string,s:int,t:double>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(8), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(8), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c9", meta.getColumnName(9));
    assertEquals(Types.TINYINT, meta.getColumnType(9));
    assertEquals("tinyint", meta.getColumnTypeName(9));
    assertEquals(4, meta.getColumnDisplaySize(9));
    assertEquals(3, meta.getPrecision(9));
    assertEquals(0, meta.getScale(9));

    assertEquals("c9", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.TINYINT, colRS.getInt("DATA_TYPE"));
    assertEquals("tinyint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(9), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(9), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c10", meta.getColumnName(10));
    assertEquals(Types.SMALLINT, meta.getColumnType(10));
    assertEquals("smallint", meta.getColumnTypeName(10));
    assertEquals(6, meta.getColumnDisplaySize(10));
    assertEquals(5, meta.getPrecision(10));
    assertEquals(0, meta.getScale(10));

    assertEquals("c10", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.SMALLINT, colRS.getInt("DATA_TYPE"));
    assertEquals("smallint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(10), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(10), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c11", meta.getColumnName(11));
    assertEquals(Types.FLOAT, meta.getColumnType(11));
    assertEquals("float", meta.getColumnTypeName(11));
    assertEquals(24, meta.getColumnDisplaySize(11));
    assertEquals(7, meta.getPrecision(11));
    assertEquals(7, meta.getScale(11));

    assertEquals("c11", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.FLOAT, colRS.getInt("DATA_TYPE"));
    assertEquals("float", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(11), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(11), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c12", meta.getColumnName(12));
    assertEquals(Types.BIGINT, meta.getColumnType(12));
    assertEquals("bigint", meta.getColumnTypeName(12));
    assertEquals(20, meta.getColumnDisplaySize(12));
    assertEquals(19, meta.getPrecision(12));
    assertEquals(0, meta.getScale(12));

    assertEquals("c12", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.BIGINT, colRS.getInt("DATA_TYPE"));
    assertEquals("bigint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(12), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(12), colRS.getInt("DECIMAL_DIGITS"));

    assertEquals("_c12", meta.getColumnName(13));
    assertEquals(Types.INTEGER, meta.getColumnType(13));
    assertEquals("int", meta.getColumnTypeName(13));
    assertEquals(11, meta.getColumnDisplaySize(13));
    assertEquals(10, meta.getPrecision(13));
    assertEquals(0, meta.getScale(13));

    assertEquals("b", meta.getColumnName(14));
    assertEquals(Types.VARCHAR, meta.getColumnType(14));
    assertEquals("string", meta.getColumnTypeName(14));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(14));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(14));
    assertEquals(0, meta.getScale(14));

    assertEquals("c17", meta.getColumnName(15));
    assertEquals(Types.TIMESTAMP, meta.getColumnType(15));
    assertEquals("timestamp", meta.getColumnTypeName(15));
    assertEquals(29, meta.getColumnDisplaySize(15));
    assertEquals(29, meta.getPrecision(15));
    assertEquals(9, meta.getScale(15));

    assertEquals("c18", meta.getColumnName(16));
    assertEquals(Types.DECIMAL, meta.getColumnType(16));
    assertEquals("decimal", meta.getColumnTypeName(16));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(16));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(16));
    assertEquals(Integer.MAX_VALUE, meta.getScale(16));

    assertEquals("c20", meta.getColumnName(17));
    assertEquals(Types.DATE, meta.getColumnType(17));
    assertEquals("date", meta.getColumnTypeName(17));
    assertEquals(10, meta.getColumnDisplaySize(17));
    assertEquals(10, meta.getPrecision(17));
    assertEquals(0, meta.getScale(17));

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        assertFalse(meta.isAutoIncrement(i));
        assertFalse(meta.isCurrency(i));
        assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(i));
    }
}

From source file:org.seasar.dbflute.logic.sql2entity.cmentity.DfCustomizeEntityMetaExtractor.java

public Map<String, DfColumnMeta> extractColumnMetaInfoMap(ResultSet rs, String sql,
        DfForcedJavaNativeProvider forcedJavaNativeProvider) throws SQLException {
    final Map<String, DfColumnMeta> columnMetaInfoMap = StringKeyMap.createAsFlexibleOrdered();
    final ResultSetMetaData md = rs.getMetaData();
    for (int i = 1; i <= md.getColumnCount(); i++) {
        final DfColumnMeta metaInfo = new DfColumnMeta();

        String sql2EntityRelatedTableName = null;
        try {/*from w  w  w  .j a v a  2  s.  c  o m*/
            sql2EntityRelatedTableName = md.getTableName(i);
        } catch (SQLException ignored) {
            // Because this table name is not required. This is for classification.
            String msg = "ResultSetMetaData.getTableName(" + i + ") threw the exception:";
            msg = msg + " " + ignored.getMessage();
            _log.info(msg);
        }
        metaInfo.setSql2EntityRelatedTableName(sql2EntityRelatedTableName);

        String columnName = md.getColumnLabel(i);
        final String relatedColumnName = md.getColumnName(i);
        metaInfo.setSql2EntityRelatedColumnName(relatedColumnName);
        if (columnName == null || columnName.trim().length() == 0) {
            columnName = relatedColumnName;
        }
        if (columnName == null || columnName.trim().length() == 0) {
            final String ln = ln();
            String msg = "The columnName is invalid: columnName=" + columnName + ln;
            msg = msg + "ResultSetMetaData returned invalid value." + ln;
            msg = msg + "sql=" + sql;
            throw new IllegalStateException(msg);
        }
        metaInfo.setColumnName(columnName);

        final int columnType = md.getColumnType(i);
        metaInfo.setJdbcDefValue(columnType);

        final String columnTypeName = md.getColumnTypeName(i);
        metaInfo.setDbTypeName(columnTypeName);

        int columnSize = md.getPrecision(i);
        if (!DfColumnExtractor.isColumnSizeValid(columnSize)) {
            // ex) sum(COLUMN)
            columnSize = md.getColumnDisplaySize(i);
        }
        metaInfo.setColumnSize(columnSize);

        final int scale = md.getScale(i);
        metaInfo.setDecimalDigits(scale);

        if (forcedJavaNativeProvider != null) {
            final String sql2entityForcedJavaNative = forcedJavaNativeProvider.provide(columnName);
            metaInfo.setSql2EntityForcedJavaNative(sql2entityForcedJavaNative);
        }

        // column comment is not set here (no comment on meta data)
        // if select column comment is specified, comment will be set later

        columnMetaInfoMap.put(columnName, metaInfo);
    }
    return columnMetaInfoMap;
}