Java Code Examples for java.sql.ResultSetMetaData#getPrecision()

The following examples show how to use java.sql.ResultSetMetaData#getPrecision() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateTableTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public ColumnMetaData[] getColumnMetaData(Statement stmt, String query)
    throws SQLException {
  ResultSet rs1 = stmt.executeQuery(query);
  assertTrue(rs1.next());
  
  ResultSetMetaData rsm = rs1.getMetaData();
  int columnCount = rsm.getColumnCount();

  ColumnMetaData[] columnMetaData = new ColumnMetaData[columnCount];
  for (int i = 1; i <= columnCount; i++) {
    int columnDisplaySize = rsm.getColumnDisplaySize(i);
    String columnName = rsm.getColumnName(i);
    int columnType = rsm.getColumnType(i);
    int precision = rsm.getPrecision(i);
    int scale = rsm.getScale(i);
    int isNullable = rsm.isNullable(i);

    columnMetaData[i - 1] = new ColumnMetaData(columnDisplaySize,
        columnName, columnType, precision, scale, isNullable);
  }
  rs1.close();
  return columnMetaData;
}
 
Example 2
Source File: CreateTableTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public ColumnMetaData[] getColumnMetaData(Statement stmt, String query)
    throws SQLException {
  ResultSet rs1 = stmt.executeQuery(query);
  assertTrue(rs1.next());
  
  ResultSetMetaData rsm = rs1.getMetaData();
  int columnCount = rsm.getColumnCount();

  ColumnMetaData[] columnMetaData = new ColumnMetaData[columnCount];
  for (int i = 1; i <= columnCount; i++) {
    int columnDisplaySize = rsm.getColumnDisplaySize(i);
    String columnName = rsm.getColumnName(i);
    int columnType = rsm.getColumnType(i);
    int precision = rsm.getPrecision(i);
    int scale = rsm.getScale(i);
    int isNullable = rsm.isNullable(i);

    columnMetaData[i - 1] = new ColumnMetaData(columnDisplaySize,
        columnName, columnType, precision, scale, isNullable);
  }
  rs1.close();
  return columnMetaData;
}
 
Example 3
Source File: SqlArgs.java    From database with Apache License 2.0 6 votes vote down vote up
public Builder(Row r) {
  try {
    ResultSetMetaData metadata = r.getMetadata();
    int columnCount = metadata.getColumnCount();
    names = new String[columnCount];
    types = new int[columnCount];
    precision = new int[columnCount];
    scale = new int[columnCount];

    for (int i = 0; i < columnCount; i++) {
      names[i] = metadata.getColumnLabel(i + 1);
      types[i] = metadata.getColumnType(i + 1);
      precision[i] = metadata.getPrecision(i + 1);
      scale[i] = metadata.getScale(i + 1);
    }

    names = tidyColumnNames(names);
  } catch (SQLException e) {
    throw new DatabaseException("Unable to retrieve metadata from ResultSet", e);
  }
}
 
Example 4
Source File: DbConn.java    From jqm with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> runSelectSingleRow(String query_key, Object... params)
{
    HashMap<String, Object> res = new HashMap<>();
    try (ResultSet rs = runSelect(query_key, params))
    {
        if (!rs.next())
        {
            throw new NoResultException("The query returned zero rows when one was expected.");
        }
        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= meta.getColumnCount(); i++)
        {
            // We take the type as returned, with an exception for small numerics (we do not want long or BigInt which cannot be cast)
            Object or;
            if (meta.getColumnType(i) == java.sql.Types.NUMERIC && meta.getPrecision(i) <= 10)
            {
                or = rs.getInt(i);
            }
            else
            {
                or = rs.getObject(i);
            }
            res.put(meta.getColumnName(i).toUpperCase(), or);
        }

        if (rs.next())
        {
            throw new NonUniqueResultException("The query returned more than one row when one was expected");
        }
    }
    catch (SQLException e)
    {
        throw new DatabaseException(e);
    }
    return res;
}
 
Example 5
Source File: JdbcDebugUtil.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
private static Object getColumnValue( ResultSet resultSet, ResultSetMetaData meta, int col ) throws SQLException {
    int type = meta.getColumnType(col);
    switch( type ) {
        case Types.BIT:
                        return new Boolean(resultSet.getBoolean(col));
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
                        return resultSet.getString(col);
        case Types.TINYINT:
        case Types.SMALLINT:
                        return new Short(resultSet.getShort(col));
        case Types.INTEGER:
                        return new Integer(resultSet.getInt(col));
        case Types.BIGINT:
                        return new Long(resultSet.getLong(col));
        case Types.NUMERIC:
                        if( meta.getScale(col)>0 ) {
                            return new Double(resultSet.getDouble(col));
                        }
                        if( meta.getPrecision(col)>=9 ) {
                            return new Long(resultSet.getLong(col));
                        }
                        return new Integer(resultSet.getInt(col));
        case Types.FLOAT:
                        return new Float(resultSet.getFloat(col));
        case Types.DOUBLE:
        case Types.REAL:
        case Types.DECIMAL:
                        return new Double(resultSet.getDouble(col));
    }
    throw new SQLException( StringUtil.format("Data type not yet handled ({0})", StringUtil.toString(type)) ); // $NLX-JdbcDebugUtil.Datatypenotyethandled0-1$
}
 
Example 6
Source File: Inspector.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public List<ColumnDef> describeSelectStatement(String sqlQuery) {
	List<ColumnDef> result = new ArrayList<ColumnDef>();
	try {
		PreparedStatement stmt = connection.prepareStatement(sqlQuery);
		try {
			ResultSetMetaData meta = stmt.getMetaData();
			for (int i = 1; i <= meta.getColumnCount(); i++) {
				String name = meta.getColumnLabel(i);
				int type = meta.getColumnType(i);
				String typeName = meta.getColumnTypeName(i);
				int size = meta.getPrecision(i);
				DataType dataType = vendor.getDataType(type, typeName, size);
				if (dataType == null) {
					log.warn("Unknown datatype '" + 
							(size == 0 ? typeName : (typeName + "(" + size + ")")) + 
							"' (" + type + ")");
				}
				boolean isNullable = meta.isNullable(i) != ResultSetMetaData.columnNoNulls;
				result.add(new ColumnDef(
						Identifier.createDelimited(name), dataType, isNullable));
			}
			return result;
		} finally {
			stmt.close();
		}
	} catch (SQLException ex) {
		throw new D2RQException(ex, D2RQException.D2RQ_SQLEXCEPTION);
	}
}
 
Example 7
Source File: SchemaInferer.java    From components with Apache License 2.0 5 votes vote down vote up
public static Schema infer(ResultSetMetaData metadata, Dbms mapping, boolean enableSpecialTableName) throws SQLException {
    List<Field> fields = new ArrayList<>();

    Set<String> existNames = new HashSet<String>();
    int index = 0;
    
    int count = metadata.getColumnCount();
    for (int i = 1; i <= count; i++) {
        int size = metadata.getPrecision(i);
        int scale = metadata.getScale(i);
        boolean nullable = ResultSetMetaData.columnNullable == metadata.isNullable(i);

        int dbtype = metadata.getColumnType(i);
        String fieldName = metadata.getColumnLabel(i);
        String dbColumnName = metadata.getColumnName(i);

        // not necessary for the result schema from the query statement
        boolean isKey = false;

        String columnTypeName = metadata.getColumnTypeName(i).toUpperCase();

        String validName = NameUtil.correct(fieldName, index++, existNames);
        existNames.add(validName);
        
        Field field = sqlType2Avro(size, scale, dbtype, nullable, validName, dbColumnName, null, isKey, mapping,
                columnTypeName);
        if(enableSpecialTableName && !validName.equals(dbColumnName)){
            field.addProp(ENABLE_SPECIAL_TABLENAME,"true");
        }
        fields.add(field);
    }

    return Schema.createRecord("DYNAMIC", null, null, false, fields);
}
 
Example 8
Source File: PreparedStatementTest.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static String toString(ResultSetMetaData metadata, int colNum) throws SQLException {
  return "ResultSetMetaData(" + colNum + ")[" +
      "columnName='" + metadata.getColumnName(colNum) + '\'' +
      ", type='" + metadata.getColumnType(colNum) + '\'' +
      ", nullable=" + metadata.isNullable(colNum) +
      ", displaySize=" + metadata.getColumnDisplaySize(colNum) +
      ", precision=" + metadata.getPrecision(colNum) +
      ", scale=" + metadata.getScale(colNum) +
      ", signed=" + metadata.isSigned(colNum) +
      ", className='" + metadata.getColumnClassName(colNum) + '\'' +
      ']';
}
 
Example 9
Source File: SQLRenderer.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
/**
 * Return a description of how to format a column.
 * 
 * @param meta The metadata for a result set
 * @param idx The index of the of column to fetch in the result set
 * @return A description of how to format that column
 * @throws SQLException
 */
public ColumnDescription getDescription(ResultSetMetaData meta, int idx)
    throws SQLException {
    
    int type = meta.getColumnType(idx);
    int precision = 0;
    int scale = 0;
    
    switch (type) {
    
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.NVARCHAR:
        case Types.LONGNVARCHAR:
        case Types.LONGVARCHAR:
        case Types.NCHAR:
            precision = meta.getColumnDisplaySize(idx);
            break;
            
        case Types.DECIMAL:
        case Types.NUMERIC:
            precision = meta.getPrecision(idx);
            scale = meta.getScale(idx);
            break;
            
        default:
            break;
    }
    
    return getDescription(
        meta.getColumnLabel(idx),
        type,
        precision,
        scale);
}
 
Example 10
Source File: ClickHouseRowSerializer.java    From clickhouse-jdbc-bridge with Apache License 2.0 5 votes vote down vote up
public static ClickHouseRowSerializer create(ResultSetMetaData meta) throws SQLException {

        ClickHouseRowSerializer serializer = new ClickHouseRowSerializer();
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            int precision = meta.getPrecision(i);
            int scale = meta.getScale(i);
            ExtractorConverter<?> ser = ClickHouseConverter.getSerializerBySQLType(meta.getColumnType(i), precision, scale);
            boolean isNullable = meta.isNullable(i) == ResultSetMetaData.columnNullable;
            ClickHouseFieldSerializer<?> fieldSerializer = new ClickHouseFieldSerializer<>(isNullable, ser);
            serializer.add(fieldSerializer);
        }
        return serializer;
    }
 
Example 11
Source File: JDBCAvroRegistryString.java    From components with Apache License 2.0 5 votes vote down vote up
protected Schema inferSchemaResultSetMetaData(ResultSetMetaData metadata) throws SQLException {
    List<Field> fields = new ArrayList<>();

    Set<String> existNames = new HashSet<String>();
    int index = 0;
    
    int count = metadata.getColumnCount();
    for (int i = 1; i <= count; i++) {
        int size = metadata.getPrecision(i);
        int scale = metadata.getScale(i);
        boolean nullable = ResultSetMetaData.columnNullable == metadata.isNullable(i);

        int dbtype = metadata.getColumnType(i);
        String fieldName = metadata.getColumnLabel(i);
        String dbColumnName = metadata.getColumnName(i);

        // not necessary for the result schema from the query statement
        boolean isKey = false;

        String validName = NameUtil.correct(fieldName, index++, existNames);
        existNames.add(validName);
        
        Field field = sqlType2Avro(size, scale, dbtype, nullable, validName, dbColumnName, null, isKey);

        fields.add(field);
    }
    return Schema.createRecord("DYNAMIC", null, null, false, fields);
}
 
Example 12
Source File: ResultSetMetaDataHolder.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public ResultSetMetaDataHolder(ResultSetMetaData m, int i) throws SQLException {
       String catalogName = m.getCatalogName(i);
       String columnClassName = m.getColumnClassName(i);
       int columnDisplaySize = m.getColumnDisplaySize(i);
       String columnLabel = m.getColumnLabel(i);
       String columnName = m.getColumnName(i);
       
       int columnType = m.getColumnType(i);
       String columnTypeName = m.getColumnTypeName(i);
       int precision = m.getPrecision(i);
       int scale = m.getScale(i);
       
       String schemaName = m.getSchemaName(i);
       String tableName = m.getTableName(i);
       
       this.catalogName = catalogName;
       this.columnClassName = columnClassName ;
       this.columnDisplaySize = columnDisplaySize;
       this.columnLabel = columnLabel;
       this.columnName = columnName;
       this.columnType=  columnType;
       this.columnTypeName = columnTypeName;
       this.precision  = precision;
       this.scale = scale;
       this.schemaName = schemaName;
       this.tableName = tableName;    		
}
 
Example 13
Source File: JdbcExplorer.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public ColumnDesc[] evalQueryMetadata(String query) {
    if (StringUtils.isEmpty(query)) {
        throw new RuntimeException("Evaluate query shall not be empty.");
    }

    try (Connection conn = dataSource.getConnection();
        Statement state = conn.createStatement();
        ResultSet rs = state.executeQuery(dataSource.convertSql(query))) {
        ResultSetMetaData rsMeta = rs.getMetaData();
        ColumnDesc[] columnDescs = new ColumnDesc[rsMeta.getColumnCount()];
        for (int i = 0; i < columnDescs.length; i++) {
            columnDescs[i] = new ColumnDesc();
            columnDescs[i].setName(rsMeta.getColumnName(i + 1).toUpperCase(Locale.ROOT));

            String kylinType = dataSource.toKylinTypeName(rsMeta.getColumnType(i + 1));
            int precision = (SqlUtil.isPrecisionApplicable(kylinType) && rsMeta.getPrecision(i + 1) > 0)
                    ? rsMeta.getPrecision(i + 1)
                    : -1;
            int scale = (SqlUtil.isScaleApplicable(kylinType) && rsMeta.getScale(i + 1) > 0)
                    ? rsMeta.getScale(i + 1)
                    : -1;

            columnDescs[i].setDatatype(new DataType(kylinType, precision, scale).toString());
            columnDescs[i].setId(String.valueOf(i + 1));
        }
        return columnDescs;
    } catch (Exception e) {
        throw new RuntimeException("Cannot evaluate metadata of query: " + query, e);
    }
}
 
Example 14
Source File: StorageManager.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
public DataField[] tableToStructureByString(String tableName,
		Connection connection) throws SQLException {
	StringBuilder sb = new StringBuilder("select * from ").append(tableName)
			.append(" where 1=0 ");
	ResultSet rs = null;
	DataField[] toReturn = null;
	try {
		rs = executeQueryWithResultSet(sb, connection);
		ResultSetMetaData structure = rs.getMetaData();
		ArrayList<DataField> toReturnArr = new ArrayList<DataField>();
		for (int i = 1; i <= structure.getColumnCount(); i++) {
			String colName = structure.getColumnLabel(i);
			if (colName.equalsIgnoreCase("pk"))
				continue;
			if (colName.equalsIgnoreCase("timed"))
				continue;
			int colType = structure.getColumnType(i);
			String colTypeName = structure.getColumnTypeName(i);
			int precision = structure.getPrecision(i);
			byte colTypeInGSN = convertLocalTypeToGSN(colType);
			if ((colTypeInGSN == DataTypes.VARCHAR)
					|| (colTypeInGSN == DataTypes.CHAR))
				toReturnArr.add(new DataField(colName, colTypeName, precision,
						colName));
			else
				toReturnArr.add(new DataField(colName, colTypeInGSN));
		}
		toReturn = toReturnArr.toArray(new DataField[] {});
	}
	finally {
		if (rs != null)
			close(rs);
	}
	return toReturn;
}
 
Example 15
Source File: DBView.java    From ralasafe with MIT License 4 votes vote down vote up
private static TableView getTable(Connection conn, String dsName,
		String schema, String tableName) throws SQLException {
	String mySchema = "";
	if (!StringUtil.isEmpty(schema)) {
		mySchema = schema + ".";
	}

	if( log.isDebugEnabled() ) {
		log.debug( "Get table/view definition: dsName=" + dsName 
				+ ", table/view Name=" + mySchema+tableName );
	}
	
	Statement stmt = null;
	ResultSet rs = null;
	ResultSet primaryKeys = null;

	try {
		stmt = conn.createStatement();

		rs = stmt.executeQuery("select * from " + mySchema + tableName
				+ " where 1=2");
		ResultSetMetaData metaData = rs.getMetaData();

		TableView table = new TableView();
		table.setSchema(schema);
		table.setName(tableName);

		DatabaseMetaData metaData2 = conn.getMetaData();
		String databaseProductName = DBUtil.getDatabaseProductName(conn);

		if (databaseProductName == DBUtil.MYSQL) {
			primaryKeys = metaData2.getPrimaryKeys(schema, null, tableName);
		} else {
			primaryKeys = metaData2.getPrimaryKeys(null, null, tableName);
		}

		Map pkColumnViewMap = new HashMap();
		while (primaryKeys.next()) {
			pkColumnViewMap.put(primaryKeys.getString("COLUMN_NAME"), null);
		}

		List columnList = new ArrayList(metaData.getColumnCount());
		for (int i = 1, columnCount = metaData.getColumnCount(); i <= columnCount; i++) {
			ColumnView column = new ColumnView();
			String columnName = metaData.getColumnName(i);
			column.setName(columnName);
			String sqlType = metaData.getColumnTypeName(i);

			if (sqlType.equalsIgnoreCase("blob")
					|| sqlType.equalsIgnoreCase("clob")
					|| sqlType.equalsIgnoreCase("text")) {
				// DO NOTHING
			} else {
				int precision = metaData.getPrecision(i);
				int scale = metaData.getScale(i);

				if (precision != 0) {
					if (scale == 0) {
						sqlType = sqlType + "(" + precision + ")";
					} else {
						sqlType = sqlType + "(" + precision + "," + scale
								+ ")";
					}
				}
			}
			column.setSqlType(sqlType);
			columnList.add(column);

			// it's a primary key?
			if (pkColumnViewMap.containsKey(columnName)) {
				pkColumnViewMap.put(columnName, column);
			}
		}

		table.setColumnViews(columnList);

		// sometimes, oracle jdbc driver returns pk info is redundance, 
		// actually the column does exist at all.  Clear them.
		clearInvalidPK(pkColumnViewMap);
		
		if (pkColumnViewMap.size() > 0) {
			table.setPkColumnViews(pkColumnViewMap.values());
		}
		return table;
	} finally {
		DBUtil.close(primaryKeys);
		DBUtil.close(rs);
		DBUtil.close(stmt);
	}
}
 
Example 16
Source File: DriverTest.java    From Kylin with Apache License 2.0 4 votes vote down vote up
@Ignore("not maintaining")
@Test
public void testWithCubeData() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    Driver driver = (Driver) Class.forName("org.apache.kylin.kylin.jdbc.Driver").newInstance();
    Properties info = new Properties();
    info.put("user", "");
    info.put("password", "");
    Connection conn = driver.connect("jdbc:kylin://localhost/default", info);

    ResultSet catalogs = conn.getMetaData().getCatalogs();
    while (catalogs.next()) {
        System.out.println(catalogs.getString("TABLE_CAT"));
    }

    ResultSet schemas = conn.getMetaData().getSchemas();
    while (schemas.next()) {
        System.out.println(schemas.getString(1));
        System.out.println(schemas.getString(2));
    }

    ResultSet tables = conn.getMetaData().getTables(null, null, null, null);
    while (tables.next()) {
        String tableName = tables.getString(3);
        assertEquals(tables.getString("TABLE_NAME"), tableName);
        ResultSet columns = conn.getMetaData().getColumns(null, null, tableName, null);

        while (columns.next()) {
            System.out.println(columns.getString("COLUMN_NAME"));
            String column = "";
            for (int i = 0; i < 23; i++) {
                column += columns.getString(i + 1) + ", ";
            }

            System.out.println("Column in table " + tableName + ": " + column);
        }
    }

    for (int j = 0; j < 3; j++) {
        Statement state = conn.createStatement();
        ResultSet resultSet = state.executeQuery("select * from test_kylin_fact");

        ResultSetMetaData metadata = resultSet.getMetaData();
        System.out.println("Metadata:");

        for (int i = 0; i < metadata.getColumnCount(); i++) {
            String metaStr = metadata.getCatalogName(i + 1) + " " + metadata.getColumnClassName(i + 1) + " " + metadata.getColumnDisplaySize(i + 1) + " " + metadata.getColumnLabel(i + 1) + " " + metadata.getColumnName(i + 1) + " " + metadata.getColumnType(i + 1) + " " + metadata.getColumnTypeName(i + 1) + " " + metadata.getPrecision(i + 1) + " " + metadata.getScale(i + 1) + " " + metadata.getSchemaName(i + 1) + " " + metadata.getTableName(i + 1);
            System.out.println(metaStr);
        }

        System.out.println("Data:");
        while (resultSet.next()) {
            String dataStr = resultSet.getFloat(1) + " " + resultSet.getInt(2) + " " + resultSet.getInt(3) + " " + resultSet.getLong(4) + " " + resultSet.getDate(5) + " " + resultSet.getString(6);
            System.out.println(dataStr);
        }
    }
}
 
Example 17
Source File: ResultSetTableModelFactory.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * No longer used.
 *
 * @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 ..
  }
}
 
Example 18
Source File: JdbcAvroRecord.java    From dbeam with Apache License 2.0 4 votes vote down vote up
static SqlFunction<ResultSet, Object> computeMapping(
    final ResultSetMetaData meta, final int column) throws SQLException {
  switch (meta.getColumnType(column)) {
    case VARCHAR:
    case CHAR:
    case CLOB:
    case LONGNVARCHAR:
    case LONGVARCHAR:
    case NCHAR:
      return resultSet -> resultSet.getString(column);
    case BIGINT:
      final int precision = meta.getPrecision(column);
      if (precision > 0 && precision <= MAX_DIGITS_BIGINT) {
        return resultSet -> resultSet.getLong(column);
      }
      // otherwise return as string
      return resultSet -> resultSet.getString(column);
    case INTEGER:
    case SMALLINT:
    case TINYINT:
      return resultSet -> resultSet.getInt(column);
    case TIMESTAMP:
    case DATE:
    case TIME:
    case TIME_WITH_TIMEZONE:
      return resultSet -> {
        final Timestamp timestamp = resultSet.getTimestamp(column, CALENDAR);
        if (timestamp != null) {
          return timestamp.getTime();
        } else {
          return null;
        }
      };
    case BOOLEAN:
      return resultSet -> resultSet.getBoolean(column);
    case BIT:
      if (meta.getPrecision(column) <= 1) {
        return resultSet -> resultSet.getBoolean(column);
      } else {
        return resultSet -> nullableBytes(resultSet.getBytes(column));
      }
    case BINARY:
    case VARBINARY:
    case LONGVARBINARY:
    case ARRAY:
    case BLOB:
      return resultSet -> nullableBytes(resultSet.getBytes(column));
    case DOUBLE:
      return resultSet -> resultSet.getDouble(column);
    case FLOAT:
    case REAL:
      return resultSet -> resultSet.getFloat(column);
    default:
      return resultSet -> resultSet.getString(column);
  }
}
 
Example 19
Source File: ResultColumnList.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generate an RCL to match the contents of a ResultSetMetaData.
 * This is useful when dealing with VTIs.
 *
 * @param rsmd          The ResultSetMetaData.
 * @param tableName     The TableName for the BCNs.
 * @param javaClassName The name of the VTI
 * @throws StandardException Thrown on error
 */
public void createListFromResultSetMetaData(ResultSetMetaData rsmd,
                                            TableName tableName,
                                            String javaClassName) throws StandardException{
    try{
        // JDBC columns #s are 1-based
        // Check to make sure # of columns >= 1
        int numColumns=rsmd.getColumnCount();

        if(numColumns<=0){
            throw StandardException.newException(SQLState.LANG_INVALID_V_T_I_COLUMN_COUNT,
                    javaClassName,String.valueOf(numColumns));
        }

        for(int index=1;index<=numColumns;index++){
            boolean nullableResult=
                    (rsmd.isNullable(index)!=ResultSetMetaData.columnNoNulls);

            TypeId cti;

            int jdbcColumnType=rsmd.getColumnType(index);

            switch(jdbcColumnType){
                case Types.JAVA_OBJECT:
                case Types.OTHER:{
                    cti=TypeId.getUserDefinedTypeId(rsmd.getColumnTypeName(index),false);
                    break;
                }
                default:{
                    cti=TypeId.getBuiltInTypeId(jdbcColumnType);
                    break;
                }
            }

            // Handle the case where a VTI returns a bad column type
            if(cti==null){
                throw StandardException.newException(SQLState.LANG_BAD_J_D_B_C_TYPE_INFO,Integer.toString(index));
            }

            // Get the maximum byte storage for this column
            int maxWidth;

            /* Get maximum byte storage from rsmd for variable
             * width types, set it to MAXINT for the long types,
             * otherwise get it from the TypeId
             */
            if(cti.variableLength()){
                maxWidth=rsmd.getColumnDisplaySize(index);
            }else if(jdbcColumnType==Types.LONGVARCHAR || jdbcColumnType==Types.LONGVARBINARY){
                maxWidth=Integer.MAX_VALUE;
            }else{
                maxWidth=0;
            }

            int precision=cti.isDecimalTypeId()?rsmd.getPrecision(index):0;
            int scale=cti.isDecimalTypeId()?rsmd.getScale(index):0;
            DataTypeDescriptor dts=new DataTypeDescriptor(cti, precision, scale, nullableResult, maxWidth);
            addColumn(tableName,rsmd.getColumnName(index),dts);
        }
    }catch(Throwable t){
        if(t instanceof StandardException){
            throw (StandardException)t;
        }else{
            throw StandardException.unexpectedUserException(t);
        }
    }
}
 
Example 20
Source File: ValueMetaBase.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
protected void getOriginalColumnMetadata( ValueMetaInterface v, ResultSetMetaData rm, int index, boolean ignoreLength )
  throws SQLException {
  // Grab the comment as a description to the field as well.
  String comments = rm.getColumnLabel( index );
  v.setComments( comments );

  // get & store more result set meta data for later use
  int originalColumnType = rm.getColumnType( index );
  v.setOriginalColumnType( originalColumnType );

  String originalColumnTypeName = rm.getColumnTypeName( index );
  v.setOriginalColumnTypeName( originalColumnTypeName );

  int originalPrecision = -1;
  if ( !ignoreLength ) {
    // Throws exception on MySQL
    originalPrecision = rm.getPrecision( index );
  }
  v.setOriginalPrecision( originalPrecision );

  int originalScale = rm.getScale( index );
  v.setOriginalScale( originalScale );

  // DISABLED FOR PERFORMANCE REASONS : PDI-1788
  //
  // boolean originalAutoIncrement=rm.isAutoIncrement(index); DISABLED FOR
  // PERFORMANCE REASONS : PDI-1788
  // v.setOriginalAutoIncrement(originalAutoIncrement);

  // int originalNullable=rm.isNullable(index); DISABLED FOR PERFORMANCE
  // REASONS : PDI-1788
  // v.setOriginalNullable(originalNullable);
  //

  boolean originalSigned = false;
  try {
    originalSigned = rm.isSigned( index );
  } catch ( Exception ignored ) {
    // This JDBC Driver doesn't support the isSigned method.
    // Nothing more we can do here.
  }
  v.setOriginalSigned( originalSigned );
}