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

The following examples show how to use io.vertx.reactivex.ext.sql.SQLConnection. These examples are extracted from open source projects. 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
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 2
Source Project: redpipe   Source File: WikiResource.java    License: 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 3
Source Project: vertx-kubernetes-workshop   Source File: AuditVerticle.java    License: 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 Project: vertx-kubernetes-workshop   Source File: AuditVerticle.java    License: 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 5
Source Project: vertx-jooq   Source File: AsyncRXQueryExecutor.java    License: 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 6
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
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 8
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 9
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 10
Source Project: redpipe   Source File: Fibers.java    License: 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 11
Source Project: redpipe   Source File: SQLUtil.java    License: 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 12
Source Project: redpipe   Source File: SQLUtil.java    License: 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 13
Source Project: vertx-kubernetes-workshop   Source File: AuditVerticle.java    License: 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 14
Source Project: vertx-rx   Source File: RxifiedSQLExamples.java    License: 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 15
private Single<SQLConnection> connect() {
    return jdbc.rxGetConnection()
        .map(c -> c.setOptions(new SQLOptions().setAutoGeneratedKeys(true)));
}
 
Example 16
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 17
private Single<SQLConnection> createTableIfNeeded(SQLConnection connection) {
    return vertx.fileSystem().rxReadFile("tables.sql")
        .map(Buffer::toString)
        .flatMapCompletable(connection::rxExecute)
        .toSingleDefault(connection);
}
 
Example 18
Source Project: redpipe   Source File: Fibers.java    License: Apache License 2.0 4 votes vote down vote up
@Suspendable
T run(SQLConnection c) throws Exception;
 
Example 19
Source Project: redpipe   Source File: SQLConnectionInjector.java    License: 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();
}
 
Example 20
Source Project: redpipe   Source File: SQLUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static Single<SQLConnection> getConnection(){
	return AppGlobals.get().getDbConnection();
}
 
Example 21
Source Project: redpipe   Source File: AppGlobals.java    License: Apache License 2.0 4 votes vote down vote up
public Single<SQLConnection> getDbConnection(){
	return dbClient.rxGetConnection();
}
 
Example 22
Source Project: vertx-kubernetes-workshop   Source File: AuditVerticle.java    License: 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 Project: vertx-rx   Source File: InTransactionSingle.java    License: 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 24
Source Project: vertx-rx   Source File: InTransactionObservable.java    License: 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 25
Source Project: vertx-rx   Source File: InTransactionFlowable.java    License: 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 26
Source Project: vertx-rx   Source File: InTransactionMaybe.java    License: 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 27
Source Project: vertx-rx   Source File: InTransactionCompletable.java    License: 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;
}