kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | a8f33563abe02bf8eb92a4fd5ba6b0c5758de970251fa68339ea9d7cc1b4e9a5 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-03-07 16:26 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-04-01 11:35 +02:00 |
| Parents | 4a433a1ccc27 |
4 files changed
modified changelog/README.md +1 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | - [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key. |
| 16 | 16 | - [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent. |
| 17 | 17 | - [improvement] JAVA-923: Position idempotent flag on object mapper queries. |
| 18 | +- [bug] JAVA-1070: The Mapper should not prepare queries synchronously. | |
| 18 | 19 | |
| 19 | 20 | |
| 20 | 21 | ### 3.0.0 |
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 | - ColumnMapper<?> mapper = entry.getKey(); | |
| 207 | - Object value = entry.getValue(); | |
| 208 | - setObject(bs, i++, value, mapper); | |
| 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 | + ColumnMapper<?> mapper = entry.getKey(); | |
| 228 | + Object value = entry.getValue(); | |
| 229 | + setObject(bs, i++, value, mapper); | |
| 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) { |
| @@ -233,18 +256,22 @@ | ||
| 233 | 256 | } |
| 234 | 257 | |
| 235 | 258 | /** |
| 236 | - * Save an entity mapped by this mapper. | |
| 259 | + * Saves an entity mapped by this mapper. | |
| 237 | 260 | * <p/> |
| 238 | 261 | * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}. |
| 239 | 262 | * |
| 240 | 263 | * @param entity the entity to save. |
| 241 | 264 | */ |
| 242 | 265 | public void save(T entity) { |
| 243 | - session().execute(saveQuery(entity)); | |
| 266 | + try { | |
| 267 | + Uninterruptibles.getUninterruptibly(saveAsync(entity)); | |
| 268 | + } catch (ExecutionException e) { | |
| 269 | + throw DriverThrowables.propagateCause(e); | |
| 270 | + } | |
| 244 | 271 | } |
| 245 | 272 | |
| 246 | 273 | /** |
| 247 | - * Save an entity mapped by this mapper and using special options for save. | |
| 274 | + * Saves an entity mapped by this mapper and using special options for save. | |
| 248 | 275 | * This method allows you to provide a suite of {@link Option} to include in |
| 249 | 276 | * the SAVE query. Options currently supported for SAVE are : |
| 250 | 277 | * <ul> |
| @@ -258,11 +285,15 @@ | ||
| 258 | 285 | * @param options the options object specified defining special options when saving. |
| 259 | 286 | */ |
| 260 | 287 | public void save(T entity, Option... options) { |
| 261 | - session().execute(saveQuery(entity, options)); | |
| 288 | + try { | |
| 289 | + Uninterruptibles.getUninterruptibly(saveAsync(entity, options)); | |
| 290 | + } catch (ExecutionException e) { | |
| 291 | + throw DriverThrowables.propagateCause(e); | |
| 292 | + } | |
| 262 | 293 | } |
| 263 | 294 | |
| 264 | 295 | /** |
| 265 | - * Save an entity mapped by this mapper asynchronously. | |
| 296 | + * Saves an entity mapped by this mapper asynchronously. | |
| 266 | 297 | * <p/> |
| 267 | 298 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}. |
| 268 | 299 | * |
| @@ -270,7 +301,7 @@ | ||
| 270 | 301 | * @return a future on the completion of the save operation. |
| 271 | 302 | */ |
| 272 | 303 | public ListenableFuture<Void> saveAsync(T entity) { |
| 273 | - return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP); | |
| 304 | + return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions)); | |
| 274 | 305 | } |
| 275 | 306 | |
| 276 | 307 | /** |
| @@ -283,7 +314,17 @@ | ||
| 283 | 314 | * @return a future on the completion of the save operation. |
| 284 | 315 | */ |
| 285 | 316 | public ListenableFuture<Void> saveAsync(T entity, Option... options) { |
| 286 | - return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP); | |
| 317 | + return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); | |
| 318 | + } | |
| 319 | + | |
| 320 | + private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) { | |
| 321 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 322 | + @Override | |
| 323 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 324 | + return session().executeAsync(bs); | |
| 325 | + } | |
| 326 | + }); | |
| 327 | + return Futures.transform(rsFuture, TO_NULL); | |
| 287 | 328 | } |
| 288 | 329 | |
| 289 | 330 | /** |
| @@ -312,10 +353,17 @@ | ||
| 312 | 353 | * at least one of those values is {@code null}. |
| 313 | 354 | */ |
| 314 | 355 | public Statement getQuery(Object... objects) { |
| 356 | + try { | |
| 357 | + return Uninterruptibles.getUninterruptibly(getQueryAsync(objects)); | |
| 358 | + } catch (ExecutionException e) { | |
| 359 | + throw DriverThrowables.propagateCause(e); | |
| 360 | + } | |
| 361 | + } | |
| 362 | + | |
| 363 | + private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) { | |
| 315 | 364 | // Order and duplicates matter for primary keys |
| 316 | 365 | List<Object> pks = new ArrayList<Object>(); |
| 317 | 366 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions); |
| 318 | - | |
| 319 | 367 | for (Object o : objects) { |
| 320 | 368 | if (o instanceof Option) { |
| 321 | 369 | Option option = (Option) o; |
| @@ -324,35 +372,38 @@ | ||
| 324 | 372 | pks.add(o); |
| 325 | 373 | } |
| 326 | 374 | } |
| 327 | - return getQuery(pks, options); | |
| 375 | + return getQueryAsync(pks, options); | |
| 328 | 376 | } |
| 329 | 377 | |
| 330 | - private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) { | |
| 331 | - | |
| 378 | + private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) { | |
| 332 | 379 | if (primaryKeys.size() != mapper.primaryKeySize()) |
| 333 | 380 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size())); |
| 334 | 381 | |
| 335 | - BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options)); | |
| 336 | - int i = 0; | |
| 337 | - for (Object value : primaryKeys) { | |
| 338 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 339 | - if (value == null) { | |
| 340 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 341 | - } | |
| 342 | - setObject(bs, i++, value, column); | |
| 343 | - } | |
| 344 | - | |
| 345 | - if (mapper.readConsistency != null) | |
| 346 | - bs.setConsistencyLevel(mapper.readConsistency); | |
| 347 | - | |
| 348 | - for (Option opt : options.values()) { | |
| 349 | - opt.checkValidFor(QueryType.GET, manager); | |
| 350 | - opt.addToPreparedStatement(bs, i); | |
| 351 | - if (opt.isIncludedInQuery()) | |
| 352 | - i++; | |
| 353 | - } | |
| 382 | + return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() { | |
| 383 | + @Override | |
| 384 | + public BoundStatement apply(PreparedStatement input) { | |
| 385 | + BoundStatement bs = new MapperBoundStatement(input); | |
| 386 | + int i = 0; | |
| 387 | + for (Object value : primaryKeys) { | |
| 388 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 389 | + if (value == null) { | |
| 390 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 391 | + } | |
| 392 | + setObject(bs, i++, value, column); | |
| 393 | + } | |
| 354 | 394 | |
| 355 | - return bs; | |
| 395 | + if (mapper.readConsistency != null) | |
| 396 | + bs.setConsistencyLevel(mapper.readConsistency); | |
| 397 | + | |
| 398 | + for (Option opt : options.values()) { | |
| 399 | + opt.checkValidFor(QueryType.GET, manager); | |
| 400 | + opt.addToPreparedStatement(bs, i); | |
| 401 | + if (opt.isIncludedInQuery()) | |
| 402 | + i++; | |
| 403 | + } | |
| 404 | + return bs; | |
| 405 | + } | |
| 406 | + }); | |
| 356 | 407 | } |
| 357 | 408 | |
| 358 | 409 | /** |
| @@ -369,7 +420,11 @@ | ||
| 369 | 420 | * at least one of those values is {@code null}. |
| 370 | 421 | */ |
| 371 | 422 | public T get(Object... objects) { |
| 372 | - return map(session().execute(getQuery(objects))).one(); | |
| 423 | + try { | |
| 424 | + return Uninterruptibles.getUninterruptibly(getAsync(objects)); | |
| 425 | + } catch (ExecutionException e) { | |
| 426 | + throw DriverThrowables.propagateCause(e); | |
| 427 | + } | |
| 373 | 428 | } |
| 374 | 429 | |
| 375 | 430 | /** |
| @@ -386,8 +441,15 @@ | ||
| 386 | 441 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 387 | 442 | * at least one of those values is {@code null}. |
| 388 | 443 | */ |
| 389 | - public ListenableFuture<T> getAsync(Object... objects) { | |
| 390 | - return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction); | |
| 444 | + public ListenableFuture<T> getAsync(final Object... objects) { | |
| 445 | + ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); | |
| 446 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 447 | + @Override | |
| 448 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 449 | + return session().executeAsync(bs); | |
| 450 | + } | |
| 451 | + }); | |
| 452 | + return Futures.transform(rsFuture, mapOneFunction); | |
| 391 | 453 | } |
| 392 | 454 | |
| 393 | 455 | /** |
| @@ -419,12 +481,11 @@ | ||
| 419 | 481 | * provided USING options. |
| 420 | 482 | */ |
| 421 | 483 | public Statement deleteQuery(T entity, Option... options) { |
| 422 | - List<Object> pks = new ArrayList<Object>(); | |
| 423 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 424 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 484 | + try { | |
| 485 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 486 | + } catch (ExecutionException e) { | |
| 487 | + throw DriverThrowables.propagateCause(e); | |
| 425 | 488 | } |
| 426 | - | |
| 427 | - return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions)); | |
| 428 | 489 | } |
| 429 | 490 | |
| 430 | 491 | /** |
| @@ -443,12 +504,11 @@ | ||
| 443 | 504 | * @return a query that delete {@code entity} (based on it's defined mapping). |
| 444 | 505 | */ |
| 445 | 506 | public Statement deleteQuery(T entity) { |
| 446 | - List<Object> pks = new ArrayList<Object>(); | |
| 447 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 448 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 507 | + try { | |
| 508 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 509 | + } catch (ExecutionException e) { | |
| 510 | + throw DriverThrowables.propagateCause(e); | |
| 449 | 511 | } |
| 450 | - | |
| 451 | - return deleteQuery(pks, defaultDeleteOptions); | |
| 452 | 512 | } |
| 453 | 513 | |
| 454 | 514 | /** |
| @@ -483,10 +543,25 @@ | ||
| 483 | 543 | * at least one of those values is {@code null}. |
| 484 | 544 | */ |
| 485 | 545 | public Statement deleteQuery(Object... objects) { |
| 546 | + try { | |
| 547 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects)); | |
| 548 | + } catch (ExecutionException e) { | |
| 549 | + throw DriverThrowables.propagateCause(e); | |
| 550 | + } | |
| 551 | + } | |
| 552 | + | |
| 553 | + private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) { | |
| 554 | + List<Object> pks = new ArrayList<Object>(); | |
| 555 | + for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 556 | + pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 557 | + } | |
| 558 | + return deleteQueryAsync(pks, options); | |
| 559 | + } | |
| 560 | + | |
| 561 | + private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) { | |
| 486 | 562 | // Order and duplicates matter for primary keys |
| 487 | 563 | List<Object> pks = new ArrayList<Object>(); |
| 488 | 564 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions); |
| 489 | - | |
| 490 | 565 | for (Object o : objects) { |
| 491 | 566 | if (o instanceof Option) { |
| 492 | 567 | Option option = (Option) o; |
| @@ -495,36 +570,40 @@ | ||
| 495 | 570 | pks.add(o); |
| 496 | 571 | } |
| 497 | 572 | } |
| 498 | - return deleteQuery(pks, options); | |
| 573 | + return deleteQueryAsync(pks, options); | |
| 499 | 574 | } |
| 500 | 575 | |
| 501 | - private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) { | |
| 576 | + private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) { | |
| 502 | 577 | if (primaryKey.size() != mapper.primaryKeySize()) |
| 503 | 578 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size())); |
| 504 | 579 | |
| 505 | - BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind(); | |
| 506 | - | |
| 507 | - if (mapper.writeConsistency != null) | |
| 508 | - bs.setConsistencyLevel(mapper.writeConsistency); | |
| 509 | - | |
| 510 | - int i = 0; | |
| 511 | - for (Option opt : options.values()) { | |
| 512 | - opt.checkValidFor(QueryType.DEL, manager); | |
| 513 | - opt.addToPreparedStatement(bs, i); | |
| 514 | - if (opt.isIncludedInQuery()) | |
| 515 | - i++; | |
| 516 | - } | |
| 580 | + return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() { | |
| 581 | + @Override | |
| 582 | + public BoundStatement apply(PreparedStatement input) { | |
| 583 | + BoundStatement bs = input.bind(); | |
| 584 | + if (mapper.writeConsistency != null) | |
| 585 | + bs.setConsistencyLevel(mapper.writeConsistency); | |
| 586 | + | |
| 587 | + int i = 0; | |
| 588 | + for (Option opt : options.values()) { | |
| 589 | + opt.checkValidFor(QueryType.DEL, manager); | |
| 590 | + opt.addToPreparedStatement(bs, i); | |
| 591 | + if (opt.isIncludedInQuery()) | |
| 592 | + i++; | |
| 593 | + } | |
| 517 | 594 | |
| 518 | - int columnNumber = 0; | |
| 519 | - for (Object value : primaryKey) { | |
| 520 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 521 | - if (value == null) { | |
| 522 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 595 | + int columnNumber = 0; | |
| 596 | + for (Object value : primaryKey) { | |
| 597 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 598 | + if (value == null) { | |
| 599 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 600 | + } | |
| 601 | + setObject(bs, i++, value, column); | |
| 602 | + columnNumber++; | |
| 603 | + } | |
| 604 | + return bs; | |
| 523 | 605 | } |
| 524 | - setObject(bs, i++, value, column); | |
| 525 | - columnNumber++; | |
| 526 | - } | |
| 527 | - return bs; | |
| 606 | + }); | |
| 528 | 607 | } |
| 529 | 608 | |
| 530 | 609 | /** |
| @@ -535,7 +614,11 @@ | ||
| 535 | 614 | * @param entity the entity to delete. |
| 536 | 615 | */ |
| 537 | 616 | public void delete(T entity) { |
| 538 | - session().execute(deleteQuery(entity)); | |
| 617 | + try { | |
| 618 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity)); | |
| 619 | + } catch (ExecutionException e) { | |
| 620 | + throw DriverThrowables.propagateCause(e); | |
| 621 | + } | |
| 539 | 622 | } |
| 540 | 623 | |
| 541 | 624 | /** |
| @@ -547,7 +630,11 @@ | ||
| 547 | 630 | * @param options the options to add to the DELETE query. |
| 548 | 631 | */ |
| 549 | 632 | public void delete(T entity, Option... options) { |
| 550 | - session().execute(deleteQuery(entity, options)); | |
| 633 | + try { | |
| 634 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity, options)); | |
| 635 | + } catch (ExecutionException e) { | |
| 636 | + throw DriverThrowables.propagateCause(e); | |
| 637 | + } | |
| 551 | 638 | } |
| 552 | 639 | |
| 553 | 640 | /** |
| @@ -559,7 +646,7 @@ | ||
| 559 | 646 | * @return a future on the completion of the deletion. |
| 560 | 647 | */ |
| 561 | 648 | public ListenableFuture<Void> deleteAsync(T entity) { |
| 562 | - return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP); | |
| 649 | + return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 563 | 650 | } |
| 564 | 651 | |
| 565 | 652 | /** |
| @@ -572,7 +659,7 @@ | ||
| 572 | 659 | * @return a future on the completion of the deletion. |
| 573 | 660 | */ |
| 574 | 661 | public ListenableFuture<Void> deleteAsync(T entity, Option... options) { |
| 575 | - return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP); | |
| 662 | + return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 576 | 663 | } |
| 577 | 664 | |
| 578 | 665 | /** |
| @@ -589,7 +676,11 @@ | ||
| 589 | 676 | * at least one of those values is {@code null}. |
| 590 | 677 | */ |
| 591 | 678 | public void delete(Object... objects) { |
| 592 | - session().execute(deleteQuery(objects)); | |
| 679 | + try { | |
| 680 | + Uninterruptibles.getUninterruptibly(deleteAsync(objects)); | |
| 681 | + } catch (ExecutionException e) { | |
| 682 | + throw DriverThrowables.propagateCause(e); | |
| 683 | + } | |
| 593 | 684 | } |
| 594 | 685 | |
| 595 | 686 | /** |
| @@ -606,10 +697,14 @@ | ||
| 606 | 697 | * at least one of those values is {@code null}. |
| 607 | 698 | */ |
| 608 | 699 | public ListenableFuture<Void> deleteAsync(Object... objects) { |
| 609 | - return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP); | |
| 700 | + return submitVoidQueryAsync(deleteQueryAsync(objects)); | |
| 610 | 701 | } |
| 611 | 702 | |
| 612 | 703 | /** |
| 704 | + * Creates a query to fetch entity given its PRIMARY KEY. | |
| 705 | + * <p/> | |
| 706 | + * <p/> | |
| 707 | + * /** | |
| 613 | 708 | * Maps the rows from a {@code ResultSet} into the class this is a mapper of. |
| 614 | 709 | * <p/> |
| 615 | 710 | * 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 | +} |