Search in sources :

Example 81 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class MetadataResource method buildQuerySchemaResponse.

private Response buildQuerySchemaResponse(String version, String persistenceUnit, String queryName, UriInfo uriInfo) {
    JPARSLogger.entering(CLASS_NAME, "buildQuerySchemaResponse", new Object[] { "GET", version, persistenceUnit, uriInfo.getRequestUri().toASCIIString() });
    final String result;
    try {
        final PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
        // We need to make sure that query with given name exists
        final DatabaseQuery query = context.getServerSession().getQuery(queryName);
        if (query == null) {
            JPARSLogger.error(context.getSessionLog(), "jpars_could_not_find_query", new Object[] { queryName, persistenceUnit });
            throw JPARSException.responseCouldNotBeBuiltForNamedQueryRequest(queryName, context.getName());
        }
        final ResourceSchema querySchema = buildQuerySchema(context, query);
        result = marshallMetadata(querySchema, MediaType.APPLICATION_JSON);
    } catch (JAXBException e) {
        throw JPARSException.exceptionOccurred(e);
    }
    return Response.ok(new StreamingOutputMarshaller(null, result, AbstractResource.APPLICATION_SCHEMA_JSON_TYPE)).build();
}
Also used : ResourceSchema(org.eclipse.persistence.internal.jpa.rs.metadata.model.v2.ResourceSchema) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) JAXBException(jakarta.xml.bind.JAXBException) PersistenceContext(org.eclipse.persistence.jpa.rs.PersistenceContext) StreamingOutputMarshaller(org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller)

Example 82 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class TableTypeTestSuite method testCreateAndDeleteSQL.

@Test
public void testCreateAndDeleteSQL() {
    xrService.getORSession().getActiveSession().getIdentityMapAccessor().initializeIdentityMaps();
    DatabaseQuery createQuery = xrService.getORSession().getQuery("create_TabletypeType");
    // by default, JPA will create a DataReadQuery, but we want a DataModifyQuery
    DataModifyQuery query = new DataModifyQuery();
    query.setIsUserDefined(createQuery.isUserDefined());
    query.copyFromQuery(createQuery);
    // Need to clone call, in case was executed as read.
    query.setDatasourceCall((Call) createQuery.getDatasourceCall().clone());
    List<String> args = new ArrayList<String>();
    Vector<DatabaseField> fieldVector = new Vector<DatabaseField>(12);
    List<Object> argVals = new ArrayList<Object>();
    argVals.add(99);
    argVals.add("Joe Black");
    argVals.add("22");
    argVals.add("Janitor");
    argVals.add("q");
    argVals.add(19000);
    argVals.add(333);
    argVals.add(1.00);
    argVals.add("1111");
    argVals.add("040404040404040404040404040404");
    argVals.add("dddddddddddddddddddddddddddddd");
    argVals.add("040404");
    fieldVector.add(new DatabaseField("ID", "TABLETYPE"));
    fieldVector.add(new DatabaseField("NAME", "TABLETYPE"));
    fieldVector.add(new DatabaseField("DEPTNO", "TABLETYPE"));
    fieldVector.add(new DatabaseField("DEPTNAME", "TABLETYPE"));
    fieldVector.add(new DatabaseField("SECTION", "TABLETYPE"));
    fieldVector.add(new DatabaseField("SAL", "TABLETYPE"));
    fieldVector.add(new DatabaseField("COMMISSION", "TABLETYPE"));
    fieldVector.add(new DatabaseField("SALES", "TABLETYPE"));
    fieldVector.add(new DatabaseField("BINID", "TABLETYPE"));
    fieldVector.add(new DatabaseField("B", "TABLETYPE"));
    fieldVector.add(new DatabaseField("C", "TABLETYPE"));
    fieldVector.add(new DatabaseField("R", "TABLETYPE"));
    for (int i = 1; i <= argVals.size(); i++) {
        args.add(String.valueOf(i));
    }
    query.setArguments(args);
    query.setArgumentValues(argVals);
    ((SQLCall) query.getDatasourceCall()).setFields(fieldVector);
    // need to create/set a translation row
    AbstractRecord row = query.rowFromArguments(argVals, (AbstractSession) xrService.getORSession());
    query.setTranslationRow(row);
    query.prepareCall(xrService.getORSession(), query.getTranslationRow());
    query.setSession((AbstractSession) xrService.getORSession());
    query.executeDatabaseQuery();
    // verify create call succeeded
    Invocation invocation = new Invocation("findByPrimaryKey_TabletypeType");
    invocation.setParameter("id", 99);
    Operation op = xrService.getOperation(invocation.getName());
    Object result = op.invoke(xrService, invocation);
    assertNotNull("Result is null after create call", result);
    Document doc = xmlPlatform.createDocument();
    XMLMarshaller marshaller = xrService.getXMLContext().createMarshaller();
    marshaller.marshal(result, doc);
    Document controlDoc = xmlParser.parse(new StringReader(NEW_PERSON2_XML));
    assertTrue("Expected:\n" + documentToString(controlDoc) + "but was:\n" + documentToString(doc), comparer.isNodeEqual(controlDoc, doc));
    // delete
    DatabaseQuery deleteQuery = xrService.getORSession().getQuery("delete_TabletypeType");
    // by default, JPA will create a DataReadQuery, but we want a DataModifyQuery
    query = new DataModifyQuery();
    query.setIsUserDefined(deleteQuery.isUserDefined());
    query.copyFromQuery(deleteQuery);
    // Need to clone call, in case was executed as read.
    query.setDatasourceCall((Call) deleteQuery.getDatasourceCall().clone());
    args = new ArrayList<String>();
    fieldVector = new Vector<DatabaseField>(12);
    argVals = new ArrayList<Object>();
    argVals.add(99);
    args.add("1");
    fieldVector.add(new DatabaseField("ID", "TABLETYPE"));
    query.setArguments(args);
    query.setArgumentValues(argVals);
    ((SQLCall) query.getDatasourceCall()).setFields(fieldVector);
    // need to create/set a translation row
    row = query.rowFromArguments(argVals, (AbstractSession) xrService.getORSession());
    query.setTranslationRow(row);
    query.prepareCall(xrService.getORSession(), query.getTranslationRow());
    query.setSession((AbstractSession) xrService.getORSession());
    query.executeDatabaseQuery();
    // verify delete call succeeded
    result = op.invoke(xrService, invocation);
    assertNull("Result not null after delete call", result);
}
Also used : SQLCall(org.eclipse.persistence.queries.SQLCall) Invocation(org.eclipse.persistence.internal.xr.Invocation) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) XMLMarshaller(org.eclipse.persistence.oxm.XMLMarshaller) ArrayList(java.util.ArrayList) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) Operation(org.eclipse.persistence.internal.xr.Operation) Document(org.w3c.dom.Document) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) StringReader(java.io.StringReader) Vector(java.util.Vector) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Test(org.junit.Test)

Example 83 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class TableTypeTestSuite method testUpdateSQL.

@SuppressWarnings("rawtypes")
@Test
public void testUpdateSQL() {
    xrService.getORSession().getActiveSession().getIdentityMapAccessor().initializeIdentityMaps();
    XMLUnmarshaller unmarshaller = xrService.getXMLContext().createUnmarshaller();
    InputSource inputSource = new InputSource(new StringReader(ONE_PERSON_XML));
    XRDynamicEntity firstPerson = (XRDynamicEntity) unmarshaller.unmarshal(inputSource);
    Float originalSal = firstPerson.get("sal");
    String originalC = firstPerson.get("c");
    firstPerson.set("sal", 112000.99);
    firstPerson.set("c", "ababababababababababababababab");
    DatabaseQuery updateQuery = xrService.getORSession().getQuery("update_TabletypeType");
    // map property names to parameter binding values
    Map<String, Integer> propOrder = new HashMap<String, Integer>();
    propOrder.put("id", 1);
    propOrder.put("name", 2);
    propOrder.put("deptno", 3);
    propOrder.put("deptname", 4);
    propOrder.put("section", 5);
    propOrder.put("sal", 6);
    propOrder.put("commission", 7);
    propOrder.put("sales", 8);
    propOrder.put("binid", 9);
    propOrder.put("b", 10);
    propOrder.put("c", 11);
    propOrder.put("r", 12);
    List<String> args = new ArrayList<String>();
    Vector<DatabaseField> fieldVector = new Vector<DatabaseField>(12);
    List<Object> argVals = new ArrayList<Object>();
    for (String prop : firstPerson.getPropertiesMap().keySet()) {
        args.add(propOrder.get(prop).toString());
        argVals.add(firstPerson.get(prop));
        fieldVector.add(new DatabaseField(prop.toUpperCase(), "TABLETYPE"));
    }
    // by default, JPA will create a DataReadQuery, but we want a DataModifyQuery
    DataModifyQuery query = new DataModifyQuery();
    query.setIsUserDefined(updateQuery.isUserDefined());
    query.copyFromQuery(updateQuery);
    // Need to clone call, in case was executed as read.
    query.setDatasourceCall((Call) updateQuery.getDatasourceCall().clone());
    query.setArguments(args);
    query.setArgumentValues(argVals);
    ((SQLCall) query.getDatasourceCall()).setFields(fieldVector);
    // need to create/set a translation row
    AbstractRecord row = query.rowFromArguments(argVals, (AbstractSession) xrService.getORSession());
    query.setTranslationRow(row);
    query.prepareCall(xrService.getORSession().getActiveSession(), row);
    query.setSession((AbstractSession) xrService.getORSession().getActiveSession());
    // execute the update
    query.executeDatabaseQuery();
    // verify update operation
    DatabaseQuery findQuery = xrService.getORSession().getActiveSession().getQuery("findByPrimaryKey_TabletypeType");
    findQuery.setIsPrepared(false);
    args = new ArrayList<String>();
    fieldVector = new Vector<DatabaseField>(12);
    argVals = new ArrayList<Object>();
    argVals.add(1);
    args.add("1");
    fieldVector.add(new DatabaseField("ID", "TABLETYPE"));
    findQuery.setArguments(args);
    findQuery.setArgumentValues(argVals);
    ((SQLCall) findQuery.getDatasourceCall()).setFields(fieldVector);
    // need to create/set a translation row
    row = findQuery.rowFromArguments(argVals, (AbstractSession) xrService.getORSession().getActiveSession());
    findQuery.setTranslationRow(row);
    findQuery.prepareCall(xrService.getORSession().getActiveSession(), row);
    findQuery.setSession((AbstractSession) xrService.getORSession().getActiveSession());
    xrService.getORSession().getActiveSession().getIdentityMapAccessor().initializeIdentityMaps();
    // execute the FindByPk
    Object result = findQuery.executeDatabaseQuery();
    assertTrue("Expected Vector, but result was " + result.getClass().getName(), result instanceof Vector);
    Vector resultVector = (Vector) result;
    assertTrue("Expected vector of size 1, but was " + resultVector.size(), resultVector.size() == 1);
    result = resultVector.get(0);
    assertTrue("Expected TableType (XRDynamicEntity) but was " + result.getClass().getName(), result instanceof XRDynamicEntity);
    // verify that 'sal' and 'c' fields were updated successfully
    XRDynamicEntity tableTypeEntity = (XRDynamicEntity) result;
    assertTrue("Expected [sal] '112000.99' but was '" + tableTypeEntity.get("sal") + "'", Float.compare(tableTypeEntity.get("sal"), 112000.99f) == 0);
    Character[] chars = tableTypeEntity.get("c");
    StringBuilder sb = new StringBuilder(chars.length);
    for (Character c : chars) {
        sb.append(c.charValue());
    }
    String charStr = sb.toString();
    assertTrue("Expected [c] 'ababababababababababababababab' but was '" + tableTypeEntity.get("c") + "'", charStr.equals("ababababababababababababababab"));
    // reset original value
    firstPerson.set("sal", originalSal);
    firstPerson.set("c", originalC);
    Invocation invocation = new Invocation("update_TabletypeType");
    invocation.setParameter("theInstance", firstPerson);
    Operation op = xrService.getOperation(invocation.getName());
    op.invoke(xrService, invocation);
}
Also used : SQLCall(org.eclipse.persistence.queries.SQLCall) InputSource(org.xml.sax.InputSource) Invocation(org.eclipse.persistence.internal.xr.Invocation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Operation(org.eclipse.persistence.internal.xr.Operation) StringReader(java.io.StringReader) XMLUnmarshaller(org.eclipse.persistence.oxm.XMLUnmarshaller) Vector(java.util.Vector) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) XRDynamicEntity(org.eclipse.persistence.internal.xr.XRDynamicEntity) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) Test(org.junit.Test)

Example 84 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class EntityManagerFactoryDelegate method addNamedQuery.

@Override
public void addNamedQuery(String name, Query query) {
    DatabaseQuery unwrapped = (DatabaseQuery) query.unwrap(DatabaseQuery.class).clone();
    QueryImpl originalQuery = query.unwrap(QueryImpl.class);
    if (originalQuery.lockMode != null) {
        ((ObjectLevelReadQuery) unwrapped).setLockModeType(originalQuery.lockMode.name(), session);
    }
    if (unwrapped.isReadQuery()) {
        ((ReadQuery) unwrapped).setInternalMax((originalQuery.getMaxResultsInternal()));
        if (query.getFirstResult() != QueryImpl.UNDEFINED) {
            ((ReadQuery) unwrapped).setFirstResult(query.getFirstResult());
        }
    }
    this.getServerSession().addQuery(name, unwrapped, true);
}
Also used : ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) ReadQuery(org.eclipse.persistence.queries.ReadQuery)

Example 85 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class EJBQueryImpl method buildEJBQLDatabaseQuery.

/**
 * Build a DatabaseQuery from an JPQL string.
 *
 * @param jpqlQuery
 *            the JPQL string.
 * @param session
 *            the session to get the descriptors for this query for.
 * @param hints
 *            a list of hints to be applied to the query.
 * @return a DatabaseQuery representing the given jpql.
 */
public static DatabaseQuery buildEJBQLDatabaseQuery(String queryName, String jpqlQuery, AbstractSession session, Enum lockMode, Map<String, Object> hints, ClassLoader classLoader) {
    // PERF: Check if the JPQL has already been parsed.
    // Only allow queries with default properties to be parse cached.
    boolean isCacheable = (queryName == null) && (hints == null);
    DatabaseQuery databaseQuery = null;
    if (isCacheable) {
        databaseQuery = (DatabaseQuery) session.getProject().getJPQLParseCache().get(jpqlQuery);
    }
    if ((databaseQuery == null) || (!databaseQuery.isPrepared())) {
        JPAQueryBuilder queryBuilder = session.getQueryBuilder();
        databaseQuery = queryBuilder.buildQuery(jpqlQuery, session);
        // filtering duplicates.
        if (databaseQuery.isReadAllQuery()) {
            ReadAllQuery readAllQuery = (ReadAllQuery) databaseQuery;
            if (readAllQuery.hasJoining() && (readAllQuery.getDistinctState() == ReadAllQuery.DONT_USE_DISTINCT)) {
                readAllQuery.setShouldFilterDuplicates(false);
            }
        } else if (databaseQuery.isModifyQuery()) {
            // By default, do not batch modify queries, as row count must be returned.
            ((ModifyQuery) databaseQuery).setIsBatchExecutionSupported(false);
        }
        ((JPQLCallQueryMechanism) databaseQuery.getQueryMechanism()).getJPQLCall().setIsParsed(true);
        // Apply the lock mode.
        if (lockMode != null && !lockMode.name().equals(ObjectLevelReadQuery.NONE)) {
            if (databaseQuery.isObjectLevelReadQuery()) {
                // set the lock mode, throw an exception.
                if (((ObjectLevelReadQuery) databaseQuery).setLockModeType(lockMode.name(), session)) {
                    throw new PersistenceException(ExceptionLocalization.buildMessage("ejb30-wrong-lock_called_without_version_locking-index", null));
                }
            } else {
                throw new IllegalArgumentException(ExceptionLocalization.buildMessage("invalid_lock_query", null));
            }
        }
        // Apply any query hints.
        databaseQuery = applyHints(hints, databaseQuery, classLoader, session);
        // If a primary key query, switch to read-object to allow cache hit.
        if (databaseQuery.isReadAllQuery() && !databaseQuery.isReportQuery() && ((ReadAllQuery) databaseQuery).shouldCheckCache()) {
            ReadAllQuery readQuery = (ReadAllQuery) databaseQuery;
            if ((readQuery.getContainerPolicy().getContainerClass() == ContainerPolicy.getDefaultContainerClass()) && (!readQuery.hasHierarchicalExpressions())) {
                databaseQuery.checkDescriptor(session);
                Expression selectionCriteria = databaseQuery.getSelectionCriteria();
                if ((selectionCriteria != null) && (databaseQuery.getDescriptor().getObjectBuilder().isPrimaryKeyExpression(true, selectionCriteria, session) || (databaseQuery.getDescriptor().getCachePolicy().isIndexableExpression(selectionCriteria, databaseQuery.getDescriptor(), session)))) {
                    ReadObjectQuery newQuery = new ReadObjectQuery();
                    newQuery.copyFromQuery(databaseQuery);
                    databaseQuery = newQuery;
                }
            }
        }
        if (isCacheable) {
            // Prepare query as hint may cause cloning (but not un-prepare
            // as in read-only).
            databaseQuery.checkPrepare(session, new DatabaseRecord());
            session.getProject().getJPQLParseCache().put(jpqlQuery, databaseQuery);
        }
    }
    return databaseQuery;
}
Also used : ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) Expression(org.eclipse.persistence.expressions.Expression) JPAQueryBuilder(org.eclipse.persistence.queries.JPAQueryBuilder) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) PersistenceException(jakarta.persistence.PersistenceException)

Aggregations

DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)86 ArrayList (java.util.ArrayList)18 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)15 List (java.util.List)14 Vector (java.util.Vector)12 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)12 ObjectLevelReadQuery (org.eclipse.persistence.queries.ObjectLevelReadQuery)12 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)8 EntityManager (jakarta.persistence.EntityManager)6 HashMap (java.util.HashMap)6 QName (javax.xml.namespace.QName)6 EJBQueryImpl (org.eclipse.persistence.internal.jpa.EJBQueryImpl)6 PersistenceContext (org.eclipse.persistence.jpa.rs.PersistenceContext)6 DataReadQuery (org.eclipse.persistence.queries.DataReadQuery)6 Session (org.eclipse.persistence.sessions.Session)6 Test (org.junit.Test)6 NonSynchronizedVector (org.eclipse.persistence.internal.helper.NonSynchronizedVector)5 ReadQuery (org.eclipse.persistence.queries.ReadQuery)5 ReportQuery (org.eclipse.persistence.queries.ReportQuery)5 PersistenceException (jakarta.persistence.PersistenceException)4