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