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