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-2025, 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"
17
18/*
19 * Run a query, return the results, exit program on failure.
20 */
22executeQuery(PGconn *conn, const char *query, bool echo)
23{
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_error_detail("Query was: %s", query);
36 exit(1);
37 }
38
39 return res;
40}
41
42
43/*
44 * As above for a SQL command (which returns nothing).
45 */
46void
47executeCommand(PGconn *conn, const char *query, bool echo)
48{
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_error_detail("Query was: %s", query);
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 */
73bool
74executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
75{
77 bool r;
78
79 if (echo)
80 printf("%s\n", query);
81
83 res = PQexec(conn, query);
85
87
88 PQclear(res);
89
90 return r;
91}
void ResetCancelConn(void)
Definition: cancel.c:107
void SetCancelConn(PGconn *conn)
Definition: cancel.c:77
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5178
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7507
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:122
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:125
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_detail(...)
Definition: logging.h:109
#define printf(...)
Definition: port.h:245
void executeCommand(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:47
PGresult * executeQuery(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:22
bool executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
Definition: query_utils.c:74
PGconn * conn
Definition: streamutil.c:53