oentoro
oentoro

Reputation: 750

Database query loop in vertx to check if value exists

I am generating a value(6 alphanumeric letters using uuid java) and check it againts database if the value already exists. If the value already exists in db, I generate new value and check the existence of the value again (and so on). In synchronous way (java), I can do this:

String voucher = this.genereatevoucher();
while(this.valuexists(voucher )){
     test = this.genereatevoucher();
}

Note that this.valuexists method check if the value exists in database then return true or false. But in vertx, the common way to query a database is:

client.getConnection(res -> {
  if (res.succeeded()) {

    SQLConnection connection = res.result();

    connection.query("SELECT * FROM some_table", res2 -> {
      if (res2.succeeded()) {

        ResultSet rs = res2.result();
        // Do something with results
      }
    });
  } else {
    // Failed to get connection - deal with it
  }
});

I can't put the code above on my method because it executed asynchronously, so my method will always return true / false (based on initial assignment). How to (possibly) do database query loop in vertx?

Upvotes: 0

Views: 550

Answers (1)

tsegismont
tsegismont

Reputation: 9128

You could put the logic inside a method which calls itself again until no matching row is found:

generateVoucher(handler);

Where handler is the code you want invoked when the no matching row is found or database query fails.

Then the method implementation looks like:

private void generateVoucher(Handler<AsyncResult<String>> handler) {
  String myId = ....;
  client.getConnection(res -> {
    if (res.succeeded()) {
      SQLConnection connection = res.result();
      connection.queryWithParams(myQuery, new JsonArray().add(myId), res2 -> {
        if (res2.succeeded()) {
          ResultSet rs = res2.result();
          boolean inDb = checkAlreadyInDb(rs);
          connection.close();
          if (inDb) {
            generateVoucher(handler);
          } else {
            handler.handle(Future.succeededFuture(myId));
          }
        } else {
          handler.handle(Future.failedFuture(res2.cause));
        }
      });
    } else {
      handler.handle(Future.failedFuture(res.cause));
    }
  });
}

Upvotes: 3

Related Questions