io.vertx.sqlclient.Transaction Java Examples

The following examples show how to use io.vertx.sqlclient.Transaction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostgresClient.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
void selectStream(AsyncResult<SQLConnection> conn, String sql, Tuple params, int chunkSize,
    Handler<AsyncResult<RowStream<Row>>> replyHandler) {
  try {
    if (conn.failed()) {
      replyHandler.handle(Future.failedFuture(conn.cause()));
      return;
    }
    final Transaction tx = conn.result().tx;
    tx.prepare(sql, res -> {
      if (res.failed()) {
        log.error(res.cause().getMessage(), res.cause());
        replyHandler.handle(Future.failedFuture(res.cause()));
        return;
      }
      PreparedStatement pq = res.result();
      RowStream<Row> rowStream = pq.createStream(chunkSize, params);
      replyHandler.handle(Future.succeededFuture(rowStream));
    });
  } catch (Exception e) {
    log.error("select stream sql: " + e.getMessage() + " - " + sql, e);
    replyHandler.handle(Future.failedFuture(e));
  }
}
 
Example #2
Source File: TransactionTestBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected void initConnector() {
  connector = handler -> {
    Pool pool = getPool();
    pool.getConnection(ar1 -> {
      if (ar1.succeeded()) {
        SqlConnection conn = ar1.result();
        conn.begin(ar2 -> {
          if (ar2.succeeded()) {
            Transaction tx = ar2.result();
            tx.completion().onComplete(ar3 -> {
              conn.close();
            });
            handler.handle(Future.succeededFuture(new Result(conn, tx)));
          } else {
            conn.close();
          }
        });
      } else {
        handler.handle(ar1.mapEmpty());
      }
    });
  };
}
 
Example #3
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * Rolls a transaction back.
 * @return a <code>CompletableFuture</code> that completes when the transaction has been rolled back.
 * @throws IllegalStateException if not called <code>beginTransaction</code> before.
 */
public CompletableFuture<Void> rollback(){
    if(!(delegate instanceof Transaction)){
        throw new IllegalStateException("Not in transaction");
    }
    CompletableFuture<Void> commit = new VertxCompletableFuture<>(vertx);
    ((Transaction) delegate).rollback(createCompletionHandler(commit));
    return commit;
}
 
Example #4
Source File: SqlConnectionImpl.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Transaction> begin() {
  if (tx != null) {
    throw new IllegalStateException();
  }
  tx = new TransactionImpl(context, conn);
  tx.completion().onComplete(ar -> {
    tx = null;
  });
  return tx.begin();
}
 
Example #5
Source File: TransactionImpl.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private synchronized void afterBegin(AsyncResult<Transaction> ar) {
  if (ar.succeeded()) {
    status = ST_PENDING;
  } else {
    status = ST_COMPLETED;
  }
  checkPending();
}
 
Example #6
Source File: ReactiveClassicGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * @return an instance of a <code>ReactiveClassicGenericQueryExecutor</code> that performs all CRUD
 * functions in the scope of a transaction. The transaction has to be committed/rolled back by calling <code>commit</code>
 * or <code>rollback</code> on the QueryExecutor returned.
 */
public Future<? extends ReactiveClassicGenericQueryExecutor> beginTransaction(){
    if(delegate instanceof Transaction){
        throw new IllegalStateException("Already in transaction");
    }
    Promise<Transaction> transactionPromise = Promise.promise();
    ((Pool) delegate).begin(transactionPromise);
    return transactionPromise.future().map(newInstance());
}
 
Example #7
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors03(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Streams require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Fetch 50 rows at a time
          RowStream<Row> stream = pq.createStream(50, Tuple.of("julien"));

          // Use the stream
          stream.exceptionHandler(err -> {
            System.out.println("Error: " + err.getMessage());
          });
          stream.endHandler(v -> {
            tx.commit();
            System.out.println("End of stream");
          });
          stream.handler(row -> {
            System.out.println("User: " + row.getString("last_name"));
          });
        }
      });
    }
  });
}
 
Example #8
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors01(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Cursors require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Create a cursor
          Cursor cursor = pq.cursor(Tuple.of("julien"));

          // Read 50 rows
          cursor.read(50, ar2 -> {
            if (ar2.succeeded()) {
              RowSet<Row> rows = ar2.result();

              // Check for more ?
              if (cursor.hasMore()) {
                // Repeat the process...
              } else {
                // No more rows - commit the transaction
                tx.commit();
              }
            }
          });
        }
      });
    }
  });
}
 
Example #9
Source File: ReactiveClassicGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * Rolls a transaction back.
 * @return a <code>Future</code> that completes when the transaction has been rolled back.
 * @throws IllegalStateException if not called <code>beginTransaction</code> before.
 */
public Future<Void> rollback(){
    if(!(delegate instanceof Transaction)){
        throw new IllegalStateException("Not in transaction");
    }
    Promise<Void> commit = Promise.promise();
    ((Transaction) delegate).rollback(commit);
    return commit.future();
}
 
Example #10
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors03(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Streams require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Fetch 50 rows at a time
          RowStream<Row> stream = pq.createStream(50, Tuple.of("julien"));

          // Use the stream
          stream.exceptionHandler(err -> {
            System.out.println("Error: " + err.getMessage());
          });
          stream.endHandler(v -> {
            tx.commit();
            System.out.println("End of stream");
          });
          stream.handler(row -> {
            System.out.println("User: " + row.getString("last_name"));
          });
        }
      });
    }
  });
}
 
Example #11
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors01(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Cursors require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Create a cursor
          Cursor cursor = pq.cursor(Tuple.of("julien"));

          // Read 50 rows
          cursor.read(50, ar2 -> {
            if (ar2.succeeded()) {
              RowSet<Row> rows = ar2.result();

              // Check for more ?
              if (cursor.hasMore()) {
                // Repeat the process...
              } else {
                // No more rows - commit the transaction
                tx.commit();
              }
            }
          });
        }
      });
    }
  });
}
 
Example #12
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 5 votes vote down vote up
/**
 * @return an instance of a <code>ReactiveCompletableFutureGenericQueryExecutor</code> that performs all CRUD
 * functions in the scope of a transaction. The transaction has to be committed/rolled back by calling <code>commit</code>
 * or <code>rollback</code> on the QueryExecutor returned.
 */
public CompletableFuture<? extends ReactiveCompletableFutureGenericQueryExecutor> beginTransaction(){
    if(delegate instanceof Transaction){
        throw new IllegalStateException("Already in transaction");
    }
    CompletableFuture<Transaction> transactionFuture = new VertxCompletableFuture<>(vertx);
    ((Pool) delegate).begin(createCompletionHandler(transactionFuture));
    return transactionFuture.thenApply(newInstance());
}
 
Example #13
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors03(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Streams require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Fetch 50 rows at a time
          RowStream<Row> stream = pq.createStream(50, Tuple.of("julien"));

          // Use the stream
          stream.exceptionHandler(err -> {
            System.out.println("Error: " + err.getMessage());
          });
          stream.endHandler(v -> {
            tx.commit();
            System.out.println("End of stream");
          });
          stream.handler(row -> {
            System.out.println("User: " + row.getString("last_name"));
          });
        }
      });
    }
  });
}
 
Example #14
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void usingCursors01(SqlConnection connection) {
  connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar0 -> {
    if (ar0.succeeded()) {
      PreparedStatement pq = ar0.result();

      // Cursors require to run within a transaction
      connection.begin(ar1 -> {
        if (ar1.succeeded()) {
          Transaction tx = ar1.result();

          // Create a cursor
          Cursor cursor = pq.cursor(Tuple.of("julien"));

          // Read 50 rows
          cursor.read(50, ar2 -> {
            if (ar2.succeeded()) {
              RowSet<Row> rows = ar2.result();

              // Check for more ?
              if (cursor.hasMore()) {
                // Repeat the process...
              } else {
                // No more rows - commit the transaction
                tx.commit();
              }
            }
          });
        }
      });
    }
  });
}
 
Example #15
Source File: SqlConnectionImpl.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
@Override
public void begin(Handler<AsyncResult<Transaction>> handler) {
  Future<Transaction> fut = begin();
  fut.onComplete(handler);
}
 
Example #16
Source File: SQLConnection.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public SQLConnection(PgConnection conn, Transaction tx, Long timerId) {
  this.conn = conn;
  this.tx = tx;
  this.timerId = timerId;
}
 
Example #17
Source File: PostgresClientTest.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction begin() {
  return null;
}
 
Example #18
Source File: ReactiveClassicQueryExecutor.java    From vertx-jooq with MIT License 4 votes vote down vote up
@Override
protected Function<Transaction, ReactiveClassicQueryExecutor<R,P,T>> newInstance() {
    return pgTransaction -> new ReactiveClassicQueryExecutor<>(configuration(), pgTransaction, pojoMapper);
}
 
Example #19
Source File: ReactiveClassicGenericQueryExecutor.java    From vertx-jooq with MIT License 4 votes vote down vote up
protected Function<Transaction, ? extends ReactiveClassicGenericQueryExecutor> newInstance() {
    return transaction -> new ReactiveClassicGenericQueryExecutor(configuration(),transaction);
}
 
Example #20
Source File: ReactiveCompletableFutureQueryExecutor.java    From vertx-jooq with MIT License 4 votes vote down vote up
@Override
protected Function<Transaction, ReactiveCompletableFutureQueryExecutor<R,P,T>> newInstance() {
    return pgTransaction -> new ReactiveCompletableFutureQueryExecutor<>(configuration(), pgTransaction, pojoMapper, vertx);
}
 
Example #21
Source File: ReactiveCompletableFutureGenericQueryExecutor.java    From vertx-jooq with MIT License 4 votes vote down vote up
protected Function<Transaction, ? extends ReactiveCompletableFutureGenericQueryExecutor> newInstance() {
    return transaction -> new ReactiveCompletableFutureGenericQueryExecutor(configuration(),transaction,vertx);
}
 
Example #22
Source File: PostgresQueryTest.java    From okapi with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction begin() {
  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
 
Example #23
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public void transaction02(Transaction tx) {
  tx.completion().onFailure(err -> {
    System.out.println("Transaction failed => rollbacked");
  });
}
 
Example #24
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public void transaction01(Pool pool) {
  pool.getConnection(res -> {
    if (res.succeeded()) {

      // Transaction must use a connection
      SqlConnection conn = res.result();

      // Begin the transaction
      conn.begin(ar0 -> {
        if (ar0.succeeded()) {
          Transaction tx = ar0.result();
          // Various statements
          conn
            .query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')")
            .execute(ar1 -> {
              if (ar1.succeeded()) {
                conn
                  .query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')")
                  .execute(ar2 -> {
                    if (ar2.succeeded()) {
                      // Commit the transaction
                      tx.commit(ar3 -> {
                        if (ar3.succeeded()) {
                          System.out.println("Transaction succeeded");
                        } else {
                          System.out.println("Transaction failed " + ar3.cause().getMessage());
                        }
                        // Return the connection to the pool
                        conn.close();
                      });
                    } else {
                      // Return the connection to the pool
                      conn.close();
                    }
                  });
              } else {
                // Return the connection to the pool
                conn.close();
              }
            });
        } else {
          // Return the connection to the pool
          conn.close();
        }
      });
    }
  });
}
 
Example #25
Source File: TransactionTestBase.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public Result(SqlClient client, Transaction tx) {
  this.client = client;
  this.tx = tx;
}
 
Example #26
Source File: ThreadLocalPool.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void begin(Handler<AsyncResult<Transaction>> handler) {
    pool().begin(handler);
}
 
Example #27
Source File: TransactionImpl.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
Future<Transaction> begin() {
  PromiseInternal<Transaction> promise = context.promise(this::afterBegin);
  ScheduledCommand<Transaction> b = doQuery(new TxCommand<>(TxCommand.Kind.BEGIN, this), promise);
  doSchedule(b.cmd, b.handler);
  return promise.future();
}
 
Example #28
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public void transaction02(Transaction tx) {
  tx.completion().onFailure(err -> {
    System.out.println("Transaction failed => rollbacked");
  });
}
 
Example #29
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public void transaction01(Pool pool) {
  pool.getConnection(res -> {
    if (res.succeeded()) {

      // Transaction must use a connection
      SqlConnection conn = res.result();

      // Begin the transaction
      conn.begin(ar0 -> {
        if (ar0.succeeded()) {
          Transaction tx = ar0.result();

          // Various statements
          conn
            .query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')")
            .execute(ar1 -> {
              if (ar1.succeeded()) {
                conn
                  .query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')")
                  .execute(ar2 -> {
                    if (ar2.succeeded()) {
                      // Commit the transaction
                      tx.commit(ar3 -> {
                        if (ar3.succeeded()) {
                          System.out.println("Transaction succeeded");
                        } else {
                          System.out.println("Transaction failed " + ar3.cause().getMessage());
                        }
                        // Return the connection to the pool
                        conn.close();
                      });
                    } else {
                      // Return the connection to the pool
                      conn.close();
                    }
                  });
              } else {
                // Return the connection to the pool
                conn.close();
              }
            });
        } else {
          // Return the connection to the pool
          conn.close();
        }
      });
    }
  });
}
 
Example #30
Source File: SqlClientExamples.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public void transaction02(Transaction tx) {
  tx.completion().onFailure(err -> {
    System.out.println("Transaction failed => rollbacked");
  });
}