PostgreSQL Source Code  git master
query_utils.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * Facilities for frontend code to query a databases.
4  *
5  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
6  * Portions Copyright (c) 1994, Regents of the University of California
7  *
8  * src/fe_utils/query_utils.c
9  *
10  *-------------------------------------------------------------------------
11  */
12 #include "postgres_fe.h"
13 
14 #include "common/logging.h"
15 #include "fe_utils/cancel.h"
16 #include "fe_utils/query_utils.h"
17 
18 /*
19  * Run a query, return the results, exit program on failure.
20  */
21 PGresult *
22 executeQuery(PGconn *conn, const char *query, bool echo)
23 {
24  PGresult *res;
25 
26  if (echo)
27  printf("%s\n", query);
28 
29  res = PQexec(conn, query);
30  if (!res ||
32  {
33  pg_log_error("query failed: %s", PQerrorMessage(conn));
34  pg_log_info("query was: %s", query);
35  PQfinish(conn);
36  exit(1);
37  }
38 
39  return res;
40 }
41 
42 
43 /*
44  * As above for a SQL command (which returns nothing).
45  */
46 void
47 executeCommand(PGconn *conn, const char *query, bool echo)
48 {
49  PGresult *res;
50 
51  if (echo)
52  printf("%s\n", query);
53 
54  res = PQexec(conn, query);
55  if (!res ||
57  {
58  pg_log_error("query failed: %s", PQerrorMessage(conn));
59  pg_log_info("query was: %s", query);
60  PQfinish(conn);
61  exit(1);
62  }
63 
64  PQclear(res);
65 }
66 
67 
68 /*
69  * As above for a SQL maintenance command (returns command success).
70  * Command is executed with a cancel handler set, so Ctrl-C can
71  * interrupt it.
72  */
73 bool
74 executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
75 {
76  PGresult *res;
77  bool r;
78 
79  if (echo)
80  printf("%s\n", query);
81 
82  SetCancelConn(conn);
83  res = PQexec(conn, query);
85 
86  r = (res && PQresultStatus(res) == PGRES_COMMAND_OK);
87 
88  if (res)
89  PQclear(res);
90 
91  return r;
92 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
#define pg_log_error(...)
Definition: logging.h:80
void ResetCancelConn(void)
Definition: cancel.c:100
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
#define printf(...)
Definition: port.h:222
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
PGconn * conn
Definition: streamutil.c:54
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
void executeCommand(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:47
void PQclear(PGresult *res)
Definition: fe-exec.c:680
bool executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:74
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142
PGresult * executeQuery(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:22
#define pg_log_info(...)
Definition: logging.h:88