Search in sources :

Example 6 with RowModel

use of org.neo4j.ogm.model.RowModel in project neo4j-ogm by neo4j.

the class RequestExecutor method executeStatements.

private void executeStatements(CompileContext context, List<ReferenceMapping> entityReferenceMappings, List<ReferenceMapping> relReferenceMappings, List<Statement> statements) {
    if (statements.size() > 0) {
        List<Statement> noCheckStatements = new ArrayList<>();
        for (Statement statement : statements) {
            if (statement.optimisticLockingConfig().isPresent()) {
                DefaultRequest request = new DefaultRequest(statement);
                try (Response<RowModel> response = session.requestHandler().execute(request)) {
                    List<RowModel> rowModels = response.toList();
                    session.optimisticLockingChecker().checkResultsCount(rowModels, statement);
                    registerEntityIds(context, rowModels, entityReferenceMappings, relReferenceMappings);
                }
            } else {
                noCheckStatements.add(statement);
            }
        }
        DefaultRequest defaultRequest = new DefaultRequest();
        defaultRequest.setStatements(noCheckStatements);
        try (Response<RowModel> response = session.requestHandler().execute(defaultRequest)) {
            registerEntityIds(context, response.toList(), entityReferenceMappings, relReferenceMappings);
        }
    }
}
Also used : Statement(org.neo4j.ogm.request.Statement) ArrayList(java.util.ArrayList) RowModel(org.neo4j.ogm.model.RowModel)

Example 7 with RowModel

use of org.neo4j.ogm.model.RowModel in project neo4j-ogm by neo4j.

the class EmbeddedRequest method execute.

@Override
public Response<RowModel> execute(DefaultRequest query) {
    // TODO this is a hack to get the embedded driver to work with executing multiple statements
    final List<RowModel> rowmodels = new ArrayList<>();
    String[] columns = null;
    for (Statement statement : query.getStatements()) {
        Result result = executeRequest(statement);
        if (columns == null) {
            columns = result.columns().toArray(new String[result.columns().size()]);
        }
        RowModelResponse rowModelResponse = new RowModelResponse(result, entityAdapter);
        RowModel model;
        while ((model = rowModelResponse.next()) != null) {
            rowmodels.add(model);
        }
        result.close();
    }
    final String[] finalColumns = columns;
    return new Response<>() {

        int currentRow = 0;

        @Override
        public RowModel next() {
            if (currentRow < rowmodels.size()) {
                return rowmodels.get(currentRow++);
            }
            return null;
        }

        @Override
        public void close() {
        }

        @Override
        public String[] columns() {
            return finalColumns;
        }
    };
}
Also used : Response(org.neo4j.ogm.response.Response) EmptyResponse(org.neo4j.ogm.response.EmptyResponse) GraphRowModelResponse(org.neo4j.ogm.drivers.embedded.response.GraphRowModelResponse) GraphModelResponse(org.neo4j.ogm.drivers.embedded.response.GraphModelResponse) RowModelResponse(org.neo4j.ogm.drivers.embedded.response.RowModelResponse) RestModelResponse(org.neo4j.ogm.drivers.embedded.response.RestModelResponse) GraphRowModelResponse(org.neo4j.ogm.drivers.embedded.response.GraphRowModelResponse) RowModelResponse(org.neo4j.ogm.drivers.embedded.response.RowModelResponse) Statement(org.neo4j.ogm.request.Statement) ArrayList(java.util.ArrayList) RowModel(org.neo4j.ogm.model.RowModel) Result(org.neo4j.graphdb.Result)

Example 8 with RowModel

use of org.neo4j.ogm.model.RowModel in project neo4j-ogm by neo4j.

the class OptimisticLockingChecker method checkResultsCount.

public void checkResultsCount(List<RowModel> models, Statement request) {
    OptimisticLockingConfig olConfig = request.optimisticLockingConfig().orElseThrow(() -> new IllegalArgumentException("Statement " + request + " doesn't require results count check"));
    StringBuilder message = new StringBuilder();
    if (olConfig.getExpectedResultsCount() != models.size()) {
        message.append("Optimistic locking exception failed. ");
        Map<String, Object> parameters = request.getParameters();
        Object type = parameters.get("type");
        List<Map<String, Object>> rows = (List<Map<String, Object>>) parameters.get("rows");
        if (rows != null) {
            Map<Long, Long> nodeIds = new HashMap<>();
            Map<Long, Long> relIds = new HashMap<>();
            for (Map<String, Object> row : rows) {
                if (type.equals("node")) {
                    nodeIds.put((Long) row.get("nodeId"), (Long) row.get(olConfig.getVersionProperty()));
                } else if (type.equals("rel")) {
                    relIds.put((Long) row.get("relId"), (Long) row.get(olConfig.getVersionProperty()));
                }
            }
            if (!models.isEmpty()) {
                int idPosition = indexOf(models.get(0).variables(), "id");
                for (RowModel model : models) {
                    Object id = model.getValues()[idPosition];
                    if (type.equals("node")) {
                        nodeIds.remove(id);
                    } else if (type.equals("rel")) {
                        relIds.remove(id);
                    }
                }
            }
            for (Map.Entry<Long, Long> node : nodeIds.entrySet()) {
                Long nodeId = node.getKey();
                session.context().detachNodeEntity(nodeId);
                message.append("Entity with type='").append(Arrays.toString(olConfig.getTypes())).append("' and id='").append(nodeId).append("' had incorrect version ").append(node.getValue());
            }
            for (Map.Entry<Long, Long> rel : relIds.entrySet()) {
                Long relId = rel.getKey();
                session.context().detachRelationshipEntity(relId);
                message.append("Relationship entity with id ").append(relId).append(" had incorrect version ").append(rel.getValue());
            }
        } else {
            Object id = parameters.get("id");
            if (id != null && models.isEmpty()) {
                if (type.equals("node")) {
                    session.context().detachNodeEntity((Long) id);
                } else if (type.equals("rel")) {
                    session.context().detachRelationshipEntity((Long) id);
                }
            }
        }
        throw new OptimisticLockingException(message.toString());
    }
}
Also used : HashMap(java.util.HashMap) OptimisticLockingException(org.neo4j.ogm.exception.OptimisticLockingException) OptimisticLockingConfig(org.neo4j.ogm.request.OptimisticLockingConfig) List(java.util.List) RowModel(org.neo4j.ogm.model.RowModel) Map(java.util.Map) HashMap(java.util.HashMap)

Example 9 with RowModel

use of org.neo4j.ogm.model.RowModel in project neo4j-ogm by neo4j.

the class DeleteDelegate method deleteAll.

/**
 * Deletes all nodes of a given type. They will get discovered by using the matching label for that type.
 * To avoid a delete of every node in the database the method will abort the delete operation if no label
 * can be determined.
 *
 * @param type  The type of the nodes/objects to be deleted.
 * @param <T>   The type to work with
 */
public <T> void deleteAll(Class<T> type) {
    ClassInfo classInfo = session.metaData().classInfo(type.getName());
    if (classInfo != null) {
        String entityLabel = classInfo.neo4jName();
        if (entityLabel == null) {
            session.warn("Unable to find database label for entity " + type.getName() + " : no results will be returned. Make sure the class is registered, " + "and not abstract without @NodeEntity annotation");
            return;
        }
        Statement request = getDeleteStatementsBasedOnType(type).delete(entityLabel);
        RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
        session.notifyListeners(new PersistenceEvent(type, Event.TYPE.PRE_DELETE));
        session.doInTransaction(() -> {
            try (Response<RowModel> response = session.requestHandler().execute(query)) {
                session.context().removeType(type);
                if (session.eventsEnabled()) {
                    session.notifyListeners(new PersistenceEvent(type, Event.TYPE.POST_DELETE));
                }
            }
        }, Transaction.Type.READ_WRITE);
    } else {
        session.warn(type.getName() + " is not a persistable class");
    }
}
Also used : Statement(org.neo4j.ogm.request.Statement) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) RowModel(org.neo4j.ogm.model.RowModel) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest)

Example 10 with RowModel

use of org.neo4j.ogm.model.RowModel in project neo4j-ogm by neo4j.

the class DeleteDelegate method deleteOneOrMoreObjects.

// TODO : this is being done in multiple requests at the moment, one per object. Why not put them in a single request?
private void deleteOneOrMoreObjects(List<?> objects, Set<Object> neighbours) {
    Set<Object> notified = new HashSet<>();
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (!notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.PRE_SAVE));
                notified.add(affectedObject);
            }
        }
    }
    for (Object object : objects) {
        MetaData metaData = session.metaData();
        ClassInfo classInfo = metaData.classInfo(object);
        if (classInfo == null) {
            session.warn(object.getClass().getName() + " is not an instance of a persistable class");
        } else {
            MappingContext mappingContext = session.context();
            Long id = mappingContext.optionalNativeId(object).filter(possibleId -> possibleId >= 0).orElseGet(() -> {
                session.warn(String.format("Instance of class %s has to be reloaded to be deleted. This can happen if the session has " + "been cleared between loading and deleting or using an object from a different transaction.", object.getClass()));
                return classInfo.getPrimaryIndexOrIdReader().apply(object).map(primaryIndexOrId -> session.load(object.getClass(), (Serializable) primaryIndexOrId)).flatMap(reloadedObject -> mappingContext.optionalNativeId(reloadedObject)).orElse(-1L);
            });
            if (id >= 0) {
                Statement request = getDeleteStatement(object, id, classInfo);
                if (session.eventsEnabled() && !notified.contains(object)) {
                    session.notifyListeners(new PersistenceEvent(object, Event.TYPE.PRE_DELETE));
                    notified.add(object);
                }
                RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
                session.doInTransaction(() -> {
                    try (Response<RowModel> response = session.requestHandler().execute(query)) {
                        if (request.optimisticLockingConfig().isPresent()) {
                            List<RowModel> rowModels = response.toList();
                            session.optimisticLockingChecker().checkResultsCount(rowModels, request);
                        }
                        if (metaData.isRelationshipEntity(classInfo.name())) {
                            session.detachRelationshipEntity(id);
                        } else {
                            session.detachNodeEntity(id);
                        }
                        // enabled in the first place.
                        if (notified.contains(object)) {
                            session.notifyListeners(new PersistenceEvent(object, Event.TYPE.POST_DELETE));
                        }
                    }
                }, Transaction.Type.READ_WRITE);
            }
        }
    }
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.POST_SAVE));
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) CypherQuery(org.neo4j.ogm.cypher.query.CypherQuery) Response(org.neo4j.ogm.response.Response) Neo4jSession(org.neo4j.ogm.session.Neo4jSession) MappingContext(org.neo4j.ogm.context.MappingContext) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) RelationshipDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.RelationshipDeleteStatements) ArrayList(java.util.ArrayList) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) HashSet(java.util.HashSet) RowModel(org.neo4j.ogm.model.RowModel) Map(java.util.Map) Event(org.neo4j.ogm.session.event.Event) Transaction(org.neo4j.ogm.transaction.Transaction) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) Result(org.neo4j.ogm.model.Result) DeleteStatements(org.neo4j.ogm.session.request.strategy.DeleteStatements) MetaData(org.neo4j.ogm.metadata.MetaData) Set(java.util.Set) NodeDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.NodeDeleteStatements) Filter(org.neo4j.ogm.cypher.Filter) Statement(org.neo4j.ogm.request.Statement) Serializable(java.io.Serializable) List(java.util.List) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) Collections(java.util.Collections) Serializable(java.io.Serializable) Statement(org.neo4j.ogm.request.Statement) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) MappingContext(org.neo4j.ogm.context.MappingContext) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) MetaData(org.neo4j.ogm.metadata.MetaData) RowModel(org.neo4j.ogm.model.RowModel) HashSet(java.util.HashSet) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest)

Aggregations

RowModel (org.neo4j.ogm.model.RowModel)13 Statement (org.neo4j.ogm.request.Statement)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 List (java.util.List)3 Test (org.junit.Test)3 ClassInfo (org.neo4j.ogm.metadata.ClassInfo)3 CypherQuery (org.neo4j.ogm.cypher.query.CypherQuery)2 DefaultRowModelRequest (org.neo4j.ogm.cypher.query.DefaultRowModelRequest)2 RowModelRequest (org.neo4j.ogm.request.RowModelRequest)2 Response (org.neo4j.ogm.response.Response)2 PersistenceEvent (org.neo4j.ogm.session.event.PersistenceEvent)2 Serializable (java.io.Serializable)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 Result (org.neo4j.driver.Result)1 ClientException (org.neo4j.driver.exceptions.ClientException)1