io.vertx.reactivex.ext.sql.SQLConnection Java Examples

The following examples show how to use io.vertx.reactivex.ext.sql.SQLConnection. 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: AsyncRXQueryExecutor.java    From vertx-jooq with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Single<T> insertReturning(Function<DSLContext, ? extends InsertResultStep<R>> queryFunction, Function<Object, T> keyMapper) {
    Query query = createQuery(queryFunction);
    log(query);
    String sql = query.getSQL();
    JsonArray bindValues = getBindValues(query);
    Function<SQLConnection, Single<? extends T>> runInsertReturning;
    if(isMysql){
        runInsertReturning = sqlConnection -> sqlConnection
                .rxUpdateWithParams(sql, bindValues)
                .map(updateResult -> keyMapper.apply(updateResult.getKeys()));
    }else{
        runInsertReturning = sqlConnection ->
                sqlConnection
                        .rxQueryWithParams(sql, bindValues)
                        .map(queryResult -> keyMapper.apply(queryResult.getResults().get(0)));
    }
    return getConnection().flatMap(executeAndClose(runInsertReturning));
}
 
Example #2
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private void storeInDatabase(JsonObject operation) {
    // 1. need to retrieve a connection
    // 2. execute the insertion statement
    // 3. close the connection


    // Step 1 get the connection
    Single<SQLConnection> connectionRetrieved = jdbc.rxGetConnection();

    // Step 2, when the connection is retrieved (this may have failed), do the insertion (upon success)
    Single<UpdateResult> update = connectionRetrieved
        .flatMap(connection ->
            connection.rxUpdateWithParams(INSERT_STATEMENT, new JsonArray().add(operation.encode()))

                // Step 3, when the insertion is done, close the connection.
                .doAfterTerminate(connection::close));

    update.subscribe(result -> {
        // Ok
    }, err -> {
        System.err.println("Failed to insert operation in database: " + err);
    });
}
 
Example #3
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private void storeInDatabase(JsonObject operation) {
    // 1. need to retrieve a connection
    // 2. execute the insertion statement
    // 3. close the connection


    // Step 1 get the connection
    Single<SQLConnection> connectionRetrieved = jdbc.rxGetConnection();

    // Step 2, when the connection is retrieved (this may have failed), do the insertion (upon success)
    Single<UpdateResult> update = connectionRetrieved
        .flatMap(connection ->
            connection.rxUpdateWithParams(INSERT_STATEMENT, new JsonArray().add(operation.encode()))

                // Step 3, when the insertion is done, close the connection.
                .doAfterTerminate(connection::close));

    update.subscribe(result -> {
        // Ok
    }, err -> {
        System.err.println("Failed to insert operation in database: " + err);
    });
}
 
Example #4
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 6 votes vote down vote up
private Single<SQLConnection> createSomeDataIfNone(SQLConnection connection) {
    return connection.rxQuery("SELECT * FROM Articles")
        .flatMap(rs -> {
            if (rs.getResults().isEmpty()) {
                Article article1 = new Article("Fallacies of distributed computing",
                    "https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing");
                Article article2 = new Article("Reactive Manifesto",
                    "https://www.reactivemanifesto.org/");
                return Single.zip(
                    insert(connection, article1, false),
                    insert(connection, article2, false),
                    (a1, a2) -> connection
                );
            } else {
                return Single.just(connection);
            }
        });
}
 
Example #5
Source File: WikiResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@GET
@Path("index2")
public Single<Template> index2(@Context SQLConnection connection,
		@Context @HasPermission("create") boolean canCreatePage){
	return connection.rxQuery(SQL.SQL_ALL_PAGES)
			.map(res -> {
				List<String> pages = res.getResults()
						.stream()
						.map(json -> json.getString(0))
						.sorted()
						.collect(Collectors.toList());
				return new Template("templates/index.ftl")
						.set("title", "Wiki home")
						.set("pages", pages)
						.set("canCreatePage", canCreatePage)
						.set("username", getUserName())
						.set("backup_gist_url", flash.get("backup_gist_url"));
	});
}
 
Example #6
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private Single<Article> insert(SQLConnection connection, Article article, boolean closeConnection) {
    String sql = "INSERT INTO Articles (title, url) VALUES (?, ?)";
    return connection
        .rxUpdateWithParams(sql, new JsonArray().add(article.getTitle()).add(article.getUrl()))
        .map(res -> new Article(res.getKeys().getLong(0), article.getTitle(), article.getUrl()))
        .doFinally(() -> {
            if (closeConnection) {
                connection.close();
            }
        });
}
 
Example #7
Source File: RxifiedSQLExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void inTransactionTransformer(SQLConnection conn) {
  conn.rxExecute("... insert into album ...")
    .andThen(conn.rxExecute("... insert into tracks ..."))
    .compose(SQLClientHelper.txCompletableTransformer(conn)) // <1>
    .andThen(conn.rxQuery("... select from album, tracks ...").map(ResultSet::getResults))
    .subscribe(rows -> {
      // send to client
    }, throwable -> {
      // handle error
    });
}
 
Example #8
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
private void retrieveOperations(RoutingContext context) {
    // We retrieve the operation using the following process:
    // 1. Get the connection
    // 2. When done, execute the query
    // 3. When done, iterate over the result to build a list taking the `operation` value of each json object
    // 5. write this list into the response
    // 4. close the connection

    //TODO
    // ----
    jdbc.getConnection(ar -> {
        SQLConnection connection = ar.result();
        if (ar.failed()) {
            context.fail(ar.cause());
        } else {
            connection.query(SELECT_STATEMENT, result -> {
                if (result.failed()) {
                    context.fail(result.cause());
                } else {
                    ResultSet set = result.result();
                    List<JsonObject> operations = set.getRows().stream()
                        .map(json -> new JsonObject(json.getString("operation")))
                        .collect(Collectors.toList());
                    // 5. write this list into the response
                    context.response().setStatusCode(200).end(Json.encodePrettily(operations));
                    // 6. close the connection
                    connection.close();
                }
            });
        }
    });
    // ----
}
 
Example #9
Source File: SQLUtil.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public static Completable doInConnectionCompletable(Func1<? super SQLConnection, ? extends Completable> func){
	return Completable.defer(() -> {
		Single<SQLConnection> connection = getConnection();
		return connection.flatMapCompletable(conn -> {
			return func.call(conn).doAfterTerminate(() -> {
				conn.close();
			});
		});
	});
}
 
Example #10
Source File: SQLUtil.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public static <T> Single<T> doInConnection(Func1<? super SQLConnection, ? extends Single<T>> func){
	return Single.defer(() -> {
		Single<SQLConnection> connection = getConnection();
		return connection.flatMap(conn -> {
			return func.call(conn).doAfterTerminate(() -> {
				conn.close();
			});
		});
	});
}
 
Example #11
Source File: Fibers.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public static <T> Single<T> fiber(SuspendableCallableWithConnection<T> body){
	return fiber(() -> {
		SQLConnection connection = await(SQLUtil.getConnection());
		try{
			return body.run(connection);
		}finally{
			connection.close();
		}
	});
}
 
Example #12
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private Completable delete(SQLConnection connection, String id) {
    String sql = "DELETE FROM Articles WHERE id = ?";
    JsonArray params = new JsonArray().add(Integer.valueOf(id));
    return connection.rxUpdateWithParams(sql, params)
        .doFinally(connection::close)
        .flatMapCompletable(ur ->
            ur.getUpdated() == 0 ?
                Completable
                    .error(new NoSuchElementException("No article with id " + id))
                : Completable.complete()
        );
}
 
Example #13
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private Completable update(SQLConnection connection, String id, Article article) {
    String sql = "UPDATE articles SET title = ?, url = ? WHERE id = ?";
    JsonArray params = new JsonArray().add(article.getTitle())
        .add(article.getUrl())
        .add(Integer.valueOf(id));
    return connection.rxUpdateWithParams(sql, params)
        .flatMapCompletable(ur ->
            ur.getUpdated() == 0 ?
                Completable
                    .error(new NoSuchElementException("No article with id " + id))
                : Completable.complete()
        )
        .doFinally(connection::close);
}
 
Example #14
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private Single<Article> queryOne(SQLConnection connection, String id) {
    String sql = "SELECT * FROM articles WHERE id = ?";
    return connection.rxQueryWithParams(sql, new JsonArray().add(Integer.valueOf(id)))
        .doFinally(connection::close)
        .map(rs -> {
            List<JsonObject> rows = rs.getRows();
            if (rows.size() == 0) {
                throw new NoSuchElementException("No article with id " + id);
            } else {
                JsonObject row = rows.get(0);
                return new Article(row);
            }
        });
}
 
Example #15
Source File: InTransactionCompletable.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
/**
 * @param sqlConnection the connection used for transaction management
 */
public InTransactionCompletable(SQLConnection sqlConnection) {
  this.sqlConnection = sqlConnection;
}
 
Example #16
Source File: InTransactionMaybe.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
/**
 * @param sqlConnection the connection used for transaction management
 */
public InTransactionMaybe(SQLConnection sqlConnection) {
  this.sqlConnection = sqlConnection;
}
 
Example #17
Source File: InTransactionFlowable.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
/**
 * @param sqlConnection the connection used for transaction management
 */
public InTransactionFlowable(SQLConnection sqlConnection) {
  this.sqlConnection = sqlConnection;
}
 
Example #18
Source File: InTransactionObservable.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
/**
 * @param sqlConnection the connection used for transaction management
 */
public InTransactionObservable(SQLConnection sqlConnection) {
  this.sqlConnection = sqlConnection;
}
 
Example #19
Source File: InTransactionSingle.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
/**
 * @param sqlConnection the connection used for transaction management
 */
public InTransactionSingle(SQLConnection sqlConnection) {
  this.sqlConnection = sqlConnection;
}
 
Example #20
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
private Single<SQLConnection> connect() {
    return jdbc.rxGetConnection()
        .map(c -> c.setOptions(new SQLOptions().setAutoGeneratedKeys(true)));
}
 
Example #21
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
private Single<List<Article>> query(SQLConnection connection) {
    return connection.rxQuery("SELECT * FROM articles")
        .map(rs -> rs.getRows().stream().map(Article::new).collect(Collectors.toList()))
        .doFinally(connection::close);
}
 
Example #22
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
private Single<JDBCClient> initializeDatabase(JDBCClient client, boolean drop) {
    // TODO - Initialize the database and return the JDBC client
    // ----
    // The database initialization is a multi-step process:
    // 1. Retrieve the connection
    // 2. Drop the table is exist
    // 3. Create the table
    // 4. Close the connection (in any case)
    // To handle such a process, we are going to create an RxJava Single and compose it with the RxJava flatMap operation:
    // retrieve the connection -> drop table -> create table -> close the connection
    // For this we use `Func1<X, Single<R>>`that takes a parameter `X` and return a `Single<R>` object.

    // This is the starting point of our operations
    // This single will be completed when the connection with the database is established.
    // We are going to use this single as a reference on the connection to close it.
    Single<SQLConnection> connectionRetrieved = client.rxGetConnection();

    // Ok, now it's time to chain all these actions (2 to 4):
    return connectionRetrieved
        .flatMap(conn -> {
            // When the connection is retrieved

            // Prepare the batch
            List<String> batch = new ArrayList<>();
            if (drop) {
                // When the table is dropped, we recreate it
                batch.add(DROP_STATEMENT);
            }
            // Just create the table
            batch.add(CREATE_TABLE_STATEMENT);

            // We compose with a statement batch
            Single<List<Integer>> next = conn.rxBatch(batch);

            // Whatever the result, if the connection has been retrieved, close it
            return next.doAfterTerminate(conn::close);
        })
        .map(list -> client);
    // ----

}
 
Example #23
Source File: AppGlobals.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public Single<SQLConnection> getDbConnection(){
	return dbClient.rxGetConnection();
}
 
Example #24
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
private Single<SQLConnection> createTableIfNeeded(SQLConnection connection) {
    return vertx.fileSystem().rxReadFile("tables.sql")
        .map(Buffer::toString)
        .flatMapCompletable(connection::rxExecute)
        .toSingleDefault(connection);
}
 
Example #25
Source File: Fibers.java    From redpipe with Apache License 2.0 4 votes vote down vote up
@Suspendable
T run(SQLConnection c) throws Exception;
 
Example #26
Source File: SQLUtil.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public static Single<SQLConnection> getConnection(){
	return AppGlobals.get().getDbConnection();
}
 
Example #27
Source File: SQLConnectionInjector.java    From redpipe with Apache License 2.0 4 votes vote down vote up
@Override
public Single<SQLConnection> resolve(Class<? extends Single<SQLConnection>> rawType, Type genericType,
		Annotation[] annotations) {
	return AppGlobals.get().getDbConnection();
}