Repository: cayenne
Updated Branches:
  refs/heads/master 758b0fb0e -> f93c39ddd


CAY-2063 Implementation of procedure call fluent API.


Project: http://git-wip-us.apache.org/repos/asf/cayenne/repo
Commit: http://git-wip-us.apache.org/repos/asf/cayenne/commit/33844827
Tree: http://git-wip-us.apache.org/repos/asf/cayenne/tree/33844827
Diff: http://git-wip-us.apache.org/repos/asf/cayenne/diff/33844827

Branch: refs/heads/master
Commit: 338448275d3f9f4eb8aaad6420deabda2065b6ff
Parents: 758b0fb
Author: Dzmitry Kazimirchyk <[email protected]>
Authored: Fri Feb 5 19:02:33 2016 +0300
Committer: Dzmitry Kazimirchyk <[email protected]>
Committed: Thu Feb 25 13:31:55 2016 +0300

----------------------------------------------------------------------
 .../org/apache/cayenne/ProcedureResult.java     |  78 +++++
 .../org/apache/cayenne/query/ProcedureCall.java | 191 +++++++++++
 .../apache/cayenne/query/ProcedureCallIT.java   | 331 +++++++++++++++++++
 3 files changed, 600 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cayenne/blob/33844827/cayenne-server/src/main/java/org/apache/cayenne/ProcedureResult.java
----------------------------------------------------------------------
diff --git 
a/cayenne-server/src/main/java/org/apache/cayenne/ProcedureResult.java 
b/cayenne-server/src/main/java/org/apache/cayenne/ProcedureResult.java
new file mode 100644
index 0000000..a303e2f
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/ProcedureResult.java
@@ -0,0 +1,78 @@
+/*****************************************************************
+ *   Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ ****************************************************************/
+package org.apache.cayenne;
+
+import java.util.List;
+
+/**
+ * Result of procedure call.
+ *
+ * @since 4.0
+ */
+public class ProcedureResult<T> {
+
+    protected List<QueryResult> results;
+    protected Class<T> resultClass;
+
+    public ProcedureResult(List<QueryResult> results) {
+        this.results = results;
+    }
+
+    public ProcedureResult(List<QueryResult> results, Class<T> resultClass) {
+        this(results);
+        this.resultClass = resultClass;
+    }
+
+    public List<QueryResult> getResults() {
+        return results;
+    }
+
+    /**
+     * Returns first list found in the procedure execution result.
+     */
+    public List<T> getSelectResult() {
+        for (QueryResult result : results) {
+            if (result.isSelectResult()) {
+                return (List<T>) result.getSelectResult();
+            }
+        }
+
+        throw new CayenneRuntimeException("This result is not a select 
result.");
+    }
+
+    /**
+     * Returns first batch update count found in the procedure execution 
result.
+     */
+    public int[] getUpdateResult() {
+        for (QueryResult result : results) {
+            if (result.isBatchUpdate()) {
+                return result.getBatchUpdateResult();
+            }
+        }
+
+        throw new CayenneRuntimeException("This result is not an update 
result.");
+    }
+
+    /**
+     * Returns procedure OUT parameter by its name defined in the mapping file.
+     */
+    public Object getParam(String paramName) {
+        return ((DataRow) getSelectResult().get(0)).get(paramName);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/33844827/cayenne-server/src/main/java/org/apache/cayenne/query/ProcedureCall.java
----------------------------------------------------------------------
diff --git 
a/cayenne-server/src/main/java/org/apache/cayenne/query/ProcedureCall.java 
b/cayenne-server/src/main/java/org/apache/cayenne/query/ProcedureCall.java
new file mode 100644
index 0000000..29bcfae
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/query/ProcedureCall.java
@@ -0,0 +1,191 @@
+/*****************************************************************
+ *   Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ ****************************************************************/
+package org.apache.cayenne.query;
+
+
+import org.apache.cayenne.DataRow;
+import org.apache.cayenne.ObjectContext;
+import org.apache.cayenne.ProcedureResult;
+import org.apache.cayenne.QueryResponse;
+import org.apache.cayenne.access.jdbc.ColumnDescriptor;
+import org.apache.cayenne.map.EntityResolver;
+import org.apache.cayenne.util.QueryResultBuilder;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Fluent API for calling stored procedures.
+ *
+ * @since 4.0
+ */
+public class ProcedureCall<T> extends IndirectQuery {
+
+    /**
+     * Creates procedure call using name of stored procedure defined in the 
mapping file.
+     */
+    public static ProcedureCall query(String procedure) {
+        return new ProcedureCall(procedure);
+    }
+
+    /**
+     * Creates procedure call returning data rows using name of stored 
procedure defined in the mapping file.
+     */
+    public static ProcedureCall<DataRow> dataRowQuery(String procedure) {
+        ProcedureCall<DataRow> procedureCall = new ProcedureCall<>(procedure);
+        procedureCall.fetchingDataRows = true;
+        return procedureCall;
+    }
+
+    /**
+     * Creates procedure call using name of stored procedure defined in the 
mapping file and specifies data type
+     * of the objects it should return.
+     */
+    public static <T> ProcedureCall<T> query(String procedure, Class<T> 
resultClass) {
+        ProcedureCall<T> procedureCall = new ProcedureCall<>(procedure, 
resultClass);
+        procedureCall.fetchingDataRows = false;
+        return procedureCall;
+    }
+
+    protected String procedureName;
+    protected Class<T> resultClass;
+    protected Map<String, Object> params;
+    protected Integer fetchLimit;
+    protected Integer fetchOffset;
+    protected CapsStrategy capsStrategy;
+    protected Boolean fetchingDataRows;
+    protected ColumnDescriptor[] resultDescriptor;
+
+    public ProcedureCall(String procedureName) {
+        this.procedureName = procedureName;
+    }
+
+    public ProcedureCall(String procedureName, Class<T> resultClass) {
+        this.procedureName = procedureName;
+        this.resultClass = resultClass;
+    }
+
+    public ProcedureCall<T> params(Map<String, ?> parameters) {
+        if (this.params == null) {
+            this.params = new HashMap<>(parameters);
+        } else {
+            Map bareMap = parameters;
+            this.params.putAll(bareMap);
+        }
+
+        this.replacementQuery = null;
+
+        return this;
+    }
+
+    public ProcedureCall<T> param(String name, Object value) {
+        if (this.params == null) {
+            this.params = new HashMap<>();
+        }
+
+        this.params.put(name, value);
+
+        this.replacementQuery = null;
+
+        return this;
+    }
+
+    public ProcedureCall<T> limit(int fetchLimit) {
+        this.fetchLimit = fetchLimit;
+
+        return this;
+    }
+
+    public ProcedureCall<T> offset(int fetchOffset) {
+        this.fetchOffset = fetchOffset;
+
+        return this;
+    }
+
+    public ProcedureCall<T> capsStrategy(CapsStrategy capsStrategy) {
+        this.capsStrategy = capsStrategy;
+
+        return this;
+    }
+
+    public ProcedureCall<T> resultDescriptor(ColumnDescriptor[] 
resultDescriptor) {
+        this.resultDescriptor = resultDescriptor;
+
+        return this;
+    }
+
+    public ProcedureResult<T> call(ObjectContext context) {
+        QueryResponse response = context.performGenericQuery(this);
+
+        QueryResultBuilder builder = 
QueryResultBuilder.builder(response.size());
+
+        for (response.reset(); response.next(); ) {
+
+            if (response.isList()) {
+                builder.addSelectResult(response.currentList());
+            } else {
+                builder.addBatchUpdateResult(response.currentUpdateCount());
+            }
+        }
+
+        return new ProcedureResult<>(builder.build(), resultClass);
+    }
+
+    public List<T> select(ObjectContext context) {
+        return call(context).getSelectResult();
+    }
+
+    public int[] update(ObjectContext context) {
+        return call(context).getUpdateResult();
+    }
+
+    @Override
+    protected Query createReplacementQuery(EntityResolver resolver) {
+        ProcedureQuery procedureQuery = new ProcedureQuery(procedureName);
+
+        if (fetchingDataRows != null) {
+            procedureQuery.setFetchingDataRows(fetchingDataRows);
+        }
+
+        if (resultClass != null) {
+            procedureQuery.resultClass = this.resultClass;
+        }
+
+        if (fetchLimit != null) {
+            procedureQuery.setFetchLimit(fetchLimit);
+        }
+
+        if (fetchOffset != null) {
+            procedureQuery.setFetchOffset(fetchOffset);
+        }
+
+        if (resultDescriptor != null) {
+            procedureQuery.addResultDescriptor(resultDescriptor);
+        }
+
+        if (capsStrategy != null) {
+            procedureQuery.setColumnNamesCapitalization(capsStrategy);
+        }
+
+        procedureQuery.setParameters(params);
+
+        return procedureQuery;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/33844827/cayenne-server/src/test/java/org/apache/cayenne/query/ProcedureCallIT.java
----------------------------------------------------------------------
diff --git 
a/cayenne-server/src/test/java/org/apache/cayenne/query/ProcedureCallIT.java 
b/cayenne-server/src/test/java/org/apache/cayenne/query/ProcedureCallIT.java
new file mode 100644
index 0000000..99e6157
--- /dev/null
+++ b/cayenne-server/src/test/java/org/apache/cayenne/query/ProcedureCallIT.java
@@ -0,0 +1,331 @@
+/*****************************************************************
+ *   Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ ****************************************************************/
+package org.apache.cayenne.query;
+
+import org.apache.cayenne.DataRow;
+import org.apache.cayenne.ProcedureResult;
+import org.apache.cayenne.access.DataContext;
+import org.apache.cayenne.access.jdbc.ColumnDescriptor;
+import org.apache.cayenne.di.Inject;
+import org.apache.cayenne.log.JdbcEventLogger;
+import org.apache.cayenne.testdo.testmap.Artist;
+import org.apache.cayenne.testdo.testmap.Painting;
+import org.apache.cayenne.tx.BaseTransaction;
+import org.apache.cayenne.tx.ExternalTransaction;
+import org.apache.cayenne.unit.UnitDbAdapter;
+import org.apache.cayenne.unit.di.server.CayenneProjects;
+import org.apache.cayenne.unit.di.server.ServerCase;
+import org.apache.cayenne.unit.di.server.UseServerRuntime;
+import org.junit.Test;
+
+import java.math.BigDecimal;
+import java.sql.Types;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
+public class ProcedureCallIT extends ServerCase {
+
+    public static final String UPDATE_STORED_PROCEDURE = 
"cayenne_tst_upd_proc";
+    public static final String UPDATE_STORED_PROCEDURE_NOPARAM = 
"cayenne_tst_upd_proc2";
+    public static final String SELECT_STORED_PROCEDURE = 
"cayenne_tst_select_proc";
+    public static final String OUT_STORED_PROCEDURE = "cayenne_tst_out_proc";
+
+    @Inject
+    private DataContext context;
+
+    @Inject
+    private UnitDbAdapter accessStackAdapter;
+
+    @Inject
+    private JdbcEventLogger jdbcEventLogger;
+
+    @Test
+    public void testUpdate() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+
+        
runProcedureSelect(ProcedureCall.query(UPDATE_STORED_PROCEDURE).param("paintingPrice",
 3000));
+
+        // check that price have doubled
+        SelectQuery select = new SelectQuery<>(Artist.class);
+        select.addPrefetch("paintingArray");
+
+        List artists = context.performQuery(select);
+        assertEquals(1, artists.size());
+
+        Artist a = (Artist) artists.get(0);
+        Painting p = a.getPaintingArray().get(0);
+        assertEquals(2000, p.getEstimatedPrice().intValue());
+    }
+
+    @Test
+    public void testUpdateNoParam() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+
+        
runProcedureSelect(ProcedureCall.query(UPDATE_STORED_PROCEDURE_NOPARAM));
+
+        // check that price have doubled
+        SelectQuery select = new SelectQuery<>(Artist.class);
+        select.addPrefetch("paintingArray");
+
+        List<?> artists = context.performQuery(select);
+        assertEquals(1, artists.size());
+
+        Artist a = (Artist) artists.get(0);
+        Painting p = a.getPaintingArray().get(0);
+        assertEquals(2000, p.getEstimatedPrice().intValue());
+    }
+
+    @Test
+    public void testSelect() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+
+        List<?> artists = runProcedureSelect(
+                ProcedureCall.query(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .param("paintingPrice", 3000)
+        ).getSelectResult();
+
+        // check the results
+        assertNotNull("Null result from StoredProcedure.", artists);
+        assertEquals(1, artists.size());
+        DataRow artistRow = (DataRow) artists.get(0);
+        Artist a = context.objectFromDataRow(Artist.class, 
uppercaseConverter(artistRow));
+        Painting p = a.getPaintingArray().get(0);
+
+        // invalidate painting, it may have been updated in the proc
+        context.invalidateObjects(p);
+        assertEquals(2000, p.getEstimatedPrice().intValue());
+    }
+
+    @Test
+    public void testFetchLimit() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+        createArtist(2000.0);
+        createArtist(3000.0);
+
+        List<?> artists = runProcedureSelect(
+                ProcedureCall.query(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .param("paintingPrice", 3000)
+                .limit(2)
+        ).getSelectResult();
+
+        assertEquals(2, artists.size());
+    }
+
+    @Test
+    public void testFetchOffset() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+        createArtist(2000.0);
+        createArtist(3000.0);
+
+        List<?> artists = runProcedureSelect(
+                ProcedureCall.query(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .param("paintingPrice", 3000)
+                .offset(2)
+        ).getSelectResult();
+
+        assertEquals(1, artists.size());
+    }
+
+    @Test
+    public void testColumnNameCapitalization() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+
+        List<DataRow> artists = runProcedureSelect(
+                ProcedureCall.query(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .capsStrategy(CapsStrategy.LOWER)
+        ).getSelectResult();
+
+        List<DataRow> artists1 = 
runProcedureSelect(ProcedureCall.query(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .capsStrategy(CapsStrategy.UPPER)
+        ).getSelectResult();
+
+        assertTrue(artists.get(0).containsKey("date_of_birth"));
+        assertFalse(artists.get(0).containsKey("DATE_OF_BIRTH"));
+
+        assertFalse(artists1.get(0).containsKey("date_of_birth"));
+        assertTrue(artists1.get(0).containsKey("DATE_OF_BIRTH"));
+
+    }
+
+    @Test
+    public void testOutParams() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        ProcedureResult result = runProcedureSelect(
+                ProcedureCall.query(OUT_STORED_PROCEDURE)
+                .param("in_param", 20)
+        );
+
+        Number price = (Number) result.getParam("out_param");
+        assertEquals(40, price.intValue());
+    }
+
+    @Test
+    public void testSelectDataObject() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        if (!accessStackAdapter.canMakeObjectsOutOfProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1101.01);
+
+        List<Artist> artists = 
runProcedureSelect(ProcedureCall.query(SELECT_STORED_PROCEDURE, Artist.class)
+                .param("aName", "An Artist")
+        ).getSelectResult();
+
+        // check the results
+        assertNotNull("Null result from StoredProcedure.", artists);
+        assertEquals(1, artists.size());
+        Artist a = (Artist) artists.get(0);
+        Painting p = a.getPaintingArray().get(0);
+
+        // invalidate painting, it may have been updated in the proc
+        context.invalidateObjects(p);
+        assertEquals(1101.01, p.getEstimatedPrice().doubleValue(), 0.02);
+    }
+
+    @Test
+    public void testSelectWithRowDescriptor() throws Exception {
+        if (!accessStackAdapter.supportsStoredProcedures()) {
+            return;
+        }
+
+        // create an artist with painting in the database
+        createArtist(1000.0);
+
+        // TESTING THIS ***
+        // A.ARTIST_ID, A.DATE_OF_BIRTH, A.ARTIST_NAME
+        ColumnDescriptor[] columns = new ColumnDescriptor[3];
+
+        // read ID as Long, and everything else as default types
+        columns[0] = new ColumnDescriptor("ARTIST_ID", Types.BIGINT);
+        columns[1] = new ColumnDescriptor("ARTIST_NAME", Types.CHAR);
+        columns[2] = new ColumnDescriptor("DATE_OF_BIRTH", Types.DATE);
+
+        List<?> rows = 
runProcedureSelect(ProcedureCall.dataRowQuery(SELECT_STORED_PROCEDURE)
+                .param("aName", "An Artist")
+                .param("paintingPrice", 3000)
+                .resultDescriptor(columns)
+        ).getSelectResult();
+
+        // check the results
+        assertNotNull("Null result from StoredProcedure.", rows);
+        assertEquals(1, rows.size());
+        DataRow artistRow = (DataRow) rows.get(0);
+
+        assertEquals(3, artistRow.size());
+
+        artistRow = uppercaseConverter(artistRow);
+
+        Object id = artistRow.get("ARTIST_ID");
+        assertNotNull(id);
+        assertTrue("Expected Long, got: " + id.getClass().getName(), id 
instanceof Long);
+    }
+
+    protected <T> ProcedureResult<T> runProcedureSelect(ProcedureCall<T> q) 
throws Exception {
+        // Sybase blows whenever a transaction wraps a SP, so turn off
+        // transactions
+
+        // TODO: it is quite the opposite with PostgreSQL. If an SP returns an
+        // open refcursor, it actually expects a TX in progress, so while we
+        // don't have refcursor unit tests, this is something to keep in mind
+        // e.g.
+        // 
http://stackoverflow.com/questions/16921942/porting-apache-cayenne-from-oracle-to-postgresql
+
+        BaseTransaction t = new ExternalTransaction(jdbcEventLogger);
+        BaseTransaction.bindThreadTransaction(t);
+
+        try {
+            return q.call(context);
+        } finally {
+            BaseTransaction.bindThreadTransaction(null);
+            t.commit();
+        }
+    }
+
+    protected void createArtist(double paintingPrice) {
+        Artist a = context.newObject(Artist.class);
+        a.setArtistName("An Artist");
+
+        Painting p = context.newObject(Painting.class);
+        p.setPaintingTitle("A Painting");
+        // converting double to string prevents rounding weirdness...
+        p.setEstimatedPrice(new BigDecimal("" + paintingPrice));
+        a.addToPaintingArray(p);
+
+        context.commitChanges();
+    }
+
+    /**
+     * An ugly hack - converting row keys to uppercase ... Tracked via CAY-148.
+     */
+    protected DataRow uppercaseConverter(DataRow row) {
+        DataRow converted = new DataRow(row.size());
+
+        for (Map.Entry<String, Object> entry : row.entrySet()) {
+            converted.put(entry.getKey().toString().toUpperCase(), 
entry.getValue());
+        }
+
+        return converted;
+    }
+}

Reply via email to