Search in sources :

Example 16 with XaSqlConnection

use of cn.mycat.vertx.xa.XaSqlConnection in project Mycat2 by MyCATApache.

the class VertxExecuter method simpleUpdate.

public static Future<long[]> simpleUpdate(MycatDataContext context, boolean insert, boolean xa, boolean onlyFirstSum, Iterable<EachSQL> eachSQLs) {
    Function<Void, Future<long[]>> function = new Function<Void, Future<long[]>>() {

        final long[] sum = new long[] { 0, 0 };

        @Override
        public Future<long[]> apply(Void unused) {
            XaSqlConnection transactionSession = (XaSqlConnection) context.getTransactionSession();
            ConcurrentHashMap<String, Future<NewMycatConnection>> map = new ConcurrentHashMap<>();
            final AtomicBoolean firstRequest = new AtomicBoolean(true);
            for (EachSQL eachSQL : eachSQLs) {
                String target = context.resolveDatasourceTargetName(eachSQL.getTarget(), true);
                String sql = eachSQL.getSql();
                List<Object> params = eachSQL.getParams();
                Future<NewMycatConnection> connectionFuture = map.computeIfAbsent(target, s -> transactionSession.getConnection(target));
                Future<long[]> future;
                if (insert) {
                    future = VertxExecuter.runInsert(connectionFuture, sql, params);
                } else {
                    future = VertxExecuter.runUpdate(connectionFuture, sql, params);
                }
                Future<NewMycatConnection> returnConnectionFuture = future.map((Function<long[], Void>) longs2 -> {
                    if (!onlyFirstSum) {
                        synchronized (sum) {
                            sum[0] = sum[0] + longs2[0];
                            sum[1] = Math.max(sum[1], longs2[1]);
                        }
                    } else if (firstRequest.compareAndSet(true, false)) {
                        sum[0] = longs2[0];
                        sum[1] = longs2[1];
                    }
                    return null;
                }).mapEmpty().flatMap(c -> Future.succeededFuture(connectionFuture.result()));
                map.put(target, returnConnectionFuture);
            }
            List<Future<NewMycatConnection>> futures = new ArrayList<>(map.values());
            return CompositeFuture.join((List) futures).map(sum);
        }
    };
    if (xa) {
        return wrapAsXaTransaction(context, function);
    } else {
        return Future.succeededFuture().flatMap(o -> function.apply(null));
    }
}
Also used : QueryPlanner(io.mycat.calcite.spm.QueryPlanner) io.mycat(io.mycat) MycatRowMetaData(io.mycat.beans.mycat.MycatRowMetaData) LoggerFactory(org.slf4j.LoggerFactory) SQLName(com.alibaba.druid.sql.ast.SQLName) Tuple(io.vertx.sqlclient.Tuple) MySQLColumnDef(io.mycat.api.collector.MySQLColumnDef) NewMycatConnection(io.mycat.newquery.NewMycatConnection) SQLReplaceable(com.alibaba.druid.sql.ast.SQLReplaceable) MycatView(io.mycat.calcite.logical.MycatView) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MysqlCollector(io.mycat.newquery.MysqlCollector) SQLExpr(com.alibaba.druid.sql.ast.SQLExpr) com.alibaba.druid.sql.ast.expr(com.alibaba.druid.sql.ast.expr) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) lombok(lombok) ArrayBindable(org.apache.calcite.runtime.ArrayBindable) NormalTable(io.mycat.calcite.table.NormalTable) MysqlObjectArrayRow(io.mycat.api.collector.MysqlObjectArrayRow) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) DbType(com.alibaba.druid.DbType) DrdsRunnerHelper(io.mycat.calcite.DrdsRunnerHelper) NotNull(org.jetbrains.annotations.NotNull) ShardingTable(io.mycat.calcite.table.ShardingTable) Iterables(com.google.common.collect.Iterables) java.util(java.util) MySQLClient(io.vertx.mysqlclient.MySQLClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Function(java.util.function.Function) Supplier(java.util.function.Supplier) CompositeFuture(io.vertx.core.CompositeFuture) MySqlASTVisitorAdapter(com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter) ImmutableList(com.google.common.collect.ImmutableList) SqlConnection(io.vertx.sqlclient.SqlConnection) Process(io.mycat.Process) Observable(io.reactivex.rxjava3.core.Observable) RowBaseIterator(io.mycat.api.collector.RowBaseIterator) RowSet(io.vertx.sqlclient.RowSet) GlobalTable(io.mycat.calcite.table.GlobalTable) RelDataType(org.apache.calcite.rel.type.RelDataType) SQLUtils(com.alibaba.druid.sql.SQLUtils) Logger(org.slf4j.Logger) ExecutorProvider(io.mycat.calcite.ExecutorProvider) Enumerable(org.apache.calcite.linq4j.Enumerable) TimeUnit(java.util.concurrent.TimeUnit) MycatSQLEvalVisitorUtils(com.alibaba.druid.sql.visitor.MycatSQLEvalVisitorUtils) MysqlPayloadObject(io.mycat.api.collector.MysqlPayloadObject) CodeExecuterContext(io.mycat.calcite.CodeExecuterContext) Row(io.vertx.sqlclient.Row) SQLStatement(com.alibaba.druid.sql.ast.SQLStatement) com.alibaba.druid.sql.ast.statement(com.alibaba.druid.sql.ast.statement) NewMycatConnection(io.mycat.newquery.NewMycatConnection) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) Function(java.util.function.Function) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) MysqlPayloadObject(io.mycat.api.collector.MysqlPayloadObject) ImmutableList(com.google.common.collect.ImmutableList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 17 with XaSqlConnection

use of cn.mycat.vertx.xa.XaSqlConnection in project Mycat2 by MyCATApache.

the class SqlResultSetService method loadResultSet.

@SneakyThrows
private Optional<Observable<MysqlPayloadObject>> loadResultSet(SQLSelectStatement sqlSelectStatement) {
    return cache.get(sqlSelectStatement.toString(), () -> {
        if (!MetaClusterCurrent.exist(DrdsSqlCompiler.class)) {
            return Optional.empty();
        }
        MycatDataContext context = new MycatDataContextImpl();
        try {
            DrdsSqlWithParams drdsSql = DrdsRunnerHelper.preParse(sqlSelectStatement, context.getDefaultSchema());
            Plan plan = DrdsRunnerHelper.getPlan(drdsSql);
            XaSqlConnection transactionSession = (XaSqlConnection) context.getTransactionSession();
            AsyncMycatDataContextImpl.SqlMycatDataContextImpl sqlMycatDataContext = new AsyncMycatDataContextImpl.SqlMycatDataContextImpl(context, plan.getCodeExecuterContext(), drdsSql);
            PrepareExecutor prepare = MetaClusterCurrent.wrapper(ExecutorProvider.class).prepare(plan);
            Observable<MysqlPayloadObject> observable = prepare.getMysqlPayloadObjectObservable(prepare.getArrayBindable(), sqlMycatDataContext, plan.getMetaData());
            observable = observable.doOnTerminate(new Action() {

                @Override
                public void run() throws Throwable {
                    transactionSession.closeStatementState().onComplete(event -> context.close());
                }
            });
            List<MysqlPayloadObject> mysqlPayloadObjects = observable.toList().blockingGet();
            observable = Observable.fromIterable(mysqlPayloadObjects);
            return Optional.ofNullable(observable);
        } catch (Throwable t) {
            context.kill();
            log.error("", t);
            return Optional.empty();
        }
    });
}
Also used : PrepareExecutor(io.mycat.calcite.PrepareExecutor) MycatDataContextImpl(io.mycat.runtime.MycatDataContextImpl) Action(io.reactivex.rxjava3.functions.Action) Plan(io.mycat.calcite.spm.Plan) MysqlPayloadObject(io.mycat.api.collector.MysqlPayloadObject) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) ExecutorProvider(io.mycat.calcite.ExecutorProvider) SneakyThrows(lombok.SneakyThrows)

Example 18 with XaSqlConnection

use of cn.mycat.vertx.xa.XaSqlConnection in project Mycat2 by MyCATApache.

the class BaseSavepointSuite method baseSavepointRollbackSavepoint.

@Test
public void baseSavepointRollbackSavepoint(VertxTestContext testContext) {
    XaSqlConnection baseXaSqlConnection = factory.apply(mySQLManager, xaLog);
    Assert.assertTrue(baseXaSqlConnection instanceof SavepointSqlConnection);
    SavepointSqlConnection savepointSqlConnection = (SavepointSqlConnection) baseXaSqlConnection;
    baseXaSqlConnection.begin().onComplete(new Handler<AsyncResult<Void>>() {

        @Override
        @SneakyThrows
        public void handle(AsyncResult<Void> event) {
            Future<Void> sss = savepointSqlConnection.createSavepoint("sss");
            sss.toCompletionStage().toCompletableFuture().get();
            Assert.assertEquals("[sss]", savepointSqlConnection.getExistedSavepoints().toString());
            savepointSqlConnection.rollbackSavepoint("sss").toCompletionStage().toCompletableFuture().get();
            Assert.assertEquals("[]", savepointSqlConnection.getExistedSavepoints().toString());
            testContext.completeNow();
        }
    });
}
Also used : SavepointSqlConnection(cn.mycat.vertx.xa.SavepointSqlConnection) SneakyThrows(lombok.SneakyThrows) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) Test(org.junit.jupiter.api.Test)

Example 19 with XaSqlConnection

use of cn.mycat.vertx.xa.XaSqlConnection in project Mycat2 by MyCATApache.

the class BaseSavepointSuite method baseSavepointRollback.

@Test
public void baseSavepointRollback(VertxTestContext testContext) {
    XaSqlConnection baseXaSqlConnection = factory.apply(mySQLManager, xaLog);
    Assert.assertTrue(baseXaSqlConnection instanceof SavepointSqlConnection);
    SavepointSqlConnection savepointSqlConnection = (SavepointSqlConnection) baseXaSqlConnection;
    baseXaSqlConnection.begin().onComplete(new Handler<AsyncResult<Void>>() {

        @Override
        @SneakyThrows
        public void handle(AsyncResult<Void> event) {
            Future<Void> sss = savepointSqlConnection.createSavepoint("sss");
            sss.toCompletionStage().toCompletableFuture().get();
            Assert.assertEquals("[sss]", savepointSqlConnection.getExistedSavepoints().toString());
            savepointSqlConnection.rollback();
            Assert.assertEquals("[]", savepointSqlConnection.getExistedSavepoints().toString());
            testContext.completeNow();
        }
    });
}
Also used : SavepointSqlConnection(cn.mycat.vertx.xa.SavepointSqlConnection) SneakyThrows(lombok.SneakyThrows) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) Test(org.junit.jupiter.api.Test)

Example 20 with XaSqlConnection

use of cn.mycat.vertx.xa.XaSqlConnection in project Mycat2 by MyCATApache.

the class BaseSavepointSuite method baseSavepointRollbackInSingleConnection.

@Test
@SneakyThrows
public void baseSavepointRollbackInSingleConnection(VertxTestContext testContext) {
    mySQLManager.getConnection("ds1").flatMap(connection -> {
        return connection.update("delete FROM `db1`.`travelrecord`").map(u -> connection);
    }).flatMap(c -> c.close()).toCompletionStage().toCompletableFuture().get();
    XaSqlConnection baseXaSqlConnection = factory.apply(mySQLManager, xaLog);
    Assert.assertTrue(baseXaSqlConnection instanceof SavepointSqlConnection);
    SavepointSqlConnection savepointSqlConnection = (SavepointSqlConnection) baseXaSqlConnection;
    baseXaSqlConnection.begin().onComplete(new Handler<AsyncResult<Void>>() {

        @Override
        @SneakyThrows
        public void handle(AsyncResult<Void> event) {
            savepointSqlConnection.createSavepoint("sss").toCompletionStage().toCompletableFuture().get();
            NewMycatConnection ds1 = savepointSqlConnection.getConnection("ds1").toCompletionStage().toCompletableFuture().get();
            ds1.insert("insert into `db1`.`travelrecord` (`id`) values ('2')").toCompletionStage().toCompletableFuture().get();
            RowSet objects = ds1.query("select * from `db1`.`travelrecord` where id = 2").toCompletionStage().toCompletableFuture().get();
            Assert.assertTrue(objects.size() > 0);
            Assert.assertEquals("[sss]", savepointSqlConnection.getExistedSavepoints().toString());
            savepointSqlConnection.rollback().toCompletionStage().toCompletableFuture().get();
            Assert.assertEquals("[]", savepointSqlConnection.getExistedSavepoints().toString());
            ds1 = savepointSqlConnection.getConnection("ds1").toCompletionStage().toCompletableFuture().get();
            objects = ds1.query("select * from `db1`.`travelrecord` where id = 2").toCompletionStage().toCompletableFuture().get();
            Assert.assertTrue(objects.size() == 0);
            savepointSqlConnection.close();
            testContext.completeNow();
        }
    });
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) NewMycatConnection(io.mycat.newquery.NewMycatConnection) SneakyThrows(lombok.SneakyThrows) RowSet(io.mycat.newquery.RowSet) BiFunction(java.util.function.BiFunction) XaLog(cn.mycat.vertx.xa.XaLog) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) AsyncResult(io.vertx.core.AsyncResult) MySQLManager(cn.mycat.vertx.xa.MySQLManager) SavepointSqlConnection(cn.mycat.vertx.xa.SavepointSqlConnection) Handler(io.vertx.core.Handler) Assert(org.junit.Assert) NewMycatConnection(io.mycat.newquery.NewMycatConnection) SavepointSqlConnection(cn.mycat.vertx.xa.SavepointSqlConnection) RowSet(io.mycat.newquery.RowSet) SneakyThrows(lombok.SneakyThrows) AsyncResult(io.vertx.core.AsyncResult) XaSqlConnection(cn.mycat.vertx.xa.XaSqlConnection) Test(org.junit.jupiter.api.Test) SneakyThrows(lombok.SneakyThrows)

Aggregations

XaSqlConnection (cn.mycat.vertx.xa.XaSqlConnection)34 AsyncResult (io.vertx.core.AsyncResult)26 Test (org.junit.jupiter.api.Test)26 Future (io.vertx.core.Future)21 NewMycatConnection (io.mycat.newquery.NewMycatConnection)20 Handler (io.vertx.core.Handler)18 MySQLManager (cn.mycat.vertx.xa.MySQLManager)17 RowSet (io.mycat.newquery.RowSet)16 XaLog (cn.mycat.vertx.xa.XaLog)15 VertxTestContext (io.vertx.junit5.VertxTestContext)15 BiFunction (java.util.function.BiFunction)15 SavepointSqlConnection (cn.mycat.vertx.xa.SavepointSqlConnection)14 SneakyThrows (lombok.SneakyThrows)14 Assert (org.junit.Assert)9 CompositeFuture (io.vertx.core.CompositeFuture)8 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 Function (java.util.function.Function)8 SqlResult (io.mycat.newquery.SqlResult)7 Row (io.vertx.sqlclient.Row)7 SqlConnection (io.vertx.sqlclient.SqlConnection)7