Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * Facilities for frontend code to query a databases.
4 : *
5 : * Portions Copyright (c) 1996-2026, 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 0 : executeQuery(PGconn *conn, const char *query, bool echo)
23 : {
24 0 : PGresult *res;
25 :
26 0 : if (echo)
27 0 : printf("%s\n", query);
28 :
29 0 : res = PQexec(conn, query);
30 0 : if (!res ||
31 0 : PQresultStatus(res) != PGRES_TUPLES_OK)
32 : {
33 0 : pg_log_error("query failed: %s", PQerrorMessage(conn));
34 0 : pg_log_error_detail("Query was: %s", query);
35 0 : PQfinish(conn);
36 0 : exit(1);
37 : }
38 :
39 0 : return res;
40 0 : }
41 :
42 :
43 : /*
44 : * As above for a SQL command (which returns nothing).
45 : */
46 : void
47 0 : executeCommand(PGconn *conn, const char *query, bool echo)
48 : {
49 0 : PGresult *res;
50 :
51 0 : if (echo)
52 0 : printf("%s\n", query);
53 :
54 0 : res = PQexec(conn, query);
55 0 : if (!res ||
56 0 : PQresultStatus(res) != PGRES_COMMAND_OK)
57 : {
58 0 : pg_log_error("query failed: %s", PQerrorMessage(conn));
59 0 : pg_log_error_detail("Query was: %s", query);
60 0 : PQfinish(conn);
61 0 : exit(1);
62 : }
63 :
64 0 : PQclear(res);
65 0 : }
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 0 : executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
75 : {
76 0 : PGresult *res;
77 0 : bool r;
78 :
79 0 : if (echo)
80 0 : printf("%s\n", query);
81 :
82 0 : SetCancelConn(conn);
83 0 : res = PQexec(conn, query);
84 0 : ResetCancelConn();
85 :
86 0 : r = (res && PQresultStatus(res) == PGRES_COMMAND_OK);
87 :
88 0 : PQclear(res);
89 :
90 0 : return r;
91 0 : }
|