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

The following examples show how to use java.sql.ResultSetMetaData#getScale() . 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: PostgresJavaRoutineJsonOutputter.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
protected DataTypeDescriptor resultColumnSQLType(ResultSetMetaData metaData, int i)
        throws SQLException {
    TypeId typeId = TypeId.getBuiltInTypeId(metaData.getColumnType(i));
    if (typeId == null) {
        try {
            typeId = TypeId.getUserDefinedTypeId(metaData.getColumnTypeName(i),
                                                 false);
        }
        catch (StandardException ex) {
            throw new SQLParserInternalException(ex);
        }
    }
    if (typeId.isDecimalTypeId()) {
        return new DataTypeDescriptor(typeId,
                                      metaData.getPrecision(i),
                                      metaData.getScale(i),
                                      metaData.isNullable(i) != ResultSetMetaData.columnNoNulls,
                                      metaData.getColumnDisplaySize(i));
        }
    else {
        return new DataTypeDescriptor(typeId,
                                      metaData.isNullable(i) != ResultSetMetaData.columnNoNulls,
                                      metaData.getColumnDisplaySize(i));
    }
}
 
Example 2
Source File: DriverTest.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@Ignore("not maintaining")
@Test
public void testPreStatementWithCubeData() throws SQLException {
    Driver driver = new Driver();
    Properties info = new Properties();
    info.put("user", "");
    info.put("password", "");
    Connection conn = driver.connect("jdbc:kylin://localhost/default", info);
    PreparedStatement state = conn.prepareStatement("select * from test_kylin_fact where seller_id=?");
    state.setLong(1, 10000001);
    ResultSet resultSet = state.executeQuery();

    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 3
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 4
Source File: ResultSetUtil.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static void resultSetToFieldPacket(String charset,
										  List<FieldPacket> fieldPks, ResultSet rs,
										  boolean isSpark) throws SQLException {
	ResultSetMetaData metaData = rs.getMetaData();
	int colunmCount = metaData.getColumnCount();
	if (colunmCount > 0) {
		//String values="";
		for (int i = 0; i < colunmCount; i++) {
			int j = i + 1;
			FieldPacket fieldPacket = new FieldPacket();
			fieldPacket.orgName = StringUtil.encode(metaData.getColumnName(j),charset);
			fieldPacket.name = StringUtil.encode(metaData.getColumnLabel(j), charset);
			if (! isSpark){
			  fieldPacket.orgTable = StringUtil.encode(metaData.getTableName(j), charset);
			  fieldPacket.table = StringUtil.encode(metaData.getTableName(j),	charset);
			  fieldPacket.db = StringUtil.encode(metaData.getSchemaName(j),charset);
			  fieldPacket.flags = toFlag(metaData, j);
			}
			fieldPacket.length = metaData.getColumnDisplaySize(j);
			
			fieldPacket.decimals = (byte) metaData.getScale(j);
			int javaType = MysqlDefs.javaTypeDetect(
					metaData.getColumnType(j), fieldPacket.decimals);
			fieldPacket.type = (byte) (MysqlDefs.javaTypeMysql(javaType) & 0xff);
			if(MysqlDefs.isBianry((byte) fieldPacket.type)) {
				// 63 represent binary character set
				fieldPacket.charsetIndex = 63;
			}
			fieldPks.add(fieldPacket);
			//values+=metaData.getColumnLabel(j)+"|"+metaData.getColumnName(j)+"  ";
		}
		// System.out.println(values);
	}


}
 
Example 5
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 6
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 7
Source File: PostgresDynamicResultSetOutputter.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static PostgresType typeFromSQL(ResultSetMetaData metaData, int columnIndex, TypesTranslator typesTranslator) throws SQLException {
    TypeId typeId = TypeId.getBuiltInTypeId(metaData.getColumnType(columnIndex));
    if (typeId == null) {
        try {
            typeId = TypeId.getUserDefinedTypeId(metaData.getColumnTypeName(columnIndex),
                                                 false);
        }
        catch (StandardException ex) {
            throw new SQLParserInternalException(ex);
        }
    }
    DataTypeDescriptor sqlType;
    if (typeId.isDecimalTypeId() || typeId.isNumericTypeId()) {
        sqlType = new DataTypeDescriptor(typeId,
                                         metaData.getPrecision(columnIndex),
                                         metaData.getScale(columnIndex),
                                         metaData.isNullable(columnIndex) != ResultSetMetaData.columnNoNulls,
                                         metaData.getColumnDisplaySize(columnIndex));
    }
    else {
        sqlType = new DataTypeDescriptor(typeId,
                                         metaData.isNullable(columnIndex) != ResultSetMetaData.columnNoNulls,
                                         metaData.getColumnDisplaySize(columnIndex));
    }
    TInstance type = typesTranslator.typeForSQLType(sqlType);
    return PostgresType.fromDerby(sqlType, type);
}
 
Example 8
Source File: JdbcDatabaseManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public ResultSetColumnMetaData(final ResultSetMetaData rsMetaData, final int j) throws SQLException {
    // @formatter:off
    this(rsMetaData.getSchemaName(j),
         rsMetaData.getCatalogName(j),
         rsMetaData.getTableName(j),
         rsMetaData.getColumnName(j),
         rsMetaData.getColumnLabel(j),
         rsMetaData.getColumnDisplaySize(j),
         rsMetaData.getColumnType(j),
         rsMetaData.getColumnTypeName(j),
         rsMetaData.getColumnClassName(j),
         rsMetaData.getPrecision(j),
         rsMetaData.getScale(j));
    // @formatter:on
}
 
Example 9
Source File: ColumnDefPacketImpl.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public ColumnDefPacketImpl(final ResultSetMetaData resultSetMetaData, int columnIndex) {
    try {
        this.columnSchema = resultSetMetaData.getSchemaName(columnIndex).getBytes();
        this.columnName = resultSetMetaData.getColumnLabel(columnIndex).getBytes();
        this.columnOrgName = resultSetMetaData.getColumnName(columnIndex).getBytes();
        this.columnNextLength = 0xC;
        this.columnLength = resultSetMetaData.getColumnDisplaySize(columnIndex);
        this.columnType = MySQLFieldsType.fromJdbcType(resultSetMetaData.getColumnType(columnIndex));
        this.columnDecimals = (byte) resultSetMetaData.getScale(columnIndex);
        this.columnCharsetSet = 0x21;
    } catch (Exception e) {
        throw new MycatException(e);
    }
}
 
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: 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 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: ValueMetaTimestamp.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public IValueMeta getValueFromSqlType(DatabaseMeta databaseMeta, String name, ResultSetMetaData rm,
                                      int index, boolean ignoreLength, boolean lazyConversion ) throws HopDatabaseException {

  try {
    int type = rm.getColumnType( index );
    if ( type == java.sql.Types.TIMESTAMP ) {
      int length = rm.getScale( index );
      IValueMeta valueMeta;
      if ( databaseMeta.supportsTimestampDataType() ) {
        valueMeta = new ValueMetaTimestamp( name );
      } else {
        valueMeta = new ValueMetaDate( name );
      }
      valueMeta.setLength( length );

      // Also get original column details, comment, etc.
      //
      getOriginalColumnMetadata( valueMeta, rm, index, ignoreLength );

      return valueMeta;
    }

    return null;
  } catch ( Exception e ) {
    throw new HopDatabaseException( "Error evaluating timestamp value metadata", e );
  }
}
 
Example 14
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 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: 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 17
Source File: DbCommonServiceImpl.java    From bdf3 with Apache License 2.0 4 votes vote down vote up
@Override
public List<ColumnInfo> findMultiColumnInfos(String dbInfoId, String sql) throws Exception {
	if (!StringUtils.hasText(sql)) {
		return null;
	}
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	Statement st = null;
	ResultSet rs = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		st = conn.createStatement();
		rs = st.executeQuery(sql);
		ResultSetMetaData rsmd = rs.getMetaData();
		int count = rsmd.getColumnCount();
		List<ColumnInfo> columnNames = new ArrayList<ColumnInfo>();
		ColumnInfo columnInfo = null;
		for (int i = 1; i <= count; i++) {
			columnInfo = new ColumnInfo();
			columnInfo.setColumnName(rsmd.getColumnLabel(i));
			columnInfo.setColumnType(rsmd.getColumnTypeName(i));
			columnInfo.setTableName(rsmd.getTableName(i));
			if (rsmd.getPrecision(i) > 0 && !columnInfo.getColumnType().equals("DATETIME") && !columnInfo.getColumnType().equals("TIMESTAMP") && !columnInfo.getColumnType().equals("DATE")) {
				columnInfo.setColumnSize(String.valueOf(rsmd.getPrecision(i)));
			}
			if (rsmd.getScale(i) > 0 && !columnInfo.getColumnType().equals("DATETIME") && !columnInfo.getColumnType().equals("TIMESTAMP") && !columnInfo.getColumnType().equals("DATE")) {
				columnInfo.setColumnSize(columnInfo.getColumnSize() + "," + rsmd.getScale(i));
			}
			int flagI = rsmd.isNullable(i);
			if (flagI == 0) {
				columnInfo.setIsnullAble(false);
			} else {
				columnInfo.setIsnullAble(true);
			}
			columnNames.add(columnInfo);
		}
		return columnNames;
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(st);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 18
Source File: TableColumnInfo.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public static TableColumnInfo createTableMetadataWithExtraSelect(Connection connection, String schema, String tableName, String fullyQualifiedTableName)
throws SQLException
{
    TableColumnInfo tableInfo = createTableMetadata(connection, schema, tableName, fullyQualifiedTableName);

    if (tableInfo == null || tableInfo.getColumns().length == 0)
    {
        List columns = new ArrayList();
        ResultSet resultSet = null;

        // Get hold of the table catalog and schema separately from the column metadata in case we have a zero-column table/view
        String catalog = null;
        String dbSchema = null;
        String dbName = null;
        Statement stm = null;
        try
        {
            stm = connection.createStatement();
            resultSet = stm.executeQuery("select * from "+fullyQualifiedTableName+" where 0 = 1");
            resultSet.next();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            dbName = resultSetMetaData.getTableName(1);
            dbSchema = resultSetMetaData.getSchemaName(1);
            if ("".equals(dbSchema))
            {
                dbSchema = null;
            }
            for(int i=0;i< columnCount; i++)
            {
                int col = i + 1;
                ColumnInfo columnInfo = new ColumnInfo(resultSetMetaData.getColumnName(col),
                        resultSetMetaData.getColumnType(col),
                        resultSetMetaData.getColumnDisplaySize(col),
                        resultSetMetaData.getPrecision(col),
                        resultSetMetaData.getScale(col),
                        col,
                        resultSetMetaData.isNullable(col) == DatabaseMetaData.columnNullable);
                columns.add(columnInfo);
            }
        }
        catch(SQLException e)
        {
            //ignore this; it's acceptable for the table to not be found.
        }
        finally
        {
            close(stm);
            close(resultSet);
        }
        if (columns.size() == 0)
        {
            return null;
        }
        tableInfo = new TableColumnInfo(catalog, dbSchema, dbName, (ColumnInfo[]) columns.toArray(new ColumnInfo[columns.size()]));
    }
    return tableInfo;
}
 
Example 19
Source File: ResultColumnList.java    From gemfirexd-oss with Apache License 2.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
 *
 * @exception 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: MySQLColumnDefinition41Packet.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
public MySQLColumnDefinition41Packet(final int sequenceId, final ResultSetMetaData resultSetMetaData, final int columnIndex) throws SQLException {
    this(sequenceId, resultSetMetaData.getSchemaName(columnIndex), resultSetMetaData.getTableName(columnIndex), resultSetMetaData.getTableName(columnIndex), 
            resultSetMetaData.getColumnLabel(columnIndex), resultSetMetaData.getColumnName(columnIndex), resultSetMetaData.getColumnDisplaySize(columnIndex), 
            MySQLColumnType.valueOfJDBCType(resultSetMetaData.getColumnType(columnIndex)), resultSetMetaData.getScale(columnIndex));
}