@Override public IParameterMetaData getParameterMetadata(String query, List<Object> params) throws OdaException { MetadataBean bean = new MetadataBean(); int paramcount = 1; String[] queryStrings = getQueryStrings(query, null); for( String queryString : queryStrings ) { int sz = queryString.length(); for( int i = 0; i < sz; i++ ) { char c = queryString.charAt(i); if( c == '?' ) { Definition definition = addColumn("param" + (paramcount++), TYPE_STRING, bean); //$NON-NLS-1$ definition.setMode(ParameterMetaData.parameterModeIn); } } } return bean; }
/** * Converts from JDBC metadata to Avatica parameters */ protected static List<AvaticaParameter> parameters(ParameterMetaData metaData) throws SQLException { if (metaData == null) { return Collections.emptyList(); } final List<AvaticaParameter> params = new ArrayList<>(); for (int i = 1; i <= metaData.getParameterCount(); i++) { params.add( new AvaticaParameter(metaData.isSigned(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getParameterType(i), metaData.getParameterTypeName(i), metaData.getParameterClassName(i), "?" + i)); } return params; }
@Test public void testPrepareBindExecuteFetchVarbinary() throws Exception { ConnectionSpec.getDatabaseLock().lock(); try { final Connection connection = getLocalConnection(); final String sql = "select x'de' || ? as c from (values (1, 'a'))"; final PreparedStatement ps = connection.prepareStatement(sql); final ParameterMetaData parameterMetaData = ps.getParameterMetaData(); assertThat(parameterMetaData.getParameterCount(), equalTo(1)); ps.setBytes(1, new byte[]{65, 0, 66}); final ResultSet resultSet = ps.executeQuery(); assertTrue(resultSet.next()); assertThat(resultSet.getBytes(1), equalTo(new byte[]{(byte) 0xDE, 65, 0, 66})); resultSet.close(); ps.close(); connection.close(); } finally { ConnectionSpec.getDatabaseLock().unlock(); } }
/** * Get the parameter meta data of this prepared statement. * * @return the meta data */ @Override public ParameterMetaData getParameterMetaData() throws SQLException { try { int id = getNextId(TraceObject.PARAMETER_META_DATA); if (isDebugEnabled()) { debugCodeAssign("ParameterMetaData", TraceObject.PARAMETER_META_DATA, id, "getParameterMetaData()"); } checkClosed(); JdbcParameterMetaData meta = new JdbcParameterMetaData( session.getTrace(), this, command, id); return meta; } catch (Exception e) { throw logAndConvert(e); } }
private void sendParameterDescription(Prepared p) throws IOException { try { PreparedStatement prep = p.prep; ParameterMetaData meta = prep.getParameterMetaData(); int count = meta.getParameterCount(); startMessage('t'); writeShort(count); for (int i = 0; i < count; i++) { int type; if (p.paramType != null && p.paramType[i] != 0) { type = p.paramType[i]; } else { type = PgServer.PG_TYPE_VARCHAR; } server.checkType(type); writeInt(type); } sendMessage(); } catch (Exception e) { sendErrorResponse(e); } }
@Test public void testSetParameterValueWithNullAndGetParameterTypeWorkingButNotForOtherDriver() throws SQLException { StatementCreatorUtils.driversWithNoSupportForGetParameterType.clear(); StatementCreatorUtils.driversWithNoSupportForGetParameterType.add("Oracle JDBC Driver"); Connection con = mock(Connection.class); DatabaseMetaData dbmd = mock(DatabaseMetaData.class); ParameterMetaData pmd = mock(ParameterMetaData.class); given(preparedStatement.getConnection()).willReturn(con); given(con.getMetaData()).willReturn(dbmd); given(dbmd.getDriverName()).willReturn("Apache Derby Embedded Driver"); given(preparedStatement.getParameterMetaData()).willReturn(pmd); given(pmd.getParameterType(1)).willReturn(Types.SMALLINT); StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null); verify(dbmd).getDriverName(); verify(pmd).getParameterType(1); verify(preparedStatement).setNull(1, Types.SMALLINT); assertEquals(1, StatementCreatorUtils.driversWithNoSupportForGetParameterType.size()); }
/** * test execute statements that no parameters would be returned if * prepareStatement("execute statement systab using values('SYS%','8000001%')"); * * @exception SQLException if error occurs */ public void testExecuteStatementUsing () throws SQLException { /* * the test no longer tests 4552, but kept as an interesting test scenario * bug 4552 - no parameters would be returned for execute statement using * System.out.println("Bug 4552 - no parameters would be returned for execute statement using"); * orig: ps = con.prepareStatement("execute statement systab using values('SYS%','8000001%')"); */ PreparedStatement ps = prepareStatement("select * from sys.systables " + "where CAST(tablename AS VARCHAR(128)) like 'SYS%' and " + "CAST(tableID AS VARCHAR(128)) like '8000001%'"); ParameterMetaData paramMetaData = ps.getParameterMetaData(); assertEquals("Unexpected parameter count", 0, paramMetaData.getParameterCount()); //expected values to be stored in a 2dim. array String parameterMetaDataArray0 [][] = null; testParameterMetaData(paramMetaData, parameterMetaDataArray0); ps.execute(); ps.close(); }
/** * tests parameterMetaData and reports error if the ParameterMetaData results * does not match the expected results. * * @param paramMetaData ParameterMetadata object * @param paramMetaDataArray 2 dimensional array containing expected test results. * @exception SQLException if any error occurs */ static void testParameterMetaData(ParameterMetaData paramMetaData, String [][] paramMetaDataArray) throws SQLException { int numParam = paramMetaData.getParameterCount(); for (int i=0, j=0; i<numParam; i++) { assertEquals("Unexpected parameter isNullable", paramMetaDataArray[i][j++], parameterIsNullableInStringForm(paramMetaData.isNullable(i+1))); assertEquals("Unexpected parameter isSigned", Boolean.valueOf(paramMetaDataArray[i][j++]).booleanValue(), paramMetaData.isSigned(i+1)); assertEquals("Unexpected parameter getPrecision", Integer.parseInt(paramMetaDataArray[i][j++]) , paramMetaData.getPrecision(i+1)); assertEquals("Unexpected parameter getScale", Integer.parseInt(paramMetaDataArray[i][j++]) , paramMetaData.getScale(i+1)); assertEquals("Unexpected parameter getParameterType", Integer.parseInt(paramMetaDataArray[i][j++]) , paramMetaData.getParameterType(i+1)); assertEquals("Unexpected parameter getParameterTypeName", paramMetaDataArray[i][j++] , paramMetaData.getParameterTypeName(i+1)); assertEquals("Unexpected parameter getParameterClassName", paramMetaDataArray[i][j++] , paramMetaData.getParameterClassName(i+1)); assertEquals("Unexpected parameter getParameterMode", paramMetaDataArray[i][j++] , parameterModeInStringForm(paramMetaData.getParameterMode(i+1))); j=0; } }
/** * Check the ParameterMetaData for a statement whose first parameter is a UDT. */ private void checkPMD ( Connection conn, String query, String expectedClassName, int expectedJDBCType, String expectedSQLTypeName, int expectedPrecision, int expectedScale ) throws Exception { PreparedStatement ps = conn.prepareStatement( query ); ParameterMetaData pmd = ps.getParameterMetaData(); assertEquals( pmd.getParameterClassName( 1 ), expectedClassName ); assertEquals( pmd.getParameterType( 1 ), expectedJDBCType ); assertEquals( pmd.getParameterTypeName( 1 ), expectedSQLTypeName ); assertEquals( pmd.getPrecision( 1 ), expectedPrecision ); assertEquals( pmd.getScale( 1 ), expectedScale ); ps.close(); }
/** * Test dynamic arguments */ public void testDynamicArgsMetaData() throws SQLException { //since there is no getParameterMetaData() call available in JSR169 //implementations, do not run this test if we are running JSR169 if (JDBC.vmSupportsJSR169()) return; PreparedStatement ps = prepareStatement( "select * from t1 where a = ? order by b " + "offset ? rows fetch next ? rows only"); ParameterMetaData pmd = ps.getParameterMetaData(); int[] expectedTypes = { Types.INTEGER, Types.BIGINT, Types.BIGINT }; for (int i = 0; i < 3; i++) { assertEquals("Unexpected parameter type", expectedTypes[i], pmd.getParameterType(i+1)); assertEquals("Derby ? args are nullable", // Why is that? Cf. logic in ParameterNode.setType ParameterMetaData.parameterNullable, pmd.isNullable(i+1)); } ps.close(); }
private void writeSQLDOPTGRP(ResultSetMetaData rsmeta, ParameterMetaData pmeta, int jdbcElemNum, boolean rtnOutput) throws DRDAProtocolException,SQLException { writer.writeByte(0); //SQLUNAMED writer.writeShort(0); //SQLName writeVCMorVCS(rtnOutput ? rsmeta.getColumnName(jdbcElemNum) : null); //SQLLabel writeVCMorVCS(null); //SQLComments writeVCMorVCS(null); //SQLDUDTGRP writeSQLUDTGRP(rsmeta, pmeta, jdbcElemNum, rtnOutput); //SQLDXGRP writeSQLDXGRP(rsmeta, pmeta, jdbcElemNum, rtnOutput); }
/** * statementにパラメータを設定します。 * @param st ステートメント。 * @param param パラメータ。 * @throws Exception 例外。 */ public void setParameter(final PreparedStatement st, final Map<String, Object> param) throws Exception { if (this.paramnames != null && param != null) { int idx = 1; ParameterMetaData meta = getParameterMetaData(st); for (String p : this.paramnames) { Object v = this.getParam(p, param); if (log.isDebugEnabled()) { log.debug(idx + " :" + p + "=" + v); } if (v == null) { st.setNull(idx, this.getParameterType(meta, idx)); } else { if (v instanceof FileObject) { log.debug("valueClass=" + v.getClass().getName()); this.setBlobData(st, idx, (FileObject) v, meta); } else { st.setObject(idx, v); } } idx++; } } }
private void testInterfaceImplementation(Connection connToCheck) throws Exception { Method[] dbmdMethods = java.sql.DatabaseMetaData.class.getMethods(); // can't do this statically, as we return different // implementations depending on JDBC version DatabaseMetaData dbmd = connToCheck.getMetaData(); checkInterfaceImplemented(dbmdMethods, dbmd.getClass(), dbmd); Statement stmtToCheck = connToCheck.createStatement(); checkInterfaceImplemented(java.sql.Statement.class.getMethods(), stmtToCheck.getClass(), stmtToCheck); PreparedStatement pStmtToCheck = connToCheck.prepareStatement("SELECT 1"); ParameterMetaData paramMd = pStmtToCheck.getParameterMetaData(); checkInterfaceImplemented(java.sql.PreparedStatement.class.getMethods(), pStmtToCheck.getClass(), pStmtToCheck); checkInterfaceImplemented(java.sql.ParameterMetaData.class.getMethods(), paramMd.getClass(), paramMd); pStmtToCheck = ((com.mysql.jdbc.Connection) connToCheck).serverPrepareStatement("SELECT 1"); checkInterfaceImplemented(java.sql.PreparedStatement.class.getMethods(), pStmtToCheck.getClass(), pStmtToCheck); ResultSet toCheckRs = connToCheck.createStatement().executeQuery("SELECT 1"); checkInterfaceImplemented(java.sql.ResultSet.class.getMethods(), toCheckRs.getClass(), toCheckRs); toCheckRs = connToCheck.createStatement().executeQuery("SELECT 1"); checkInterfaceImplemented(java.sql.ResultSetMetaData.class.getMethods(), toCheckRs.getMetaData().getClass(), toCheckRs.getMetaData()); if (versionMeetsMinimum(5, 0, 0)) { createProcedure("interfaceImpl", "(IN p1 INT)\nBEGIN\nSELECT 1;\nEND"); CallableStatement cstmt = connToCheck.prepareCall("{CALL interfaceImpl(?)}"); checkInterfaceImplemented(java.sql.CallableStatement.class.getMethods(), cstmt.getClass(), cstmt); } checkInterfaceImplemented(java.sql.Connection.class.getMethods(), connToCheck.getClass(), connToCheck); }
/** * @see java.sql.PreparedStatement#getParameterMetaData() */ @Override public ParameterMetaData getParameterMetaData() throws SQLException { synchronized (checkClosed().getConnectionMutex()) { if (this.parameterMetaData == null) { this.parameterMetaData = new MysqlParameterMetadata(this.parameterFields, this.parameterCount, getExceptionInterceptor()); } return this.parameterMetaData; } }
@Override public ParameterMetaData getParameterMetaData() throws SQLException { synchronized (checkClosed().getConnectionMutex()) { if (this.placeholderToParameterIndexMap == null) { return this.paramInfo; } return new CallableStatementParamInfo(this.paramInfo); } }
/** * @see PreparedStatement#getParameterMetaData() */ public ParameterMetaData getParameterMetaData() throws SQLException { synchronized (checkClosed().getConnectionMutex()) { if (this.parameterMetaData == null) { if (this.connection.getGenerateSimpleParameterMetadata()) { this.parameterMetaData = new MysqlParameterMetadata(this.parameterCount); } else { this.parameterMetaData = new MysqlParameterMetadata(null, this.parameterCount, getExceptionInterceptor()); } } return this.parameterMetaData; } }
public ParameterMetaData getParameterMetaData() throws SQLException { try { if (this.wrappedStmt != null) { return ((PreparedStatement) this.wrappedStmt).getParameterMetaData(); } throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); } catch (SQLException sqlEx) { checkAndFireConnectionError(sqlEx); } return null; }
@Override public MetadataBean getParameterMetadata(String query, final List<Object> params) { try { query = processQuery(query); return (MetadataBean) new JdbcTemplate(getDataSourceHolder().getDataSource()).execute(query, new PreparedStatementCallback() { @Override public Object doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException { addParamsToStatement(statement, params); try { ParameterMetaData parameterMetaData = statement.getParameterMetaData(); return new MetadataBean(parameterMetaData); } catch( SQLException sqle ) { return null; } } }); } catch( Exception e ) { String msg = CurrentLocale.get("com.tle.core.reporting.error.parameter.metadata") + query; LOGGER.error(msg, e); throw new RuntimeException(msg, e); } }
protected static Signature signature(ResultSetMetaData metaData, ParameterMetaData parameterMetaData, String sql, Meta.StatementType statementType) throws SQLException { final CursorFactory cf = CursorFactory.LIST; // because JdbcResultSet#frame return new Signature(columns(metaData), sql, parameters(parameterMetaData), null, cf, statementType); }
@Test public void testPrepareSetsMaxRows() throws Exception { final String id = UUID.randomUUID().toString(); final String sql = "SELECT * FROM FOO"; final int maxRows = 500; final ConnectionHandle ch = new ConnectionHandle(id); final AtomicInteger statementIdGenerator = new AtomicInteger(0); JdbcMeta meta = Mockito.mock(JdbcMeta.class); Connection connection = Mockito.mock(Connection.class); PreparedStatement statement = Mockito.mock(PreparedStatement.class); ResultSetMetaData resultSetMetaData = Mockito.mock(ResultSetMetaData.class); ParameterMetaData parameterMetaData = Mockito.mock(ParameterMetaData.class); @SuppressWarnings("unchecked") Cache<Integer, StatementInfo> statementCache = (Cache<Integer, StatementInfo>) Mockito.mock(Cache.class); Mockito.when(meta.getStatementIdGenerator()).thenReturn(statementIdGenerator); Mockito.when(meta.getStatementCache()).thenReturn(statementCache); Mockito.when(meta.getConnection(id)).thenReturn(connection); Mockito.when(connection.prepareStatement(sql)).thenReturn(statement); Mockito.when(statement.isWrapperFor(AvaticaPreparedStatement.class)).thenReturn(false); Mockito.when(statement.getMetaData()).thenReturn(resultSetMetaData); Mockito.when(statement.getParameterMetaData()).thenReturn(parameterMetaData); // Call the real methods Mockito.doCallRealMethod().when(meta).setMaxRows(statement, maxRows); Mockito.doCallRealMethod().when(meta).prepare(ch, sql, maxRows); meta.prepare(ch, sql, maxRows); Mockito.verify(statement).setMaxRows(maxRows); }
private void checkStatementExecuteQuery(Connection connection, boolean prepare) throws SQLException { final String sql = "select * from (\n" + " values (1, 'a'), (null, 'b'), (3, 'c')) as t (c1, c2)"; final Statement statement; final ResultSet resultSet; final ParameterMetaData parameterMetaData; if (prepare) { final PreparedStatement ps = connection.prepareStatement(sql); statement = ps; parameterMetaData = ps.getParameterMetaData(); resultSet = ps.executeQuery(); } else { statement = connection.createStatement(); parameterMetaData = null; resultSet = statement.executeQuery(sql); } if (parameterMetaData != null) { assertThat(parameterMetaData.getParameterCount(), equalTo(0)); } final ResultSetMetaData metaData = resultSet.getMetaData(); assertEquals(2, metaData.getColumnCount()); assertEquals("C1", metaData.getColumnName(1)); assertEquals("C2", metaData.getColumnName(2)); assertTrue(resultSet.next()); assertTrue(resultSet.next()); assertTrue(resultSet.next()); assertFalse(resultSet.next()); resultSet.close(); statement.close(); connection.close(); }