/*
(non-Javadoc)

@see
com.impetus.client.cassandra.CassandraClientBase#delete(java.lang.Object,
java.lang.Object)
335561
@Override
    public void delete(Object entity, Object pKey)
    {
        if (!isOpen())
        {
            throw new PersistenceException("ThriftClient is closed.");
        }

        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
        Connection conn = null;
        try
        {
            conn = getConnection();
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    metadata.getPersistenceUnit());

            AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());
            // For secondary tables.
            List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())
                    .getSecondaryTablesName();
            secondaryTables.add(metadata.getTableName());

            for (String tableName : secondaryTables)
            {
                if (isCql3Enabled(metadata))
                {
                    String deleteQuery = onDeleteQuery(metadata, tableName, metaModel, pKey);
                    executeCQLQuery(deleteQuery, isCql3Enabled(metadata));

                }
                else
                {
                    if (metadata.isCounterColumnType())
                    {
                        deleteRecordFromCounterColumnFamily(pKey, tableName, metadata, getConsistencyLevel());
                    }
                    else
                    {
                        ColumnPath path = new ColumnPath(tableName);

                        conn.getClient().remove(
                                CassandraUtilities.toBytes(pKey, metadata.getIdAttribute().getJavaType()), path,
                                generator.getTimestamp(), getConsistencyLevel());
                    }
                }
            }
            getIndexManager().remove(metadata, entity, pKey);

            // Delete from Inverted Index if applicable
            invertedIndexHandler.delete(entity, metadata, getConsistencyLevel(), kunderaMetadata);
        }
        catch (InvalidRequestException e)
        {
            log.error("Error while deleting of column family {} for row key {}, Caused by: .", metadata.getTableName(),
                    pKey, e);
            throw new KunderaException(e);
        }
        catch (TException e)
        {
            log.error("Error while deleting of column family {} for row key {}, Caused by: .", metadata.getTableName(),
                    pKey, e);
            throw new KunderaException(e);
        }
        finally
        {
            releaseConnection(conn);
        }
    }
1172951
@NonNull
  public static DeleteSelection deleteFrom(@NonNull String table) {
    return deleteFrom(CqlIdentifier.fromCql(table));
  }
1172167
@Override
	public int delete(Extensions extensions) throws SQLException {

		DeleteBuilder<Extensions, Void> db = deleteBuilder();

		setUniqueWhere(db.where(), extensions.getExtensionName(), true,
				extensions.getTableName(), true, extensions.getColumnName());

		int deleted = db.delete();

		return deleted;
	}
1265552
@Override
    public void delete(ZooPC obj) {
    	if (obj.getClass() == GenericObject.class) {
    		throw new IllegalArgumentException();
//    		deleteGeneric((GenericObject) obj);
//    		return;
    	}
    	
        if (!isStarted) {
            this.sie = node.getSchemaIE(cls);
            isStarted = true;
        }

        //updated index
        //This is buffered to reduce look-ups to find field indices.
        buffer[bufferCnt++] = obj;
        if (bufferCnt == BUFFER_SIZE) {
            flushBuffer();
        }
    }
559263
@SuppressWarnings("unchecked")
	@Override
	public int delete(final Object entity) {
		@SuppressWarnings("rawtypes")
		EntityHandler handler = this.getEntityHandler();
		if (!handler.getEntityType().isInstance(entity)) {
			throw new IllegalArgumentException("Entity type not supported");
		}

		try {
			Class<?> type = entity.getClass();
			TableMetadata metadata = handler.getMetadata(this.transactionManager, type);
			SqlContext context = handler.createDeleteContext(this, metadata, type, true);
			context.setSqlKind(SqlKind.DELETE);
			handler.setDeleteParams(context, entity);
			return handler.doDelete(this, context, entity);
		} catch (SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.DELETE, e);
		}
	}
514896
public void deleteCascades(Object entity) {
		if (entity != null) {
			List<Field> fields = ClassUtil.getAnnotatedFields(entity.getClass(), Reference.class);
			for (Field field : fields) {
				Cascade[] cascades = ClassUtil.getFieldAnnotationValue("cascade", field, Reference.class, Cascade[].class);
				if (Arrays.asList(cascades).contains(Cascade.DELETE)) {
					Object referencedEntity = ClassUtil.getValueOfField(field, entity);
					if(referencedEntity != null){
						try {
							apitraryDaoSupport.resolveApitraryEntityId(referencedEntity);
							apitraryDaoSupport.delete(referencedEntity);
						} catch (ApitraryOrmIdException aoie) {
							/*
							 * TODO find better way for exception without breaking th cascade flow
							 */
							log.warn(aoie);
						}
					}
				}
			}
		}
	}
1218188
@Override
	public synchronized void delete(int contextId, int type, String data) throws DatabaseException {
    	SqlPreparedStatementWrapper psDeleteData = null;
    	try {
        	psDeleteData = DbSQL.getSingleton().getPreparedStatement("context.ps.delete");
			psDeleteData.getPs().setInt(1, contextId);
			psDeleteData.getPs().setInt(2, type);
			psDeleteData.getPs().setString(3, data);
			psDeleteData.getPs().executeUpdate();
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psDeleteData);
		}
    }
1097647
@Override
    public String delete(EntityDeleteOperation deleter) throws ServiceException {
        deleter.setProxyData(createProxyData());
        ClientResponse clientResponse =  getResource(deleter.getUri()).delete(ClientResponse.class);
        PipelineHelpers.throwIfNotSuccess(clientResponse);
        if (clientResponse.getHeaders().containsKey("operation-id")) {
            List<String> operationIds = clientResponse.getHeaders().get("operation-id");
            if (operationIds.size() >= 0) {
                return operationIds.get(0);
            }
        }
        return null;
    }
275452
@Override
    public void delete(Object entity, Object pKey)
    {
        s = getStatelessSession();
        Transaction tx = null;
        tx = onBegin();
        s.delete(entity);
        onCommit(tx);

        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
                metadata.getPersistenceUnit());
        if (!MetadataUtils.useSecondryIndex(getClientMetadata()))
        {
            getIndexManager().remove(metadata, entity, pKey);
        }
    }
113387
@Override
	public void setDeleteParams(final SqlContext context, final Object entity) {
		setFields(context, entity, SqlKind.DELETE, MappingColumn::getCamelName);
	}
648593
@Override
    public void delete(Object entity, Object key)
    {
        // All Modifying Neo4J operations must be executed within a transaction
        checkActiveTransaction();

        GraphDatabaseService graphDb = getConnection();

        // Find Node for this particular entity
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
        Node node = mapper.searchNode(key, m, graphDb, true);
        if (node != null)
        {
            // Remove this particular node, if not already deleted in current
            // transaction
            if (!((Neo4JTransaction) resource).containsNodeId(node.getId()))
            {
                node.delete();

                // Manually remove node index if applicable
                indexer.deleteNodeIndex(m, graphDb, node);

                // Remove all relationship edges attached to this node
                // (otherwise an
                // exception is thrown)
                for (Relationship relationship : node.getRelationships())
                {
                    relationship.delete();

                    // Manually remove relationship index if applicable
                    indexer.deleteRelationshipIndex(m, graphDb, relationship);
                }

                ((Neo4JTransaction) resource).addNodeId(node.getId());
            }
        }
        else
        {
            if (log.isDebugEnabled())
                log.debug("Entity to be deleted doesn't exist in graph. Doing nothing");
        }
    }
1340322
@Override
    public void delete(Object entity, Object pKey)
    {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
        Object connection = getConnection();
        Pipeline pipeLine = null;
        try
        {
            if (isBoundTransaction())
            {
                pipeLine = ((Jedis) connection).pipelined();
                onDelete(entity, pKey, pipeLine);
            }
            else
            {
                onDelete(entity, pKey, connection);
            }
            getIndexManager().remove(metadata, entity, pKey);
        }
        finally
        {
            if (pipeLine != null)
            {
                pipeLine.sync();
            }
            onCleanup(connection);
        }
    }
207508
@Override
    public void delete(Object entity, Object pKey)
    {
        HttpResponse response = null;
        try
        {
            EntityMetadata entityMetadata = KunderaMetadataManager
                    .getEntityMetadata(kunderaMetadata, entity.getClass());
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    entityMetadata.getPersistenceUnit());
            String _id = null;
            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
            {
                Field field = (Field) entityMetadata.getIdAttribute().getJavaMember();
                EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute()
                        .getBindableJavaType());
                _id = CouchDBObjectMapper.get_Id(field, pKey, embeddableType, entityMetadata.getTableName());
            }
            else
            {
                _id = entityMetadata.getTableName() + PropertyAccessorHelper.getString(pKey);
            }
            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()
                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);
            HttpGet get = new HttpGet(uri);
            get.addHeader("Accept", "application/json");
            response = httpClient.execute(get);

            Reader reader = new InputStreamReader(response.getEntity().getContent());
            JsonObject json = gson.fromJson(reader, JsonObject.class);
            closeContent(response);
            if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND))
            {
                onDelete(entityMetadata.getSchema(), _id, response, json);
            }
        }
        catch (Exception e)
        {
            log.error("Error while deleting object, Caused by {}.", e);
            throw new KunderaException(e);
        }
        finally
        {
            closeContent(response);
        }
    }
56880
private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("deleteByQuery " + cld.getClassNameOfObject() + ", " + query);
        }

        if (query instanceof QueryBySQL)
        {
            String sql = ((QueryBySQL) query).getSql();
            this.dbAccess.executeUpdateSQL(sql, cld);
        }
        else
        {
            // if query is Identity based transform it to a criteria based query first
            if (query instanceof QueryByIdentity)
            {
                QueryByIdentity qbi = (QueryByIdentity) query;
                Object oid = qbi.getExampleObject();
                // make sure it's an Identity
                if (!(oid instanceof Identity))
                {
                    oid = serviceIdentity().buildIdentity(oid);
                }
                query = referencesBroker.getPKQuery((Identity) oid);
            }

            if (!cld.isInterface())
            {
                this.dbAccess.executeDelete(query, cld);
            }

            // if class is an extent, we have to delete all extent classes too
            String lastUsedTable = cld.getFullTableName();
            if (cld.isExtent())
            {
                Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();

                while (extents.hasNext())
                {
                    ClassDescriptor extCld = (ClassDescriptor) extents.next();

                    // read same table only once
                    if (!extCld.getFullTableName().equals(lastUsedTable))
                    {
                        lastUsedTable = extCld.getFullTableName();
                        this.dbAccess.executeDelete(query, extCld);
                    }
                }
            }

        }
    }
807063
private void performDeletion(final ClassDescriptor cld, final Object obj, final Identity oid, final boolean ignoreReferences) throws PersistenceBrokerException
    {
            // 1. delete dependend collections
            if (!ignoreReferences  && cld.getCollectionDescriptors().size() > 0)
            {
                deleteCollections(obj, cld.getCollectionDescriptors());
            }
            // 2. delete object from directly mapped table
            try
            {
                dbAccess.executeDelete(cld, obj); // use obj not oid to delete, BRJ
            }
            catch(OptimisticLockException e)
            {
                // ensure that the outdated object be removed from cache
                objectCache.remove(oid);
                throw e;
            }

            // 3. Add OID to the set of deleted objects
            deletedDuringTransaction.add(oid);

            // 4. delete dependend upon objects last to avoid FK violations
            if (cld.getObjectReferenceDescriptors().size() > 0)
            {
                deleteReferences(cld, obj, oid, ignoreReferences);
            }
            // remove obj from the object cache:
            objectCache.remove(oid);
    }
874521
public int deleteById(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {
		if (mappedDelete == null) {
			mappedDelete = MappedDelete.build(dao, tableInfo);
		}
		int result = mappedDelete.deleteById(databaseConnection, id, objectCache);
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	}
955399
@Override
  public <SN,N> MutationResult subDelete(final K key, final String cf, final SN supercolumnName,
      final N columnName, final Serializer<SN> sNameSerializer, final Serializer<N> nameSerializer) {
    return new MutationResultImpl(keyspace.doExecute(new KeyspaceOperationCallback<Void>() {
      @Override
      public Void doInKeyspace(KeyspaceService ks) throws HectorException {
        ks.remove(keySerializer.toByteBuffer(key), ThriftFactory.createSuperColumnPath(cf,
            supercolumnName, columnName, sNameSerializer, nameSerializer));
        return null;
      }
    }, consistency));
  }