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