package examples;
import io.vertx.pgclient.*;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.data.Numeric;
import io.vertx.pgclient.pubsub.PgSubscriber;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlResult;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.SqlClient;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;
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.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@Source
public class PgClientExamples {
public void gettingStarted() {
PgConnectOptions connectOptions = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
PgPool client = PgPool.pool(connectOptions, poolOptions);
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
if (ar.succeeded()) {
RowSet 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 = PgPool.pool();
PgConnection.connect(vertx, res -> {
});
}
public void configureFromDataObject(Vertx vertx) {
PgConnectOptions connectOptions = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
PgPool pool = PgPool.pool(vertx, connectOptions, poolOptions);
pool.getConnection(ar -> {
});
}
public void configureDefaultSchema() {
PgConnectOptions connectOptions = new PgConnectOptions();
connectOptions.addProperty("search_path", "myschema");
}
public void configureFromUri(Vertx vertx) {
String connectionUri = "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";
PgPool pool = PgPool.pool(connectionUri);
PgConnection.connect(vertx, connectionUri, res -> {
});
}
public void connecting01() {
PgConnectOptions connectOptions = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
PgPool client = PgPool.pool(connectOptions, poolOptions);
}
public void connecting02(Vertx vertx) {
PgConnectOptions connectOptions = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
PgPool client = PgPool.pool(vertx, connectOptions, poolOptions);
}
public void connecting03(PgPool pool) {
pool.close();
}
public void connecting04(Vertx vertx) {
PgConnectOptions connectOptions = new PgConnectOptions()
.setPort(5432)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
PgPool client = PgPool.pool(vertx, connectOptions, poolOptions);
client.getConnection(ar1 -> {
if (ar1.succeeded()) {
System.out.println("Connected");
SqlConnection 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");
PgConnection.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) {
PgConnectOptions connectOptions = new PgConnectOptions()
.setHost("/var/run/postgresql")
.setPort(5432)
.setDatabase("the-db");
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
PgPool client = PgPool.pool(connectOptions, poolOptions);
PgPool client2 = PgPool.pool(vertx, connectOptions, poolOptions);
}
public void typeMapping01(Pool pool) {
pool.query("SELECT 1::BIGINT \"VAL\"", ar -> {
RowSet rowSet = ar.result();
Row row = rowSet.iterator().next();
Object value = row.getValue(0);
Integer intValue = row.getInteger(0);
});
}
public void typeMapping02(Pool pool) {
pool.query("SELECT 1::BIGINT \"VAL\"", ar -> {
RowSet 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"));
PgConnection.connect(vertx, options, res -> {
if (res.succeeded()) {
} else {
System.out.println("Could not connect " + res.cause());
}
});
}
public void jsonExample() {
Tuple tuple = Tuple.of(
Tuple.JSON_NULL,
new JsonObject().put("foo", "bar"),
3);
Object value = tuple.get(Object.class, 0);
value = tuple.get(Object.class, 1);
value = tuple.get(Object.class, 3);
value = tuple.getInteger(3);
}
public void numericExample(Row row) {
Numeric numeric = row.get(Numeric.class, 0);
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(SqlClient client) {
client.preparedQuery("SELECT address, (address).city FROM address_book WHERE id=$1", Tuple.of(3), ar -> {
if (ar.succeeded()) {
RowSet 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(SqlClient client) {
client.preparedQuery("INSERT INTO address_book (id, address) VALUES ($1, $2)", Tuple.of(3, "('Anytown', 'Second Ave', false)"), ar -> {
if (ar.succeeded()) {
RowSet rows = ar.result();
System.out.println(rows.rowCount());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void collector01Example(SqlClient 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()) {
SqlResult<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(SqlClient client) {
Collector<Row, ?, String> collector = Collectors.mapping(
row -> row.getString("last_name"),
Collectors.joining(",", "(", ")")
);
client.query("SELECT * FROM users",
collector,
ar -> {
if (ar.succeeded()) {
SqlResult<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");
}
});
}
}