| 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.*; |
| 19 | import com.datastax.driver.core.querybuilder.Delete; |
| 20 | import com.datastax.driver.core.querybuilder.Insert; |
| 21 | import com.datastax.driver.core.querybuilder.QueryBuilder; |
| 22 | import com.datastax.driver.mapping.Mapper.Option.SaveNullFields; |
| 23 | import com.datastax.driver.mapping.annotations.Computed; |
| 24 | import com.google.common.base.Function; |
| 25 | import com.google.common.base.Functions; |
| 26 | import com.google.common.base.Objects; |
| 27 | import com.google.common.base.Preconditions; |
| 28 | import com.google.common.util.concurrent.*; |
| 29 | import org.slf4j.Logger; |
| 30 | import org.slf4j.LoggerFactory; |
| 31 | |
| 32 | import java.util.*; |
| 33 | import java.util.concurrent.ConcurrentHashMap; |
| 34 | import java.util.concurrent.ConcurrentMap; |
| 35 | import java.util.concurrent.ExecutionException; |
| 36 | |
| 37 | import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS; |
| 38 | import static com.google.common.base.Preconditions.checkArgument; |
| 39 | |
| 40 | /** |
| 41 | * An object handling the mapping of a particular class. |
| 42 | * <p/> |
| 43 | * A {@code Mapper} object is obtained from a {@code MappingManager} using the |
| 44 | * {@link MappingManager#mapper} method. |
| 45 | */ |
| 46 | public class Mapper<T> { |
| 47 | |
| 48 | private static final Logger logger = LoggerFactory.getLogger(Mapper.class); |
| 49 | private static final Function<Object, Void> TO_NULL = Functions.constant(null); |
| 50 | |
| 51 | final MappingManager manager; |
| 52 | final ProtocolVersion protocolVersion; |
| 53 | final Class<T> klass; |
| 54 | final EntityMapper<T> mapper; |
| 55 | final TableMetadata tableMetadata; |
| 56 | |
| 57 | // Cache prepared statements for each type of query we use. |
| 58 | private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); |
| 59 | |
| 60 | private volatile EnumMap<Option.Type, Option> defaultSaveOptions; |
| 61 | private volatile EnumMap<Option.Type, Option> defaultGetOptions; |
| 62 | private volatile EnumMap<Option.Type, Option> defaultDeleteOptions; |
| 63 | |
| 64 | private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class); |
| 65 | |
| 66 | final Function<ResultSet, T> mapOneFunction; |
| 67 | final Function<ResultSet, T> mapOneFunctionWithoutAliases; |
| 68 | final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases; |
| 69 | |
| 70 | Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) { |
| 71 | this.manager = manager; |
| 72 | this.klass = klass; |
| 73 | this.mapper = mapper; |
| 74 | |
| 75 | KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace()); |
| 76 | this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable()); |
| 77 | |
| 78 | this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 79 | this.mapOneFunction = new Function<ResultSet, T>() { |
| 80 | @Override |
| 81 | public T apply(ResultSet rs) { |
| 82 | return Mapper.this.map(rs).one(); |
| 83 | } |
| 84 | }; |
| 85 | this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() { |
| 86 | @Override |
| 87 | public T apply(ResultSet rs) { |
| 88 | return Mapper.this.map(rs).one(); |
| 89 | } |
| 90 | }; |
| 91 | this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() { |
| 92 | @Override |
| 93 | public Result<T> apply(ResultSet rs) { |
| 94 | return Mapper.this.map(rs); |
| 95 | } |
| 96 | }; |
| 97 | |
| 98 | this.defaultSaveOptions = NO_OPTIONS; |
| 99 | this.defaultGetOptions = NO_OPTIONS; |
| 100 | this.defaultDeleteOptions = NO_OPTIONS; |
| 101 | } |
| 102 | |
| 103 | Session session() { |
| 104 | return manager.getSession(); |
| 105 | } |
| 106 | |
| 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; |
| 134 | } |
| 135 | } else { |
| 136 | return existingFuture; |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { |
| 141 | return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); |
| 142 | } |
| 143 | |
| 144 | Class<T> getMappedClass() { |
| 145 | return klass; |
| 146 | } |
| 147 | |
| 148 | /** |
| 149 | * The {@code TableMetadata} for this mapper. |
| 150 | * |
| 151 | * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set. |
| 152 | */ |
| 153 | public TableMetadata getTableMetadata() { |
| 154 | return tableMetadata; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * The {@code MappingManager} managing this mapper. |
| 159 | * |
| 160 | * @return the {@code MappingManager} managing this mapper. |
| 161 | */ |
| 162 | public MappingManager getManager() { |
| 163 | return manager; |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Creates a query that can be used to save the provided entity. |
| 168 | * <p/> |
| 169 | * This method is useful if you want to setup a number of options (tracing, |
| 170 | * conistency level, ...) of the returned statement before executing it manually |
| 171 | * or need access to the {@code ResultSet} object after execution (to get the |
| 172 | * trace, the execution info, ...), but in other cases, calling {@link #save} |
| 173 | * or {@link #saveAsync} is shorter. |
| 174 | * |
| 175 | * @param entity the entity to save. |
| 176 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 177 | */ |
| 178 | public Statement saveQuery(T entity) { |
| 179 | try { |
| 180 | return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions)); |
| 181 | } catch (ExecutionException e) { |
| 182 | throw DriverThrowables.propagateCause(e); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Creates a query that can be used to save the provided entity. |
| 188 | * <p/> |
| 189 | * This method is useful if you want to setup a number of options (tracing, |
| 190 | * conistency level, ...) of the returned statement before executing it manually |
| 191 | * or need access to the {@code ResultSet} object after execution (to get the |
| 192 | * trace, the execution info, ...), but in other cases, calling {@link #save} |
| 193 | * or {@link #saveAsync} is shorter. |
| 194 | * This method allows you to provide a suite of {@link Option} to include in |
| 195 | * the SAVE query. Options currently supported for SAVE are : |
| 196 | * <ul> |
| 197 | * <li>Timestamp</li> |
| 198 | * <li>Time-to-live (ttl)</li> |
| 199 | * <li>Consistency level</li> |
| 200 | * <li>Tracing</li> |
| 201 | * </ul> |
| 202 | * |
| 203 | * @param entity the entity to save. |
| 204 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 205 | */ |
| 206 | public Statement saveQuery(T entity, Option... options) { |
| 207 | try { |
| 208 | return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); |
| 209 | } catch (ExecutionException e) { |
| 210 | throw DriverThrowables.propagateCause(e); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { |
| 215 | final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); |
| 216 | boolean saveNullFields = shouldSaveNullFields(options); |
| 217 | |
| 218 | for (ColumnMapper<T> cm : mapper.allColumns()) { |
| 219 | Object value = cm.getValue(entity); |
| 220 | if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) { |
| 221 | values.put(cm, value); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { |
| 226 | @Override |
| 227 | public BoundStatement apply(PreparedStatement input) { |
| 228 | BoundStatement bs = input.bind(); |
| 229 | int i = 0; |
| 230 | for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { |
| 231 | ColumnMapper<?> mapper = entry.getKey(); |
| 232 | Object value = entry.getValue(); |
| 233 | setObject(bs, i++, value, mapper); |
| 234 | } |
| 235 | |
| 236 | if (mapper.writeConsistency != null) |
| 237 | bs.setConsistencyLevel(mapper.writeConsistency); |
| 238 | |
| 239 | for (Option opt : options.values()) { |
| 240 | opt.checkValidFor(QueryType.SAVE, manager); |
| 241 | opt.addToPreparedStatement(bs, i++); |
| 242 | } |
| 243 | |
| 244 | return bs; |
| 245 | } |
| 246 | }); |
| 247 | } |
| 248 | |
| 249 | private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) { |
| 250 | SaveNullFields option = (SaveNullFields) options.get(SAVE_NULL_FIELDS); |
| 251 | return option == null || option.saveNullFields; |
| 252 | } |
| 253 | |
| 254 | private static void setObject(BoundStatement bs, int i, Object value, ColumnMapper<?> mapper) { |
| 255 | TypeCodec<Object> customCodec = mapper.getCustomCodec(); |
| 256 | if (customCodec != null) |
| 257 | bs.set(i, value, customCodec); |
| 258 | else |
| 259 | bs.set(i, value, mapper.getJavaType()); |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * Saves an entity mapped by this mapper. |
| 264 | * <p/> |
| 265 | * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}. |
| 266 | * |
| 267 | * @param entity the entity to save. |
| 268 | */ |
| 269 | public void save(T entity) { |
| 270 | try { |
| 271 | Uninterruptibles.getUninterruptibly(saveAsync(entity)); |
| 272 | } catch (ExecutionException e) { |
| 273 | throw DriverThrowables.propagateCause(e); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Saves an entity mapped by this mapper and using special options for save. |
| 279 | * This method allows you to provide a suite of {@link Option} to include in |
| 280 | * the SAVE query. Options currently supported for SAVE are : |
| 281 | * <ul> |
| 282 | * <li>Timestamp</li> |
| 283 | * <li>Time-to-live (ttl)</li> |
| 284 | * <li>Consistency level</li> |
| 285 | * <li>Tracing</li> |
| 286 | * </ul> |
| 287 | * |
| 288 | * @param entity the entity to save. |
| 289 | * @param options the options object specified defining special options when saving. |
| 290 | */ |
| 291 | public void save(T entity, Option... options) { |
| 292 | try { |
| 293 | Uninterruptibles.getUninterruptibly(saveAsync(entity, options)); |
| 294 | } catch (ExecutionException e) { |
| 295 | throw DriverThrowables.propagateCause(e); |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /** |
| 300 | * Saves an entity mapped by this mapper asynchronously. |
| 301 | * <p/> |
| 302 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}. |
| 303 | * |
| 304 | * @param entity the entity to save. |
| 305 | * @return a future on the completion of the save operation. |
| 306 | */ |
| 307 | public ListenableFuture<Void> saveAsync(T entity) { |
| 308 | return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions)); |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Save an entity mapped by this mapper asynchronously using special options for save. |
| 313 | * <p/> |
| 314 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}. |
| 315 | * |
| 316 | * @param entity the entity to save. |
| 317 | * @param options the options object specified defining special options when saving. |
| 318 | * @return a future on the completion of the save operation. |
| 319 | */ |
| 320 | public ListenableFuture<Void> saveAsync(T entity, Option... options) { |
| 321 | return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); |
| 322 | } |
| 323 | |
| 324 | private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) { |
| 325 | ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { |
| 326 | @Override |
| 327 | public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { |
| 328 | return session().executeAsync(bs); |
| 329 | } |
| 330 | }); |
| 331 | return Futures.transform(rsFuture, TO_NULL); |
| 332 | } |
| 333 | |
| 334 | /** |
| 335 | * Creates a query to fetch entity given its PRIMARY KEY. |
| 336 | * <p/> |
| 337 | * The values provided must correspond to the columns composing the PRIMARY |
| 338 | * KEY (in the order of said primary key). |
| 339 | * <p/> |
| 340 | * This method is useful if you want to setup a number of options (tracing, |
| 341 | * conistency level, ...) of the returned statement before executing it manually, |
| 342 | * but in other cases, calling {@link #get} or {@link #getAsync} is shorter. |
| 343 | * <p/> |
| 344 | * This method allows you to provide a suite of {@link Option} to include in |
| 345 | * the GET query. Options currently supported for GET are : |
| 346 | * <ul> |
| 347 | * <li>Consistency level</li> |
| 348 | * <li>Tracing</li> |
| 349 | * </ul> |
| 350 | * |
| 351 | * @param objects the primary key of the entity to fetch, or more precisely |
| 352 | * the values for the columns of said primary key in the order of the primary key. |
| 353 | * Can be followed by {@link Option} to include in the DELETE query. |
| 354 | * @return a query that fetch the entity of PRIMARY KEY {@code objects}. |
| 355 | * @throws IllegalArgumentException if the number of value provided differ from |
| 356 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 357 | * at least one of those values is {@code null}. |
| 358 | */ |
| 359 | public Statement getQuery(Object... objects) { |
| 360 | try { |
| 361 | return Uninterruptibles.getUninterruptibly(getQueryAsync(objects)); |
| 362 | } catch (ExecutionException e) { |
| 363 | throw DriverThrowables.propagateCause(e); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) { |
| 368 | // Order and duplicates matter for primary keys |
| 369 | List<Object> pks = new ArrayList<Object>(); |
| 370 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions); |
| 371 | for (Object o : objects) { |
| 372 | if (o instanceof Option) { |
| 373 | Option option = (Option) o; |
| 374 | options.put(option.type, option); |
| 375 | } else { |
| 376 | pks.add(o); |
| 377 | } |
| 378 | } |
| 379 | return getQueryAsync(pks, options); |
| 380 | } |
| 381 | |
| 382 | private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) { |
| 383 | if (primaryKeys.size() != mapper.primaryKeySize()) |
| 384 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size())); |
| 385 | |
| 386 | return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() { |
| 387 | @Override |
| 388 | public BoundStatement apply(PreparedStatement input) { |
| 389 | BoundStatement bs = new MapperBoundStatement(input); |
| 390 | int i = 0; |
| 391 | for (Object value : primaryKeys) { |
| 392 | ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); |
| 393 | if (value == null) { |
| 394 | throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); |
| 395 | } |
| 396 | setObject(bs, i++, value, column); |
| 397 | } |
| 398 | |
| 399 | if (mapper.readConsistency != null) |
| 400 | bs.setConsistencyLevel(mapper.readConsistency); |
| 401 | |
| 402 | for (Option opt : options.values()) { |
| 403 | opt.checkValidFor(QueryType.GET, manager); |
| 404 | opt.addToPreparedStatement(bs, i); |
| 405 | if (opt.isIncludedInQuery()) |
| 406 | i++; |
| 407 | } |
| 408 | return bs; |
| 409 | } |
| 410 | }); |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * Fetch an entity based on its primary key. |
| 415 | * <p/> |
| 416 | * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}. |
| 417 | * |
| 418 | * @param objects the primary key of the entity to fetch, or more precisely |
| 419 | * the values for the columns of said primary key in the order of the primary key. |
| 420 | * Can be followed by {@link Option} to include in the DELETE query. |
| 421 | * @return the entity fetched or {@code null} if it doesn't exist. |
| 422 | * @throws IllegalArgumentException if the number of value provided differ from |
| 423 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 424 | * at least one of those values is {@code null}. |
| 425 | */ |
| 426 | public T get(Object... objects) { |
| 427 | try { |
| 428 | return Uninterruptibles.getUninterruptibly(getAsync(objects)); |
| 429 | } catch (ExecutionException e) { |
| 430 | throw DriverThrowables.propagateCause(e); |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | /** |
| 435 | * Fetch an entity based on its primary key asynchronously. |
| 436 | * <p/> |
| 437 | * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}. |
| 438 | * |
| 439 | * @param objects the primary key of the entity to fetch, or more precisely |
| 440 | * the values for the columns of said primary key in the order of the primary key. |
| 441 | * Can be followed by {@link Option} to include in the DELETE query. |
| 442 | * @return a future on the fetched entity. The return future will yield |
| 443 | * {@code null} if said entity doesn't exist. |
| 444 | * @throws IllegalArgumentException if the number of value provided differ from |
| 445 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 446 | * at least one of those values is {@code null}. |
| 447 | */ |
| 448 | public ListenableFuture<T> getAsync(final Object... objects) { |
| 449 | ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); |
| 450 | ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { |
| 451 | @Override |
| 452 | public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { |
| 453 | return session().executeAsync(bs); |
| 454 | } |
| 455 | }); |
| 456 | return Futures.transform(rsFuture, mapOneFunction); |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * Creates a query that can be used to delete the provided entity. |
| 461 | * <p/> |
| 462 | * This method is a shortcut that extract the PRIMARY KEY from the |
| 463 | * provided entity and call {@link #deleteQuery(Object...)} with it. |
| 464 | * This method allows you to provide a suite of {@link Option} to include in |
| 465 | * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp} |
| 466 | * is supported for DELETE queries. |
| 467 | * <p/> |
| 468 | * This method is useful if you want to setup a number of options (tracing, |
| 469 | * conistency level, ...) of the returned statement before executing it manually |
| 470 | * or need access to the {@code ResultSet} object after execution (to get the |
| 471 | * trace, the execution info, ...), but in other cases, calling {@link #delete} |
| 472 | * or {@link #deleteAsync} is shorter. |
| 473 | * <p/> |
| 474 | * This method allows you to provide a suite of {@link Option} to include in |
| 475 | * the DELETE query. Options currently supported for DELETE are : |
| 476 | * <ul> |
| 477 | * <li>Timestamp</li> |
| 478 | * <li>Consistency level</li> |
| 479 | * <li>Tracing</li> |
| 480 | * </ul> |
| 481 | * |
| 482 | * @param entity the entity to delete. |
| 483 | * @param options the options to add to the DELETE query. |
| 484 | * @return a query that delete {@code entity} (based on it's defined mapping) with |
| 485 | * provided USING options. |
| 486 | */ |
| 487 | public Statement deleteQuery(T entity, Option... options) { |
| 488 | try { |
| 489 | return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); |
| 490 | } catch (ExecutionException e) { |
| 491 | throw DriverThrowables.propagateCause(e); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | /** |
| 496 | * Creates a query that can be used to delete the provided entity. |
| 497 | * <p/> |
| 498 | * This method is a shortcut that extract the PRIMARY KEY from the |
| 499 | * provided entity and call {@link #deleteQuery(Object...)} with it. |
| 500 | * <p/> |
| 501 | * This method is useful if you want to setup a number of options (tracing, |
| 502 | * conistency level, ...) of the returned statement before executing it manually |
| 503 | * or need access to the {@code ResultSet} object after execution (to get the |
| 504 | * trace, the execution info, ...), but in other cases, calling {@link #delete} |
| 505 | * or {@link #deleteAsync} is shorter. |
| 506 | * |
| 507 | * @param entity the entity to delete. |
| 508 | * @return a query that delete {@code entity} (based on it's defined mapping). |
| 509 | */ |
| 510 | public Statement deleteQuery(T entity) { |
| 511 | try { |
| 512 | return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions)); |
| 513 | } catch (ExecutionException e) { |
| 514 | throw DriverThrowables.propagateCause(e); |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | /** |
| 519 | * Creates a query that can be used to delete an entity given its PRIMARY KEY. |
| 520 | * <p/> |
| 521 | * The values provided must correspond to the columns composing the PRIMARY |
| 522 | * KEY (in the order of said primary key). The values can also contain, after |
| 523 | * specifying the primary keys columns, a suite of {@link Option} to include in |
| 524 | * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp} |
| 525 | * is supported for DELETE queries. |
| 526 | * <p/> |
| 527 | * This method is useful if you want to setup a number of options (tracing, |
| 528 | * conistency level, ...) of the returned statement before executing it manually |
| 529 | * or need access to the {@code ResultSet} object after execution (to get the |
| 530 | * trace, the execution info, ...), but in other cases, calling {@link #delete} |
| 531 | * or {@link #deleteAsync} is shorter. |
| 532 | * This method allows you to provide a suite of {@link Option} to include in |
| 533 | * the DELETE query. Options currently supported for DELETE are : |
| 534 | * <ul> |
| 535 | * <li>Timestamp</li> |
| 536 | * <li>Consistency level</li> |
| 537 | * <li>Tracing</li> |
| 538 | * </ul> |
| 539 | * |
| 540 | * @param objects the primary key of the entity to delete, or more precisely |
| 541 | * the values for the columns of said primary key in the order of the primary key. |
| 542 | * Can be followed by {@link Option} to include in the DELETE |
| 543 | * query. |
| 544 | * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}. |
| 545 | * @throws IllegalArgumentException if the number of value provided differ from |
| 546 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 547 | * at least one of those values is {@code null}. |
| 548 | */ |
| 549 | public Statement deleteQuery(Object... objects) { |
| 550 | try { |
| 551 | return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects)); |
| 552 | } catch (ExecutionException e) { |
| 553 | throw DriverThrowables.propagateCause(e); |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) { |
| 558 | List<Object> pks = new ArrayList<Object>(); |
| 559 | for (int i = 0; i < mapper.primaryKeySize(); i++) { |
| 560 | pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); |
| 561 | } |
| 562 | return deleteQueryAsync(pks, options); |
| 563 | } |
| 564 | |
| 565 | private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) { |
| 566 | // Order and duplicates matter for primary keys |
| 567 | List<Object> pks = new ArrayList<Object>(); |
| 568 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions); |
| 569 | for (Object o : objects) { |
| 570 | if (o instanceof Option) { |
| 571 | Option option = (Option) o; |
| 572 | options.put(option.type, option); |
| 573 | } else { |
| 574 | pks.add(o); |
| 575 | } |
| 576 | } |
| 577 | return deleteQueryAsync(pks, options); |
| 578 | } |
| 579 | |
| 580 | private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) { |
| 581 | if (primaryKey.size() != mapper.primaryKeySize()) |
| 582 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size())); |
| 583 | |
| 584 | return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() { |
| 585 | @Override |
| 586 | public BoundStatement apply(PreparedStatement input) { |
| 587 | BoundStatement bs = input.bind(); |
| 588 | if (mapper.writeConsistency != null) |
| 589 | bs.setConsistencyLevel(mapper.writeConsistency); |
| 590 | |
| 591 | int i = 0; |
| 592 | for (Option opt : options.values()) { |
| 593 | opt.checkValidFor(QueryType.DEL, manager); |
| 594 | opt.addToPreparedStatement(bs, i); |
| 595 | if (opt.isIncludedInQuery()) |
| 596 | i++; |
| 597 | } |
| 598 | |
| 599 | int columnNumber = 0; |
| 600 | for (Object value : primaryKey) { |
| 601 | ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); |
| 602 | if (value == null) { |
| 603 | throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); |
| 604 | } |
| 605 | setObject(bs, i++, value, column); |
| 606 | columnNumber++; |
| 607 | } |
| 608 | return bs; |
| 609 | } |
| 610 | }); |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Deletes an entity mapped by this mapper. |
| 615 | * <p/> |
| 616 | * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}. |
| 617 | * |
| 618 | * @param entity the entity to delete. |
| 619 | */ |
| 620 | public void delete(T entity) { |
| 621 | try { |
| 622 | Uninterruptibles.getUninterruptibly(deleteAsync(entity)); |
| 623 | } catch (ExecutionException e) { |
| 624 | throw DriverThrowables.propagateCause(e); |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | /** |
| 629 | * Deletes an entity mapped by this mapper using provided options. |
| 630 | * <p/> |
| 631 | * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}. |
| 632 | * |
| 633 | * @param entity the entity to delete. |
| 634 | * @param options the options to add to the DELETE query. |
| 635 | */ |
| 636 | public void delete(T entity, Option... options) { |
| 637 | try { |
| 638 | Uninterruptibles.getUninterruptibly(deleteAsync(entity, options)); |
| 639 | } catch (ExecutionException e) { |
| 640 | throw DriverThrowables.propagateCause(e); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /** |
| 645 | * Deletes an entity mapped by this mapper asynchronously. |
| 646 | * <p/> |
| 647 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}. |
| 648 | * |
| 649 | * @param entity the entity to delete. |
| 650 | * @return a future on the completion of the deletion. |
| 651 | */ |
| 652 | public ListenableFuture<Void> deleteAsync(T entity) { |
| 653 | return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions)); |
| 654 | } |
| 655 | |
| 656 | /** |
| 657 | * Deletes an entity mapped by this mapper asynchronously using provided options. |
| 658 | * <p/> |
| 659 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}. |
| 660 | * |
| 661 | * @param entity the entity to delete. |
| 662 | * @param options the options to add to the DELETE query. |
| 663 | * @return a future on the completion of the deletion. |
| 664 | */ |
| 665 | public ListenableFuture<Void> deleteAsync(T entity, Option... options) { |
| 666 | return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); |
| 667 | } |
| 668 | |
| 669 | /** |
| 670 | * Deletes an entity based on its primary key. |
| 671 | * <p/> |
| 672 | * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}. |
| 673 | * |
| 674 | * @param objects the primary key of the entity to delete, or more precisely |
| 675 | * the values for the columns of said primary key in the order |
| 676 | * of the primary key.Can be followed by {@link Option} to include |
| 677 | * in the DELETE query. |
| 678 | * @throws IllegalArgumentException if the number of value provided differ from |
| 679 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 680 | * at least one of those values is {@code null}. |
| 681 | */ |
| 682 | public void delete(Object... objects) { |
| 683 | try { |
| 684 | Uninterruptibles.getUninterruptibly(deleteAsync(objects)); |
| 685 | } catch (ExecutionException e) { |
| 686 | throw DriverThrowables.propagateCause(e); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | /** |
| 691 | * Deletes an entity based on its primary key asynchronously. |
| 692 | * <p/> |
| 693 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}. |
| 694 | * |
| 695 | * @param objects the primary key of the entity to delete, or more precisely |
| 696 | * the values for the columns of said primary key in the order |
| 697 | * of the primary key. Can be followed by {@link Option} to include |
| 698 | * in the DELETE query. |
| 699 | * @throws IllegalArgumentException if the number of value provided differ from |
| 700 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 701 | * at least one of those values is {@code null}. |
| 702 | */ |
| 703 | public ListenableFuture<Void> deleteAsync(Object... objects) { |
| 704 | return submitVoidQueryAsync(deleteQueryAsync(objects)); |
| 705 | } |
| 706 | |
| 707 | /** |
| 708 | * Creates a query to fetch entity given its PRIMARY KEY. |
| 709 | * <p/> |
| 710 | * <p/> |
| 711 | * /** |
| 712 | * Maps the rows from a {@code ResultSet} into the class this is a mapper of. |
| 713 | * <p/> |
| 714 | * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with |
| 715 | * {@link com.datastax.driver.mapping.annotations.Query @Query} in an |
| 716 | * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns |
| 717 | * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be |
| 718 | * populated. |
| 719 | * <p/> |
| 720 | * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be |
| 721 | * mapped, as if the object came from a direct {@link #get(Object...)} call. |
| 722 | * |
| 723 | * @param resultSet the {@code ResultSet} to map. |
| 724 | * @return the mapped result set. Note that the returned mapped result set |
| 725 | * will encapsulate {@code resultSet} and so consuming results from this |
| 726 | * returned mapped result set will consume results from {@code resultSet} |
| 727 | * and vice-versa. |
| 728 | */ |
| 729 | public Result<T> map(ResultSet resultSet) { |
| 730 | boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet); |
| 731 | return new Result<T>(resultSet, mapper, protocolVersion, useAlias); |
| 732 | } |
| 733 | |
| 734 | private boolean isFromMapperQuery(ResultSet resultSet) { |
| 735 | return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement; |
| 736 | } |
| 737 | |
| 738 | /** |
| 739 | * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use |
| 740 | * {@link #map(ResultSet)} instead of this method. |
| 741 | */ |
| 742 | @Deprecated |
| 743 | public Result<T> mapAliased(ResultSet resultSet) { |
| 744 | return map(resultSet); |
| 745 | } |
| 746 | |
| 747 | /** |
| 748 | * Set the default save {@link Option} for this object mapper, that will be used |
| 749 | * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})} |
| 750 | * to check available save options. |
| 751 | * |
| 752 | * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}. |
| 753 | */ |
| 754 | public void setDefaultSaveOptions(Option... options) { |
| 755 | this.defaultSaveOptions = toMap(options); |
| 756 | } |
| 757 | |
| 758 | /** |
| 759 | * Reset the default save options for this object mapper. |
| 760 | */ |
| 761 | public void resetDefaultSaveOptions() { |
| 762 | this.defaultSaveOptions = NO_OPTIONS; |
| 763 | } |
| 764 | |
| 765 | /** |
| 766 | * Set the default get {@link Option} for this object mapper, that will be used |
| 767 | * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available |
| 768 | * get options. |
| 769 | * |
| 770 | * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}. |
| 771 | */ |
| 772 | public void setDefaultGetOptions(Option... options) { |
| 773 | this.defaultGetOptions = toMap(options); |
| 774 | |
| 775 | } |
| 776 | |
| 777 | /** |
| 778 | * Reset the default save options for this object mapper. |
| 779 | */ |
| 780 | public void resetDefaultGetOptions() { |
| 781 | this.defaultGetOptions = NO_OPTIONS; |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Set the default delete {@link Option} for this object mapper, that will be used |
| 786 | * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )} |
| 787 | * to check available delete options. |
| 788 | * |
| 789 | * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}. |
| 790 | */ |
| 791 | public void setDefaultDeleteOptions(Option... options) { |
| 792 | this.defaultDeleteOptions = toMap(options); |
| 793 | } |
| 794 | |
| 795 | /** |
| 796 | * Reset the default delete options for this object mapper. |
| 797 | */ |
| 798 | public void resetDefaultDeleteOptions() { |
| 799 | this.defaultDeleteOptions = NO_OPTIONS; |
| 800 | } |
| 801 | |
| 802 | private static EnumMap<Option.Type, Option> toMap(Option[] options) { |
| 803 | EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class); |
| 804 | for (Option option : options) { |
| 805 | result.put(option.type, option); |
| 806 | } |
| 807 | return result; |
| 808 | } |
| 809 | |
| 810 | private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) { |
| 811 | EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults); |
| 812 | for (Option option : options) { |
| 813 | result.put(option.type, option); |
| 814 | } |
| 815 | return result; |
| 816 | } |
| 817 | |
| 818 | /** |
| 819 | * An option for a mapper operation. |
| 820 | * <p/> |
| 821 | * Options can be passed to individual operations: |
| 822 | * <pre> |
| 823 | * mapper.save(myObject, Option.ttl(3600)); |
| 824 | * </pre> |
| 825 | * <p/> |
| 826 | * The mapper can also have defaults, that will apply to all operations that do not |
| 827 | * override these particular option: |
| 828 | * <pre> |
| 829 | * mapper.setDefaultSaveOptions(Option.ttl(3600)); |
| 830 | * mapper.save(myObject); |
| 831 | * </pre> |
| 832 | * <p/> |
| 833 | * <p/> |
| 834 | * See the static methods in this class for available options. |
| 835 | */ |
| 836 | public static abstract class Option { |
| 837 | |
| 838 | enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS} |
| 839 | |
| 840 | final Type type; |
| 841 | |
| 842 | protected Option(Type type) { |
| 843 | this.type = type; |
| 844 | } |
| 845 | |
| 846 | /** |
| 847 | * Creates a new Option object to add time-to-live to a mapper operation. This is |
| 848 | * only valid for save operations. |
| 849 | * <p/> |
| 850 | * Note that this option is only available if using {@link ProtocolVersion#V2} or above. |
| 851 | * |
| 852 | * @param ttl the TTL (in seconds). |
| 853 | * @return the option. |
| 854 | */ |
| 855 | public static Option ttl(int ttl) { |
| 856 | return new Ttl(ttl); |
| 857 | } |
| 858 | |
| 859 | /** |
| 860 | * Creates a new Option object to add a timestamp to a mapper operation. This is |
| 861 | * only valid for save and delete operations. |
| 862 | * <p/> |
| 863 | * Note that this option is only available if using {@link ProtocolVersion#V2} or above. |
| 864 | * |
| 865 | * @param timestamp the timestamp (in microseconds). |
| 866 | * @return the option. |
| 867 | */ |
| 868 | public static Option timestamp(long timestamp) { |
| 869 | return new Timestamp(timestamp); |
| 870 | } |
| 871 | |
| 872 | /** |
| 873 | * Creates a new Option object to add a consistency level value to a mapper operation. This |
| 874 | * is valid for save, delete and get operations. |
| 875 | * <p/> |
| 876 | * Note that the consistency level can also be defined at the mapper level, as a parameter |
| 877 | * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant |
| 878 | * for backward compatibility). This option, whether defined on a specific call or as the |
| 879 | * default, will always take precedence over the annotation. |
| 880 | * |
| 881 | * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation. |
| 882 | * @return the option. |
| 883 | */ |
| 884 | public static Option consistencyLevel(ConsistencyLevel cl) { |
| 885 | return new ConsistencyLevelOption(cl); |
| 886 | } |
| 887 | |
| 888 | /** |
| 889 | * Creates a new Option object to enable query tracing for a mapper operation. This |
| 890 | * is valid for save, delete and get operations. |
| 891 | * |
| 892 | * @param enabled whether to enable tracing. |
| 893 | * @return the option. |
| 894 | */ |
| 895 | public static Option tracing(boolean enabled) { |
| 896 | return new Tracing(enabled); |
| 897 | } |
| 898 | |
| 899 | /** |
| 900 | * Creates a new Option object to specify whether null entity fields should be included in |
| 901 | * insert queries. This option is valid only for save operations. |
| 902 | * <p/> |
| 903 | * If this option is not specified, it defaults to {@code true} (null fields are saved). |
| 904 | * |
| 905 | * @param enabled whether to include null fields in queries. |
| 906 | * @return the option. |
| 907 | */ |
| 908 | public static Option saveNullFields(boolean enabled) { |
| 909 | return new SaveNullFields(enabled); |
| 910 | } |
| 911 | |
| 912 | public Type getType() { |
| 913 | return this.type; |
| 914 | } |
| 915 | |
| 916 | abstract void appendTo(Insert.Options usings); |
| 917 | |
| 918 | abstract void appendTo(Delete.Options usings); |
| 919 | |
| 920 | abstract void addToPreparedStatement(BoundStatement bs, int i); |
| 921 | |
| 922 | abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException; |
| 923 | |
| 924 | abstract boolean isIncludedInQuery(); |
| 925 | |
| 926 | static class Ttl extends Option { |
| 927 | |
| 928 | private final int ttlValue; |
| 929 | |
| 930 | Ttl(int value) { |
| 931 | super(Type.TTL); |
| 932 | this.ttlValue = value; |
| 933 | } |
| 934 | |
| 935 | @Override |
| 936 | void appendTo(Insert.Options usings) { |
| 937 | usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker())); |
| 938 | } |
| 939 | |
| 940 | @Override |
| 941 | void appendTo(Delete.Options usings) { |
| 942 | throw new UnsupportedOperationException("shouldn't be called"); |
| 943 | } |
| 944 | |
| 945 | @Override |
| 946 | void addToPreparedStatement(BoundStatement bs, int i) { |
| 947 | bs.setInt(i, this.ttlValue); |
| 948 | } |
| 949 | |
| 950 | @Override |
| 951 | void checkValidFor(QueryType qt, MappingManager manager) { |
| 952 | checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above"); |
| 953 | checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries"); |
| 954 | } |
| 955 | |
| 956 | @Override |
| 957 | boolean isIncludedInQuery() { |
| 958 | return true; |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | static class Timestamp extends Option { |
| 963 | |
| 964 | private final long tsValue; |
| 965 | |
| 966 | Timestamp(long value) { |
| 967 | super(Type.TIMESTAMP); |
| 968 | this.tsValue = value; |
| 969 | } |
| 970 | |
| 971 | @Override |
| 972 | void appendTo(Insert.Options usings) { |
| 973 | usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker())); |
| 974 | } |
| 975 | |
| 976 | @Override |
| 977 | void appendTo(Delete.Options usings) { |
| 978 | usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker())); |
| 979 | } |
| 980 | |
| 981 | @Override |
| 982 | void checkValidFor(QueryType qt, MappingManager manager) { |
| 983 | checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above"); |
| 984 | checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries"); |
| 985 | } |
| 986 | |
| 987 | @Override |
| 988 | void addToPreparedStatement(BoundStatement bs, int i) { |
| 989 | bs.setLong(i, this.tsValue); |
| 990 | } |
| 991 | |
| 992 | @Override |
| 993 | boolean isIncludedInQuery() { |
| 994 | return true; |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | static class ConsistencyLevelOption extends Option { |
| 999 | |
| 1000 | private final ConsistencyLevel cl; |
| 1001 | |
| 1002 | ConsistencyLevelOption(ConsistencyLevel cl) { |
| 1003 | super(Type.CL); |
| 1004 | this.cl = cl; |
| 1005 | } |
| 1006 | |
| 1007 | @Override |
| 1008 | void appendTo(Insert.Options usings) { |
| 1009 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1010 | } |
| 1011 | |
| 1012 | @Override |
| 1013 | void appendTo(Delete.Options usings) { |
| 1014 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1015 | } |
| 1016 | |
| 1017 | @Override |
| 1018 | void addToPreparedStatement(BoundStatement bs, int i) { |
| 1019 | bs.setConsistencyLevel(cl); |
| 1020 | } |
| 1021 | |
| 1022 | @Override |
| 1023 | void checkValidFor(QueryType qt, MappingManager manager) { |
| 1024 | checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, |
| 1025 | "Consistency level option is only allowed in save, delete and get queries"); |
| 1026 | } |
| 1027 | |
| 1028 | @Override |
| 1029 | boolean isIncludedInQuery() { |
| 1030 | return false; |
| 1031 | } |
| 1032 | } |
| 1033 | |
| 1034 | static class Tracing extends Option { |
| 1035 | |
| 1036 | private final boolean tracing; |
| 1037 | |
| 1038 | Tracing(boolean tracing) { |
| 1039 | super(Type.TRACING); |
| 1040 | this.tracing = tracing; |
| 1041 | } |
| 1042 | |
| 1043 | @Override |
| 1044 | void appendTo(Insert.Options usings) { |
| 1045 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1046 | } |
| 1047 | |
| 1048 | @Override |
| 1049 | void appendTo(Delete.Options usings) { |
| 1050 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1051 | } |
| 1052 | |
| 1053 | @Override |
| 1054 | void addToPreparedStatement(BoundStatement bs, int i) { |
| 1055 | if (this.tracing) |
| 1056 | bs.enableTracing(); |
| 1057 | } |
| 1058 | |
| 1059 | @Override |
| 1060 | void checkValidFor(QueryType qt, MappingManager manager) { |
| 1061 | checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, |
| 1062 | "Tracing option is only allowed in save, delete and get queries"); |
| 1063 | } |
| 1064 | |
| 1065 | @Override |
| 1066 | boolean isIncludedInQuery() { |
| 1067 | return false; |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | static class SaveNullFields extends Option { |
| 1072 | |
| 1073 | private final boolean saveNullFields; |
| 1074 | |
| 1075 | SaveNullFields(boolean saveNullFields) { |
| 1076 | super(SAVE_NULL_FIELDS); |
| 1077 | this.saveNullFields = saveNullFields; |
| 1078 | } |
| 1079 | |
| 1080 | @Override |
| 1081 | void appendTo(Insert.Options usings) { |
| 1082 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1083 | } |
| 1084 | |
| 1085 | @Override |
| 1086 | void appendTo(Delete.Options usings) { |
| 1087 | throw new UnsupportedOperationException("shouldn't be called"); |
| 1088 | } |
| 1089 | |
| 1090 | @Override |
| 1091 | void addToPreparedStatement(BoundStatement bs, int i) { |
| 1092 | // nothing to do |
| 1093 | } |
| 1094 | |
| 1095 | @Override |
| 1096 | void checkValidFor(QueryType qt, MappingManager manager) { |
| 1097 | checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries"); |
| 1098 | } |
| 1099 | |
| 1100 | @Override |
| 1101 | boolean isIncludedInQuery() { |
| 1102 | return false; |
| 1103 | } |
| 1104 | } |
| 1105 | |
| 1106 | } |
| 1107 | |
| 1108 | private static class MapperQueryKey { |
| 1109 | private final QueryType queryType; |
| 1110 | private final EnumSet<Option.Type> optionTypes; |
| 1111 | private final Set<ColumnMapper<?>> columns; |
| 1112 | |
| 1113 | MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) { |
| 1114 | Preconditions.checkNotNull(queryType); |
| 1115 | Preconditions.checkNotNull(options); |
| 1116 | Preconditions.checkNotNull(columnMappers); |
| 1117 | this.queryType = queryType; |
| 1118 | this.columns = columnMappers; |
| 1119 | this.optionTypes = EnumSet.noneOf(Option.Type.class); |
| 1120 | for (Option opt : options.values()) { |
| 1121 | if (opt.isIncludedInQuery()) |
| 1122 | this.optionTypes.add(opt.type); |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | @Override |
| 1127 | public boolean equals(Object other) { |
| 1128 | if (this == other) |
| 1129 | return true; |
| 1130 | if (other instanceof MapperQueryKey) { |
| 1131 | MapperQueryKey that = (MapperQueryKey) other; |
| 1132 | return this.queryType.equals(that.queryType) |
| 1133 | && this.optionTypes.equals(that.optionTypes) |
| 1134 | && this.columns.equals(that.columns); |
| 1135 | } |
| 1136 | return false; |
| 1137 | } |
| 1138 | |
| 1139 | @Override |
| 1140 | public int hashCode() { |
| 1141 | return Objects.hashCode(queryType, optionTypes, columns); |
| 1142 | } |
| 1143 | } |
| 1144 | } |