/** * delete Data Metadatas. * * @param uris uri list * @param removeDataMetadata flag to remove data meta data */ @SuppressWarnings("checkstyle:methodname") private void _deleteDataMetadatas( @Nullable final List<String> uris, final boolean removeDataMetadata ) { if (uris != null && !uris.isEmpty()) { final List<String> paramVariables = uris.stream().map(s -> "?").collect(Collectors.toList()); final String[] aUris = uris.toArray(new String[0]); final String paramString = Joiner.on(",").skipNulls().join(paramVariables); final List<Long> ids = jdbcTemplate .query(String.format(SQL.GET_DATA_METADATA_IDS, paramString), aUris, (rs, rowNum) -> rs.getLong("id")); if (!ids.isEmpty()) { final List<String> idParamVariables = ids.stream().map(s -> "?").collect(Collectors.toList()); final SqlParameterValue[] aIds = ids.stream().map(id -> new SqlParameterValue(Types.BIGINT, id)) .toArray(SqlParameterValue[]::new); final String idParamString = Joiner.on(",").skipNulls().join(idParamVariables); jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA_DELETE, idParamString), (Object[]) aIds); if (removeDataMetadata) { jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA, idParamString), (Object[]) aIds); } } } }
@Override public void delete(final QualifiedName name, final boolean updateUserMetadata) { try { jdbcTemplate .update(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME, new SqlParameterValue(Types.VARCHAR, name.toString())); jdbcTemplate.update(SQL_DELETE_TAG_ITEM, new SqlParameterValue(Types.VARCHAR, name.toString())); if (updateUserMetadata) { // Set the tags in user metadata final Map<String, Set<String>> data = Maps.newHashMap(); data.put(NAME_TAGS, Sets.newHashSet()); userMetadataService .saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)), true); } } catch (Exception e) { final String message = String.format("Failed to delete all tags for name %s", name); log.error(message, e); throw new UserMetadataServiceException(message, e); } }
/** * remove. * * @param name qualifiedName * @param tags tags * @param updateUserMetadata flag to update user metadata */ public void remove(final QualifiedName name, final Set<String> tags, final boolean updateUserMetadata) { try { jdbcTemplate.update(String.format(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME_TAGS, "'" + Joiner.on("','").skipNulls().join(tags) + "'"), new SqlParameterValue(Types.VARCHAR, name.toString())); if (updateUserMetadata) { final TagItem tagItem = get(name); tagItem.getValues().removeAll(tags); final Map<String, Set<String>> data = Maps.newHashMap(); data.put(NAME_TAGS, tagItem.getValues()); userMetadataService .saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)), true); } } catch (Exception e) { final String message = String.format("Failed to remove tags for name %s", name); log.error(message, e); throw new UserMetadataServiceException(message, e); } }
private List<PartitionSequenceIds> getPartitionSequenceIds(final QualifiedName tableName, final List<String> partitionNames) { final List<String> paramVariables = partitionNames.stream().map(s -> "?").collect(Collectors.toList()); final String paramVariableString = Joiner.on(",").skipNulls().join(paramVariables); final SqlParameterValue[] values = new SqlParameterValue[partitionNames.size() + 2]; int index = 0; values[index++] = new SqlParameterValue(Types.VARCHAR, tableName.getDatabaseName()); values[index++] = new SqlParameterValue(Types.VARCHAR, tableName.getTableName()); for (String partitionName : partitionNames) { values[index++] = new SqlParameterValue(Types.VARCHAR, partitionName); } return jdbcTemplate.query( String.format(SQL.PARTITIONS_SELECT, paramVariableString), values, (rs, rowNum) -> new PartitionSequenceIds(rs.getLong("part_id"), rs.getLong("sd_id"), rs.getLong("serde_id"))); }
@Test public void testExecuteWithTypedParameters() throws SQLException { given(preparedStatement.executeUpdate()).willReturn(1); params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback<Object>() { @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException { assertEquals(preparedStatement, ps); ps.executeUpdate(); return "result"; } }); assertEquals("result", result); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setObject(2, 1, Types.INTEGER); verify(preparedStatement).close(); verify(connection).close(); }
private void addExternalIds() { FudgeMsgEnvelope env = s_fudgeContext.toFudgeMsg(ExternalId.of("A", "B")); byte[] bytes = s_fudgeContext.toByteArray(env.getMessage()); String cls = ExternalId.class.getName(); LobHandler lobHandler = new DefaultLobHandler(); final JdbcOperations template = _cfgMaster.getDbConnector().getJdbcOperations(); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 101, 101, toSqlTimestamp(_version1aInstant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1aInstant), MAX_SQL_TIMESTAMP, "TestConfig101", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 102, 102, toSqlTimestamp(_version1bInstant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1bInstant), MAX_SQL_TIMESTAMP, "TestConfig102", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 201, 201, toSqlTimestamp(_version1cInstant), toSqlTimestamp(_version2Instant), toSqlTimestamp(_version1cInstant), MAX_SQL_TIMESTAMP, "TestConfig201", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 202, 201, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP, "TestConfig202", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); _totalExternalIds = 3; }
private void addExternalIdBundles() { FudgeMsgEnvelope env = s_fudgeContext.toFudgeMsg(ExternalIdBundle.of(ExternalId.of("C", "D"), ExternalId.of("E", "F"))); byte[] bytes = s_fudgeContext.toByteArray(env.getMessage()); String cls = ExternalIdBundle.class.getName(); LobHandler lobHandler = new DefaultLobHandler(); final JdbcOperations template = _cfgMaster.getDbConnector().getJdbcOperations(); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 301, 301, toSqlTimestamp(_version1aInstant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1aInstant), MAX_SQL_TIMESTAMP, "TestConfig301", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 302, 302, toSqlTimestamp(_version1bInstant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1bInstant), MAX_SQL_TIMESTAMP, "TestConfig302", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 401, 401, toSqlTimestamp(_version1cInstant), toSqlTimestamp(_version2Instant), toSqlTimestamp(_version1cInstant), MAX_SQL_TIMESTAMP, "TestConfig401", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); template.update("INSERT INTO cfg_config VALUES (?,?,?,?,?, ?,?,?,?)", 402, 401, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP, "TestConfig402", cls, new SqlParameterValue(Types.BLOB, new SqlLobValue(bytes, lobHandler))); _totalBundles = 3; }
/** * Convert a Map of named parameter values to a corresponding array. * @param parsedSql the parsed SQL statement * @param paramSource the source for named parameters * @param declaredParams the List of declared SqlParameter objects * (may be {@code null}). If specified, the parameter metadata will * be built into the value array in the form of SqlParameterValue objects. * @return the array of values */ public static Object[] buildValueArray( ParsedSql parsedSql, SqlParameterSource paramSource, List<SqlParameter> declaredParams) { Object[] paramArray = new Object[parsedSql.getTotalParameterCount()]; if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) { throw new InvalidDataAccessApiUsageException( "Not allowed to mix named and traditional ? placeholders. You have " + parsedSql.getNamedParameterCount() + " named parameter(s) and " + parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " + parsedSql.getOriginalSql()); } List<String> paramNames = parsedSql.getParameterNames(); for (int i = 0; i < paramNames.size(); i++) { String paramName = paramNames.get(i); try { Object value = paramSource.getValue(paramName); SqlParameter param = findParameter(declaredParams, paramName, i); paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value); } catch (IllegalArgumentException ex) { throw new InvalidDataAccessApiUsageException( "No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage()); } } return paramArray; }
/** * Add a parameter to this parameter source. * @param paramName the name of the parameter * @param value the value of the parameter * @return a reference to this parameter source, * so it's possible to chain several calls together */ public MapSqlParameterSource addValue(String paramName, Object value) { Assert.notNull(paramName, "Parameter name must not be null"); this.values.put(paramName, value); if (value instanceof SqlParameterValue) { registerSqlType(paramName, ((SqlParameterValue) value).getSqlType()); } return this; }
/** * Add a Map of parameters to this parameter source. * @param values a Map holding existing parameter values (can be {@code null}) * @return a reference to this parameter source, * so it's possible to chain several calls together */ public MapSqlParameterSource addValues(Map<String, ?> values) { if (values != null) { for (Map.Entry<String, ?> entry : values.entrySet()) { this.values.put(entry.getKey(), entry.getValue()); if (entry.getValue() instanceof SqlParameterValue) { SqlParameterValue value = (SqlParameterValue) entry.getValue(); registerSqlType(entry.getKey(), value.getSqlType()); } } } return this; }
/** * Create a wrapped value if parameter has type information, plain object if not. * @param source the source of paramer values and type information * @param parameterName the name of the parameter * @return the value object */ public static Object getTypedValue(SqlParameterSource source, String parameterName) { int sqlType = source.getSqlType(parameterName); if (sqlType != SqlParameterSource.TYPE_UNKNOWN) { if (source.getTypeName(parameterName) != null) { return new SqlParameterValue(sqlType, source.getTypeName(parameterName), source.getValue(parameterName)); } else { return new SqlParameterValue(sqlType, source.getValue(parameterName)); } } else { return source.getValue(parameterName); } }
/** * executeUpdateForKey. * * @param query sql query string * @param keyValues parameters * @return number of updated rows */ private int executeUpdateForKey(final String query, final String... keyValues) { try { final SqlParameterValue[] values = Arrays.stream(keyValues).map(keyValue -> new SqlParameterValue(Types.VARCHAR, keyValue)) .toArray(SqlParameterValue[]::new); return jdbcTemplate.update(query, (Object[]) values); } catch (Exception e) { final String message = String.format("Failed to save data for %s", Arrays.toString(keyValues)); log.error(message, e); throw new UserMetadataServiceException(message, e); } }
@Override @Transactional(readOnly = true) public List<QualifiedName> searchByOwners(final Set<String> owners) { final List<QualifiedName> result = Lists.newArrayList(); final StringBuilder query = new StringBuilder(SQL.SEARCH_DEFINITION_METADATA_NAMES); final List<SqlParameterValue> paramList = Lists.newArrayList(); query.append(" where 1=0"); owners.forEach(s -> { query.append(" or data like ?"); paramList.add(new SqlParameterValue(Types.VARCHAR, "%\"userId\":\"" + s.trim() + "\"%")); }); final SqlParameterValue[] params = new SqlParameterValue[paramList.size()]; try { // Handler for reading the result set final ResultSetExtractor<Void> handler = rs -> { while (rs.next()) { final String definitionName = rs.getString("name"); result.add(QualifiedName.fromString(definitionName, false)); } return null; }; jdbcTemplate.query(query.toString(), paramList.toArray(params), handler); } catch (Exception e) { log.error("Failed to search by owners", e); throw new UserMetadataServiceException("Failed to search by owners", e); } return result; }
@SuppressWarnings("checkstyle:methodname") private void _delete(final List<PartitionSequenceIds> subPartitionIds) { final List<String> paramVariables = subPartitionIds.stream().map(s -> "?").collect(Collectors.toList()); final SqlParameterValue[] partIds = subPartitionIds.stream().map(p -> new SqlParameterValue(Types.BIGINT, p.getPartId())) .toArray(SqlParameterValue[]::new); final SqlParameterValue[] sdsIds = subPartitionIds.stream().map(p -> new SqlParameterValue(Types.BIGINT, p.getSdsId())) .toArray(SqlParameterValue[]::new); final SqlParameterValue[] serdeIds = subPartitionIds.stream().filter(p -> p.getSerdeId() != null) .map(p -> new SqlParameterValue(Types.BIGINT, p.getSerdeId())) .toArray(SqlParameterValue[]::new); final String paramVariableString = Joiner.on(",").skipNulls().join(paramVariables); jdbcTemplate.update( String.format(SQL.PARTITION_KEY_VALS_DELETES, paramVariableString), (Object[]) partIds); jdbcTemplate.update( String.format(SQL.PARTITION_PARAMS_DELETES, paramVariableString), (Object[]) partIds); jdbcTemplate.update( String.format(SQL.PARTITIONS_DELETES, paramVariableString), (Object[]) partIds); jdbcTemplate.update( String.format(SQL.SERDE_PARAMS_DELETES, paramVariableString), (Object[]) serdeIds); jdbcTemplate.update( String.format(SQL.SDS_DELETES, paramVariableString), (Object[]) sdsIds); jdbcTemplate.update( String.format(SQL.SERDES_DELETES, paramVariableString), (Object[]) serdeIds); }
@Test public void sqlParameterValueRegistersSqlType() throws Exception { MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(2, "Foo")); assertEquals("Correct SQL Type not registered", 2, msps.getSqlType("FOO")); MapSqlParameterSource msps2 = new MapSqlParameterSource(); msps2.addValues(msps.getValues()); assertEquals("Correct SQL Type not registered", 2, msps2.getSqlType("FOO")); }
@Test public void testQueryWithRowCallbackHandler() throws SQLException { given(resultSet.next()).willReturn(true, false); given(resultSet.getInt("id")).willReturn(1); given(resultSet.getString("forename")).willReturn("rod"); params.put("id", new SqlParameterValue(Types.DECIMAL, 1)); params.put("country", "UK"); final List<Customer> customers = new LinkedList<Customer>(); namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); customers.add(cust); } }); assertEquals(1, customers.size()); assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); verify(preparedStatement).close(); verify(connection).close(); }
@Test public void testQueryWithRowMapper() throws SQLException { given(resultSet.next()).willReturn(true, false); given(resultSet.getInt("id")).willReturn(1); given(resultSet.getString("forename")).willReturn("rod"); params.put("id", new SqlParameterValue(Types.DECIMAL, 1)); params.put("country", "UK"); List<Customer> customers = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowMapper<Customer>() { @Override public Customer mapRow(ResultSet rs, int rownum) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; } }); assertEquals(1, customers.size()); assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); verify(preparedStatement).close(); verify(connection).close(); }
@Test public void testUpdateWithTypedParameters() throws SQLException { given(preparedStatement.executeUpdate()).willReturn(1); params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); assertEquals(1, rowsAffected); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setObject(2, 1, Types.INTEGER); verify(preparedStatement).close(); verify(connection).close(); }
private Object blob(String name, ExternalIdBundle bundle) { MockLegalEntity value = new MockLegalEntity(name, bundle, Currency.GBP); String xml = JodaBeanSer.COMPACT.xmlWriter().write(value); byte[] bytes = ZipUtils.deflateString(xml); SqlLobValue lob = new SqlLobValue(bytes, getDbConnector().getDialect().getLobHandler()); return new SqlParameterValue(Types.BLOB, lob); }
private Object blob(String name, ExternalIdBundle bundle) { MockConvention value = new MockConvention(name, bundle, Currency.GBP); String xml = JodaBeanSerialization.serializer(false).xmlWriter().write(value); byte[] bytes = ZipUtils.deflateString(xml); SqlLobValue lob = new SqlLobValue(bytes, getDbConnector().getDialect().getLobHandler()); return new SqlParameterValue(Types.BLOB, lob); }
private Object blob(String name, ExternalIdBundle bundle) { EquitySecurity value = new EquitySecurity("LONDON", "LON", "LSE", Currency.GBP); value.setName(name); value.setExternalIdBundle(bundle); String xml = JodaBeanSerialization.serializer(false).xmlWriter().write(value); byte[] bytes = ZipUtils.deflateString(xml); SqlLobValue lob = new SqlLobValue(bytes, getDbConnector().getDialect().getLobHandler()); return new SqlParameterValue(Types.BLOB, lob); }
@Override public int[] call() throws Exception { JdbcTemplate jdbcTemplate = createJdbcTemplate(shard.getTargetDataSource(), ShardJdbcTemplate.this); String interceptedSql = shardDataSource.getSqlInterceptor().intercept(sql, shard.getTableContext()); return jdbcTemplate.batchUpdate(interceptedSql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int statementIndex) throws SQLException { Object[] args = argsList.get(statementIndex); for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg instanceof SqlParameterValue) { SqlParameterValue paramValue = (SqlParameterValue) arg; StatementCreatorUtils.setParameterValue(ps, i + 1, paramValue, paramValue.getValue()); } else { StatementCreatorUtils.setParameterValue(ps, i + 1, SqlTypeValue.TYPE_UNKNOWN, arg); } } } @Override public int getBatchSize() { return argsList.size(); } }); }
public static void buildArgumentList(List<SqlParameterValue> pv, CommonFieldsBase entity, DataField f) { switch (f.getDataType()) { case BOOLEAN: pv.add(getBindValue(f, entity.getBooleanField(f))); break; case STRING: case URI: pv.add(getBindValue(f, entity.getStringField(f))); break; case INTEGER: pv.add(getBindValue(f, entity.getLongField(f))); break; case DECIMAL: pv.add(getBindValue(f, entity.getNumericField(f))); break; case DATETIME: pv.add(getBindValue(f, entity.getDateField(f))); break; case BINARY: pv.add(getBindValue(f, entity.getBlobField(f))); break; case LONG_STRING: pv.add(getBindValue(f, entity.getStringField(f))); break; default: throw new IllegalStateException("Unexpected data type"); } }
private void createLogContent(StringBuilder b, int i, SqlParameterValue arg) { b.append("\nbinding[").append(i).append("]: type: "); switch ( arg.getSqlType() ) { case java.sql.Types.BOOLEAN: b.append("BOOLEAN"); break; case java.sql.Types.BIGINT: b.append("BIGINT"); break; case java.sql.Types.DECIMAL: b.append("DECIMAL"); break; case java.sql.Types.DOUBLE: b.append("DOUBLE"); break; case java.sql.Types.TIMESTAMP: b.append("TIMESTAMP"); break; case java.sql.Types.VARCHAR: b.append("VARCHAR"); break; case java.sql.Types.VARBINARY: b.append("VARBINARY"); break; default: b.append("**").append(arg.getSqlType()).append("**"); } if ( arg.getValue() == null ) { b.append(" is null"); } else { b.append(" = ").append(arg.getValue()); } }
private void createLogContent(StringBuilder b, int i, SqlParameterValue arg) { b.append("\nbinding[").append(i).append("]: type: "); switch ( arg.getSqlType() ) { case java.sql.Types.BIT: b.append("BIT"); break; case java.sql.Types.BIGINT: b.append("BIGINT"); break; case java.sql.Types.DECIMAL: b.append("DECIMAL"); break; case java.sql.Types.DOUBLE: b.append("DOUBLE"); break; case java.sql.Types.TIMESTAMP: b.append("TIMESTAMP"); break; case java.sql.Types.NVARCHAR: b.append("NVARCHAR"); break; case java.sql.Types.VARBINARY: b.append("VARBINARY"); break; default: b.append("**").append(arg.getSqlType()).append("**"); } if ( arg.getValue() == null ) { b.append(" is null"); } else { b.append(" = ").append(arg.getValue()); } }
public static int setValues(PreparedStatement ps, Object[] args, int startIndex) throws SQLException { int j = startIndex; if (args != null) { for (int i = 0; i < args.length; i++, j++) { Object arg = args[i]; if (arg instanceof SqlParameterValue) { SqlParameterValue paramValue = (SqlParameterValue) arg; StatementCreatorUtils.setParameterValue(ps, j, paramValue, paramValue.getValue()); } else { StatementCreatorUtils.setParameterValue(ps, j, Types.OTHER, arg); } } } return j; }