io.vertx.ext.sql.assist.SQLExecutePgImpl Maven / Gradle / Ivy
package io.vertx.ext.sql.assist;
import java.util.ArrayList;
import java.util.List;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;
/**
* JDBCClient版的SQL实现
*
* @author Mirren
*
*/
public class SQLExecutePgImpl implements SQLExecute {
/** PostgreSQL 客户端 */
private PgPool client;
public SQLExecutePgImpl(PgPool client) {
super();
this.client = client;
}
@Override
public PgPool getClient() {
return client;
}
@Override
public void queryAsObj(SqlAndParams qp, Handler> handler) {
queryExecute(qp, query -> {
if (query.succeeded()) {
RowSet result = query.result();
List names = result.columnsNames();
List rows = new ArrayList<>();
for (Row row : result) {
JsonObject data = new JsonObject();
for (int i = 0; i < names.size(); i++) {
data.put(names.get(i), row.getValue(i));
}
rows.add(data);
}
if (rows != null && rows.size() > 0) {
handler.handle(Future.succeededFuture(rows.get(0)));
} else {
handler.handle(Future.succeededFuture());
}
} else {
handler.handle(Future.failedFuture(query.cause()));
}
});
}
@Override
public void queryAsListObj(SqlAndParams qp, Handler>> handler) {
queryExecute(qp, query -> {
if (query.succeeded()) {
RowSet result = query.result();
List names = result.columnsNames();
List rows = new ArrayList<>();
for (Row row : result) {
JsonObject data = new JsonObject();
for (int i = 0; i < names.size(); i++) {
data.put(names.get(i), row.getValue(i));
}
rows.add(data);
}
handler.handle(Future.succeededFuture(rows));
} else {
handler.handle(Future.failedFuture(query.cause()));
}
});
}
@Override
public void queryAsListArray(SqlAndParams qp, Handler>> handler) {
queryExecute(qp, query -> {
if (query.succeeded()) {
RowSet result = query.result();
List rows = new ArrayList<>();
for (Row row : result) {
JsonArray data = new JsonArray();
for (int i = 0; i < row.size(); i++) {
data.add(row.getValue(i));
}
rows.add(data);
}
handler.handle(Future.succeededFuture(rows));
} else {
handler.handle(Future.failedFuture(query.cause()));
}
});
}
@Override
public void update(SqlAndParams qp, Handler> handler) {
updateExecute(qp, result -> {
if (result.succeeded()) {
int updated = result.result().rowCount();
handler.handle(Future.succeededFuture(updated));
} else {
handler.handle(Future.failedFuture(result.cause()));
}
});
}
@Override
public void batch(SqlAndParams qp, Handler>> handler) {
if (qp.succeeded()) {
client.getConnection(conn -> {
if (conn.succeeded()) {
SqlConnection connection = conn.result();
List batch = new ArrayList<>();
List params = qp.getBatchParams();
for (JsonArray param : params) {
@SuppressWarnings("unchecked")
List