Search in sources :

Example 21 with DatabaseCall

use of org.eclipse.persistence.internal.databaseaccess.DatabaseCall in project eclipselink by eclipse-ee4j.

the class TestParameterBinding method testABS_ForceBindJPQLParameters.

@Test
public void testABS_ForceBindJPQLParameters() {
    EntityManager em = forceBindEMF.createEntityManager();
    try {
        // 1: Test ABS function with parameter
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 2, COUNT(ABS(?1)) FROM GenericEntity s " + "WHERE s.itemInteger1 = ABS(?1)", GenericEntity.class);
        query.setParameter(1, -3);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.isDB2Z()) {
            Assert.fail("Expected a failure from " + pl);
        }
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 2, call.getParameters().size());
        }
    } catch (PersistenceException e) {
        Platform pl = forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        // ABS is a built-in function and built-in functions do not support untyped parameters on DB2/z
        if (pl.isDB2Z()) {
            Assert.assertEquals(DatabaseException.class, e.getCause().getClass());
            Assert.assertEquals("com.ibm.db2.jcc.am.SqlSyntaxErrorException", e.getCause().getCause().getClass().getName());
        } else {
            Assert.fail("Unexpected failure: " + e);
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 2: Test ABS function with literal
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 2, COUNT(ABS(-3)) FROM GenericEntity s " + "WHERE s.itemInteger1 = ABS(-3)", GenericEntity.class);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 0, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) Platform(org.eclipse.persistence.internal.databaseaccess.Platform) GenericEntity(org.eclipse.persistence.jpa.test.property.model.GenericEntity) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) Test(org.junit.Test)

Example 22 with DatabaseCall

use of org.eclipse.persistence.internal.databaseaccess.DatabaseCall in project eclipselink by eclipse-ee4j.

the class TestParameterBinding method testEXISTS_ForceBindJPQLParameters.

@Test
public void testEXISTS_ForceBindJPQLParameters() {
    EntityManager em = forceBindEMF.createEntityManager();
    try {
        // 9: Test string parameter in sub query
        TypedQuery<GenericEntity> query = em.createQuery("SELECT s FROM GenericEntity s " + "WHERE s.itemString1 = ?1  AND EXISTS (SELECT 1 FROM GenericEntity e WHERE s.itemInteger1 = ?2 )", GenericEntity.class);
        query.setParameter(1, "Test");
        query.setParameter(2, 33);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 2, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 10: Test string literal in sub query
        TypedQuery<GenericEntity> query = em.createQuery("SELECT s FROM GenericEntity s " + "WHERE s.itemString1 = 'Test' AND EXISTS (SELECT 1 FROM GenericEntity e WHERE s.itemInteger1 = 33 )", GenericEntity.class);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 0, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) GenericEntity(org.eclipse.persistence.jpa.test.property.model.GenericEntity) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) Test(org.junit.Test)

Example 23 with DatabaseCall

use of org.eclipse.persistence.internal.databaseaccess.DatabaseCall in project eclipselink by eclipse-ee4j.

the class LOBValueWriter method buildAndExecuteCall.

protected void buildAndExecuteCall(DatabaseCall dbCall, AbstractSession session) {
    DatabaseQuery query = dbCall.getQuery();
    if (!query.isWriteObjectQuery()) {
        // if not writequery, should not go through the locator writing..
        return;
    }
    WriteObjectQuery writeQuery = (WriteObjectQuery) query;
    writeQuery.setAccessor(accessor);
    // build a select statement form the query
    SQLSelectStatement selectStatement = buildSelectStatementForLocator(writeQuery, dbCall, session);
    // then build a call from the statement
    DatabaseCall call = buildCallFromSelectStatementForLocator(selectStatement, writeQuery, dbCall, session);
    accessor.executeCall(call, call.getQuery().getTranslationRow(), session);
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) WriteObjectQuery(org.eclipse.persistence.queries.WriteObjectQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) SQLSelectStatement(org.eclipse.persistence.internal.expressions.SQLSelectStatement)

Example 24 with DatabaseCall

use of org.eclipse.persistence.internal.databaseaccess.DatabaseCall in project eclipselink by eclipse-ee4j.

the class LOBValueWriter method buildAndExecuteSelectCalls.

// Bug 3110860: RETURNINGPOLICY-OBTAINED PK CAUSES LOB TO BE INSERTED INCORRECTLY
// The deferred locator SELECT calls should be generated and executed after ReturningPolicy
// merges PK obtained from the db into the object held by the query.
// That's why original (insert or update) calls are saved,
// and both building and executing of SELECT statements postponed until
// this method is called.
/**
 * Build and execute the deferred select calls.
 */
public void buildAndExecuteSelectCalls(AbstractSession session) {
    if ((calls == null) || calls.isEmpty()) {
        // no deferred select calls (it means no locator is required)
        return;
    }
    // all INSERTs have been executed, time to execute the SELECTs
    try {
        for (Iterator<DatabaseCall> callIt = calls.iterator(); callIt.hasNext(); ) {
            DatabaseCall dbCall = callIt.next();
            buildAndExecuteCall(dbCall, session);
        }
    } finally {
        // after executing all select calls, need to empty the collection.
        // this is necessary in the nested unit of work cases.
        calls.clear();
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall)

Example 25 with DatabaseCall

use of org.eclipse.persistence.internal.databaseaccess.DatabaseCall in project eclipselink by eclipse-ee4j.

the class ReadAllQuery method executeObjectLevelReadQuery.

/**
 * INTERNAL:
 * Execute the query.
 * Get the rows and build the object from the rows.
 * @exception  DatabaseException - an error has occurred on the database
 * @return java.lang.Object collection of objects resulting from execution of query.
 */
@Override
protected Object executeObjectLevelReadQuery() throws DatabaseException {
    Object result = null;
    if (this.containerPolicy.overridesRead()) {
        this.executionTime = System.currentTimeMillis();
        return this.containerPolicy.execute();
    }
    if (this.descriptor.isDescriptorForInterface()) {
        Object returnValue = this.descriptor.getInterfacePolicy().selectAllObjectsUsingMultipleTableSubclassRead(this);
        this.executionTime = System.currentTimeMillis();
        return returnValue;
    }
    if (this.descriptor.hasTablePerClassPolicy() && this.descriptor.isAbstract()) {
        result = this.containerPolicy.containerInstance();
        if (this.shouldIncludeData) {
            ComplexQueryResult complexResult = new ComplexQueryResult();
            complexResult.setResult(result);
            complexResult.setData(new ArrayList());
            result = complexResult;
        }
    } else {
        Object sopObject = getTranslationRow().getSopObject();
        boolean useOptimization = false;
        if (sopObject == null) {
            useOptimization = usesResultSetAccessOptimization();
        }
        if (useOptimization) {
            DatabaseCall call = ((DatasourceCallQueryMechanism) this.queryMechanism).selectResultSet();
            this.executionTime = System.currentTimeMillis();
            Statement statement = call.getStatement();
            ResultSet resultSet = call.getResult();
            DatabaseAccessor dbAccessor = (DatabaseAccessor) getAccessor();
            boolean exceptionOccured = false;
            try {
                if (this.session.isUnitOfWork()) {
                    result = registerResultSetInUnitOfWork(resultSet, call.getFields(), call.getFieldsArray(), (UnitOfWorkImpl) this.session, this.translationRow);
                } else {
                    result = this.containerPolicy.containerInstance();
                    this.descriptor.getObjectBuilder().buildObjectsFromResultSetInto(this, resultSet, call.getFields(), call.getFieldsArray(), result);
                }
            } catch (SQLException exception) {
                exceptionOccured = true;
                DatabaseException commException = dbAccessor.processExceptionForCommError(this.session, exception, call);
                if (commException != null) {
                    throw commException;
                }
                throw DatabaseException.sqlException(exception, call, dbAccessor, this.session, false);
            } finally {
                try {
                    if (resultSet != null) {
                        resultSet.close();
                    }
                    if (dbAccessor != null) {
                        if (statement != null) {
                            dbAccessor.releaseStatement(statement, call.getSQLString(), call, this.session);
                        }
                    }
                    if (call.hasAllocatedConnection()) {
                        getExecutionSession().releaseConnectionAfterCall(this);
                    }
                } catch (RuntimeException cleanupException) {
                    if (!exceptionOccured) {
                        throw cleanupException;
                    }
                } catch (SQLException cleanupSQLException) {
                    if (!exceptionOccured) {
                        throw DatabaseException.sqlException(cleanupSQLException, call, dbAccessor, this.session, false);
                    }
                }
            }
        } else {
            List<AbstractRecord> rows;
            if (sopObject != null) {
                Object valuesIterator = this.containerPolicy.iteratorFor(getTranslationRow().getSopObject());
                int size = this.containerPolicy.sizeFor(sopObject);
                rows = new ArrayList<>(size);
                while (this.containerPolicy.hasNext(valuesIterator)) {
                    Object memberSopObject = this.containerPolicy.next(valuesIterator, this.session);
                    DatabaseRecord memberRow = new DatabaseRecord(0);
                    memberRow.setSopObject(memberSopObject);
                    rows.add(memberRow);
                }
                this.executionTime = System.currentTimeMillis();
            } else {
                rows = getQueryMechanism().selectAllRows();
                this.executionTime = System.currentTimeMillis();
                // If using 1-m joins, must set all rows.
                if (hasJoining() && this.joinedAttributeManager.isToManyJoin()) {
                    this.joinedAttributeManager.setDataResults(rows, this.session);
                }
                // Batch fetching in IN requires access to the rows to build the id array.
                if ((this.batchFetchPolicy != null) && this.batchFetchPolicy.isIN()) {
                    this.batchFetchPolicy.setDataResults(rows);
                }
            }
            if (this.session.isUnitOfWork()) {
                // 
                result = registerResultInUnitOfWork(rows, (UnitOfWorkImpl) this.session, this.translationRow, true);
            } else {
                if (rows instanceof ThreadCursoredList) {
                    result = this.containerPolicy.containerInstance();
                } else {
                    result = this.containerPolicy.containerInstance(rows.size());
                }
                this.descriptor.getObjectBuilder().buildObjectsInto(this, rows, result);
            }
            if (sopObject != null) {
                if (!this.descriptor.getObjectBuilder().isSimple()) {
                    // remove sopObject so it's not stuck in any value holder.
                    for (AbstractRecord row : rows) {
                        row.setSopObject(null);
                    }
                }
            } else {
                if (this.shouldIncludeData) {
                    ComplexQueryResult complexResult = new ComplexQueryResult();
                    complexResult.setResult(result);
                    complexResult.setData(rows);
                    result = complexResult;
                }
            }
        }
    }
    // Add the other (already registered) results and return them.
    if (this.descriptor.hasTablePerClassPolicy()) {
        result = this.containerPolicy.concatenateContainers(result, this.descriptor.getTablePerClassPolicy().selectAllObjectsUsingMultipleTableSubclassRead(this), this.session);
    }
    // If the results were empty, then ensure they get cached still.
    if (shouldCacheQueryResults() && this.containerPolicy.isEmpty(result)) {
        this.temporaryCachedQueryResults = InvalidObject.instance();
    }
    return result;
}
Also used : DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) SQLException(java.sql.SQLException) Statement(java.sql.Statement) ThreadCursoredList(org.eclipse.persistence.internal.helper.ThreadCursoredList) DatasourceCallQueryMechanism(org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism) ArrayList(java.util.ArrayList) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) ResultSet(java.sql.ResultSet) InvalidObject(org.eclipse.persistence.internal.helper.InvalidObject) DatabaseAccessor(org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException)

Aggregations

DatabaseCall (org.eclipse.persistence.internal.databaseaccess.DatabaseCall)31 DatabasePlatform (org.eclipse.persistence.internal.databaseaccess.DatabasePlatform)11 EntityManager (jakarta.persistence.EntityManager)9 DatabaseException (org.eclipse.persistence.exceptions.DatabaseException)9 EntityManagerFactoryImpl (org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl)8 GenericEntity (org.eclipse.persistence.jpa.test.property.model.GenericEntity)8 Test (org.junit.Test)8 SQLCall (org.eclipse.persistence.queries.SQLCall)6 StoredProcedureCall (org.eclipse.persistence.queries.StoredProcedureCall)6 PersistenceException (jakarta.persistence.PersistenceException)5 Platform (org.eclipse.persistence.internal.databaseaccess.Platform)5 AbstractRecord (org.eclipse.persistence.internal.sessions.AbstractRecord)5 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 DatabaseAccessor (org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor)4 DatasourceCallQueryMechanism (org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism)4 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)4 ResultSetMetaData (java.sql.ResultSetMetaData)3 Statement (java.sql.Statement)3 UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)3