Search in sources :

Example 21 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project tests by datanucleus.

the class JPQLSubqueryTest method testHavingSubquery.

/**
 * Simple query using a subquery in the HAVING clause.
 */
public void testHavingSubquery() {
    if (!(storeMgr instanceof RDBMSStoreManager)) {
        return;
    }
    DatastoreAdapter dba = ((RDBMSStoreManager) storeMgr).getDatastoreAdapter();
    if (!dba.supportsOption(DatastoreAdapter.SUBQUERY_IN_HAVING)) {
        return;
    }
    try {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Account a1 = new Account();
            a1.setUsername("Flintstone");
            a1.setId(1);
            em.persist(a1);
            Organisation o1 = new Organisation("Flintstone");
            o1.setDescription("Freds organisation");
            em.persist(o1);
            // TODO Come up with a better sample query. Why does the JPA TCK/Spec have none?
            List<Person> result = em.createQuery("SELECT o FROM " + Organisation.class.getName() + " o " + "GROUP BY o.name HAVING EXISTS (SELECT a FROM " + Account.class.getName() + " a WHERE a.username = o.name)").getResultList();
            assertNotNull(result);
            assertEquals(1, result.size());
            tx.rollback();
        } catch (Exception e) {
            LOG.error("Exception in query", e);
            fail("Exception executing query with HAVING subquery : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        clean(Person.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Account(org.datanucleus.samples.annotations.models.company.Account) EntityManager(javax.persistence.EntityManager) Organisation(org.datanucleus.samples.annotations.models.company.Organisation) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) Person(org.datanucleus.samples.annotations.models.company.Person) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Example 22 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project tests by datanucleus.

the class StoredProcedureTest method testExecuteOutputParam.

public void testExecuteOutputParam() {
    if (vendorID == null) {
        return;
    }
    if (storeMgr instanceof RDBMSStoreManager) {
        DatastoreAdapter dba = ((RDBMSStoreManager) storeMgr).getDatastoreAdapter();
        if (!dba.supportsOption(DatastoreAdapter.STORED_PROCEDURES)) {
            LOG.warn("Database doesnt support stored procedures so ignoring the test");
            return;
        }
    }
    String procName = "DN_PROC_OUTPUTPARAM";
    RDBMSStoreManager rdbmsMgr = (RDBMSStoreManager) storeMgr;
    ManagedConnection mc = rdbmsMgr.getConnectionManager().getConnection(-1);
    try {
        Connection conn = (Connection) mc.getConnection();
        Statement stmt = conn.createStatement();
        // Drop it first
        String dropStmt = "DROP PROCEDURE IF EXISTS " + procName;
        stmt.execute(dropStmt);
        // Create it
        String createStmt = "CREATE PROCEDURE " + procName + "(OUT PARAM1 INT) BEGIN " + "SELECT COUNT(*) INTO PARAM1 FROM JPA_AN_PERSON; END";
        stmt.execute(createStmt);
    } catch (SQLException sqle) {
        fail("Exception in drop-create of stored procedure : " + sqle.getMessage());
    } finally {
        mc.close();
    }
    try {
        JPAEntityManager em = (JPAEntityManager) getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Person p = new Person(101, "Fred", "Flintstone", "fred.flintstone@warnerbros.com");
            em.persist(p);
            tx.commit();
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            fail("Exception in test : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
        em = (JPAEntityManager) getEM();
        tx = em.getTransaction();
        try {
            tx.begin();
            // Get value to compare against
            Query q = em.createQuery("SELECT COUNT(p) FROM " + Person.class.getName() + " p");
            Long count = (Long) q.getSingleResult();
            // Execute stored proc and compare
            StoredProcedureQuery spq = em.createStoredProcedureQuery(procName);
            spq.registerStoredProcedureParameter("PARAM1", Integer.class, ParameterMode.OUT);
            boolean val = spq.execute();
            assertFalse("Flag for result set returned true but should have been false", val);
            Object paramVal = spq.getOutputParameterValue("PARAM1");
            assertEquals("Output parameter is incorrect", new Integer(count.intValue()), paramVal);
            tx.commit();
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            fail("Exception in test : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        // Cleanup data
        clean(Person.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) StoredProcedureQuery(javax.persistence.StoredProcedureQuery) Query(javax.persistence.Query) SQLException(java.sql.SQLException) Statement(java.sql.Statement) StoredProcedureQuery(javax.persistence.StoredProcedureQuery) Connection(java.sql.Connection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) JPAEntityManager(org.datanucleus.api.jpa.JPAEntityManager) SQLException(java.sql.SQLException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) Person(org.datanucleus.samples.annotations.models.company.Person)

Example 23 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project tests by datanucleus.

the class RDBMSAdapterFactoryTest method testGetNewDatastoreAdapter2.

/**
 * datastores are identified by product name
 * test unknown product with given adapterClassName
 */
public void testGetNewDatastoreAdapter2() {
    DatabaseMetaData md = new DatabaseMetaData();
    md.setProductName("unknown");
    md.setProductVersion("1");
    DatastoreAdapter adapter = factory.getNewDatastoreAdapter(clr, md, DerbyAdapter.class.getName(), pluginMgr);
    assertNotNull(adapter);
    assertEquals(DerbyAdapter.class.getName(), adapter.getClass().getName());
}
Also used : DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) DatabaseMetaData(org.datanucleus.store.rdbms.adapter.DatabaseMetaData)

Example 24 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project tests by datanucleus.

the class RDBMSAdapterFactoryTest method testGetNewDatastoreAdapter3.

/**
 * datastores are identified by product name
 * test Derby adapter with null adapterClassName
 */
public void testGetNewDatastoreAdapter3() {
    DatabaseMetaData md = new DatabaseMetaData();
    // test Derby adapter
    md.setProductName("Derby");
    md.setProductVersion("10");
    DatastoreAdapter adapter = factory.getNewDatastoreAdapter(clr, md, null, pluginMgr);
    assertNotNull(adapter);
    assertEquals(DerbyAdapter.class.getName(), adapter.getClass().getName());
}
Also used : DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) DatabaseMetaData(org.datanucleus.store.rdbms.adapter.DatabaseMetaData)

Example 25 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project tests by datanucleus.

the class JDOQLSubqueryTest method testAPISubqueryWithParameter.

/**
 * Test a simple subquery using API form and a parameter in the subquery.
 */
public void testAPISubqueryWithParameter() {
    if (storeMgr instanceof RDBMSStoreManager) {
        DatastoreAdapter dba = ((RDBMSStoreManager) storeMgr).getDatastoreAdapter();
        if (!dba.supportsOption(DatastoreAdapter.ACCESS_PARENTQUERY_IN_SUBQUERY_JOINED)) {
            // Access of outer query cols not supported by this datastore so dont test it
            LOG.warn("Database doesnt support use of parameters with subqueries so omitting the test");
            return;
        }
    }
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        // Persist Employees
        Employee emp1 = new Employee(101, "Fred", "Smith", "fred.smith@company.com", 100f, "10001");
        Employee emp2 = new Employee(102, "John", "Smith", "john.smith@company.com", 80f, "10002");
        Employee emp3 = new Employee(103, "Jim", "Smith", "jim.smith@company.com", 80f, "10003");
        Employee emp4 = new Employee(104, "Geoff", "Jones", "f2.s2@company.com", 200f, "10004");
        pm.makePersistent(emp1);
        pm.makePersistent(emp2);
        pm.makePersistent(emp3);
        pm.makePersistent(emp4);
        pm.flush();
        // Find the Employees earning more than the average salary of people with the same surname
        Query subquery = pm.newQuery(Employee.class);
        subquery.setResult("avg(this.salary)");
        subquery.setFilter("this.lastName == :lastNameParam");
        Query q = pm.newQuery(Employee.class, "salary > averageSalaryForFamily");
        q.addSubquery(subquery, "double averageSalaryForFamily", null, "this.lastName");
        // NOTE : HSQL <= 1.8 doesnt seem to support and conditions back to the outer query
        List results = (List) q.execute();
        assertNotNull("No results from query!", results);
        assertEquals("Number of Employees with more than average salary was wrong", 1, results.size());
        // Don't commit the data
        tx.rollback();
    } catch (JDOUserException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
Also used : Employee(org.jpox.samples.models.company.Employee) Transaction(javax.jdo.Transaction) Query(javax.jdo.Query) PersistenceManager(javax.jdo.PersistenceManager) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) List(java.util.List) JDOUserException(javax.jdo.JDOUserException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Aggregations

DatastoreAdapter (org.datanucleus.store.rdbms.adapter.DatastoreAdapter)46 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)24 SQLException (java.sql.SQLException)17 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)10 ResultSet (java.sql.ResultSet)8 List (java.util.List)8 Connection (java.sql.Connection)7 Statement (java.sql.Statement)7 EntityTransaction (javax.persistence.EntityTransaction)7 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)7 Person (org.datanucleus.samples.annotations.models.company.Person)7 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)7 PreparedStatement (java.sql.PreparedStatement)6 ArrayList (java.util.ArrayList)6 SQLController (org.datanucleus.store.rdbms.SQLController)6 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)6 StoredProcedureQuery (javax.persistence.StoredProcedureQuery)5 JPAEntityManager (org.datanucleus.api.jpa.JPAEntityManager)5 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)5 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)5