[#2202] Add Mock JDBC objects for unit testing with jOOQ

This commit is contained in:
Lukas Eder 2013-02-15 20:49:03 +01:00
parent 2b3fb59dbe
commit e3ec046490
10 changed files with 3675 additions and 1352 deletions

View File

@ -51,6 +51,7 @@ import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@ -60,12 +61,15 @@ import java.util.UUID;
import javax.swing.UIManager;
import junit.framework.Assert;
import org.jooq.ArrayRecord;
import org.jooq.DAO;
import org.jooq.DataType;
import org.jooq.ExecuteType;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Query;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.Record2;
@ -132,6 +136,10 @@ import org.jooq.test._.testcases.ValuesConstructorTests;
import org.jooq.tools.JooqLogger;
import org.jooq.tools.StopWatch;
import org.jooq.tools.StringUtils;
import org.jooq.tools.jdbc.MockConnection;
import org.jooq.tools.jdbc.MockDataProvider;
import org.jooq.tools.jdbc.MockExecuteContext;
import org.jooq.tools.jdbc.MockResult;
import org.jooq.tools.reflect.ReflectException;
import org.jooq.types.UByte;
import org.jooq.types.UInteger;
@ -452,6 +460,68 @@ public abstract class jOOQAbstractTest<
if (!connectionInitialised) {
connectionInitialised = true;
connection = getConnection0(null, null);
final Connection c = connection;
// Reactivate this, to enable mock connections
if (false)
connection = new MockConnection(new MockDataProvider() {
@Override
public MockResult[] execute(MockExecuteContext context) throws SQLException {
Executor executor = new Executor(c, getDialect());
if (context.isSingleBatch()) {
Query query = executor.query(context.getSQL(), new Object[context.getBatchBindings()[0].length]);
int[] result =
executor.batch(query)
.bind(context.getBatchBindings())
.execute();
MockResult[] r = new MockResult[result.length];
for (int i = 0; i < r.length; i++) {
r[i] = new MockResult(result[i], null);
}
return r;
}
else if (context.isMultiBatch()) {
List<Query> queries = new ArrayList<Query>();
for (String sql : context.getBatchSQL()) {
queries.add(executor.query(sql));
}
int[] result =
executor.batch(queries)
.execute();
MockResult[] r = new MockResult[result.length];
for (int i = 0; i < r.length; i++) {
r[i] = new MockResult(result[i], null);
}
return r;
}
else if (context.getSQL().toLowerCase().matches("(?s:\\W*(select|with).*)")) {
List<Result<Record>> result = executor.fetchMany(context.getSQL(), context.getBindings());
MockResult[] r = new MockResult[result.size()];
for (int i = 0; i < result.size(); i++) {
r[i] = new MockResult(result.get(i).size(), result.get(i));
}
return r;
}
else {
int result = executor.execute(context.getSQL(), context.getBindings());
MockResult[] r = new MockResult[1];
r[0] = new MockResult(result, null);
return r;
}
}
});
if (RUN_CONSOLE_IN_PROCESS) {
try {

View File

@ -73,6 +73,7 @@ import org.jooq.Table;
import org.jooq.exception.InvalidResultException;
import org.jooq.tools.Convert;
import org.jooq.tools.StringUtils;
import org.jooq.tools.jdbc.MockResultSet;
import org.jooq.tools.json.JSONObject;
import org.w3c.dom.Document;
@ -1020,7 +1021,7 @@ class ResultImpl<R extends Record> implements Result<R>, AttachableInternal {
@Override
public final ResultSet intoResultSet() {
return new ResultSetImpl(this);
return new MockResultSet(this);
}
@Override

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,406 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.tools.jdbc;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
/**
* A mock connection.
* <p>
* Mock connections can be used to supply jOOQ with unit test data, avoiding the
* round-trip of using an actual in-memory test database, such as Derby, H2 or
* HSQLDB. A usage example:
* <p>
* <code><pre>
* MockDataProvider provider = new MockDataProvider() {
* public MockResult[] execute(MockExecuteContext context) throws SQLException {
* Result&lt;MyTableRecord> result = executor.newResult(MY_TABLE);
* result.add(executor.newRecord(MY_TABLE));
*
* return new MockResult[] {
* new MockResult(1, result);
* };
* }
* };
* Connection connection = new MockConnection(provider);
* Executor create = new Executor(connection, dialect);
* assertEquals(1, create.selectOne().fetch().size());
* <p>
* While this <code>MockConnection</code> can be used independently of jOOQ, it
* has been optimised for usage with jOOQ. JDBC features that are not used by
* jOOQ (e.g. procedure bind value access by parameter name) are not supported
* in this mock framework
*
* @author Lukas Eder
*/
public class MockConnection extends JDBC41Connection implements Connection {
private final MockDataProvider data;
private boolean isClosed;
public MockConnection(MockDataProvider data) {
this.data = data;
}
// -------------------------------------------------------------------------
// XXX: Utilities
// -------------------------------------------------------------------------
private void checkNotClosed() throws SQLException {
if (isClosed) {
throw new SQLException("Connection is already closed");
}
}
// -------------------------------------------------------------------------
// XXX: Creating statements
// -------------------------------------------------------------------------
@Override
public Statement createStatement() throws SQLException {
return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return createStatement(resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data);
result.resultSetType = resultSetType;
result.resultSetConcurrency = resultSetConcurrency;
result.resultSetHoldability = resultSetHoldability;
return result;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data, sql);
result.resultSetType = resultSetType;
result.resultSetConcurrency = resultSetConcurrency;
result.resultSetHoldability = resultSetHoldability;
return result;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data, sql);
result.autoGeneratedKeys = autoGeneratedKeys;
return result;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data, sql);
result.autoGeneratedKeys = Statement.RETURN_GENERATED_KEYS;
result.columnIndexes = columnIndexes;
return result;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data, sql);
result.autoGeneratedKeys = Statement.RETURN_GENERATED_KEYS;
result.columnNames = columnNames;
return result;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareCall(sql, resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
checkNotClosed();
MockStatement result = new MockStatement(this, data, sql);
result.resultSetType = resultSetType;
result.resultSetConcurrency = resultSetConcurrency;
result.resultSetHoldability = resultSetHoldability;
return result;
}
// -------------------------------------------------------------------------
// XXX: Ignored operations
// -------------------------------------------------------------------------
@Override
public void commit() throws SQLException {
checkNotClosed();
}
@Override
public void rollback() throws SQLException {
checkNotClosed();
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
checkNotClosed();
}
@Override
public void close() throws SQLException {
isClosed = true;
}
@Override
public Savepoint setSavepoint() throws SQLException {
checkNotClosed();
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
checkNotClosed();
return null;
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkNotClosed();
}
@Override
public boolean isClosed() throws SQLException {
return isClosed;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
checkNotClosed();
}
@Override
public boolean getAutoCommit() throws SQLException {
checkNotClosed();
return false;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
checkNotClosed();
}
@Override
public boolean isReadOnly() throws SQLException {
checkNotClosed();
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
checkNotClosed();}
@Override
public String getCatalog() throws SQLException {
checkNotClosed();
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException {
checkNotClosed();
return null;
}
@Override
public void clearWarnings() throws SQLException {
checkNotClosed();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
checkNotClosed();
}
@Override
public int getTransactionIsolation() throws SQLException {
checkNotClosed();
return 0;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
checkNotClosed();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
checkNotClosed();
return null;
}
@Override
public void setHoldability(int holdability) throws SQLException {
checkNotClosed();
}
@Override
public int getHoldability() throws SQLException {
checkNotClosed();
return 0;
}
@Override
public boolean isValid(int timeout) throws SQLException {
checkNotClosed();
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
checkNotClosed();
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
checkNotClosed();
return null;
}
// -------------------------------------------------------------------------
// XXX: Unsupported operations
// -------------------------------------------------------------------------
@Override
public DatabaseMetaData getMetaData() throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public String nativeSQL(String sql) throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public Clob createClob() throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public Blob createBlob() throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public NClob createNClob() throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public SQLXML createSQLXML() throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
throw new SQLFeatureNotSupportedException("Unsupported Operation");
}
}

View File

@ -0,0 +1,140 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.tools.jdbc;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.jooq.Query;
import org.jooq.ResultQuery;
import org.jooq.impl.Executor;
/**
* A data provider for mock query executions.
* <p>
* Supply this data provider to your {@link MockConnection} in order to globally
* provide data for SQL statements.
* <p>
* See {@link #execute(MockExecuteContext)} for details.
*
* @author Lukas Eder
* @see MockConnection
*/
public interface MockDataProvider {
/**
* Execution callback for a JDBC query execution.
* <p>
* This callback will be called by {@link MockStatement} upon the various
* statement execution methods. These include:
* <p>
* <ul>
* <li> {@link Statement#execute(String)}</li>
* <li> {@link Statement#execute(String, int)}</li>
* <li> {@link Statement#execute(String, int[])}</li>
* <li> {@link Statement#execute(String, String[])}</li>
* <li> {@link Statement#executeBatch()}</li>
* <li> {@link Statement#executeQuery(String)}</li>
* <li> {@link Statement#executeUpdate(String)}</li>
* <li> {@link Statement#executeUpdate(String, int)}</li>
* <li> {@link Statement#executeUpdate(String, int[])}</li>
* <li> {@link Statement#executeUpdate(String, String[])}</li>
* <li> {@link PreparedStatement#execute()}</li>
* <li> {@link PreparedStatement#executeQuery()}</li>
* <li> {@link PreparedStatement#executeUpdate()}</li>
* </ul>
* <p>
* The various execution modes are unified into this simple method.
* Implementations should adhere to this contract:
* <p>
* <ul>
* <li><code>MockStatement</code> does not distinguish between "static" and
* "prepared" statements. However, a non-empty
* {@link MockExecuteContext#getBindings()} is a strong indicator for a
* {@link PreparedStatement}.</li>
* <li><code>MockStatement</code> does not distinguish between "batch" and
* "single" statements. However...
* <ul>
* <li>A {@link MockExecuteContext#getBatchSQL()} with more than one SQL
* string is a strong indicator for a "multi-batch statement", as understood
* by jOOQ's {@link Executor#batch(Query...)}.</li>
* <li>A {@link MockExecuteContext#getBatchBindings()} with more than one
* bind variable array is a strong indicator for a "single-batch statement",
* as understood by jOOQ's {@link Executor#batch(Query)}.</li>
* </ul>
* </li>
* <li>It is recommended to return as many <code>MockResult</code> objects
* as batch executions. In other words, you should guarantee that:
* <p>
* <code><pre>
* int multiSize = context.getBatchSQL().length;
* int singleSize = context.getBatchBindings().length;
* assertEquals(result.length, Math.max(multiSize, singleSize))
* </pre></code>
* <p>
* This holds true also for non-batch executions (where both sizes are equal
* to <code>1</code>)</li>
* <li>You may also return more than one result for non-batch executions.
* This is useful for procedure calls with several result sets.
* <ul>
* <li>In JDBC, such additional result sets can be obtained with
* {@link Statement#getMoreResults()}.</li>
* <li>In jOOQ, such additional result sets can be obtained with
* {@link ResultQuery#fetchMany()}</li>
* </ul>
* </li>
* <li>If generated keys ({@link Statement#RETURN_GENERATED_KEYS}) are
* requested from this execution, you can also add {@link MockResult#data}
* to your result, in addition to the affected {@link MockResult#rows}. The
* relevant flag is passed from <code>MockStatement</code> to any of these
* properties:
* <ul>
* <li> {@link MockExecuteContext#getAutoGeneratedKeys()}</li>
* <li> {@link MockExecuteContext#getColumnIndexes()}</li>
* <li> {@link MockExecuteContext#getColumnNames()}</li>
* </ul>
* </li>
* </ul>
*
* @param context The execution context.
* @return The execution results. This should be non-null and non-empty, as
* every execution is expected to return at least one result.
* @throws SQLException A <code>SQLException</code> that is passed through
* to jOOQ.
*/
MockResult[] execute(MockExecuteContext context) throws SQLException;
}

View File

@ -0,0 +1,214 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.tools.jdbc;
import java.sql.Statement;
import org.jooq.Query;
import org.jooq.impl.Executor;
/**
* A mock execution context.
* <p>
* This context is passed to
* {@link MockDataProvider#execute(MockExecuteContext)}, as a context object
* containing all relevant information about a given query execution.
*
* @author Lukas Eder
* @see MockDataProvider
*/
public class MockExecuteContext {
private final String[] sql;
private final Object[][] bindings;
private final int autoGeneratedKeys;
private final int[] columnIndexes;
private final String[] columnNames;
/**
* Create a new mock execution context.
*
* @param sql The SQL statement(s)
* @param bindings The bind variable(s)
*/
public MockExecuteContext(String[] sql, Object[][] bindings) {
this(sql, bindings, Statement.NO_GENERATED_KEYS, null, null);
}
/**
* Create a new mock execution context.
*
* @param sql The SQL statement(s)
* @param bindings The bind variable(s)
* @param autoGeneratedKeys The corresponding value from
* <code>MockStatement</code>
*/
public MockExecuteContext(String[] sql, Object[][] bindings, int autoGeneratedKeys) {
this(sql, bindings, autoGeneratedKeys, null, null);
}
/**
* Create a new mock execution context.
* <p>
*
* @param sql The SQL statement(s)
* @param bindings The bind variable(s)
* @param columnIndexes The corresponding value from
* <code>MockStatement</code>
*/
public MockExecuteContext(String[] sql, Object[][] bindings, int[] columnIndexes) {
this(sql, bindings, Statement.RETURN_GENERATED_KEYS, columnIndexes, null);
}
/**
* Create a new mock execution context.
* <p>
*
* @param sql The SQL statement(s)
* @param bindings The bind variable(s)
* @param columnNames The corresponding value from
* <code>MockStatement</code>
*/
public MockExecuteContext(String[] sql, Object[][] bindings, String[] columnNames) {
this(sql, bindings, Statement.RETURN_GENERATED_KEYS, null, columnNames);
}
MockExecuteContext(String[] sql, Object[][] bindings, int autoGeneratedKeys, int[] columnIndexes,
String[] columnNames) {
this.sql = sql;
this.bindings = bindings;
this.autoGeneratedKeys = autoGeneratedKeys;
this.columnIndexes = columnIndexes;
this.columnNames = columnNames;
}
/**
* Whether this execution context is a from a batch statement.
*
* @return Whether this execution context is a from a batch statement.
*/
public boolean isBatch() {
return isSingleBatch() || isMultiBatch();
}
/**
* Whether this execution context is from a "single batch" statement.
*
* @return Whether this execution context is from a "single batch"
* statement.
* @see Executor#batch(Query)
*/
public boolean isSingleBatch() {
return bindings.length > 1;
}
/**
* Whether this execution context is from a "multi batch" statement.
*
* @return Whether this execution context is from a "multi batch" statement.
* @see Executor#batch(Query...)
*/
public boolean isMultiBatch() {
return sql.length > 1;
}
/**
* Get all batch SQL statements of a "multi batch" statement.
*
* @return All batch SQL statements of a "multi batch" statement, or an
* array of length <code>1</code> with the single statement.
*/
public String[] getBatchSQL() {
return sql;
}
/**
* Get all bind variables of a "single batch" statement.
*
* @return All bind variables of a "single batch" statment, or an array of
* length <code>1</code> with the bind variables of a single
* statement.
*/
public Object[][] getBatchBindings() {
return bindings;
}
/**
* Get the single (or first "multi batch") SQL statement.
*
* @return The single (or first "multi batch") SQL statement.
*/
public String getSQL() {
return sql[0];
}
/**
* Get the single (or first "single batch") set of bind variables.
*
* @return The single (or first "single batch") set of bind variables.
*/
public Object[] getBindings() {
return bindings[0];
}
/**
* The corresponding value from <code>MockStatement</code>.
*
* @return The corresponding value from <code>MockStatement</code>.
*/
public int getAutoGeneratedKeys() {
return autoGeneratedKeys;
}
/**
* The corresponding value from <code>MockStatement</code>.
*
* @return The corresponding value from <code>MockStatement</code>.
*/
public int[] getColumnIndexes() {
return columnIndexes;
}
/**
* The corresponding value from <code>MockStatement</code>.
*
* @return The corresponding value from <code>MockStatement</code>.
*/
public String[] getColumnNames() {
return columnNames;
}
}

View File

@ -0,0 +1,93 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.tools.jdbc;
import java.sql.Statement;
import org.jooq.Result;
/**
* A mock result.
* <p>
* This type is used to wrap unified results of DDL and DML query executions.
* JDBC execution results can be summarised to two properties:
* <ul>
* <li> {@link Statement#getUpdateCount()}: The number of affected rows</li>
* <li> {@link Statement#getResultSet()}: The result set</li>
* </ul>
* <p>
* See {@link MockDataProvider#execute(MockExecuteContext)} for more details
*
* @author Lukas Eder
* @see MockDataProvider
*/
public class MockResult {
/**
* The number of affected rows for this execution result.
* <p>
* This number corresponds to the value of
* {@link Statement#getUpdateCount()}. The following values are possible:
* <ul>
* <li>Positive numbers: the number of affected rows by a given query
* execution</li>
* <li>0: no rows were affected by a given query execution</li>
* <li>-1: the row count is not applicable</li>
* </ul>
*/
public final int rows;
/**
* The result data associated with this execution result.
* <p>
* This object describes the result data (including meta data). If the given
* query execution did not provide any results, this may be
* <code>null</code>. Note, that this can also be used to provide a result
* for {@link Statement#getGeneratedKeys()}
*/
public final Result<?> data;
/**
* Create a new <code>MockResult</code>.
*
* @param rows The number of affected rows
* @param data The result data
*/
public MockResult(int rows, Result<?> data) {
this.rows = rows;
this.data = data;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,271 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.tools.jdbc;
import java.io.Serializable;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.jooq.AttachableInternal;
import org.jooq.Configuration;
import org.jooq.Field;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.impl.Executor;
import org.jooq.types.UNumber;
/**
* A mock result set meta data object.
*
* @author Lukas Eder
* @see MockConnection
*/
public class MockResultSetMetaData implements ResultSetMetaData, Serializable {
/**
* Generated UID
*/
private static final long serialVersionUID = -6859273409631070434L;
/**
* The result set reference.
*/
private final MockResultSet rs;
/**
* Create a new mock result set meta data object
*/
public MockResultSetMetaData(MockResultSet rs) {
this.rs = rs;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public int getColumnCount() throws SQLException {
rs.checkNotClosed();
return rs.result.fieldsRow().size();
}
@Override
public boolean isAutoIncrement(int column) throws SQLException {
rs.checkNotClosed();
return false;
}
@Override
public boolean isCaseSensitive(int column) throws SQLException {
rs.checkNotClosed();
return true;
}
@Override
public boolean isSearchable(int column) throws SQLException {
rs.checkNotClosed();
return true;
}
@Override
public boolean isCurrency(int column) throws SQLException {
rs.checkNotClosed();
return false;
}
@Override
public int isNullable(int column) throws SQLException {
rs.checkNotClosed();
// TODO: Check generated JSR-303 or JPA annotations for nullability
return ResultSetMetaData.columnNullableUnknown;
}
@Override
public boolean isSigned(int column) throws SQLException {
rs.checkNotClosed();
Field<?> field = rs.result.field(column - 1);
Class<?> type = field.getType();
return Number.class.isAssignableFrom(type) && !UNumber.class.isAssignableFrom(type);
}
@Override
public int getColumnDisplaySize(int column) throws SQLException {
return 0;
}
@Override
public String getColumnLabel(int column) throws SQLException {
return getColumnName(column);
}
@Override
public String getColumnName(int column) throws SQLException {
rs.checkNotClosed();
return rs.result.field(column - 1).getName();
}
@Override
public String getSchemaName(int column) throws SQLException {
rs.checkNotClosed();
Field<?> field = rs.result.field(column - 1);
if (field instanceof TableField) {
Table<?> table = ((TableField<?, ?>) field).getTable();
if (table != null) {
Schema schema = table.getSchema();
if (schema != null) {
Configuration configuration = ((AttachableInternal) rs.result).getConfiguration();
Schema mapped = null;
if (configuration != null) {
mapped = new Executor(configuration).map(schema);
}
if (mapped != null) {
return mapped.getName();
}
else {
return schema.getName();
}
}
}
}
// By default, no schema is available
return "";
}
@Override
public int getPrecision(int column) throws SQLException {
rs.checkNotClosed();
// TODO: Check generated JSR-303 or JPA annotations for precision
return 0;
}
@Override
public int getScale(int column) throws SQLException {
rs.checkNotClosed();
// TODO: Check generated JSR-303 or JPA annotations for scale
return 0;
}
@Override
public String getTableName(int column) throws SQLException {
rs.checkNotClosed();
Field<?> field = rs.result.field(column - 1);
if (field instanceof TableField) {
Table<?> table = ((TableField<?, ?>) field).getTable();
if (table != null) {
return table.getName();
}
}
// By default, no table is available
return "";
}
@Override
public String getCatalogName(int column) throws SQLException {
rs.checkNotClosed();
// jOOQ doesn't support catalogs yet
return "";
}
@Override
public int getColumnType(int column) throws SQLException {
rs.checkNotClosed();
return rs.result.field(column - 1).getDataType().getSQLType();
}
@Override
public String getColumnTypeName(int column) throws SQLException {
rs.checkNotClosed();
return rs.result.field(column - 1).getDataType().getTypeName();
}
@Override
public boolean isReadOnly(int column) throws SQLException {
rs.checkNotClosed();
return true;
}
@Override
public boolean isWritable(int column) throws SQLException {
rs.checkNotClosed();
return false;
}
@Override
public boolean isDefinitelyWritable(int column) throws SQLException {
rs.checkNotClosed();
return false;
}
@Override
public String getColumnClassName(int column) throws SQLException {
rs.checkNotClosed();
return rs.result.field(column - 1).getType().getName();
}
}

File diff suppressed because it is too large Load Diff