#include "service.h"
#include <stdio.h>
#include <string.h>
#include "resource.h"
int pg_query(pblock *pb, Session *sn, Request *rq) {
char *respool = pblock_findval(
"resource", pb);
char *query = pblock_findval(
"query", pb);
if(!respool) {
log_ereport(
LOG_MISCONFIG,
"pg-query: missing resource parameter");
return REQ_ABORTED;
}
if(!query) {
log_ereport(
LOG_MISCONFIG,
"pg-query: missing query parameter");
return REQ_ABORTED;
}
ResourceData *res = resourcepool_lookup(sn, rq, respool,
0);
if(!res) {
log_ereport(
LOG_FAILURE,
"pg-query: cannot get resource ''%s''", respool);
return REQ_ABORTED;
}
PGconn *connection = res->data;
if(pg_check_connection(
LOG_FAILURE, respool, connection)) {
return REQ_ABORTED;
}
PGresult *result = PQexec(connection, query);
if(!result)
return REQ_ABORTED;
pblock_remove(
"content-type", rq->srvhdrs);
pblock_nvinsert(
"content-type",
"text/html", rq->srvhdrs);
protocol_status(sn, rq,
200,
NULL);
http_start_response(sn, rq);
net_printf(sn->csd,
"%s",
"<!DOCTYPE html>\n<html><head></head><body>\n");
int nfields = PQnfields(result);
if(nfields >
0) {
net_printf(sn->csd,
"<table>\n<tr>\n");
for(
int i=
0;i<nfields;i++) {
char *fieldName = PQfname(result, i);
char *fieldNameEscaped = util_html_escape(fieldName);
if(fieldNameEscaped) {
net_printf(sn->csd,
"<th>%s</th>\n", fieldNameEscaped);
FREE(fieldNameEscaped);
}
}
net_printf(sn->csd,
"</tr>\n");
int nrows = PQntuples(result);
for(
int r=
0;r<nrows;r++) {
net_printf(sn->csd,
"<tr>\n");
for(
int c=
0;c<nfields;c++) {
char *fieldValue = PQgetvalue(result, r, c);
char *fieldValueEscaped = util_html_escape(fieldValue);
if(fieldValueEscaped) {
net_printf(sn->csd,
"<td>%s</td>\n", fieldValueEscaped);
FREE(fieldValueEscaped);
}
}
net_printf(sn->csd,
"</tr>\n");
}
net_printf(sn->csd,
"</table>\n");
}
else {
net_printf(sn->csd,
"<p>%s</p>\n", PQresStatus(PQresultStatus(result)));
}
net_printf(sn->csd,
"%s",
"</body></html>\n");
PQclear(result);
return REQ_PROCEED;
}