Search in sources :

Example 21 with Transaction

use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.

the class BaseAutoIndexManagerTestClass method executeForIndexes.

void executeForIndexes(Consumer<List<IndexInfo>> consumer) {
    Session session = sessionFactory.openSession();
    try (Transaction tx = session.beginTransaction()) {
        Result indexResult = session.query("CALL db.indexes()", emptyMap());
        List<IndexInfo> indexes = new ArrayList<>();
        for (Map<String, Object> queryResult : indexResult.queryResults()) {
            if (AutoIndex.isNodeOrRelationshipLookup(queryResult)) {
                continue;
            }
            if (isVersionOrGreater("4.0.0")) {
                Object[] labelsOrTypes = (Object[]) queryResult.get("labelsOrTypes");
                IndexInfo indexInfo = new IndexInfo((String) queryResult.get("uniqueness"), (labelsOrTypes instanceof String[] ? (String[]) labelsOrTypes : new String[0]));
                indexes.add(indexInfo);
            } else {
                String indexType = (String) queryResult.get("type");
                String[] labels = queryResult.get("tokenNames") != null ? // 3.5
                (String[]) queryResult.get("tokenNames") : // 3.4(-)
                new String[] { (String) queryResult.get("label") };
                IndexInfo indexInfo = new IndexInfo(indexType, labels);
                indexes.add(indexInfo);
            }
        }
        List<IndexInfo> pureIndexes = indexes.stream().filter(indexInfo -> !indexInfo.isConstraintIndex()).collect(toList());
        consumer.accept(pureIndexes);
        tx.commit();
    }
}
Also used : Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) LoggerContext(ch.qos.logback.classic.LoggerContext) ArrayList(java.util.ArrayList) Map(java.util.Map) After(org.junit.After) Assertions(org.assertj.core.api.Assertions) Transaction(org.neo4j.ogm.transaction.Transaction) StreamSupport(java.util.stream.StreamSupport) Result(org.neo4j.ogm.model.Result) Before(org.junit.Before) DatabaseException(org.neo4j.driver.exceptions.DatabaseException) Session(org.neo4j.ogm.session.Session) AbstractThrowableAssert(org.assertj.core.api.AbstractThrowableAssert) Logger(org.slf4j.Logger) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) File(java.io.File) Consumer(java.util.function.Consumer) Level(ch.qos.logback.classic.Level) List(java.util.List) Stream(java.util.stream.Stream) Configuration(org.neo4j.ogm.config.Configuration) SessionFactory(org.neo4j.ogm.session.SessionFactory) TestContainersTestBase(org.neo4j.ogm.testutil.TestContainersTestBase) Collections(java.util.Collections) Transaction(org.neo4j.ogm.transaction.Transaction) ArrayList(java.util.ArrayList) Session(org.neo4j.ogm.session.Session) Result(org.neo4j.ogm.model.Result)

Example 22 with Transaction

use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.

the class BaseAutoIndexManagerTestClass method executeForConstraints.

void executeForConstraints(Consumer<List<ConstraintInfo>> consumer) {
    Session session = sessionFactory.openSession();
    try (Transaction tx = session.beginTransaction()) {
        Result constraintResult = session.query("CALL db.constraints()", emptyMap());
        List<ConstraintInfo> constraints = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : constraintResult) {
            constraints.add(new ConstraintInfo());
        }
        consumer.accept(constraints);
        tx.commit();
    }
}
Also used : Transaction(org.neo4j.ogm.transaction.Transaction) ArrayList(java.util.ArrayList) Session(org.neo4j.ogm.session.Session) Result(org.neo4j.ogm.model.Result)

Example 23 with Transaction

use of org.neo4j.ogm.transaction.Transaction 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)

Example 24 with Transaction

use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.

the class Neo4jSession method doInTransaction.

/**
 * For internal use only. Opens a new transaction if necessary before running statements
 * in case an explicit transaction does not exist. It is designed to be the central point
 * for handling exceptions coming from the DB and apply commit / rollback rules.
 *
 * @param function The callback to execute.
 * @param <T>      The result type.
 * @param txType   Transaction type, readonly or not.
 * @return The result of the transaction function.
 */
public <T> T doInTransaction(TransactionalUnitOfWork<T> function, boolean forceTx, Transaction.Type txType) {
    Transaction transaction = txManager.getCurrentTransaction();
    // If we (force) create a new transaction, we are in charge of handling rollback in case of errors
    // and cleaning up afterwards.
    boolean newTransaction = false;
    try {
        if (forceTx || (driver.requiresTransaction() && transaction == null)) {
            transaction = beginTransaction(txType);
            newTransaction = true;
        }
        T result = function.doInTransaction();
        if (newTransaction && txManager.canCommit()) {
            transaction.commit();
        }
        return result;
    } catch (CypherException e) {
        if (newTransaction && txManager.canRollback()) {
            logger.warn("Error executing query : {} - {}. Rolling back transaction.", e.getCode(), e.getDescription());
            transaction.rollback();
        }
        throw e;
    } catch (Throwable e) {
        if (newTransaction && txManager.canRollback()) {
            logger.warn("Error executing query : {}. Rolling back transaction.", e.getMessage());
            transaction.rollback();
        }
        throw driver.getExceptionTranslator().translateExceptionIfPossible(e);
    } finally {
        if (newTransaction && transaction != null && !transaction.status().equals(Transaction.Status.CLOSED)) {
            transaction.close();
        }
    }
}
Also used : Transaction(org.neo4j.ogm.transaction.Transaction) CypherException(org.neo4j.ogm.exception.CypherException)

Example 25 with Transaction

use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.

the class SatelliteIntegrationTest method shouldCommitLongTransaction.

@Test
public void shouldCommitLongTransaction() {
    Long id;
    try (Transaction tx = session.beginTransaction()) {
        // load all
        Collection<Satellite> satellites = session.loadAll(Satellite.class);
        assertThat(satellites).hasSize(11);
        Satellite satellite = satellites.iterator().next();
        id = satellite.getId();
        satellite.setName("Updated satellite");
        // update
        session.save(satellite);
        session.clear();
        // refetch
        Satellite updatedSatellite = session.load(Satellite.class, id);
        assertThat(updatedSatellite.getName()).isEqualTo("Updated satellite");
        tx.commit();
    }
    session.clear();
    // fetch - after commit should be changed
    // note, that because we aren't starting a new tx, we will be given an autocommit one.
    Satellite reloadedSatellite = session.load(Satellite.class, id);
    assertThat(reloadedSatellite.getName()).isEqualTo("Updated satellite");
}
Also used : Transaction(org.neo4j.ogm.transaction.Transaction) Satellite(org.neo4j.ogm.domain.satellites.Satellite) Test(org.junit.Test)

Aggregations

Transaction (org.neo4j.ogm.transaction.Transaction)47 Test (org.junit.Test)30 Session (org.neo4j.ogm.session.Session)10 ArrayList (java.util.ArrayList)5 Neo4jSession (org.neo4j.ogm.session.Neo4jSession)5 SessionConfig (org.neo4j.driver.SessionConfig)4 Result (org.neo4j.ogm.model.Result)4 HashSet (java.util.HashSet)3 LinkedHashSet (java.util.LinkedHashSet)3 HttpResponseException (org.apache.http.client.HttpResponseException)3 Bike (org.neo4j.ogm.domain.gh817.Bike)3 Studio (org.neo4j.ogm.domain.music.Studio)3 Satellite (org.neo4j.ogm.domain.satellites.Satellite)3 User (org.neo4j.ogm.domain.social.User)3 SessionFactory (org.neo4j.ogm.session.SessionFactory)3 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2