package examples;
import io.reactiverse.pgclient.*;
import io.reactiverse.pgclient.data.Json;
import io.reactiverse.pgclient.data.Numeric;
import io.reactiverse.pgclient.pubsub.PgSubscriber;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.PemTrustOptions;
import io.vertx.docgen.Source;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@Source
public class Examples {
public void gettingStarted() {
PgPoolOptions options = new PgPoolOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setMaxSize(5);
PgPool client = PgClient.pool(options);
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
if (ar.succeeded()) {
PgRowSet result = ar.result();
System.out.println("Got " + result.size() + " rows ");
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
client.close();
});
}
public void configureFromEnv(Vertx vertx) {
PgPool pool = PgClient.pool();
PgClient.connect(vertx, res -> {
});
}
public void configureFromUri(Vertx vertx) {
String connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";
PgPool pool = PgClient.pool(connectionUri);
PgClient.connect(vertx, connectionUri, res -> {
});
}
public void connecting01() {
PgPoolOptions options = new PgPoolOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setMaxSize(5);
PgPool client = PgClient.pool(options);
}
public void connecting02(Vertx vertx) {
PgPoolOptions options = new PgPoolOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setMaxSize(5);
PgPool client = PgClient.pool(vertx, options);
}
public void connecting03(PgPool pool) {
pool.close();
}
public void connecting04(Vertx vertx) {
PgPoolOptions options = new PgPoolOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setMaxSize(5);
PgPool client = PgClient.pool(vertx, options);
client.getConnection(ar1 -> {
if (ar1.succeeded()) {
System.out.println("Connected");
PgConnection conn = ar1.result();
conn.query("SELECT * FROM users WHERE id='julien'", ar2 -> {
if (ar2.succeeded()) {
conn.query("SELECT * FROM users WHERE id='emad'", ar3 -> {
conn.close();
});
} else {
conn.close();
}
});
} else {
System.out.println("Could not connect: " + ar1.cause().getMessage());
}
});
}
public void connecting05(Vertx vertx) {
PgConnectOptions options = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PgClient.connect(vertx, options, res -> {
if (res.succeeded()) {
System.out.println("Connected");
PgConnection conn = res.result();
conn.query("SELECT * FROM users WHERE id='julien'", ar2 -> {
if (ar2.succeeded()) {
conn.query("SELECT * FROM users WHERE id='emad'", ar3 -> {
conn.close();
});
} else {
conn.close();
}
});
} else {
System.out.println("Could not connect: " + res.cause().getMessage());
}
});
}
public void connecting06(Vertx vertx) {
PgPoolOptions options = new PgPoolOptions()
.setHost("/var/run/postgresql")
.setPort(5432)
.setDatabase("the-db");
PgPool client = PgClient.pool(options);
PgPool client2 = PgClient.pool(vertx, options);
}
public void queries01(PgClient client) {
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
if (ar.succeeded()) {
PgRowSet result = ar.result();
System.out.println("Got " + result.size() + " rows ");
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void queries02(PgClient client) {
client.preparedQuery("SELECT * FROM users WHERE id=$1", Tuple.of("julien"), ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
System.out.println("Got " + rows.size() + " rows ");
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void queries03(PgClient client) {
client.preparedQuery("SELECT first_name, last_name FROM users", ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
for (Row row : rows) {
System.out.println("User " + row.getString(0) + " " + row.getString(1));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void queries04(PgClient client) {
client.preparedQuery("INSERT INTO users (first_name, last_name) VALUES ($1, $2)", Tuple.of("Julien", "Viet"), ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
System.out.println(rows.rowCount());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void queries05(Row row) {
System.out.println("User " + row.getString(0) + " " + row.getString(1));
}
public void queries06(Row row) {
System.out.println("User " + row.getString("first_name") + " " + row.getString("last_name"));
}
public void queries07(Row row) {
String firstName = row.getString("first_name");
Boolean male = row.getBoolean("male");
Integer age = row.getInteger("age");
}
public void queries08(PgClient client) {
List<Tuple> batch = new ArrayList<>();
batch.add(Tuple.of("julien", "Julien Viet"));
batch.add(Tuple.of("emad", "Emad Alblueshi"));
client.preparedBatch("INSERT INTO USERS (id, name) VALUES ($1, $2)", batch, res -> {
if (res.succeeded()) {
PgRowSet rows = res.result();
} else {
System.out.println("Batch failed " + res.cause());
}
});
}
public void queries09(Vertx vertx, PgPoolOptions options) {
options.setCachePreparedStatements(true);
PgPool client = PgClient.pool(vertx, options);
}
public void queries10(PgClient client) {
client.preparedQuery("INSERT INTO color (color_name) VALUES ($1), ($2), ($3) RETURNING color_id", Tuple.of("white", "red", "blue"), ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
System.out.println(rows.rowCount());
for (Row row : rows) {
System.out.println("generated key: " + row.getInteger("color_id"));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void usingConnections01(Vertx vertx, PgPool pool) {
pool.getConnection(ar1 -> {
if (ar1.succeeded()) {
PgConnection connection = ar1.result();
connection.query("SELECT * FROM users WHERE id='julien'", ar2 -> {
if (ar1.succeeded()) {
connection.query("SELECT * FROM users WHERE id='paulo'", ar3 -> {
connection.close();
});
} else {
connection.close();
}
});
}
});
}
public void usingConnections02(PgConnection connection) {
connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> {
if (ar1.succeeded()) {
PgPreparedQuery pq = ar1.result();
pq.execute(Tuple.of("julien"), ar2 -> {
if (ar2.succeeded()) {
PgRowSet rows = ar2.result();
}
});
}
});
}
public void usingConnections03(PgConnection connection) {
connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", ar1 -> {
if (ar1.succeeded()) {
PgPreparedQuery prepared = ar1.result();
List<Tuple> batch = new ArrayList();
batch.add(Tuple.of("julien", "Julien Viet"));
batch.add(Tuple.of("emad", "Emad Alblueshi"));
prepared.batch(batch, res -> {
if (res.succeeded()) {
PgRowSet rows = res.result();
} else {
System.out.println("Batch failed " + res.cause());
}
});
}
});
}
public void transaction01(PgPool pool) {
pool.getConnection(res -> {
if (res.succeeded()) {
PgConnection conn = res.result();
PgTransaction tx = conn.begin();
conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {});
conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {});
tx.commit(ar -> {
if (ar.succeeded()) {
System.out.println("Transaction succeeded");
} else {
System.out.println("Transaction failed " + ar.cause().getMessage());
}
conn.close();
});
}
});
}
public void transaction02(PgPool pool) {
pool.getConnection(res -> {
if (res.succeeded()) {
PgConnection conn = res.result();
PgTransaction tx = conn
.begin()
.abortHandler(v -> {
System.out.println("Transaction failed => rollbacked");
});
conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {
if (ar.succeeded()) {
} else {
tx.rollback();
conn.close();
}
});
conn.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {
});
tx.commit(ar -> {
conn.close();
});
}
});
}
public void transaction03(PgPool pool) {
pool.begin(res -> {
if (res.succeeded()) {
PgTransaction tx = res.result();
tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')", ar -> {});
tx.query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')", ar -> {});
tx.commit(ar -> {
if (ar.succeeded()) {
System.out.println("Transaction succeeded");
} else {
System.out.println("Transaction failed " + ar.cause().getMessage());
}
});
}
});
}
public void usingCursors01(PgConnection connection) {
connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> {
if (ar1.succeeded()) {
PgPreparedQuery pq = ar1.result();
PgTransaction tx = connection.begin();
PgCursor cursor = pq.cursor(Tuple.of("julien"));
cursor.read(50, ar2 -> {
if (ar2.succeeded()) {
PgRowSet rows = ar2.result();
if (cursor.hasMore()) {
} else {
tx.commit();
}
}
});
}
});
}
public void usingCursors02(PgCursor cursor) {
cursor.read(50, ar2 -> {
if (ar2.succeeded()) {
cursor.close();
}
});
}
public void usingCursors03(PgConnection connection) {
connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> {
if (ar1.succeeded()) {
PgPreparedQuery pq = ar1.result();
PgTransaction tx = connection.begin();
PgStream<Row> stream = pq.createStream(50, Tuple.of("julien"));
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"));
});
}
});
}
public void typeMapping01(PgPool pool) {
pool.query("SELECT 1::BIGINT \"VAL\"", ar -> {
PgRowSet rowSet = ar.result();
Row row = rowSet.iterator().next();
Object value = row.getValue(0);
Integer intValue = row.getInteger(0);
});
}
public void typeMapping02(PgPool pool) {
pool.query("SELECT 1::BIGINT \"VAL\"", ar -> {
PgRowSet rowSet = ar.result();
Row row = rowSet.iterator().next();
Object value = row.getValue(0);
Integer intValue = row.getInteger(0);
});
}
public void pubsub01(PgConnection connection) {
connection.notificationHandler(notification -> {
System.out.println("Received " + notification.getPayload() + " on channel " + notification.getChannel());
});
connection.query("LISTEN some-channel", ar -> {
System.out.println("Subscribed to channel");
});
}
public void pubsub02(Vertx vertx) {
PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
);
subscriber.channel("channel1").handler(payload -> {
System.out.println("Received " + payload);
});
subscriber.connect(ar -> {
if (ar.succeeded()) {
subscriber.channel("channel2").handler(payload -> {
System.out.println("Received " + payload);
});
}
});
}
public void pubsub03(Vertx vertx) {
PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
);
subscriber.connect(ar -> {
if (ar.succeeded()) {
subscriber.channel("Complex.Channel.Name").handler(payload -> {
System.out.println("Received " + payload);
});
subscriber.channel("Complex.Channel.Name").subscribeHandler(subscribed -> {
subscriber.actualConnection().query(
"NOTIFY \"Complex.Channel.Name\", 'msg'", notified -> {
System.out.println("Notified \"Complex.Channel.Name\"");
});
});
subscriber.channel("simple_channel").handler(payload -> {
System.out.println("Received " + payload);
});
subscriber.channel("simple_channel").subscribeHandler(subscribed -> {
subscriber.actualConnection().query(
"NOTIFY Simple_CHANNEL, 'msg'", notified -> {
System.out.println("Notified simple_channel");
});
});
subscriber.channel(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbb"
).handler(payload -> {
System.out.println("Received " + payload);
});
}
});
}
public void pubsub04(Vertx vertx) {
PgSubscriber subscriber = PgSubscriber.subscriber(vertx, new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
);
subscriber.reconnectPolicy(retries -> {
if (retries < 10) {
return 100L;
} else {
return -1L;
}
});
}
public void ex10(Vertx vertx) {
PgConnectOptions options = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setSslMode(SslMode.VERIFY_CA)
.setPemTrustOptions(new PemTrustOptions().addCertPath("/path/to/cert.pem"));
PgClient.connect(vertx, options, res -> {
if (res.succeeded()) {
} else {
System.out.println("Could not connect " + res.cause());
}
});
}
public void jsonExample() {
Tuple tuple = Tuple.of(
Json.create(Json.create(null)),
Json.create(Json.create(new JsonObject().put("foo", "bar"))),
Json.create(Json.create(null)));
Object value = tuple.getJson(0).value();
value = tuple.getJson(1).value();
value = tuple.getJson(3).value();
}
public void numericExample(Row row) {
Numeric numeric = row.getNumeric("value");
if (numeric.isNaN()) {
} else {
BigDecimal value = numeric.bigDecimalValue();
}
}
public void arrayExample() {
Tuple tuple = Tuple.of(new String[]{ "a", "tuple", "with", "arrays" });
tuple.addStringArray(new String[]{"another", "array"});
String[] array = tuple.getStringArray(0);
}
public void customType01Example(PgClient client) {
client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
for (Row row : rows) {
System.out.println("Full Address " + row.getString(0) + ", City " + row.getString(1));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void customType02Example(PgClient client) {
client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), ar -> {
if (ar.succeeded()) {
PgRowSet rows = ar.result();
System.out.println(rows.rowCount());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void collector01Example(PgClient client) {
Collector<Row, ?, Map<Long, String>> collector = Collectors.toMap(
row -> row.getLong("id"),
row -> row.getString("last_name"));
client.query("SELECT * FROM users",
collector,
ar -> {
if (ar.succeeded()) {
PgResult<Map<Long, String>> result = ar.result();
Map<Long, String> map = result.value();
System.out.println("Got " + map);
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void collector02Example(PgClient client) {
Collector<Row, ?, String> collector = Collectors.mapping(
row -> row.getString("last_name"),
Collectors.joining(",", "(", ")")
);
client.query("SELECT * FROM users",
collector,
ar -> {
if (ar.succeeded()) {
PgResult<String> result = ar.result();
String list = result.value();
System.out.println("Got " + list);
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void cancelRequest(PgConnection connection) {
connection.query("SELECT pg_sleep(20)", ar -> {
if (ar.succeeded()) {
System.out.println("Query success");
} else {
System.out.println("Failed to query due to " + ar.cause().getMessage());
}
});
connection.cancelRequest(ar -> {
if (ar.succeeded()) {
System.out.println("Cancelling request has been sent");
} else {
System.out.println("Failed to send cancelling request");
}
});
}
}