Search in sources :

Example 1 with Wrapper

use of java.sql.Wrapper in project json-in-db by oracle.

the class JSONP method main.

public static void main(String[] args) throws Exception {
    JsonBuilderFactory factory = Json.createBuilderFactory(null);
    OracleRDBMSClient client = new OracleRDBMSClient();
    PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource();
    pool.setMaxStatements(50);
    pool.setURL(String.join("", args));
    pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
    try (Connection con = pool.getConnection()) {
        OracleDatabase db = client.getDatabase(con);
        OracleCollection col = db.openCollection("employees");
        JsonObject obj = factory.createObjectBuilder().add("name", "Clark").add("job", "Manager").add("salary", 80000).build();
        col.insert(db.createDocumentFrom(obj));
        System.out.println("Inserted employee Clark ");
        // retrieve employee Smith
        OracleDocument doc = col.find().filter("{\"name\":\"Smith\"}").getOne();
        obj = doc.getContentAs(JsonObject.class);
        System.out.println("Retrieved Smith from the database");
        System.out.println(obj.toString());
        // Values such as JsonObject, JsonArray, JsonParser, and JsonGenerator
        // produced from SODA can be mapped back and forth between the javax.json
        // counterparts using the facade pattern. Mapping back and forth does not
        // make a copy of the data but rather it provides an alternate view of the same
        // data.
        // Smith timestamp attribute is reported as a string when using the javax.json apis
        JsonValue value = obj.get("created");
        System.out.println(value + " is of type " + value.getValueType());
        // However, we can unwrap the object to get the true type
        OracleJsonObject oraObj = ((Wrapper) obj).unwrap(OracleJsonObject.class);
        OracleJsonValue oraValue = oraObj.get("created");
        System.out.println(oraValue + " is of type " + oraValue.getOracleJsonType());
        // Values can be rewraped at any time
        JsonObject obj2 = oraObj.wrap(JsonObject.class);
        System.out.println(obj.equals(obj2));
    }
}
Also used : OracleDatabase(oracle.soda.OracleDatabase) Wrapper(java.sql.Wrapper) OracleJsonValue(oracle.sql.json.OracleJsonValue) OracleDocument(oracle.soda.OracleDocument) JsonBuilderFactory(javax.json.JsonBuilderFactory) OracleRDBMSClient(oracle.soda.rdbms.OracleRDBMSClient) Connection(java.sql.Connection) OracleJsonValue(oracle.sql.json.OracleJsonValue) JsonValue(javax.json.JsonValue) JsonObject(javax.json.JsonObject) OracleJsonObject(oracle.sql.json.OracleJsonObject) PoolDataSource(oracle.ucp.jdbc.PoolDataSource) OracleCollection(oracle.soda.OracleCollection) OracleJsonObject(oracle.sql.json.OracleJsonObject)

Example 2 with Wrapper

use of java.sql.Wrapper in project aws-mysql-jdbc by awslabs.

the class ClientPreparedStatement method executePreparedBatchAsMultiStatement.

/**
 * Rewrites the already prepared statement into a multi-statement
 * query of 'statementsPerBatch' values and executes the entire batch
 * using this new statement.
 *
 * @param batchTimeout
 *            timeout for the batch execution
 * @return update counts in the same fashion as executeBatch()
 *
 * @throws SQLException
 *             if a database access error occurs or this method is called on a closed PreparedStatement
 */
protected long[] executePreparedBatchAsMultiStatement(int batchTimeout) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        // This is kind of an abuse, but it gets the job done
        if (this.batchedValuesClause == null) {
            this.batchedValuesClause = ((PreparedQuery<?>) this.query).getOriginalSql() + ";";
        }
        JdbcConnection locallyScopedConn = this.connection;
        boolean multiQueriesEnabled = locallyScopedConn.getPropertySet().getBooleanProperty(PropertyKey.allowMultiQueries).getValue();
        CancelQueryTask timeoutTask = null;
        try {
            clearWarnings();
            int numBatchedArgs = this.query.getBatchedArgs().size();
            if (this.retrieveGeneratedKeys) {
                this.batchedGeneratedKeys = new ArrayList<>(numBatchedArgs);
            }
            int numValuesPerBatch = ((PreparedQuery<?>) this.query).computeBatchSize(numBatchedArgs);
            if (numBatchedArgs < numValuesPerBatch) {
                numValuesPerBatch = numBatchedArgs;
            }
            java.sql.PreparedStatement batchedStatement = null;
            int batchedParamIndex = 1;
            int numberToExecuteAsMultiValue = 0;
            int batchCounter = 0;
            int updateCountCounter = 0;
            long[] updateCounts = new long[numBatchedArgs * getParseInfo().getNumberOfQueries()];
            SQLException sqlEx = null;
            try {
                if (!multiQueriesEnabled) {
                    ((NativeSession) locallyScopedConn.getSession()).enableMultiQueries();
                }
                batchedStatement = this.retrieveGeneratedKeys ? ((Wrapper) locallyScopedConn.prepareStatement(generateMultiStatementForBatch(numValuesPerBatch), RETURN_GENERATED_KEYS)).unwrap(java.sql.PreparedStatement.class) : ((Wrapper) locallyScopedConn.prepareStatement(generateMultiStatementForBatch(numValuesPerBatch))).unwrap(java.sql.PreparedStatement.class);
                timeoutTask = startQueryTimer((StatementImpl) batchedStatement, batchTimeout);
                numberToExecuteAsMultiValue = numBatchedArgs < numValuesPerBatch ? numBatchedArgs : numBatchedArgs / numValuesPerBatch;
                int numberArgsToExecute = numberToExecuteAsMultiValue * numValuesPerBatch;
                for (int i = 0; i < numberArgsToExecute; i++) {
                    if (i != 0 && i % numValuesPerBatch == 0) {
                        try {
                            batchedStatement.execute();
                        } catch (SQLException ex) {
                            sqlEx = handleExceptionForBatch(batchCounter, numValuesPerBatch, updateCounts, ex);
                        }
                        updateCountCounter = processMultiCountsAndKeys((StatementImpl) batchedStatement, updateCountCounter, updateCounts);
                        batchedStatement.clearParameters();
                        batchedParamIndex = 1;
                    }
                    batchedParamIndex = setOneBatchedParameterSet(batchedStatement, batchedParamIndex, this.query.getBatchedArgs().get(batchCounter++));
                }
                try {
                    batchedStatement.execute();
                } catch (SQLException ex) {
                    sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch, updateCounts, ex);
                }
                updateCountCounter = processMultiCountsAndKeys((StatementImpl) batchedStatement, updateCountCounter, updateCounts);
                batchedStatement.clearParameters();
                numValuesPerBatch = numBatchedArgs - batchCounter;
                if (timeoutTask != null) {
                    // we need to check the cancel state now because we loose if after the following batchedStatement.close()
                    ((JdbcPreparedStatement) batchedStatement).checkCancelTimeout();
                }
            } finally {
                if (batchedStatement != null) {
                    batchedStatement.close();
                    batchedStatement = null;
                }
            }
            try {
                if (numValuesPerBatch > 0) {
                    batchedStatement = this.retrieveGeneratedKeys ? locallyScopedConn.prepareStatement(generateMultiStatementForBatch(numValuesPerBatch), RETURN_GENERATED_KEYS) : locallyScopedConn.prepareStatement(generateMultiStatementForBatch(numValuesPerBatch));
                    if (timeoutTask != null) {
                        timeoutTask.setQueryToCancel((Query) batchedStatement);
                    }
                    batchedParamIndex = 1;
                    while (batchCounter < numBatchedArgs) {
                        batchedParamIndex = setOneBatchedParameterSet(batchedStatement, batchedParamIndex, this.query.getBatchedArgs().get(batchCounter++));
                    }
                    try {
                        batchedStatement.execute();
                    } catch (SQLException ex) {
                        sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch, updateCounts, ex);
                    }
                    updateCountCounter = processMultiCountsAndKeys((StatementImpl) batchedStatement, updateCountCounter, updateCounts);
                    batchedStatement.clearParameters();
                }
                if (timeoutTask != null) {
                    stopQueryTimer(timeoutTask, true, true);
                    timeoutTask = null;
                }
                if (sqlEx != null) {
                    throw SQLError.createBatchUpdateException(sqlEx, updateCounts, this.exceptionInterceptor);
                }
                return updateCounts;
            } finally {
                if (batchedStatement != null) {
                    batchedStatement.close();
                }
            }
        } finally {
            stopQueryTimer(timeoutTask, false, false);
            resetCancelledState();
            if (!multiQueriesEnabled) {
                ((NativeSession) locallyScopedConn.getSession()).disableMultiQueries();
            }
            clearBatch();
        }
    }
}
Also used : Wrapper(java.sql.Wrapper) SQLException(java.sql.SQLException) ClientPreparedQuery(com.mysql.cj.ClientPreparedQuery) PreparedQuery(com.mysql.cj.PreparedQuery) CancelQueryTask(com.mysql.cj.CancelQueryTask) NativeSession(com.mysql.cj.NativeSession)

Example 3 with Wrapper

use of java.sql.Wrapper in project datasource-proxy by ttddyy.

the class JdbcLifecycleEventExecutionListenerTest method methodInvocation.

@Test
public void methodInvocation() {
    // TODO: parameterized test
    List<Class<? extends Wrapper>> proxyClasses = Arrays.asList(DataSource.class, Connection.class, ResultSet.class, Statement.class, PreparedStatement.class, CallableStatement.class);
    for (Class<? extends Wrapper> proxyClass : proxyClasses) {
        Wrapper mock = mock(proxyClass);
        Method[] methods = proxyClass.getMethods();
        for (Method method : methods) {
            String expectedBeforeName = "before" + capitalize(method.getName());
            String expectedAfterName = "after" + capitalize(method.getName());
            // create a listener
            List<String> invokedMethodNames = new ArrayList<String>();
            List<List<Object>> invokedMethodArgs = new ArrayList<List<Object>>();
            JdbcLifecycleEventListener proxyListener = createProxyListener(invokedMethodNames, invokedMethodArgs);
            JdbcLifecycleEventExecutionListener listener = new JdbcLifecycleEventExecutionListener(proxyListener);
            MethodExecutionContext methodExecContext = new MethodExecutionContext();
            methodExecContext.setMethod(method);
            methodExecContext.setTarget(mock);
            listener.beforeMethod(methodExecContext);
            String description = "method=" + method.getName();
            assertThat(invokedMethodNames).describedAs(description).hasSize(2).containsExactly("beforeMethod", expectedBeforeName);
            assertThat(invokedMethodArgs).describedAs(description).hasSize(2);
            assertThat(invokedMethodArgs.get(0)).describedAs(description).hasSize(1).containsExactly(methodExecContext);
            assertThat(invokedMethodArgs.get(1)).describedAs(description).hasSize(1).containsExactly(methodExecContext);
            invokedMethodNames.clear();
            invokedMethodArgs.clear();
            listener.afterMethod(methodExecContext);
            assertThat(invokedMethodNames).hasSize(2).containsExactly(expectedAfterName, "afterMethod");
            assertThat(invokedMethodArgs).hasSize(2);
            assertThat(invokedMethodArgs.get(0)).hasSize(1).containsExactly(methodExecContext);
            assertThat(invokedMethodArgs.get(1)).hasSize(1).containsExactly(methodExecContext);
        }
    }
}
Also used : Wrapper(java.sql.Wrapper) MethodExecutionContext(net.ttddyy.dsproxy.listener.MethodExecutionContext) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.jupiter.api.Test)

Aggregations

Wrapper (java.sql.Wrapper)3 CancelQueryTask (com.mysql.cj.CancelQueryTask)1 ClientPreparedQuery (com.mysql.cj.ClientPreparedQuery)1 NativeSession (com.mysql.cj.NativeSession)1 PreparedQuery (com.mysql.cj.PreparedQuery)1 Method (java.lang.reflect.Method)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 JsonBuilderFactory (javax.json.JsonBuilderFactory)1 JsonObject (javax.json.JsonObject)1 JsonValue (javax.json.JsonValue)1 MethodExecutionContext (net.ttddyy.dsproxy.listener.MethodExecutionContext)1 OracleCollection (oracle.soda.OracleCollection)1 OracleDatabase (oracle.soda.OracleDatabase)1 OracleDocument (oracle.soda.OracleDocument)1 OracleRDBMSClient (oracle.soda.rdbms.OracleRDBMSClient)1 OracleJsonObject (oracle.sql.json.OracleJsonObject)1 OracleJsonValue (oracle.sql.json.OracleJsonValue)1