kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | aa7d4fd67322650fb8d747e7ebe5b125d8268aab58c87f2939a260f864e2e3de |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2016-02-19 19:43 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-03-07 16:23 +01:00 |
| Parents | df3d1644b9dd |
4 files changed
modified changelog/README.md +1 −0
| @@ -31,6 +31,7 @@ | ||
| 31 | 31 | - [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent. |
| 32 | 32 | - [improvement] JAVA-923: Position idempotent flag on object mapper queries. |
| 33 | 33 | - [new feature] JAVA-1019: SchemaBuilder support for CREATE/ALTER/DROP KEYSPACE. |
| 34 | +- [bug] JAVA-1070: The Mapper should not prepare queries synchronously. | |
| 34 | 35 | |
| 35 | 36 | Merged from 2.0 branch: |
| 36 | 37 |
added driver-mapping/src/main/java/com/datastax/driver/mapping/DriverThrowables.java +45 −0
| @@ -0,0 +1,45 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 19 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 20 | + | |
| 21 | +import java.util.concurrent.ExecutionException; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Copied here from com.datastax.driver.core.DriverThrowables | |
| 25 | + * because we don't want this class to be public. | |
| 26 | + */ | |
| 27 | +class DriverThrowables { | |
| 28 | + | |
| 29 | + static RuntimeException propagateCause(ExecutionException e) { | |
| 30 | + Throwable cause = e.getCause(); | |
| 31 | + | |
| 32 | + if (cause instanceof Error) | |
| 33 | + throw ((Error) cause); | |
| 34 | + | |
| 35 | + // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been | |
| 36 | + // created on the I/O thread receiving the response. Which means that the stacktrace associated | |
| 37 | + // with said cause will make no mention of the current thread. This is painful for say, finding | |
| 38 | + // out which execute() statement actually raised the exception. So instead, we re-create the | |
| 39 | + // exception. | |
| 40 | + if (cause instanceof DriverException) | |
| 41 | + throw ((DriverException) cause).copy(); | |
| 42 | + else | |
| 43 | + throw new DriverInternalError("Unexpected exception thrown", cause); | |
| 44 | + } | |
| 45 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +214 −119
| @@ -25,12 +25,14 @@ | ||
| 25 | 25 | import com.google.common.base.Functions; |
| 26 | 26 | import com.google.common.base.Objects; |
| 27 | 27 | import com.google.common.base.Preconditions; |
| 28 | -import com.google.common.util.concurrent.Futures; | |
| 29 | -import com.google.common.util.concurrent.ListenableFuture; | |
| 28 | +import com.google.common.util.concurrent.*; | |
| 30 | 29 | import org.slf4j.Logger; |
| 31 | 30 | import org.slf4j.LoggerFactory; |
| 32 | 31 | |
| 33 | 32 | import java.util.*; |
| 33 | +import java.util.concurrent.ConcurrentHashMap; | |
| 34 | +import java.util.concurrent.ConcurrentMap; | |
| 35 | +import java.util.concurrent.ExecutionException; | |
| 34 | 36 | |
| 35 | 37 | import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS; |
| 36 | 38 | import static com.google.common.base.Preconditions.checkArgument; |
| @@ -44,6 +46,7 @@ | ||
| 44 | 46 | public class Mapper<T> { |
| 45 | 47 | |
| 46 | 48 | private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class); |
| 49 | + private static final Function<Object, Void> TO_NULL = Functions.constant(null); | |
| 47 | 50 | |
| 48 | 51 | final MappingManager manager; |
| 49 | 52 | final ProtocolVersion protocolVersion; |
| @@ -52,9 +55,7 @@ | ||
| 52 | 55 | final TableMetadata tableMetadata; |
| 53 | 56 | |
| 54 | 57 | // Cache prepared statements for each type of query we use. |
| 55 | - private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap(); | |
| 56 | - | |
| 57 | - private static final Function<Object, Void> NOOP = Functions.constant(null); | |
| 58 | + private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); | |
| 58 | 59 | |
| 59 | 60 | private volatile EnumMap<Option.Type, Option> defaultSaveOptions; |
| 60 | 61 | private volatile EnumMap<Option.Type, Option> defaultGetOptions; |
| @@ -103,32 +104,41 @@ | ||
| 103 | 104 | return manager.getSession(); |
| 104 | 105 | } |
| 105 | 106 | |
| 106 | - PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 107 | - | |
| 108 | - MapperQueryKey pqk = new MapperQueryKey(type, columns, options); | |
| 109 | - | |
| 110 | - PreparedStatement stmt = preparedQueries.get(pqk); | |
| 111 | - if (stmt == null) { | |
| 112 | - synchronized (preparedQueries) { | |
| 113 | - stmt = preparedQueries.get(pqk); | |
| 114 | - if (stmt == null) { | |
| 115 | - String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 116 | - logger.debug("Preparing query {}", queryString); | |
| 117 | - SimpleStatement s = new SimpleStatement(queryString); | |
| 118 | - // all queries generated by the mapper are idempotent | |
| 119 | - s.setIdempotent(true); | |
| 120 | - stmt = session().prepare(s); | |
| 121 | - Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries); | |
| 122 | - newQueries.put(pqk, stmt); | |
| 123 | - preparedQueries = newQueries; | |
| 124 | - } | |
| 107 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 108 | + | |
| 109 | + final MapperQueryKey pqk = new MapperQueryKey(type, columns, options); | |
| 110 | + ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk); | |
| 111 | + if (existingFuture == null) { | |
| 112 | + final SettableFuture<PreparedStatement> future = SettableFuture.create(); | |
| 113 | + ListenableFuture<PreparedStatement> old = preparedQueries.putIfAbsent(pqk, future); | |
| 114 | + if (old != null) { | |
| 115 | + return old; | |
| 116 | + } else { | |
| 117 | + String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 118 | + logger.debug("Preparing query {}", queryString); | |
| 119 | + SimpleStatement s = new SimpleStatement(queryString); | |
| 120 | + // all queries generated by the mapper are idempotent | |
| 121 | + s.setIdempotent(true); | |
| 122 | + Futures.addCallback(session().prepareAsync(s), new FutureCallback<PreparedStatement>() { | |
| 123 | + @Override | |
| 124 | + public void onSuccess(PreparedStatement stmt) { | |
| 125 | + future.set(stmt); | |
| 126 | + } | |
| 127 | + | |
| 128 | + @Override | |
| 129 | + public void onFailure(Throwable t) { | |
| 130 | + future.setException(t); | |
| 131 | + } | |
| 132 | + }); | |
| 133 | + return future; | |
| 125 | 134 | } |
| 135 | + } else { | |
| 136 | + return existingFuture; | |
| 126 | 137 | } |
| 127 | - return stmt; | |
| 128 | 138 | } |
| 129 | 139 | |
| 130 | - PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) { | |
| 131 | - return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 140 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { | |
| 141 | + return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 132 | 142 | } |
| 133 | 143 | |
| 134 | 144 | /** |
| @@ -162,7 +172,11 @@ | ||
| 162 | 172 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 163 | 173 | */ |
| 164 | 174 | public Statement saveQuery(T entity) { |
| 165 | - return saveQuery(entity, this.defaultSaveOptions); | |
| 175 | + try { | |
| 176 | + return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions)); | |
| 177 | + } catch (ExecutionException e) { | |
| 178 | + throw DriverThrowables.propagateCause(e); | |
| 179 | + } | |
| 166 | 180 | } |
| 167 | 181 | |
| 168 | 182 | /** |
| @@ -186,11 +200,15 @@ | ||
| 186 | 200 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 187 | 201 | */ |
| 188 | 202 | public Statement saveQuery(T entity, Option... options) { |
| 189 | - return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions)); | |
| 203 | + try { | |
| 204 | + return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); | |
| 205 | + } catch (ExecutionException e) { | |
| 206 | + throw DriverThrowables.propagateCause(e); | |
| 207 | + } | |
| 190 | 208 | } |
| 191 | 209 | |
| 192 | - private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) { | |
| 193 | - Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 210 | + private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { | |
| 211 | + final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 194 | 212 | boolean saveNullFields = shouldSaveNullFields(options); |
| 195 | 213 | |
| 196 | 214 | for (ColumnMapper<T> cm : mapper.allColumns()) { |
| @@ -200,23 +218,28 @@ | ||
| 200 | 218 | } |
| 201 | 219 | } |
| 202 | 220 | |
| 203 | - BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind(); | |
| 204 | - int i = 0; | |
| 205 | - for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 206 | - DataType type = entry.getKey().getDataType(); | |
| 207 | - Object value = entry.getValue(); | |
| 208 | - bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion)); | |
| 209 | - } | |
| 221 | + return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { | |
| 222 | + @Override | |
| 223 | + public BoundStatement apply(PreparedStatement input) { | |
| 224 | + BoundStatement bs = input.bind(); | |
| 225 | + int i = 0; | |
| 226 | + for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 227 | + DataType type = entry.getKey().getDataType(); | |
| 228 | + Object value = entry.getValue(); | |
| 229 | + bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion)); | |
| 230 | + } | |
| 210 | 231 | |
| 211 | - if (mapper.writeConsistency != null) | |
| 212 | - bs.setConsistencyLevel(mapper.writeConsistency); | |
| 232 | + if (mapper.writeConsistency != null) | |
| 233 | + bs.setConsistencyLevel(mapper.writeConsistency); | |
| 213 | 234 | |
| 214 | - for (Option opt : options.values()) { | |
| 215 | - opt.checkValidFor(QueryType.SAVE, manager); | |
| 216 | - opt.addToPreparedStatement(bs, i++); | |
| 217 | - } | |
| 235 | + for (Option opt : options.values()) { | |
| 236 | + opt.checkValidFor(QueryType.SAVE, manager); | |
| 237 | + opt.addToPreparedStatement(bs, i++); | |
| 238 | + } | |
| 218 | 239 | |
| 219 | - return bs; | |
| 240 | + return bs; | |
| 241 | + } | |
| 242 | + }); | |
| 220 | 243 | } |
| 221 | 244 | |
| 222 | 245 | private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) { |
| @@ -225,18 +248,22 @@ | ||
| 225 | 248 | } |
| 226 | 249 | |
| 227 | 250 | /** |
| 228 | - * Save an entity mapped by this mapper. | |
| 251 | + * Saves an entity mapped by this mapper. | |
| 229 | 252 | * <p/> |
| 230 | 253 | * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}. |
| 231 | 254 | * |
| 232 | 255 | * @param entity the entity to save. |
| 233 | 256 | */ |
| 234 | 257 | public void save(T entity) { |
| 235 | - session().execute(saveQuery(entity)); | |
| 258 | + try { | |
| 259 | + Uninterruptibles.getUninterruptibly(saveAsync(entity)); | |
| 260 | + } catch (ExecutionException e) { | |
| 261 | + throw DriverThrowables.propagateCause(e); | |
| 262 | + } | |
| 236 | 263 | } |
| 237 | 264 | |
| 238 | 265 | /** |
| 239 | - * Save an entity mapped by this mapper and using special options for save. | |
| 266 | + * Saves an entity mapped by this mapper and using special options for save. | |
| 240 | 267 | * This method allows you to provide a suite of {@link Option} to include in |
| 241 | 268 | * the SAVE query. Options currently supported for SAVE are : |
| 242 | 269 | * <ul> |
| @@ -250,11 +277,15 @@ | ||
| 250 | 277 | * @param options the options object specified defining special options when saving. |
| 251 | 278 | */ |
| 252 | 279 | public void save(T entity, Option... options) { |
| 253 | - session().execute(saveQuery(entity, options)); | |
| 280 | + try { | |
| 281 | + Uninterruptibles.getUninterruptibly(saveAsync(entity, options)); | |
| 282 | + } catch (ExecutionException e) { | |
| 283 | + throw DriverThrowables.propagateCause(e); | |
| 284 | + } | |
| 254 | 285 | } |
| 255 | 286 | |
| 256 | 287 | /** |
| 257 | - * Save an entity mapped by this mapper asynchronously. | |
| 288 | + * Saves an entity mapped by this mapper asynchronously. | |
| 258 | 289 | * <p/> |
| 259 | 290 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}. |
| 260 | 291 | * |
| @@ -262,7 +293,7 @@ | ||
| 262 | 293 | * @return a future on the completion of the save operation. |
| 263 | 294 | */ |
| 264 | 295 | public ListenableFuture<Void> saveAsync(T entity) { |
| 265 | - return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP); | |
| 296 | + return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions)); | |
| 266 | 297 | } |
| 267 | 298 | |
| 268 | 299 | /** |
| @@ -275,7 +306,17 @@ | ||
| 275 | 306 | * @return a future on the completion of the save operation. |
| 276 | 307 | */ |
| 277 | 308 | public ListenableFuture<Void> saveAsync(T entity, Option... options) { |
| 278 | - return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP); | |
| 309 | + return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); | |
| 310 | + } | |
| 311 | + | |
| 312 | + private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) { | |
| 313 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 314 | + @Override | |
| 315 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 316 | + return session().executeAsync(bs); | |
| 317 | + } | |
| 318 | + }); | |
| 319 | + return Futures.transform(rsFuture, TO_NULL); | |
| 279 | 320 | } |
| 280 | 321 | |
| 281 | 322 | /** |
| @@ -304,10 +345,17 @@ | ||
| 304 | 345 | * at least one of those values is {@code null}. |
| 305 | 346 | */ |
| 306 | 347 | public Statement getQuery(Object... objects) { |
| 348 | + try { | |
| 349 | + return Uninterruptibles.getUninterruptibly(getQueryAsync(objects)); | |
| 350 | + } catch (ExecutionException e) { | |
| 351 | + throw DriverThrowables.propagateCause(e); | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 355 | + private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) { | |
| 307 | 356 | // Order and duplicates matter for primary keys |
| 308 | 357 | List<Object> pks = new ArrayList<Object>(); |
| 309 | 358 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions); |
| 310 | - | |
| 311 | 359 | for (Object o : objects) { |
| 312 | 360 | if (o instanceof Option) { |
| 313 | 361 | Option option = (Option) o; |
| @@ -316,35 +364,38 @@ | ||
| 316 | 364 | pks.add(o); |
| 317 | 365 | } |
| 318 | 366 | } |
| 319 | - return getQuery(pks, options); | |
| 367 | + return getQueryAsync(pks, options); | |
| 320 | 368 | } |
| 321 | 369 | |
| 322 | - private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) { | |
| 323 | - | |
| 370 | + private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) { | |
| 324 | 371 | if (primaryKeys.size() != mapper.primaryKeySize()) |
| 325 | 372 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size())); |
| 326 | 373 | |
| 327 | - BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options)); | |
| 328 | - int i = 0; | |
| 329 | - for (Object value : primaryKeys) { | |
| 330 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 331 | - if (value == null) { | |
| 332 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 333 | - } | |
| 334 | - bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion)); | |
| 335 | - } | |
| 336 | - | |
| 337 | - if (mapper.readConsistency != null) | |
| 338 | - bs.setConsistencyLevel(mapper.readConsistency); | |
| 339 | - | |
| 340 | - for (Option opt : options.values()) { | |
| 341 | - opt.checkValidFor(QueryType.GET, manager); | |
| 342 | - opt.addToPreparedStatement(bs, i); | |
| 343 | - if (opt.isIncludedInQuery()) | |
| 344 | - i++; | |
| 345 | - } | |
| 374 | + return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() { | |
| 375 | + @Override | |
| 376 | + public BoundStatement apply(PreparedStatement input) { | |
| 377 | + BoundStatement bs = new MapperBoundStatement(input); | |
| 378 | + int i = 0; | |
| 379 | + for (Object value : primaryKeys) { | |
| 380 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 381 | + if (value == null) { | |
| 382 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 383 | + } | |
| 384 | + bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion)); | |
| 385 | + } | |
| 346 | 386 | |
| 347 | - return bs; | |
| 387 | + if (mapper.readConsistency != null) | |
| 388 | + bs.setConsistencyLevel(mapper.readConsistency); | |
| 389 | + | |
| 390 | + for (Option opt : options.values()) { | |
| 391 | + opt.checkValidFor(QueryType.GET, manager); | |
| 392 | + opt.addToPreparedStatement(bs, i); | |
| 393 | + if (opt.isIncludedInQuery()) | |
| 394 | + i++; | |
| 395 | + } | |
| 396 | + return bs; | |
| 397 | + } | |
| 398 | + }); | |
| 348 | 399 | } |
| 349 | 400 | |
| 350 | 401 | /** |
| @@ -361,7 +412,11 @@ | ||
| 361 | 412 | * at least one of those values is {@code null}. |
| 362 | 413 | */ |
| 363 | 414 | public T get(Object... objects) { |
| 364 | - return map(session().execute(getQuery(objects))).one(); | |
| 415 | + try { | |
| 416 | + return Uninterruptibles.getUninterruptibly(getAsync(objects)); | |
| 417 | + } catch (ExecutionException e) { | |
| 418 | + throw DriverThrowables.propagateCause(e); | |
| 419 | + } | |
| 365 | 420 | } |
| 366 | 421 | |
| 367 | 422 | /** |
| @@ -378,8 +433,15 @@ | ||
| 378 | 433 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 379 | 434 | * at least one of those values is {@code null}. |
| 380 | 435 | */ |
| 381 | - public ListenableFuture<T> getAsync(Object... objects) { | |
| 382 | - return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction); | |
| 436 | + public ListenableFuture<T> getAsync(final Object... objects) { | |
| 437 | + ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); | |
| 438 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 439 | + @Override | |
| 440 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 441 | + return session().executeAsync(bs); | |
| 442 | + } | |
| 443 | + }); | |
| 444 | + return Futures.transform(rsFuture, mapOneFunction); | |
| 383 | 445 | } |
| 384 | 446 | |
| 385 | 447 | /** |
| @@ -411,12 +473,11 @@ | ||
| 411 | 473 | * provided USING options. |
| 412 | 474 | */ |
| 413 | 475 | public Statement deleteQuery(T entity, Option... options) { |
| 414 | - List<Object> pks = new ArrayList<Object>(); | |
| 415 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 416 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 476 | + try { | |
| 477 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 478 | + } catch (ExecutionException e) { | |
| 479 | + throw DriverThrowables.propagateCause(e); | |
| 417 | 480 | } |
| 418 | - | |
| 419 | - return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions)); | |
| 420 | 481 | } |
| 421 | 482 | |
| 422 | 483 | /** |
| @@ -435,12 +496,11 @@ | ||
| 435 | 496 | * @return a query that delete {@code entity} (based on it's defined mapping). |
| 436 | 497 | */ |
| 437 | 498 | public Statement deleteQuery(T entity) { |
| 438 | - List<Object> pks = new ArrayList<Object>(); | |
| 439 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 440 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 499 | + try { | |
| 500 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 501 | + } catch (ExecutionException e) { | |
| 502 | + throw DriverThrowables.propagateCause(e); | |
| 441 | 503 | } |
| 442 | - | |
| 443 | - return deleteQuery(pks, defaultDeleteOptions); | |
| 444 | 504 | } |
| 445 | 505 | |
| 446 | 506 | /** |
| @@ -475,10 +535,25 @@ | ||
| 475 | 535 | * at least one of those values is {@code null}. |
| 476 | 536 | */ |
| 477 | 537 | public Statement deleteQuery(Object... objects) { |
| 538 | + try { | |
| 539 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects)); | |
| 540 | + } catch (ExecutionException e) { | |
| 541 | + throw DriverThrowables.propagateCause(e); | |
| 542 | + } | |
| 543 | + } | |
| 544 | + | |
| 545 | + private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) { | |
| 546 | + List<Object> pks = new ArrayList<Object>(); | |
| 547 | + for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 548 | + pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 549 | + } | |
| 550 | + return deleteQueryAsync(pks, options); | |
| 551 | + } | |
| 552 | + | |
| 553 | + private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) { | |
| 478 | 554 | // Order and duplicates matter for primary keys |
| 479 | 555 | List<Object> pks = new ArrayList<Object>(); |
| 480 | 556 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions); |
| 481 | - | |
| 482 | 557 | for (Object o : objects) { |
| 483 | 558 | if (o instanceof Option) { |
| 484 | 559 | Option option = (Option) o; |
| @@ -487,36 +562,40 @@ | ||
| 487 | 562 | pks.add(o); |
| 488 | 563 | } |
| 489 | 564 | } |
| 490 | - return deleteQuery(pks, options); | |
| 565 | + return deleteQueryAsync(pks, options); | |
| 491 | 566 | } |
| 492 | 567 | |
| 493 | - private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) { | |
| 568 | + private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) { | |
| 494 | 569 | if (primaryKey.size() != mapper.primaryKeySize()) |
| 495 | 570 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size())); |
| 496 | 571 | |
| 497 | - BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind(); | |
| 498 | - | |
| 499 | - if (mapper.writeConsistency != null) | |
| 500 | - bs.setConsistencyLevel(mapper.writeConsistency); | |
| 501 | - | |
| 502 | - int i = 0; | |
| 503 | - for (Option opt : options.values()) { | |
| 504 | - opt.checkValidFor(QueryType.DEL, manager); | |
| 505 | - opt.addToPreparedStatement(bs, i); | |
| 506 | - if (opt.isIncludedInQuery()) | |
| 507 | - i++; | |
| 508 | - } | |
| 572 | + return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() { | |
| 573 | + @Override | |
| 574 | + public BoundStatement apply(PreparedStatement input) { | |
| 575 | + BoundStatement bs = input.bind(); | |
| 576 | + if (mapper.writeConsistency != null) | |
| 577 | + bs.setConsistencyLevel(mapper.writeConsistency); | |
| 578 | + | |
| 579 | + int i = 0; | |
| 580 | + for (Option opt : options.values()) { | |
| 581 | + opt.checkValidFor(QueryType.DEL, manager); | |
| 582 | + opt.addToPreparedStatement(bs, i); | |
| 583 | + if (opt.isIncludedInQuery()) | |
| 584 | + i++; | |
| 585 | + } | |
| 509 | 586 | |
| 510 | - int columnNumber = 0; | |
| 511 | - for (Object value : primaryKey) { | |
| 512 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 513 | - if (value == null) { | |
| 514 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 587 | + int columnNumber = 0; | |
| 588 | + for (Object value : primaryKey) { | |
| 589 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 590 | + if (value == null) { | |
| 591 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 592 | + } | |
| 593 | + bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion)); | |
| 594 | + columnNumber++; | |
| 595 | + } | |
| 596 | + return bs; | |
| 515 | 597 | } |
| 516 | - bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion)); | |
| 517 | - columnNumber++; | |
| 518 | - } | |
| 519 | - return bs; | |
| 598 | + }); | |
| 520 | 599 | } |
| 521 | 600 | |
| 522 | 601 | /** |
| @@ -527,7 +606,11 @@ | ||
| 527 | 606 | * @param entity the entity to delete. |
| 528 | 607 | */ |
| 529 | 608 | public void delete(T entity) { |
| 530 | - session().execute(deleteQuery(entity)); | |
| 609 | + try { | |
| 610 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity)); | |
| 611 | + } catch (ExecutionException e) { | |
| 612 | + throw DriverThrowables.propagateCause(e); | |
| 613 | + } | |
| 531 | 614 | } |
| 532 | 615 | |
| 533 | 616 | /** |
| @@ -539,7 +622,11 @@ | ||
| 539 | 622 | * @param options the options to add to the DELETE query. |
| 540 | 623 | */ |
| 541 | 624 | public void delete(T entity, Option... options) { |
| 542 | - session().execute(deleteQuery(entity, options)); | |
| 625 | + try { | |
| 626 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity, options)); | |
| 627 | + } catch (ExecutionException e) { | |
| 628 | + throw DriverThrowables.propagateCause(e); | |
| 629 | + } | |
| 543 | 630 | } |
| 544 | 631 | |
| 545 | 632 | /** |
| @@ -551,7 +638,7 @@ | ||
| 551 | 638 | * @return a future on the completion of the deletion. |
| 552 | 639 | */ |
| 553 | 640 | public ListenableFuture<Void> deleteAsync(T entity) { |
| 554 | - return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP); | |
| 641 | + return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 555 | 642 | } |
| 556 | 643 | |
| 557 | 644 | /** |
| @@ -564,7 +651,7 @@ | ||
| 564 | 651 | * @return a future on the completion of the deletion. |
| 565 | 652 | */ |
| 566 | 653 | public ListenableFuture<Void> deleteAsync(T entity, Option... options) { |
| 567 | - return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP); | |
| 654 | + return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 568 | 655 | } |
| 569 | 656 | |
| 570 | 657 | /** |
| @@ -581,7 +668,11 @@ | ||
| 581 | 668 | * at least one of those values is {@code null}. |
| 582 | 669 | */ |
| 583 | 670 | public void delete(Object... objects) { |
| 584 | - session().execute(deleteQuery(objects)); | |
| 671 | + try { | |
| 672 | + Uninterruptibles.getUninterruptibly(deleteAsync(objects)); | |
| 673 | + } catch (ExecutionException e) { | |
| 674 | + throw DriverThrowables.propagateCause(e); | |
| 675 | + } | |
| 585 | 676 | } |
| 586 | 677 | |
| 587 | 678 | /** |
| @@ -598,10 +689,14 @@ | ||
| 598 | 689 | * at least one of those values is {@code null}. |
| 599 | 690 | */ |
| 600 | 691 | public ListenableFuture<Void> deleteAsync(Object... objects) { |
| 601 | - return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP); | |
| 692 | + return submitVoidQueryAsync(deleteQueryAsync(objects)); | |
| 602 | 693 | } |
| 603 | 694 | |
| 604 | 695 | /** |
| 696 | + * Creates a query to fetch entity given its PRIMARY KEY. | |
| 697 | + * <p/> | |
| 698 | + * <p/> | |
| 699 | + * /** | |
| 605 | 700 | * Maps the rows from a {@code ResultSet} into the class this is a mapper of. |
| 606 | 701 | * <p/> |
| 607 | 702 | * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with |
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAsyncTest.java +186 −0
| @@ -0,0 +1,186 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | +import com.datastax.driver.core.Cluster; | |
| 20 | +import com.datastax.driver.core.Session; | |
| 21 | +import com.datastax.driver.core.utils.MoreFutures.SuccessCallback; | |
| 22 | +import com.datastax.driver.core.utils.UUIDs; | |
| 23 | +import com.datastax.driver.mapping.annotations.Column; | |
| 24 | +import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 25 | +import com.datastax.driver.mapping.annotations.Table; | |
| 26 | +import com.google.common.base.Function; | |
| 27 | +import com.google.common.base.Objects; | |
| 28 | +import com.google.common.util.concurrent.Futures; | |
| 29 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 30 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 31 | +import org.testng.annotations.Test; | |
| 32 | + | |
| 33 | +import java.util.UUID; | |
| 34 | +import java.util.concurrent.CountDownLatch; | |
| 35 | + | |
| 36 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 37 | +import static java.util.concurrent.TimeUnit.MINUTES; | |
| 38 | +import static org.testng.Assert.fail; | |
| 39 | + | |
| 40 | +/** | |
| 41 | + * Basic tests for the mapping module. | |
| 42 | + */ | |
| 43 | +@SuppressWarnings("unused") | |
| 44 | +public class MapperAsyncTest extends CCMTestsSupport { | |
| 45 | + | |
| 46 | + private static final String KEYSPACE = "mapper_async_test_ks"; | |
| 47 | + | |
| 48 | + private final User paul = new User("Paul", "paul@yahoo.com"); | |
| 49 | + | |
| 50 | + @Override | |
| 51 | + public void onTestContextInitialized() { | |
| 52 | + execute( | |
| 53 | + String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, KEYSPACE, 1), | |
| 54 | + String.format("CREATE TABLE %s.users (user_id uuid PRIMARY KEY, name text, email text)", KEYSPACE) | |
| 55 | + ); | |
| 56 | + } | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * Validates that when using save, get and deleteAsync using the same executor as the caller that the driver | |
| 60 | + * does not block indefinitely in a netty worker thread. | |
| 61 | + * | |
| 62 | + * @jira_ticket JAVA-1070 | |
| 63 | + * @test_category queries:async | |
| 64 | + * @test_category object_mapper | |
| 65 | + */ | |
| 66 | + @Test(groups = "short") | |
| 67 | + public void should_get_query_async_without_blocking() { | |
| 68 | + | |
| 69 | + final CountDownLatch latch = new CountDownLatch(1); | |
| 70 | + | |
| 71 | + // create a second cluster to perform everything asynchronously, | |
| 72 | + // including session initialization | |
| 73 | + Cluster cluster2 = register( | |
| 74 | + createClusterBuilderNoDebouncing() | |
| 75 | + .addContactPoints(getContactPoints()) | |
| 76 | + .withPort(ccm().getBinaryPort()) | |
| 77 | + .build()); | |
| 78 | + | |
| 79 | + ListenableFuture<MappingManager> mappingManagerFuture = Futures.transform( | |
| 80 | + cluster2.connectAsync(), | |
| 81 | + new Function<Session, MappingManager>() { | |
| 82 | + @Override | |
| 83 | + public MappingManager apply(Session session) { | |
| 84 | + return new MappingManager(session); | |
| 85 | + } | |
| 86 | + }); | |
| 87 | + | |
| 88 | + Futures.addCallback(mappingManagerFuture, new SuccessCallback<MappingManager>() { | |
| 89 | + | |
| 90 | + @Override | |
| 91 | + public void onSuccess(MappingManager manager) { | |
| 92 | + | |
| 93 | + final Mapper<User> mapper = manager.mapper(User.class); | |
| 94 | + ListenableFuture<Void> saveFuture = mapper.saveAsync(paul); | |
| 95 | + Futures.addCallback(saveFuture, new SuccessCallback<Void>() { | |
| 96 | + | |
| 97 | + @Override | |
| 98 | + public void onSuccess(Void result) { | |
| 99 | + ListenableFuture<User> getFuture = mapper.getAsync(paul.getUserId()); | |
| 100 | + Futures.addCallback(getFuture, new SuccessCallback<User>() { | |
| 101 | + | |
| 102 | + @Override | |
| 103 | + public void onSuccess(User paul) { | |
| 104 | + | |
| 105 | + Futures.addCallback(mapper.deleteAsync(paul), new SuccessCallback<Void>() { | |
| 106 | + @Override | |
| 107 | + public void onSuccess(Void result) { | |
| 108 | + latch.countDown(); | |
| 109 | + } | |
| 110 | + }); | |
| 111 | + } | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + }); | |
| 115 | + } | |
| 116 | + }); | |
| 117 | + | |
| 118 | + try { | |
| 119 | + Uninterruptibles.awaitUninterruptibly(latch, 5, MINUTES); | |
| 120 | + } catch (Exception e) { | |
| 121 | + fail("Operation did not complete normally within 5 minutes"); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + | |
| 125 | + @Table(name = "users", keyspace = KEYSPACE) | |
| 126 | + public static class User { | |
| 127 | + | |
| 128 | + @PartitionKey | |
| 129 | + @Column(name = "user_id") | |
| 130 | + private UUID userId; | |
| 131 | + | |
| 132 | + private String name; | |
| 133 | + | |
| 134 | + private String email; | |
| 135 | + | |
| 136 | + public User() { | |
| 137 | + } | |
| 138 | + | |
| 139 | + public User(String name, String email) { | |
| 140 | + this.userId = UUIDs.random(); | |
| 141 | + this.name = name; | |
| 142 | + this.email = email; | |
| 143 | + } | |
| 144 | + | |
| 145 | + public UUID getUserId() { | |
| 146 | + return userId; | |
| 147 | + } | |
| 148 | + | |
| 149 | + public void setUserId(UUID userId) { | |
| 150 | + this.userId = userId; | |
| 151 | + } | |
| 152 | + | |
| 153 | + public String getName() { | |
| 154 | + return name; | |
| 155 | + } | |
| 156 | + | |
| 157 | + public void setName(String name) { | |
| 158 | + this.name = name; | |
| 159 | + } | |
| 160 | + | |
| 161 | + public String getEmail() { | |
| 162 | + return email; | |
| 163 | + } | |
| 164 | + | |
| 165 | + public void setEmail(String email) { | |
| 166 | + this.email = email; | |
| 167 | + } | |
| 168 | + | |
| 169 | + @Override | |
| 170 | + public boolean equals(Object other) { | |
| 171 | + if (other == null || other.getClass() != this.getClass()) | |
| 172 | + return false; | |
| 173 | + | |
| 174 | + User that = (User) other; | |
| 175 | + return Objects.equal(userId, that.userId) | |
| 176 | + && Objects.equal(name, that.name) | |
| 177 | + && Objects.equal(email, that.email); | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Override | |
| 181 | + public int hashCode() { | |
| 182 | + return Objects.hashCode(userId, name, email); | |
| 183 | + } | |
| 184 | + } | |
| 185 | + | |
| 186 | +} |