LCOV - code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 456 892 51.1 %
Date: 2020-06-03 10:06:28 Functions: 28 33 84.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * psql - the PostgreSQL interactive terminal
       3             :  *
       4             :  * Copyright (c) 2000-2020, PostgreSQL Global Development Group
       5             :  *
       6             :  * src/bin/psql/common.c
       7             :  */
       8             : #include "postgres_fe.h"
       9             : 
      10             : #include <ctype.h>
      11             : #include <limits.h>
      12             : #include <math.h>
      13             : #include <signal.h>
      14             : #ifndef WIN32
      15             : #include <unistd.h>               /* for write() */
      16             : #else
      17             : #include <io.h>                   /* for _write() */
      18             : #include <win32.h>
      19             : #endif
      20             : 
      21             : #include "command.h"
      22             : #include "common.h"
      23             : #include "common/logging.h"
      24             : #include "copy.h"
      25             : #include "crosstabview.h"
      26             : #include "fe_utils/cancel.h"
      27             : #include "fe_utils/mbprint.h"
      28             : #include "fe_utils/string_utils.h"
      29             : #include "portability/instr_time.h"
      30             : #include "settings.h"
      31             : 
      32             : static bool DescribeQuery(const char *query, double *elapsed_msec);
      33             : static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
      34             : static bool command_no_begin(const char *query);
      35             : static bool is_select_command(const char *query);
      36             : 
      37             : 
      38             : /*
      39             :  * openQueryOutputFile --- attempt to open a query output file
      40             :  *
      41             :  * fname == NULL selects stdout, else an initial '|' selects a pipe,
      42             :  * else plain file.
      43             :  *
      44             :  * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
      45             :  * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
      46             :  *
      47             :  * On error, reports suitable error message and returns false.
      48             :  */
      49             : bool
      50        4672 : openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
      51             : {
      52        4672 :     if (!fname || fname[0] == '\0')
      53             :     {
      54        4672 :         *fout = stdout;
      55        4672 :         *is_pipe = false;
      56             :     }
      57           0 :     else if (*fname == '|')
      58             :     {
      59           0 :         *fout = popen(fname + 1, "w");
      60           0 :         *is_pipe = true;
      61             :     }
      62             :     else
      63             :     {
      64           0 :         *fout = fopen(fname, "w");
      65           0 :         *is_pipe = false;
      66             :     }
      67             : 
      68        4672 :     if (*fout == NULL)
      69             :     {
      70           0 :         pg_log_error("%s: %m", fname);
      71           0 :         return false;
      72             :     }
      73             : 
      74        4672 :     return true;
      75             : }
      76             : 
      77             : /*
      78             :  * setQFout
      79             :  * -- handler for -o command line option and \o command
      80             :  *
      81             :  * On success, updates pset with the new output file and returns true.
      82             :  * On failure, returns false without changing pset state.
      83             :  */
      84             : bool
      85        4672 : setQFout(const char *fname)
      86             : {
      87             :     FILE       *fout;
      88             :     bool        is_pipe;
      89             : 
      90             :     /* First make sure we can open the new output file/pipe */
      91        4672 :     if (!openQueryOutputFile(fname, &fout, &is_pipe))
      92           0 :         return false;
      93             : 
      94             :     /* Close old file/pipe */
      95        4672 :     if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
      96             :     {
      97           0 :         if (pset.queryFoutPipe)
      98           0 :             pclose(pset.queryFout);
      99             :         else
     100           0 :             fclose(pset.queryFout);
     101             :     }
     102             : 
     103        4672 :     pset.queryFout = fout;
     104        4672 :     pset.queryFoutPipe = is_pipe;
     105             : 
     106             :     /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
     107        4672 :     set_sigpipe_trap_state(is_pipe);
     108        4672 :     restore_sigpipe_trap();
     109             : 
     110        4672 :     return true;
     111             : }
     112             : 
     113             : 
     114             : /*
     115             :  * Variable-fetching callback for flex lexer
     116             :  *
     117             :  * If the specified variable exists, return its value as a string (malloc'd
     118             :  * and expected to be freed by the caller); else return NULL.
     119             :  *
     120             :  * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
     121             :  * escaped for the specified quoting requirement.  (Failure in escaping
     122             :  * should lead to printing an error and returning NULL.)
     123             :  *
     124             :  * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
     125             :  * In psql, passthrough points to a ConditionalStack, which we check to
     126             :  * determine whether variable expansion is allowed.
     127             :  */
     128             : char *
     129         924 : psql_get_variable(const char *varname, PsqlScanQuoteType quote,
     130             :                   void *passthrough)
     131             : {
     132         924 :     char       *result = NULL;
     133             :     const char *value;
     134             : 
     135             :     /* In an inactive \if branch, suppress all variable substitutions */
     136         924 :     if (passthrough && !conditional_active((ConditionalStack) passthrough))
     137          40 :         return NULL;
     138             : 
     139         884 :     value = GetVariable(pset.vars, varname);
     140         884 :     if (!value)
     141         268 :         return NULL;
     142             : 
     143         616 :     switch (quote)
     144             :     {
     145         588 :         case PQUOTE_PLAIN:
     146         588 :             result = pg_strdup(value);
     147         588 :             break;
     148          28 :         case PQUOTE_SQL_LITERAL:
     149             :         case PQUOTE_SQL_IDENT:
     150             :             {
     151             :                 /*
     152             :                  * For these cases, we use libpq's quoting functions, which
     153             :                  * assume the string is in the connection's client encoding.
     154             :                  */
     155             :                 char       *escaped_value;
     156             : 
     157          28 :                 if (!pset.db)
     158             :                 {
     159           0 :                     pg_log_error("cannot escape without active connection");
     160           0 :                     return NULL;
     161             :                 }
     162             : 
     163          28 :                 if (quote == PQUOTE_SQL_LITERAL)
     164             :                     escaped_value =
     165          24 :                         PQescapeLiteral(pset.db, value, strlen(value));
     166             :                 else
     167             :                     escaped_value =
     168           4 :                         PQescapeIdentifier(pset.db, value, strlen(value));
     169             : 
     170          28 :                 if (escaped_value == NULL)
     171             :                 {
     172           0 :                     const char *error = PQerrorMessage(pset.db);
     173             : 
     174           0 :                     pg_log_info("%s", error);
     175           0 :                     return NULL;
     176             :                 }
     177             : 
     178             :                 /*
     179             :                  * Rather than complicate the lexer's API with a notion of
     180             :                  * which free() routine to use, just pay the price of an extra
     181             :                  * strdup().
     182             :                  */
     183          28 :                 result = pg_strdup(escaped_value);
     184          28 :                 PQfreemem(escaped_value);
     185          28 :                 break;
     186             :             }
     187           0 :         case PQUOTE_SHELL_ARG:
     188             :             {
     189             :                 /*
     190             :                  * For this we use appendShellStringNoError, which is
     191             :                  * encoding-agnostic, which is fine since the shell probably
     192             :                  * is too.  In any case, the only special character is "'",
     193             :                  * which is not known to appear in valid multibyte characters.
     194             :                  */
     195             :                 PQExpBufferData buf;
     196             : 
     197           0 :                 initPQExpBuffer(&buf);
     198           0 :                 if (!appendShellStringNoError(&buf, value))
     199             :                 {
     200           0 :                     pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
     201             :                                  value);
     202           0 :                     free(buf.data);
     203           0 :                     return NULL;
     204             :                 }
     205           0 :                 result = buf.data;
     206           0 :                 break;
     207             :             }
     208             : 
     209             :             /* No default: we want a compiler warning for missing cases */
     210             :     }
     211             : 
     212         616 :     return result;
     213             : }
     214             : 
     215             : 
     216             : /*
     217             :  * for backend Notice messages (INFO, WARNING, etc)
     218             :  */
     219             : void
     220       10974 : NoticeProcessor(void *arg, const char *message)
     221             : {
     222             :     (void) arg;                 /* not used */
     223       10974 :     pg_log_info("%s", message);
     224       10974 : }
     225             : 
     226             : 
     227             : 
     228             : /*
     229             :  * Code to support query cancellation
     230             :  *
     231             :  * Before we start a query, we enable the SIGINT signal catcher to send a
     232             :  * cancel request to the backend.
     233             :  *
     234             :  * SIGINT is supposed to abort all long-running psql operations, not only
     235             :  * database queries.  In most places, this is accomplished by checking
     236             :  * cancel_pressed during long-running loops.  However, that won't work when
     237             :  * blocked on user input (in readline() or fgets()).  In those places, we
     238             :  * set sigint_interrupt_enabled true while blocked, instructing the signal
     239             :  * catcher to longjmp through sigint_interrupt_jmp.  We assume readline and
     240             :  * fgets are coded to handle possible interruption.
     241             :  *
     242             :  * On Windows, currently this does not work, so control-C is less useful
     243             :  * there, and the callback is just a no-op.
     244             :  */
     245             : volatile bool sigint_interrupt_enabled = false;
     246             : 
     247             : sigjmp_buf  sigint_interrupt_jmp;
     248             : 
     249             : static void
     250           0 : psql_cancel_callback(void)
     251             : {
     252             : #ifndef WIN32
     253             :     /* if we are waiting for input, longjmp out of it */
     254           0 :     if (sigint_interrupt_enabled)
     255             :     {
     256           0 :         sigint_interrupt_enabled = false;
     257           0 :         siglongjmp(sigint_interrupt_jmp, 1);
     258             :     }
     259             : #endif
     260             : 
     261             :     /* else, set cancel flag to stop any long-running loops */
     262           0 :     cancel_pressed = true;
     263           0 : }
     264             : 
     265             : void
     266        4680 : psql_setup_cancel_handler(void)
     267             : {
     268        4680 :     setup_cancel_handler(psql_cancel_callback);
     269        4680 : }
     270             : 
     271             : 
     272             : /* ConnectionUp
     273             :  *
     274             :  * Returns whether our backend connection is still there.
     275             :  */
     276             : static bool
     277       17988 : ConnectionUp(void)
     278             : {
     279       17988 :     return PQstatus(pset.db) != CONNECTION_BAD;
     280             : }
     281             : 
     282             : 
     283             : 
     284             : /* CheckConnection
     285             :  *
     286             :  * Verify that we still have a good connection to the backend, and if not,
     287             :  * see if it can be restored.
     288             :  *
     289             :  * Returns true if either the connection was still there, or it could be
     290             :  * restored successfully; false otherwise.  If, however, there was no
     291             :  * connection and the session is non-interactive, this will exit the program
     292             :  * with a code of EXIT_BADCONN.
     293             :  */
     294             : static bool
     295       17988 : CheckConnection(void)
     296             : {
     297             :     bool        OK;
     298             : 
     299       17988 :     OK = ConnectionUp();
     300       17988 :     if (!OK)
     301             :     {
     302           8 :         if (!pset.cur_cmd_interactive)
     303             :         {
     304           8 :             pg_log_fatal("connection to server was lost");
     305           8 :             exit(EXIT_BADCONN);
     306             :         }
     307             : 
     308           0 :         fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
     309           0 :         PQreset(pset.db);
     310           0 :         OK = ConnectionUp();
     311           0 :         if (!OK)
     312             :         {
     313           0 :             fprintf(stderr, _("Failed.\n"));
     314             : 
     315             :             /*
     316             :              * Transition to having no connection.  Keep this bit in sync with
     317             :              * do_connect().
     318             :              */
     319           0 :             PQfinish(pset.db);
     320           0 :             pset.db = NULL;
     321           0 :             ResetCancelConn();
     322           0 :             UnsyncVariables();
     323             :         }
     324             :         else
     325             :         {
     326           0 :             fprintf(stderr, _("Succeeded.\n"));
     327             : 
     328             :             /*
     329             :              * Re-sync, just in case anything changed.  Keep this in sync with
     330             :              * do_connect().
     331             :              */
     332           0 :             SyncVariables();
     333           0 :             connection_warnings(false); /* Must be after SyncVariables */
     334             :         }
     335             :     }
     336             : 
     337       17980 :     return OK;
     338             : }
     339             : 
     340             : 
     341             : 
     342             : 
     343             : /*
     344             :  * AcceptResult
     345             :  *
     346             :  * Checks whether a result is valid, giving an error message if necessary;
     347             :  * and ensures that the connection to the backend is still up.
     348             :  *
     349             :  * Returns true for valid result, false for error state.
     350             :  */
     351             : static bool
     352      174216 : AcceptResult(const PGresult *result)
     353             : {
     354             :     bool        OK;
     355             : 
     356      174216 :     if (!result)
     357           0 :         OK = false;
     358             :     else
     359      174216 :         switch (PQresultStatus(result))
     360             :         {
     361      156240 :             case PGRES_COMMAND_OK:
     362             :             case PGRES_TUPLES_OK:
     363             :             case PGRES_EMPTY_QUERY:
     364             :             case PGRES_COPY_IN:
     365             :             case PGRES_COPY_OUT:
     366             :                 /* Fine, do nothing */
     367      156240 :                 OK = true;
     368      156240 :                 break;
     369             : 
     370       17976 :             case PGRES_BAD_RESPONSE:
     371             :             case PGRES_NONFATAL_ERROR:
     372             :             case PGRES_FATAL_ERROR:
     373       17976 :                 OK = false;
     374       17976 :                 break;
     375             : 
     376           0 :             default:
     377           0 :                 OK = false;
     378           0 :                 pg_log_error("unexpected PQresultStatus: %d",
     379             :                              PQresultStatus(result));
     380           0 :                 break;
     381             :         }
     382             : 
     383      174216 :     if (!OK)
     384             :     {
     385       17976 :         const char *error = PQerrorMessage(pset.db);
     386             : 
     387       17976 :         if (strlen(error))
     388       17976 :             pg_log_info("%s", error);
     389             : 
     390       17976 :         CheckConnection();
     391             :     }
     392             : 
     393      174208 :     return OK;
     394             : }
     395             : 
     396             : 
     397             : /*
     398             :  * Set special variables from a query result
     399             :  * - ERROR: true/false, whether an error occurred on this query
     400             :  * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
     401             :  * - ROW_COUNT: how many rows were returned or affected, or "0"
     402             :  * - LAST_ERROR_SQLSTATE: same for last error
     403             :  * - LAST_ERROR_MESSAGE: message of last error
     404             :  *
     405             :  * Note: current policy is to apply this only to the results of queries
     406             :  * entered by the user, not queries generated by slash commands.
     407             :  */
     408             : static void
     409      159052 : SetResultVariables(PGresult *results, bool success)
     410             : {
     411      159052 :     if (success)
     412             :     {
     413      141008 :         const char *ntuples = PQcmdTuples(results);
     414             : 
     415      141008 :         SetVariable(pset.vars, "ERROR", "false");
     416      141008 :         SetVariable(pset.vars, "SQLSTATE", "00000");
     417      141008 :         SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
     418             :     }
     419             :     else
     420             :     {
     421       18044 :         const char *code = PQresultErrorField(results, PG_DIAG_SQLSTATE);
     422       18044 :         const char *mesg = PQresultErrorField(results, PG_DIAG_MESSAGE_PRIMARY);
     423             : 
     424       18044 :         SetVariable(pset.vars, "ERROR", "true");
     425             : 
     426             :         /*
     427             :          * If there is no SQLSTATE code, use an empty string.  This can happen
     428             :          * for libpq-detected errors (e.g., lost connection, ENOMEM).
     429             :          */
     430       18044 :         if (code == NULL)
     431           2 :             code = "";
     432       18044 :         SetVariable(pset.vars, "SQLSTATE", code);
     433       18044 :         SetVariable(pset.vars, "ROW_COUNT", "0");
     434       18044 :         SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
     435       18044 :         SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
     436             :     }
     437      159052 : }
     438             : 
     439             : 
     440             : /*
     441             :  * ClearOrSaveResult
     442             :  *
     443             :  * If the result represents an error, remember it for possible display by
     444             :  * \errverbose.  Otherwise, just PQclear() it.
     445             :  *
     446             :  * Note: current policy is to apply this to the results of all queries,
     447             :  * including "back door" queries, for debugging's sake.  It's OK to use
     448             :  * PQclear() directly on results known to not be error results, however.
     449             :  */
     450             : static void
     451      159436 : ClearOrSaveResult(PGresult *result)
     452             : {
     453      159436 :     if (result)
     454             :     {
     455      159092 :         switch (PQresultStatus(result))
     456             :         {
     457       18044 :             case PGRES_NONFATAL_ERROR:
     458             :             case PGRES_FATAL_ERROR:
     459       18044 :                 if (pset.last_error_result)
     460       17186 :                     PQclear(pset.last_error_result);
     461       18044 :                 pset.last_error_result = result;
     462       18044 :                 break;
     463             : 
     464      141048 :             default:
     465      141048 :                 PQclear(result);
     466      141048 :                 break;
     467             :         }
     468         344 :     }
     469      159436 : }
     470             : 
     471             : 
     472             : /*
     473             :  * Print microtiming output.  Always print raw milliseconds; if the interval
     474             :  * is >= 1 second, also break it down into days/hours/minutes/seconds.
     475             :  */
     476             : static void
     477           0 : PrintTiming(double elapsed_msec)
     478             : {
     479             :     double      seconds;
     480             :     double      minutes;
     481             :     double      hours;
     482             :     double      days;
     483             : 
     484           0 :     if (elapsed_msec < 1000.0)
     485             :     {
     486             :         /* This is the traditional (pre-v10) output format */
     487           0 :         printf(_("Time: %.3f ms\n"), elapsed_msec);
     488           0 :         return;
     489             :     }
     490             : 
     491             :     /*
     492             :      * Note: we could print just seconds, in a format like %06.3f, when the
     493             :      * total is less than 1min.  But that's hard to interpret unless we tack
     494             :      * on "s" or otherwise annotate it.  Forcing the display to include
     495             :      * minutes seems like a better solution.
     496             :      */
     497           0 :     seconds = elapsed_msec / 1000.0;
     498           0 :     minutes = floor(seconds / 60.0);
     499           0 :     seconds -= 60.0 * minutes;
     500           0 :     if (minutes < 60.0)
     501             :     {
     502           0 :         printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
     503             :                elapsed_msec, (int) minutes, seconds);
     504           0 :         return;
     505             :     }
     506             : 
     507           0 :     hours = floor(minutes / 60.0);
     508           0 :     minutes -= 60.0 * hours;
     509           0 :     if (hours < 24.0)
     510             :     {
     511           0 :         printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
     512             :                elapsed_msec, (int) hours, (int) minutes, seconds);
     513           0 :         return;
     514             :     }
     515             : 
     516           0 :     days = floor(hours / 24.0);
     517           0 :     hours -= 24.0 * days;
     518           0 :     printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
     519             :            elapsed_msec, days, (int) hours, (int) minutes, seconds);
     520             : }
     521             : 
     522             : 
     523             : /*
     524             :  * PSQLexec
     525             :  *
     526             :  * This is the way to send "backdoor" queries (those not directly entered
     527             :  * by the user). It is subject to -E but not -e.
     528             :  *
     529             :  * Caller is responsible for handling the ensuing processing if a COPY
     530             :  * command is sent.
     531             :  *
     532             :  * Note: we don't bother to check PQclientEncoding; it is assumed that no
     533             :  * caller uses this path to issue "SET CLIENT_ENCODING".
     534             :  */
     535             : PGresult *
     536       14920 : PSQLexec(const char *query)
     537             : {
     538             :     PGresult   *res;
     539             : 
     540       14920 :     if (!pset.db)
     541             :     {
     542           0 :         pg_log_error("You are currently not connected to a database.");
     543           0 :         return NULL;
     544             :     }
     545             : 
     546       14920 :     if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
     547             :     {
     548           0 :         printf(_("********* QUERY **********\n"
     549             :                  "%s\n"
     550             :                  "**************************\n\n"), query);
     551           0 :         fflush(stdout);
     552           0 :         if (pset.logfile)
     553             :         {
     554           0 :             fprintf(pset.logfile,
     555           0 :                     _("********* QUERY **********\n"
     556             :                       "%s\n"
     557             :                       "**************************\n\n"), query);
     558           0 :             fflush(pset.logfile);
     559             :         }
     560             : 
     561           0 :         if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
     562           0 :             return NULL;
     563             :     }
     564             : 
     565       14920 :     SetCancelConn(pset.db);
     566             : 
     567       14920 :     res = PQexec(pset.db, query);
     568             : 
     569       14920 :     ResetCancelConn();
     570             : 
     571       14920 :     if (!AcceptResult(res))
     572             :     {
     573           0 :         ClearOrSaveResult(res);
     574           0 :         res = NULL;
     575             :     }
     576             : 
     577       14920 :     return res;
     578             : }
     579             : 
     580             : 
     581             : /*
     582             :  * PSQLexecWatch
     583             :  *
     584             :  * This function is used for \watch command to send the query to
     585             :  * the server and print out the results.
     586             :  *
     587             :  * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
     588             :  * e.g., because of the interrupt, -1 on error.
     589             :  */
     590             : int
     591           0 : PSQLexecWatch(const char *query, const printQueryOpt *opt)
     592             : {
     593             :     PGresult   *res;
     594           0 :     double      elapsed_msec = 0;
     595             :     instr_time  before;
     596             :     instr_time  after;
     597             : 
     598           0 :     if (!pset.db)
     599             :     {
     600           0 :         pg_log_error("You are currently not connected to a database.");
     601           0 :         return 0;
     602             :     }
     603             : 
     604           0 :     SetCancelConn(pset.db);
     605             : 
     606           0 :     if (pset.timing)
     607           0 :         INSTR_TIME_SET_CURRENT(before);
     608             : 
     609           0 :     res = PQexec(pset.db, query);
     610             : 
     611           0 :     ResetCancelConn();
     612             : 
     613           0 :     if (!AcceptResult(res))
     614             :     {
     615           0 :         ClearOrSaveResult(res);
     616           0 :         return 0;
     617             :     }
     618             : 
     619           0 :     if (pset.timing)
     620             :     {
     621           0 :         INSTR_TIME_SET_CURRENT(after);
     622           0 :         INSTR_TIME_SUBTRACT(after, before);
     623           0 :         elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
     624             :     }
     625             : 
     626             :     /*
     627             :      * If SIGINT is sent while the query is processing, the interrupt will be
     628             :      * consumed.  The user's intention, though, is to cancel the entire watch
     629             :      * process, so detect a sent cancellation request and exit in this case.
     630             :      */
     631           0 :     if (cancel_pressed)
     632             :     {
     633           0 :         PQclear(res);
     634           0 :         return 0;
     635             :     }
     636             : 
     637           0 :     switch (PQresultStatus(res))
     638             :     {
     639           0 :         case PGRES_TUPLES_OK:
     640           0 :             printQuery(res, opt, pset.queryFout, false, pset.logfile);
     641           0 :             break;
     642             : 
     643           0 :         case PGRES_COMMAND_OK:
     644           0 :             fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
     645           0 :             break;
     646             : 
     647           0 :         case PGRES_EMPTY_QUERY:
     648           0 :             pg_log_error("\\watch cannot be used with an empty query");
     649           0 :             PQclear(res);
     650           0 :             return -1;
     651             : 
     652           0 :         case PGRES_COPY_OUT:
     653             :         case PGRES_COPY_IN:
     654             :         case PGRES_COPY_BOTH:
     655           0 :             pg_log_error("\\watch cannot be used with COPY");
     656           0 :             PQclear(res);
     657           0 :             return -1;
     658             : 
     659           0 :         default:
     660           0 :             pg_log_error("unexpected result status for \\watch");
     661           0 :             PQclear(res);
     662           0 :             return -1;
     663             :     }
     664             : 
     665           0 :     PQclear(res);
     666             : 
     667           0 :     fflush(pset.queryFout);
     668             : 
     669             :     /* Possible microtiming output */
     670           0 :     if (pset.timing)
     671           0 :         PrintTiming(elapsed_msec);
     672             : 
     673           0 :     return 1;
     674             : }
     675             : 
     676             : 
     677             : /*
     678             :  * PrintNotifications: check for asynchronous notifications, and print them out
     679             :  */
     680             : static void
     681      159100 : PrintNotifications(void)
     682             : {
     683             :     PGnotify   *notify;
     684             : 
     685      159100 :     PQconsumeInput(pset.db);
     686      159100 :     while ((notify = PQnotifies(pset.db)) != NULL)
     687             :     {
     688             :         /* for backward compatibility, only show payload if nonempty */
     689           0 :         if (notify->extra[0])
     690           0 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
     691             :                     notify->relname, notify->extra, notify->be_pid);
     692             :         else
     693           0 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
     694             :                     notify->relname, notify->be_pid);
     695           0 :         fflush(pset.queryFout);
     696           0 :         PQfreemem(notify);
     697           0 :         PQconsumeInput(pset.db);
     698             :     }
     699      159100 : }
     700             : 
     701             : 
     702             : /*
     703             :  * PrintQueryTuples: assuming query result is OK, print its tuples
     704             :  *
     705             :  * Returns true if successful, false otherwise.
     706             :  */
     707             : static bool
     708       60830 : PrintQueryTuples(const PGresult *results)
     709             : {
     710       60830 :     bool        result = true;
     711             : 
     712             :     /* write output to \g argument, if any */
     713       60830 :     if (pset.gfname)
     714             :     {
     715             :         FILE       *fout;
     716             :         bool        is_pipe;
     717             : 
     718           0 :         if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
     719           0 :             return false;
     720           0 :         if (is_pipe)
     721           0 :             disable_sigpipe_trap();
     722             : 
     723           0 :         printQuery(results, &pset.popt, fout, false, pset.logfile);
     724           0 :         if (ferror(fout))
     725             :         {
     726           0 :             pg_log_error("could not print result table: %m");
     727           0 :             result = false;
     728             :         }
     729             : 
     730           0 :         if (is_pipe)
     731             :         {
     732           0 :             pclose(fout);
     733           0 :             restore_sigpipe_trap();
     734             :         }
     735             :         else
     736           0 :             fclose(fout);
     737             :     }
     738             :     else
     739             :     {
     740       60830 :         printQuery(results, &pset.popt, pset.queryFout, false, pset.logfile);
     741       60830 :         if (ferror(pset.queryFout))
     742             :         {
     743           0 :             pg_log_error("could not print result table: %m");
     744           0 :             result = false;
     745             :         }
     746             :     }
     747             : 
     748       60830 :     return result;
     749             : }
     750             : 
     751             : 
     752             : /*
     753             :  * StoreQueryTuple: assuming query result is OK, save data into variables
     754             :  *
     755             :  * Returns true if successful, false otherwise.
     756             :  */
     757             : static bool
     758         148 : StoreQueryTuple(const PGresult *result)
     759             : {
     760         148 :     bool        success = true;
     761             : 
     762         148 :     if (PQntuples(result) < 1)
     763             :     {
     764           8 :         pg_log_error("no rows returned for \\gset");
     765           8 :         success = false;
     766             :     }
     767         140 :     else if (PQntuples(result) > 1)
     768             :     {
     769           8 :         pg_log_error("more than one row returned for \\gset");
     770           8 :         success = false;
     771             :     }
     772             :     else
     773             :     {
     774             :         int         i;
     775             : 
     776         300 :         for (i = 0; i < PQnfields(result); i++)
     777             :         {
     778         172 :             char       *colname = PQfname(result, i);
     779             :             char       *varname;
     780             :             char       *value;
     781             : 
     782             :             /* concatenate prefix and column name */
     783         172 :             varname = psprintf("%s%s", pset.gset_prefix, colname);
     784             : 
     785         172 :             if (!PQgetisnull(result, 0, i))
     786         168 :                 value = PQgetvalue(result, 0, i);
     787             :             else
     788             :             {
     789             :                 /* for NULL value, unset rather than set the variable */
     790           4 :                 value = NULL;
     791             :             }
     792             : 
     793         172 :             if (!SetVariable(pset.vars, varname, value))
     794             :             {
     795           4 :                 free(varname);
     796           4 :                 success = false;
     797           4 :                 break;
     798             :             }
     799             : 
     800         168 :             free(varname);
     801             :         }
     802             :     }
     803             : 
     804         148 :     return success;
     805             : }
     806             : 
     807             : 
     808             : /*
     809             :  * ExecQueryTuples: assuming query result is OK, execute each query
     810             :  * result field as a SQL statement
     811             :  *
     812             :  * Returns true if successful, false otherwise.
     813             :  */
     814             : static bool
     815          20 : ExecQueryTuples(const PGresult *result)
     816             : {
     817          20 :     bool        success = true;
     818          20 :     int         nrows = PQntuples(result);
     819          20 :     int         ncolumns = PQnfields(result);
     820             :     int         r,
     821             :                 c;
     822             : 
     823             :     /*
     824             :      * We must turn off gexec_flag to avoid infinite recursion.  Note that
     825             :      * this allows ExecQueryUsingCursor to be applied to the individual query
     826             :      * results.  SendQuery prevents it from being applied when fetching the
     827             :      * queries-to-execute, because it can't handle recursion either.
     828             :      */
     829          20 :     pset.gexec_flag = false;
     830             : 
     831         188 :     for (r = 0; r < nrows; r++)
     832             :     {
     833         348 :         for (c = 0; c < ncolumns; c++)
     834             :         {
     835         180 :             if (!PQgetisnull(result, r, c))
     836             :             {
     837         176 :                 const char *query = PQgetvalue(result, r, c);
     838             : 
     839             :                 /* Abandon execution if cancel_pressed */
     840         176 :                 if (cancel_pressed)
     841           0 :                     goto loop_exit;
     842             : 
     843             :                 /*
     844             :                  * ECHO_ALL mode should echo these queries, but SendQuery
     845             :                  * assumes that MainLoop did that, so we have to do it here.
     846             :                  */
     847         176 :                 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
     848             :                 {
     849         172 :                     puts(query);
     850         172 :                     fflush(stdout);
     851             :                 }
     852             : 
     853         176 :                 if (!SendQuery(query))
     854             :                 {
     855             :                     /* Error - abandon execution if ON_ERROR_STOP */
     856           4 :                     success = false;
     857           4 :                     if (pset.on_error_stop)
     858           0 :                         goto loop_exit;
     859             :                 }
     860             :             }
     861             :         }
     862             :     }
     863             : 
     864          20 : loop_exit:
     865             : 
     866             :     /*
     867             :      * Restore state.  We know gexec_flag was on, else we'd not be here. (We
     868             :      * also know it'll get turned off at end of command, but that's not ours
     869             :      * to do here.)
     870             :      */
     871          20 :     pset.gexec_flag = true;
     872             : 
     873             :     /* Return true if all queries were successful */
     874          20 :     return success;
     875             : }
     876             : 
     877             : 
     878             : /*
     879             :  * ProcessResult: utility function for use by SendQuery() only
     880             :  *
     881             :  * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
     882             :  * PQexec() has stopped at the PGresult associated with the first such
     883             :  * command.  In that event, we'll marshal data for the COPY and then cycle
     884             :  * through any subsequent PGresult objects.
     885             :  *
     886             :  * When the command string contained no such COPY command, this function
     887             :  * degenerates to an AcceptResult() call.
     888             :  *
     889             :  * Changes its argument to point to the last PGresult of the command string,
     890             :  * or NULL if that result was for a COPY TO STDOUT.  (Returning NULL prevents
     891             :  * the command status from being printed, which we want in that case so that
     892             :  * the status line doesn't get taken as part of the COPY data.)
     893             :  *
     894             :  * Returns true on complete success, false otherwise.  Possible failure modes
     895             :  * include purely client-side problems; check the transaction status for the
     896             :  * server-side opinion.
     897             :  */
     898             : static bool
     899      159016 : ProcessResult(PGresult **results)
     900             : {
     901      159016 :     bool        success = true;
     902      159016 :     bool        first_cycle = true;
     903             : 
     904             :     for (;;)
     905          24 :     {
     906             :         ExecStatusType result_status;
     907             :         bool        is_copy;
     908             :         PGresult   *next_result;
     909             : 
     910      159040 :         if (!AcceptResult(*results))
     911             :         {
     912             :             /*
     913             :              * Failure at this point is always a server-side failure or a
     914             :              * failure to submit the command string.  Either way, we're
     915             :              * finished with this command string.
     916             :              */
     917       17964 :             success = false;
     918       17964 :             break;
     919             :         }
     920             : 
     921      141068 :         result_status = PQresultStatus(*results);
     922      141068 :         switch (result_status)
     923             :         {
     924      140348 :             case PGRES_EMPTY_QUERY:
     925             :             case PGRES_COMMAND_OK:
     926             :             case PGRES_TUPLES_OK:
     927      140348 :                 is_copy = false;
     928      140348 :                 break;
     929             : 
     930         720 :             case PGRES_COPY_OUT:
     931             :             case PGRES_COPY_IN:
     932         720 :                 is_copy = true;
     933         720 :                 break;
     934             : 
     935           0 :             default:
     936             :                 /* AcceptResult() should have caught anything else. */
     937           0 :                 is_copy = false;
     938           0 :                 pg_log_error("unexpected PQresultStatus: %d", result_status);
     939           0 :                 break;
     940             :         }
     941             : 
     942      141068 :         if (is_copy)
     943             :         {
     944             :             /*
     945             :              * Marshal the COPY data.  Either subroutine will get the
     946             :              * connection out of its COPY state, then call PQresultStatus()
     947             :              * once and report any error.
     948             :              *
     949             :              * For COPY OUT, direct the output to pset.copyStream if it's set,
     950             :              * otherwise to pset.gfname if it's set, otherwise to queryFout.
     951             :              * For COPY IN, use pset.copyStream as data source if it's set,
     952             :              * otherwise cur_cmd_source.
     953             :              */
     954             :             FILE       *copystream;
     955             :             PGresult   *copy_result;
     956             : 
     957         720 :             SetCancelConn(pset.db);
     958         720 :             if (result_status == PGRES_COPY_OUT)
     959             :             {
     960         264 :                 bool        need_close = false;
     961         264 :                 bool        is_pipe = false;
     962             : 
     963         264 :                 if (pset.copyStream)
     964             :                 {
     965             :                     /* invoked by \copy */
     966          36 :                     copystream = pset.copyStream;
     967             :                 }
     968         228 :                 else if (pset.gfname)
     969             :                 {
     970             :                     /* invoked by \g */
     971           0 :                     if (openQueryOutputFile(pset.gfname,
     972             :                                             &copystream, &is_pipe))
     973             :                     {
     974           0 :                         need_close = true;
     975           0 :                         if (is_pipe)
     976           0 :                             disable_sigpipe_trap();
     977             :                     }
     978             :                     else
     979           0 :                         copystream = NULL;  /* discard COPY data entirely */
     980             :                 }
     981             :                 else
     982             :                 {
     983             :                     /* fall back to the generic query output stream */
     984         228 :                     copystream = pset.queryFout;
     985             :                 }
     986             : 
     987         264 :                 success = handleCopyOut(pset.db,
     988             :                                         copystream,
     989             :                                         &copy_result)
     990         264 :                     && success
     991         528 :                     && (copystream != NULL);
     992             : 
     993             :                 /*
     994             :                  * Suppress status printing if the report would go to the same
     995             :                  * place as the COPY data just went.  Note this doesn't
     996             :                  * prevent error reporting, since handleCopyOut did that.
     997             :                  */
     998         264 :                 if (copystream == pset.queryFout)
     999             :                 {
    1000         264 :                     PQclear(copy_result);
    1001         264 :                     copy_result = NULL;
    1002             :                 }
    1003             : 
    1004         264 :                 if (need_close)
    1005             :                 {
    1006             :                     /* close \g argument file/pipe */
    1007           0 :                     if (is_pipe)
    1008             :                     {
    1009           0 :                         pclose(copystream);
    1010           0 :                         restore_sigpipe_trap();
    1011             :                     }
    1012             :                     else
    1013             :                     {
    1014           0 :                         fclose(copystream);
    1015             :                     }
    1016             :                 }
    1017             :             }
    1018             :             else
    1019             :             {
    1020             :                 /* COPY IN */
    1021         456 :                 copystream = pset.copyStream ? pset.copyStream : pset.cur_cmd_source;
    1022         912 :                 success = handleCopyIn(pset.db,
    1023             :                                        copystream,
    1024         456 :                                        PQbinaryTuples(*results),
    1025         456 :                                        &copy_result) && success;
    1026             :             }
    1027         720 :             ResetCancelConn();
    1028             : 
    1029             :             /*
    1030             :              * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
    1031             :              * status, or with NULL if we want to suppress printing anything.
    1032             :              */
    1033         720 :             PQclear(*results);
    1034         720 :             *results = copy_result;
    1035             :         }
    1036      140348 :         else if (first_cycle)
    1037             :         {
    1038             :             /* fast path: no COPY commands; PQexec visited all results */
    1039      140336 :             break;
    1040             :         }
    1041             : 
    1042             :         /*
    1043             :          * Check PQgetResult() again.  In the typical case of a single-command
    1044             :          * string, it will return NULL.  Otherwise, we'll have other results
    1045             :          * to process that may include other COPYs.  We keep the last result.
    1046             :          */
    1047         732 :         next_result = PQgetResult(pset.db);
    1048         732 :         if (!next_result)
    1049         708 :             break;
    1050             : 
    1051          24 :         PQclear(*results);
    1052          24 :         *results = next_result;
    1053          24 :         first_cycle = false;
    1054             :     }
    1055             : 
    1056      159008 :     SetResultVariables(*results, success);
    1057             : 
    1058             :     /* may need this to recover from conn loss during COPY */
    1059      159008 :     if (!first_cycle && !CheckConnection())
    1060           0 :         return false;
    1061             : 
    1062      159008 :     return success;
    1063             : }
    1064             : 
    1065             : 
    1066             : /*
    1067             :  * PrintQueryStatus: report command status as required
    1068             :  *
    1069             :  * Note: Utility function for use by PrintQueryResults() only.
    1070             :  */
    1071             : static void
    1072       79988 : PrintQueryStatus(PGresult *results)
    1073             : {
    1074             :     char        buf[16];
    1075             : 
    1076       79988 :     if (!pset.quiet)
    1077             :     {
    1078         958 :         if (pset.popt.topt.format == PRINT_HTML)
    1079             :         {
    1080           0 :             fputs("<p>", pset.queryFout);
    1081           0 :             html_escaped_print(PQcmdStatus(results), pset.queryFout);
    1082           0 :             fputs("</p>\n", pset.queryFout);
    1083             :         }
    1084             :         else
    1085         958 :             fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
    1086             :     }
    1087             : 
    1088       79988 :     if (pset.logfile)
    1089           0 :         fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
    1090             : 
    1091       79988 :     snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
    1092       79988 :     SetVariable(pset.vars, "LASTOID", buf);
    1093       79988 : }
    1094             : 
    1095             : 
    1096             : /*
    1097             :  * PrintQueryResults: print out (or store or execute) query results as required
    1098             :  *
    1099             :  * Note: Utility function for use by SendQuery() only.
    1100             :  *
    1101             :  * Returns true if the query executed successfully, false otherwise.
    1102             :  */
    1103             : static bool
    1104      140748 : PrintQueryResults(PGresult *results)
    1105             : {
    1106             :     bool        success;
    1107             :     const char *cmdstatus;
    1108             : 
    1109      140748 :     if (!results)
    1110           0 :         return false;
    1111             : 
    1112      140748 :     switch (PQresultStatus(results))
    1113             :     {
    1114       61070 :         case PGRES_TUPLES_OK:
    1115             :             /* store or execute or print the data ... */
    1116       61070 :             if (pset.gset_prefix)
    1117         132 :                 success = StoreQueryTuple(results);
    1118       60938 :             else if (pset.gexec_flag)
    1119          20 :                 success = ExecQueryTuples(results);
    1120       60918 :             else if (pset.crosstab_flag)
    1121          88 :                 success = PrintResultsInCrosstab(results);
    1122             :             else
    1123       60830 :                 success = PrintQueryTuples(results);
    1124             :             /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
    1125       61070 :             cmdstatus = PQcmdStatus(results);
    1126       61070 :             if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
    1127       60794 :                 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
    1128       60544 :                 strncmp(cmdstatus, "DELETE", 6) == 0)
    1129         630 :                 PrintQueryStatus(results);
    1130       61070 :             break;
    1131             : 
    1132       79358 :         case PGRES_COMMAND_OK:
    1133       79358 :             PrintQueryStatus(results);
    1134       79358 :             success = true;
    1135       79358 :             break;
    1136             : 
    1137         320 :         case PGRES_EMPTY_QUERY:
    1138         320 :             success = true;
    1139         320 :             break;
    1140             : 
    1141           0 :         case PGRES_COPY_OUT:
    1142             :         case PGRES_COPY_IN:
    1143             :             /* nothing to do here */
    1144           0 :             success = true;
    1145           0 :             break;
    1146             : 
    1147           0 :         case PGRES_BAD_RESPONSE:
    1148             :         case PGRES_NONFATAL_ERROR:
    1149             :         case PGRES_FATAL_ERROR:
    1150           0 :             success = false;
    1151           0 :             break;
    1152             : 
    1153           0 :         default:
    1154           0 :             success = false;
    1155           0 :             pg_log_error("unexpected PQresultStatus: %d",
    1156             :                          PQresultStatus(results));
    1157           0 :             break;
    1158             :     }
    1159             : 
    1160      140748 :     fflush(pset.queryFout);
    1161             : 
    1162      140748 :     return success;
    1163             : }
    1164             : 
    1165             : 
    1166             : /*
    1167             :  * SendQuery: send the query string to the backend
    1168             :  * (and print out results)
    1169             :  *
    1170             :  * Note: This is the "front door" way to send a query. That is, use it to
    1171             :  * send queries actually entered by the user. These queries will be subject to
    1172             :  * single step mode.
    1173             :  * To send "back door" queries (generated by slash commands, etc.) in a
    1174             :  * controlled way, use PSQLexec().
    1175             :  *
    1176             :  * Returns true if the query executed successfully, false otherwise.
    1177             :  */
    1178             : bool
    1179      159108 : SendQuery(const char *query)
    1180             : {
    1181             :     PGresult   *results;
    1182             :     PGTransactionStatusType transaction_status;
    1183      159108 :     double      elapsed_msec = 0;
    1184      159108 :     bool        OK = false;
    1185             :     int         i;
    1186      159108 :     bool        on_error_rollback_savepoint = false;
    1187             :     static bool on_error_rollback_warning = false;
    1188             : 
    1189      159108 :     if (!pset.db)
    1190             :     {
    1191           0 :         pg_log_error("You are currently not connected to a database.");
    1192           0 :         goto sendquery_cleanup;
    1193             :     }
    1194             : 
    1195      159108 :     if (pset.singlestep)
    1196             :     {
    1197             :         char        buf[3];
    1198             : 
    1199           0 :         fflush(stderr);
    1200           0 :         printf(_("***(Single step mode: verify command)*******************************************\n"
    1201             :                  "%s\n"
    1202             :                  "***(press return to proceed or enter x and return to cancel)********************\n"),
    1203             :                query);
    1204           0 :         fflush(stdout);
    1205           0 :         if (fgets(buf, sizeof(buf), stdin) != NULL)
    1206           0 :             if (buf[0] == 'x')
    1207           0 :                 goto sendquery_cleanup;
    1208           0 :         if (cancel_pressed)
    1209           0 :             goto sendquery_cleanup;
    1210             :     }
    1211      159108 :     else if (pset.echo == PSQL_ECHO_QUERIES)
    1212             :     {
    1213          10 :         puts(query);
    1214          10 :         fflush(stdout);
    1215             :     }
    1216             : 
    1217      159108 :     if (pset.logfile)
    1218             :     {
    1219           0 :         fprintf(pset.logfile,
    1220           0 :                 _("********* QUERY **********\n"
    1221             :                   "%s\n"
    1222             :                   "**************************\n\n"), query);
    1223           0 :         fflush(pset.logfile);
    1224             :     }
    1225             : 
    1226      159108 :     SetCancelConn(pset.db);
    1227             : 
    1228      159108 :     transaction_status = PQtransactionStatus(pset.db);
    1229             : 
    1230      159108 :     if (transaction_status == PQTRANS_IDLE &&
    1231      145310 :         !pset.autocommit &&
    1232           0 :         !command_no_begin(query))
    1233             :     {
    1234           0 :         results = PQexec(pset.db, "BEGIN");
    1235           0 :         if (PQresultStatus(results) != PGRES_COMMAND_OK)
    1236             :         {
    1237           0 :             pg_log_info("%s", PQerrorMessage(pset.db));
    1238           0 :             ClearOrSaveResult(results);
    1239           0 :             ResetCancelConn();
    1240           0 :             goto sendquery_cleanup;
    1241             :         }
    1242           0 :         ClearOrSaveResult(results);
    1243           0 :         transaction_status = PQtransactionStatus(pset.db);
    1244             :     }
    1245             : 
    1246      159108 :     if (transaction_status == PQTRANS_INTRANS &&
    1247       13270 :         pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
    1248           0 :         (pset.cur_cmd_interactive ||
    1249           0 :          pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
    1250             :     {
    1251           0 :         if (on_error_rollback_warning == false && pset.sversion < 80000)
    1252           0 :         {
    1253             :             char        sverbuf[32];
    1254             : 
    1255           0 :             pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
    1256             :                            formatPGVersionNumber(pset.sversion, false,
    1257             :                                                  sverbuf, sizeof(sverbuf)));
    1258           0 :             on_error_rollback_warning = true;
    1259             :         }
    1260             :         else
    1261             :         {
    1262           0 :             results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
    1263           0 :             if (PQresultStatus(results) != PGRES_COMMAND_OK)
    1264             :             {
    1265           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
    1266           0 :                 ClearOrSaveResult(results);
    1267           0 :                 ResetCancelConn();
    1268           0 :                 goto sendquery_cleanup;
    1269             :             }
    1270           0 :             ClearOrSaveResult(results);
    1271           0 :             on_error_rollback_savepoint = true;
    1272             :         }
    1273             :     }
    1274             : 
    1275      159108 :     if (pset.gdesc_flag)
    1276             :     {
    1277             :         /* Describe query's result columns, without executing it */
    1278          40 :         OK = DescribeQuery(query, &elapsed_msec);
    1279          40 :         ResetCancelConn();
    1280          40 :         results = NULL;         /* PQclear(NULL) does nothing */
    1281             :     }
    1282      159068 :     else if (pset.fetch_count <= 0 || pset.gexec_flag ||
    1283          60 :              pset.crosstab_flag || !is_select_command(query))
    1284      159008 :     {
    1285             :         /* Default fetch-it-all-and-print mode */
    1286             :         instr_time  before,
    1287             :                     after;
    1288             : 
    1289      159016 :         if (pset.timing)
    1290           0 :             INSTR_TIME_SET_CURRENT(before);
    1291             : 
    1292      159016 :         results = PQexec(pset.db, query);
    1293             : 
    1294             :         /* these operations are included in the timing result: */
    1295      159016 :         ResetCancelConn();
    1296      159016 :         OK = ProcessResult(&results);
    1297             : 
    1298      159008 :         if (pset.timing)
    1299             :         {
    1300           0 :             INSTR_TIME_SET_CURRENT(after);
    1301           0 :             INSTR_TIME_SUBTRACT(after, before);
    1302           0 :             elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
    1303             :         }
    1304             : 
    1305             :         /* but printing results isn't: */
    1306      159008 :         if (OK && results)
    1307      140724 :             OK = PrintQueryResults(results);
    1308             :     }
    1309             :     else
    1310             :     {
    1311             :         /* Fetch-in-segments mode */
    1312          52 :         OK = ExecQueryUsingCursor(query, &elapsed_msec);
    1313          52 :         ResetCancelConn();
    1314          52 :         results = NULL;         /* PQclear(NULL) does nothing */
    1315             :     }
    1316             : 
    1317      159100 :     if (!OK && pset.echo == PSQL_ECHO_ERRORS)
    1318           0 :         pg_log_info("STATEMENT:  %s", query);
    1319             : 
    1320             :     /* If we made a temporary savepoint, possibly release/rollback */
    1321      159100 :     if (on_error_rollback_savepoint)
    1322             :     {
    1323           0 :         const char *svptcmd = NULL;
    1324             : 
    1325           0 :         transaction_status = PQtransactionStatus(pset.db);
    1326             : 
    1327           0 :         switch (transaction_status)
    1328             :         {
    1329           0 :             case PQTRANS_INERROR:
    1330             :                 /* We always rollback on an error */
    1331           0 :                 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
    1332           0 :                 break;
    1333             : 
    1334           0 :             case PQTRANS_IDLE:
    1335             :                 /* If they are no longer in a transaction, then do nothing */
    1336           0 :                 break;
    1337             : 
    1338           0 :             case PQTRANS_INTRANS:
    1339             : 
    1340             :                 /*
    1341             :                  * Do nothing if they are messing with savepoints themselves:
    1342             :                  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
    1343             :                  * If they issued a SAVEPOINT, releasing ours would remove
    1344             :                  * theirs.
    1345             :                  */
    1346           0 :                 if (results &&
    1347           0 :                     (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
    1348           0 :                      strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
    1349           0 :                      strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
    1350           0 :                     svptcmd = NULL;
    1351             :                 else
    1352           0 :                     svptcmd = "RELEASE pg_psql_temporary_savepoint";
    1353           0 :                 break;
    1354             : 
    1355           0 :             case PQTRANS_ACTIVE:
    1356             :             case PQTRANS_UNKNOWN:
    1357             :             default:
    1358           0 :                 OK = false;
    1359             :                 /* PQTRANS_UNKNOWN is expected given a broken connection. */
    1360           0 :                 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
    1361           0 :                     pg_log_error("unexpected transaction status (%d)",
    1362             :                                  transaction_status);
    1363           0 :                 break;
    1364             :         }
    1365             : 
    1366           0 :         if (svptcmd)
    1367             :         {
    1368             :             PGresult   *svptres;
    1369             : 
    1370           0 :             svptres = PQexec(pset.db, svptcmd);
    1371           0 :             if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
    1372             :             {
    1373           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
    1374           0 :                 ClearOrSaveResult(svptres);
    1375           0 :                 OK = false;
    1376             : 
    1377           0 :                 PQclear(results);
    1378           0 :                 ResetCancelConn();
    1379           0 :                 goto sendquery_cleanup;
    1380             :             }
    1381           0 :             PQclear(svptres);
    1382             :         }
    1383             :     }
    1384             : 
    1385      159100 :     ClearOrSaveResult(results);
    1386             : 
    1387             :     /* Possible microtiming output */
    1388      159100 :     if (pset.timing)
    1389           0 :         PrintTiming(elapsed_msec);
    1390             : 
    1391             :     /* check for events that may occur during query execution */
    1392             : 
    1393      159100 :     if (pset.encoding != PQclientEncoding(pset.db) &&
    1394           0 :         PQclientEncoding(pset.db) >= 0)
    1395             :     {
    1396             :         /* track effects of SET CLIENT_ENCODING */
    1397           0 :         pset.encoding = PQclientEncoding(pset.db);
    1398           0 :         pset.popt.topt.encoding = pset.encoding;
    1399           0 :         SetVariable(pset.vars, "ENCODING",
    1400             :                     pg_encoding_to_char(pset.encoding));
    1401             :     }
    1402             : 
    1403      159100 :     PrintNotifications();
    1404             : 
    1405             :     /* perform cleanup that should occur after any attempted query */
    1406             : 
    1407      159100 : sendquery_cleanup:
    1408             : 
    1409             :     /* reset \g's output-to-filename trigger */
    1410      159100 :     if (pset.gfname)
    1411             :     {
    1412           0 :         free(pset.gfname);
    1413           0 :         pset.gfname = NULL;
    1414             :     }
    1415             : 
    1416             :     /* restore print settings if \g changed them */
    1417      159100 :     if (pset.gsavepopt)
    1418             :     {
    1419          24 :         restorePsetInfo(&pset.popt, pset.gsavepopt);
    1420          24 :         pset.gsavepopt = NULL;
    1421             :     }
    1422             : 
    1423             :     /* reset \gset trigger */
    1424      159100 :     if (pset.gset_prefix)
    1425             :     {
    1426         148 :         free(pset.gset_prefix);
    1427         148 :         pset.gset_prefix = NULL;
    1428             :     }
    1429             : 
    1430             :     /* reset \gdesc trigger */
    1431      159100 :     pset.gdesc_flag = false;
    1432             : 
    1433             :     /* reset \gexec trigger */
    1434      159100 :     pset.gexec_flag = false;
    1435             : 
    1436             :     /* reset \crosstabview trigger */
    1437      159100 :     pset.crosstab_flag = false;
    1438      795500 :     for (i = 0; i < lengthof(pset.ctv_args); i++)
    1439             :     {
    1440      636400 :         pg_free(pset.ctv_args[i]);
    1441      636400 :         pset.ctv_args[i] = NULL;
    1442             :     }
    1443             : 
    1444      159100 :     return OK;
    1445             : }
    1446             : 
    1447             : 
    1448             : /*
    1449             :  * DescribeQuery: describe the result columns of a query, without executing it
    1450             :  *
    1451             :  * Returns true if the operation executed successfully, false otherwise.
    1452             :  *
    1453             :  * If pset.timing is on, total query time (exclusive of result-printing) is
    1454             :  * stored into *elapsed_msec.
    1455             :  */
    1456             : static bool
    1457          40 : DescribeQuery(const char *query, double *elapsed_msec)
    1458             : {
    1459             :     PGresult   *results;
    1460             :     bool        OK;
    1461             :     instr_time  before,
    1462             :                 after;
    1463             : 
    1464          40 :     *elapsed_msec = 0;
    1465             : 
    1466          40 :     if (pset.timing)
    1467           0 :         INSTR_TIME_SET_CURRENT(before);
    1468             : 
    1469             :     /*
    1470             :      * To parse the query but not execute it, we prepare it, using the unnamed
    1471             :      * prepared statement.  This is invisible to psql users, since there's no
    1472             :      * way to access the unnamed prepared statement from psql user space. The
    1473             :      * next Parse or Query protocol message would overwrite the statement
    1474             :      * anyway.  (So there's no great need to clear it when done, which is a
    1475             :      * good thing because libpq provides no easy way to do that.)
    1476             :      */
    1477          40 :     results = PQprepare(pset.db, "", query, 0, NULL);
    1478          40 :     if (PQresultStatus(results) != PGRES_COMMAND_OK)
    1479             :     {
    1480           8 :         pg_log_info("%s", PQerrorMessage(pset.db));
    1481           8 :         SetResultVariables(results, false);
    1482           8 :         ClearOrSaveResult(results);
    1483           8 :         return false;
    1484             :     }
    1485          32 :     PQclear(results);
    1486             : 
    1487          32 :     results = PQdescribePrepared(pset.db, "");
    1488          64 :     OK = AcceptResult(results) &&
    1489          32 :         (PQresultStatus(results) == PGRES_COMMAND_OK);
    1490          32 :     if (OK && results)
    1491             :     {
    1492          32 :         if (PQnfields(results) > 0)
    1493             :         {
    1494             :             PQExpBufferData buf;
    1495             :             int         i;
    1496             : 
    1497          24 :             initPQExpBuffer(&buf);
    1498             : 
    1499          24 :             printfPQExpBuffer(&buf,
    1500             :                               "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
    1501             :                               "FROM (VALUES ",
    1502             :                               gettext_noop("Column"),
    1503             :                               gettext_noop("Type"));
    1504             : 
    1505         108 :             for (i = 0; i < PQnfields(results); i++)
    1506             :             {
    1507             :                 const char *name;
    1508             :                 char       *escname;
    1509             : 
    1510          84 :                 if (i > 0)
    1511          60 :                     appendPQExpBufferStr(&buf, ",");
    1512             : 
    1513          84 :                 name = PQfname(results, i);
    1514          84 :                 escname = PQescapeLiteral(pset.db, name, strlen(name));
    1515             : 
    1516          84 :                 if (escname == NULL)
    1517             :                 {
    1518           0 :                     pg_log_info("%s", PQerrorMessage(pset.db));
    1519           0 :                     PQclear(results);
    1520           0 :                     termPQExpBuffer(&buf);
    1521           0 :                     return false;
    1522             :                 }
    1523             : 
    1524          84 :                 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
    1525             :                                   escname,
    1526             :                                   PQftype(results, i),
    1527             :                                   PQfmod(results, i));
    1528             : 
    1529          84 :                 PQfreemem(escname);
    1530             :             }
    1531             : 
    1532          24 :             appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
    1533          24 :             PQclear(results);
    1534             : 
    1535          24 :             results = PQexec(pset.db, buf.data);
    1536          24 :             OK = AcceptResult(results);
    1537             : 
    1538          24 :             if (pset.timing)
    1539             :             {
    1540           0 :                 INSTR_TIME_SET_CURRENT(after);
    1541           0 :                 INSTR_TIME_SUBTRACT(after, before);
    1542           0 :                 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
    1543             :             }
    1544             : 
    1545          24 :             if (OK && results)
    1546          24 :                 OK = PrintQueryResults(results);
    1547             : 
    1548          24 :             termPQExpBuffer(&buf);
    1549             :         }
    1550             :         else
    1551           8 :             fprintf(pset.queryFout,
    1552           8 :                     _("The command has no result, or the result has no columns.\n"));
    1553             :     }
    1554             : 
    1555          32 :     SetResultVariables(results, OK);
    1556          32 :     ClearOrSaveResult(results);
    1557             : 
    1558          32 :     return OK;
    1559             : }
    1560             : 
    1561             : 
    1562             : /*
    1563             :  * ExecQueryUsingCursor: run a SELECT-like query using a cursor
    1564             :  *
    1565             :  * This feature allows result sets larger than RAM to be dealt with.
    1566             :  *
    1567             :  * Returns true if the query executed successfully, false otherwise.
    1568             :  *
    1569             :  * If pset.timing is on, total query time (exclusive of result-printing) is
    1570             :  * stored into *elapsed_msec.
    1571             :  */
    1572             : static bool
    1573          52 : ExecQueryUsingCursor(const char *query, double *elapsed_msec)
    1574             : {
    1575          52 :     bool        OK = true;
    1576             :     PGresult   *results;
    1577             :     PQExpBufferData buf;
    1578          52 :     printQueryOpt my_popt = pset.popt;
    1579             :     FILE       *fout;
    1580             :     bool        is_pipe;
    1581          52 :     bool        is_pager = false;
    1582          52 :     bool        started_txn = false;
    1583          52 :     int64       total_tuples = 0;
    1584             :     int         ntuples;
    1585             :     int         fetch_count;
    1586             :     char        fetch_cmd[64];
    1587             :     instr_time  before,
    1588             :                 after;
    1589             :     int         flush_error;
    1590             : 
    1591          52 :     *elapsed_msec = 0;
    1592             : 
    1593             :     /* initialize print options for partial table output */
    1594          52 :     my_popt.topt.start_table = true;
    1595          52 :     my_popt.topt.stop_table = false;
    1596          52 :     my_popt.topt.prior_records = 0;
    1597             : 
    1598          52 :     if (pset.timing)
    1599           0 :         INSTR_TIME_SET_CURRENT(before);
    1600             : 
    1601             :     /* if we're not in a transaction, start one */
    1602          52 :     if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
    1603             :     {
    1604          52 :         results = PQexec(pset.db, "BEGIN");
    1605         104 :         OK = AcceptResult(results) &&
    1606          52 :             (PQresultStatus(results) == PGRES_COMMAND_OK);
    1607          52 :         ClearOrSaveResult(results);
    1608          52 :         if (!OK)
    1609           0 :             return false;
    1610          52 :         started_txn = true;
    1611             :     }
    1612             : 
    1613             :     /* Send DECLARE CURSOR */
    1614          52 :     initPQExpBuffer(&buf);
    1615          52 :     appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
    1616             :                       query);
    1617             : 
    1618          52 :     results = PQexec(pset.db, buf.data);
    1619         104 :     OK = AcceptResult(results) &&
    1620          52 :         (PQresultStatus(results) == PGRES_COMMAND_OK);
    1621          52 :     if (!OK)
    1622           0 :         SetResultVariables(results, OK);
    1623          52 :     ClearOrSaveResult(results);
    1624          52 :     termPQExpBuffer(&buf);
    1625          52 :     if (!OK)
    1626           0 :         goto cleanup;
    1627             : 
    1628          52 :     if (pset.timing)
    1629             :     {
    1630           0 :         INSTR_TIME_SET_CURRENT(after);
    1631           0 :         INSTR_TIME_SUBTRACT(after, before);
    1632           0 :         *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
    1633             :     }
    1634             : 
    1635             :     /*
    1636             :      * In \gset mode, we force the fetch count to be 2, so that we will throw
    1637             :      * the appropriate error if the query returns more than one row.
    1638             :      */
    1639          52 :     if (pset.gset_prefix)
    1640          16 :         fetch_count = 2;
    1641             :     else
    1642          36 :         fetch_count = pset.fetch_count;
    1643             : 
    1644          52 :     snprintf(fetch_cmd, sizeof(fetch_cmd),
    1645             :              "FETCH FORWARD %d FROM _psql_cursor",
    1646             :              fetch_count);
    1647             : 
    1648             :     /* prepare to write output to \g argument, if any */
    1649          52 :     if (pset.gfname)
    1650             :     {
    1651           0 :         if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
    1652             :         {
    1653           0 :             OK = false;
    1654           0 :             goto cleanup;
    1655             :         }
    1656           0 :         if (is_pipe)
    1657           0 :             disable_sigpipe_trap();
    1658             :     }
    1659             :     else
    1660             :     {
    1661          52 :         fout = pset.queryFout;
    1662          52 :         is_pipe = false;        /* doesn't matter */
    1663             :     }
    1664             : 
    1665             :     /* clear any pre-existing error indication on the output stream */
    1666          52 :     clearerr(fout);
    1667             : 
    1668             :     for (;;)
    1669             :     {
    1670         100 :         if (pset.timing)
    1671           0 :             INSTR_TIME_SET_CURRENT(before);
    1672             : 
    1673             :         /* get fetch_count tuples at a time */
    1674         100 :         results = PQexec(pset.db, fetch_cmd);
    1675             : 
    1676         100 :         if (pset.timing)
    1677             :         {
    1678           0 :             INSTR_TIME_SET_CURRENT(after);
    1679           0 :             INSTR_TIME_SUBTRACT(after, before);
    1680           0 :             *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
    1681             :         }
    1682             : 
    1683         100 :         if (PQresultStatus(results) != PGRES_TUPLES_OK)
    1684             :         {
    1685             :             /* shut down pager before printing error message */
    1686           4 :             if (is_pager)
    1687             :             {
    1688           4 :                 ClosePager(fout);
    1689           4 :                 is_pager = false;
    1690             :             }
    1691             : 
    1692           4 :             OK = AcceptResult(results);
    1693             :             Assert(!OK);
    1694           4 :             SetResultVariables(results, OK);
    1695           4 :             ClearOrSaveResult(results);
    1696           4 :             break;
    1697             :         }
    1698             : 
    1699          96 :         if (pset.gset_prefix)
    1700             :         {
    1701             :             /* StoreQueryTuple will complain if not exactly one row */
    1702          16 :             OK = StoreQueryTuple(results);
    1703          16 :             ClearOrSaveResult(results);
    1704          16 :             break;
    1705             :         }
    1706             : 
    1707             :         /*
    1708             :          * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
    1709             :          */
    1710             : 
    1711          80 :         ntuples = PQntuples(results);
    1712          80 :         total_tuples += ntuples;
    1713             : 
    1714          80 :         if (ntuples < fetch_count)
    1715             :         {
    1716             :             /* this is the last result set, so allow footer decoration */
    1717          32 :             my_popt.topt.stop_table = true;
    1718             :         }
    1719          48 :         else if (fout == stdout && !is_pager)
    1720             :         {
    1721             :             /*
    1722             :              * If query requires multiple result sets, hack to ensure that
    1723             :              * only one pager instance is used for the whole mess
    1724             :              */
    1725          36 :             fout = PageOutput(INT_MAX, &(my_popt.topt));
    1726          36 :             is_pager = true;
    1727             :         }
    1728             : 
    1729          80 :         printQuery(results, &my_popt, fout, is_pager, pset.logfile);
    1730             : 
    1731          80 :         ClearOrSaveResult(results);
    1732             : 
    1733             :         /* after the first result set, disallow header decoration */
    1734          80 :         my_popt.topt.start_table = false;
    1735          80 :         my_popt.topt.prior_records += ntuples;
    1736             : 
    1737             :         /*
    1738             :          * Make sure to flush the output stream, so intermediate results are
    1739             :          * visible to the client immediately.  We check the results because if
    1740             :          * the pager dies/exits/etc, there's no sense throwing more data at
    1741             :          * it.
    1742             :          */
    1743          80 :         flush_error = fflush(fout);
    1744             : 
    1745             :         /*
    1746             :          * Check if we are at the end, if a cancel was pressed, or if there
    1747             :          * were any errors either trying to flush out the results, or more
    1748             :          * generally on the output stream at all.  If we hit any errors
    1749             :          * writing things to the stream, we presume $PAGER has disappeared and
    1750             :          * stop bothering to pull down more data.
    1751             :          */
    1752         128 :         if (ntuples < fetch_count || cancel_pressed || flush_error ||
    1753          48 :             ferror(fout))
    1754             :             break;
    1755             :     }
    1756             : 
    1757          52 :     if (pset.gfname)
    1758             :     {
    1759             :         /* close \g argument file/pipe */
    1760           0 :         if (is_pipe)
    1761             :         {
    1762           0 :             pclose(fout);
    1763           0 :             restore_sigpipe_trap();
    1764             :         }
    1765             :         else
    1766           0 :             fclose(fout);
    1767             :     }
    1768          52 :     else if (is_pager)
    1769             :     {
    1770             :         /* close transient pager */
    1771          32 :         ClosePager(fout);
    1772             :     }
    1773             : 
    1774          52 :     if (OK)
    1775             :     {
    1776             :         /*
    1777             :          * We don't have a PGresult here, and even if we did it wouldn't have
    1778             :          * the right row count, so fake SetResultVariables().  In error cases,
    1779             :          * we already set the result variables above.
    1780             :          */
    1781             :         char        buf[32];
    1782             : 
    1783          40 :         SetVariable(pset.vars, "ERROR", "false");
    1784          40 :         SetVariable(pset.vars, "SQLSTATE", "00000");
    1785          40 :         snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
    1786          40 :         SetVariable(pset.vars, "ROW_COUNT", buf);
    1787             :     }
    1788             : 
    1789          12 : cleanup:
    1790          52 :     if (pset.timing)
    1791           0 :         INSTR_TIME_SET_CURRENT(before);
    1792             : 
    1793             :     /*
    1794             :      * We try to close the cursor on either success or failure, but on failure
    1795             :      * ignore the result (it's probably just a bleat about being in an aborted
    1796             :      * transaction)
    1797             :      */
    1798          52 :     results = PQexec(pset.db, "CLOSE _psql_cursor");
    1799          52 :     if (OK)
    1800             :     {
    1801          80 :         OK = AcceptResult(results) &&
    1802          40 :             (PQresultStatus(results) == PGRES_COMMAND_OK);
    1803          40 :         ClearOrSaveResult(results);
    1804             :     }
    1805             :     else
    1806          12 :         PQclear(results);
    1807             : 
    1808          52 :     if (started_txn)
    1809             :     {
    1810          52 :         results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
    1811         104 :         OK &= AcceptResult(results) &&
    1812          52 :             (PQresultStatus(results) == PGRES_COMMAND_OK);
    1813          52 :         ClearOrSaveResult(results);
    1814             :     }
    1815             : 
    1816          52 :     if (pset.timing)
    1817             :     {
    1818           0 :         INSTR_TIME_SET_CURRENT(after);
    1819           0 :         INSTR_TIME_SUBTRACT(after, before);
    1820           0 :         *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
    1821             :     }
    1822             : 
    1823          52 :     return OK;
    1824             : }
    1825             : 
    1826             : 
    1827             : /*
    1828             :  * Advance the given char pointer over white space and SQL comments.
    1829             :  */
    1830             : static const char *
    1831          60 : skip_white_space(const char *query)
    1832             : {
    1833          60 :     int         cnestlevel = 0; /* slash-star comment nest level */
    1834             : 
    1835          60 :     while (*query)
    1836             :     {
    1837          60 :         int         mblen = PQmblen(query, pset.encoding);
    1838             : 
    1839             :         /*
    1840             :          * Note: we assume the encoding is a superset of ASCII, so that for
    1841             :          * example "query[0] == '/'" is meaningful.  However, we do NOT assume
    1842             :          * that the second and subsequent bytes of a multibyte character
    1843             :          * couldn't look like ASCII characters; so it is critical to advance
    1844             :          * by mblen, not 1, whenever we haven't exactly identified the
    1845             :          * character we are skipping over.
    1846             :          */
    1847          60 :         if (isspace((unsigned char) *query))
    1848           0 :             query += mblen;
    1849          60 :         else if (query[0] == '/' && query[1] == '*')
    1850             :         {
    1851           0 :             cnestlevel++;
    1852           0 :             query += 2;
    1853             :         }
    1854          60 :         else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
    1855             :         {
    1856           0 :             cnestlevel--;
    1857           0 :             query += 2;
    1858             :         }
    1859          60 :         else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
    1860             :         {
    1861           0 :             query += 2;
    1862             : 
    1863             :             /*
    1864             :              * We have to skip to end of line since any slash-star inside the
    1865             :              * -- comment does NOT start a slash-star comment.
    1866             :              */
    1867           0 :             while (*query)
    1868             :             {
    1869           0 :                 if (*query == '\n')
    1870             :                 {
    1871           0 :                     query++;
    1872           0 :                     break;
    1873             :                 }
    1874           0 :                 query += PQmblen(query, pset.encoding);
    1875             :             }
    1876             :         }
    1877          60 :         else if (cnestlevel > 0)
    1878           0 :             query += mblen;
    1879             :         else
    1880          60 :             break;              /* found first token */
    1881             :     }
    1882             : 
    1883          60 :     return query;
    1884             : }
    1885             : 
    1886             : 
    1887             : /*
    1888             :  * Check whether a command is one of those for which we should NOT start
    1889             :  * a new transaction block (ie, send a preceding BEGIN).
    1890             :  *
    1891             :  * These include the transaction control statements themselves, plus
    1892             :  * certain statements that the backend disallows inside transaction blocks.
    1893             :  */
    1894             : static bool
    1895           0 : command_no_begin(const char *query)
    1896             : {
    1897             :     int         wordlen;
    1898             : 
    1899             :     /*
    1900             :      * First we must advance over any whitespace and comments.
    1901             :      */
    1902           0 :     query = skip_white_space(query);
    1903             : 
    1904             :     /*
    1905             :      * Check word length (since "beginx" is not "begin").
    1906             :      */
    1907           0 :     wordlen = 0;
    1908           0 :     while (isalpha((unsigned char) query[wordlen]))
    1909           0 :         wordlen += PQmblen(&query[wordlen], pset.encoding);
    1910             : 
    1911             :     /*
    1912             :      * Transaction control commands.  These should include every keyword that
    1913             :      * gives rise to a TransactionStmt in the backend grammar, except for the
    1914             :      * savepoint-related commands.
    1915             :      *
    1916             :      * (We assume that START must be START TRANSACTION, since there is
    1917             :      * presently no other "START foo" command.)
    1918             :      */
    1919           0 :     if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
    1920           0 :         return true;
    1921           0 :     if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
    1922           0 :         return true;
    1923           0 :     if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
    1924           0 :         return true;
    1925           0 :     if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
    1926           0 :         return true;
    1927           0 :     if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
    1928           0 :         return true;
    1929           0 :     if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
    1930           0 :         return true;
    1931           0 :     if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
    1932             :     {
    1933             :         /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
    1934           0 :         query += wordlen;
    1935             : 
    1936           0 :         query = skip_white_space(query);
    1937             : 
    1938           0 :         wordlen = 0;
    1939           0 :         while (isalpha((unsigned char) query[wordlen]))
    1940           0 :             wordlen += PQmblen(&query[wordlen], pset.encoding);
    1941             : 
    1942           0 :         if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
    1943           0 :             return true;
    1944           0 :         return false;
    1945             :     }
    1946             : 
    1947             :     /*
    1948             :      * Commands not allowed within transactions.  The statements checked for
    1949             :      * here should be exactly those that call PreventInTransactionBlock() in
    1950             :      * the backend.
    1951             :      */
    1952           0 :     if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
    1953           0 :         return true;
    1954           0 :     if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
    1955             :     {
    1956             :         /* CLUSTER with any arguments is allowed in transactions */
    1957           0 :         query += wordlen;
    1958             : 
    1959           0 :         query = skip_white_space(query);
    1960             : 
    1961           0 :         if (isalpha((unsigned char) query[0]))
    1962           0 :             return false;       /* has additional words */
    1963           0 :         return true;            /* it's CLUSTER without arguments */
    1964             :     }
    1965             : 
    1966           0 :     if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
    1967             :     {
    1968           0 :         query += wordlen;
    1969             : 
    1970           0 :         query = skip_white_space(query);
    1971             : 
    1972           0 :         wordlen = 0;
    1973           0 :         while (isalpha((unsigned char) query[wordlen]))
    1974           0 :             wordlen += PQmblen(&query[wordlen], pset.encoding);
    1975             : 
    1976           0 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
    1977           0 :             return true;
    1978           0 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
    1979           0 :             return true;
    1980             : 
    1981             :         /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
    1982           0 :         if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
    1983             :         {
    1984           0 :             query += wordlen;
    1985             : 
    1986           0 :             query = skip_white_space(query);
    1987             : 
    1988           0 :             wordlen = 0;
    1989           0 :             while (isalpha((unsigned char) query[wordlen]))
    1990           0 :                 wordlen += PQmblen(&query[wordlen], pset.encoding);
    1991             :         }
    1992             : 
    1993           0 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
    1994             :         {
    1995           0 :             query += wordlen;
    1996             : 
    1997           0 :             query = skip_white_space(query);
    1998             : 
    1999           0 :             wordlen = 0;
    2000           0 :             while (isalpha((unsigned char) query[wordlen]))
    2001           0 :                 wordlen += PQmblen(&query[wordlen], pset.encoding);
    2002             : 
    2003           0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2004           0 :                 return true;
    2005             :         }
    2006             : 
    2007           0 :         return false;
    2008             :     }
    2009             : 
    2010           0 :     if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
    2011             :     {
    2012           0 :         query += wordlen;
    2013             : 
    2014           0 :         query = skip_white_space(query);
    2015             : 
    2016           0 :         wordlen = 0;
    2017           0 :         while (isalpha((unsigned char) query[wordlen]))
    2018           0 :             wordlen += PQmblen(&query[wordlen], pset.encoding);
    2019             : 
    2020             :         /* ALTER SYSTEM isn't allowed in xacts */
    2021           0 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
    2022           0 :             return true;
    2023             : 
    2024           0 :         return false;
    2025             :     }
    2026             : 
    2027             :     /*
    2028             :      * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
    2029             :      * aren't really valid commands so we don't care much. The other four
    2030             :      * possible matches are correct.
    2031             :      */
    2032           0 :     if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
    2033           0 :         (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
    2034             :     {
    2035           0 :         query += wordlen;
    2036             : 
    2037           0 :         query = skip_white_space(query);
    2038             : 
    2039           0 :         wordlen = 0;
    2040           0 :         while (isalpha((unsigned char) query[wordlen]))
    2041           0 :             wordlen += PQmblen(&query[wordlen], pset.encoding);
    2042             : 
    2043           0 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
    2044           0 :             return true;
    2045           0 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
    2046           0 :             return true;
    2047           0 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
    2048           0 :             return true;
    2049           0 :         if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
    2050           0 :                              pg_strncasecmp(query, "table", 5) == 0))
    2051             :         {
    2052           0 :             query += wordlen;
    2053           0 :             query = skip_white_space(query);
    2054           0 :             wordlen = 0;
    2055           0 :             while (isalpha((unsigned char) query[wordlen]))
    2056           0 :                 wordlen += PQmblen(&query[wordlen], pset.encoding);
    2057             : 
    2058             :             /*
    2059             :              * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
    2060             :              * xacts.
    2061             :              */
    2062           0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2063           0 :                 return true;
    2064             :         }
    2065             : 
    2066             :         /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
    2067           0 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
    2068             :         {
    2069           0 :             query += wordlen;
    2070             : 
    2071           0 :             query = skip_white_space(query);
    2072             : 
    2073           0 :             wordlen = 0;
    2074           0 :             while (isalpha((unsigned char) query[wordlen]))
    2075           0 :                 wordlen += PQmblen(&query[wordlen], pset.encoding);
    2076             : 
    2077           0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2078           0 :                 return true;
    2079             : 
    2080           0 :             return false;
    2081             :         }
    2082             : 
    2083           0 :         return false;
    2084             :     }
    2085             : 
    2086             :     /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
    2087           0 :     if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
    2088             :     {
    2089           0 :         query += wordlen;
    2090             : 
    2091           0 :         query = skip_white_space(query);
    2092             : 
    2093           0 :         wordlen = 0;
    2094           0 :         while (isalpha((unsigned char) query[wordlen]))
    2095           0 :             wordlen += PQmblen(&query[wordlen], pset.encoding);
    2096             : 
    2097           0 :         if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
    2098           0 :             return true;
    2099           0 :         return false;
    2100             :     }
    2101             : 
    2102           0 :     return false;
    2103             : }
    2104             : 
    2105             : 
    2106             : /*
    2107             :  * Check whether the specified command is a SELECT (or VALUES).
    2108             :  */
    2109             : static bool
    2110          60 : is_select_command(const char *query)
    2111             : {
    2112             :     int         wordlen;
    2113             : 
    2114             :     /*
    2115             :      * First advance over any whitespace, comments and left parentheses.
    2116             :      */
    2117             :     for (;;)
    2118             :     {
    2119          60 :         query = skip_white_space(query);
    2120          60 :         if (query[0] == '(')
    2121           0 :             query++;
    2122             :         else
    2123          60 :             break;
    2124             :     }
    2125             : 
    2126             :     /*
    2127             :      * Check word length (since "selectx" is not "select").
    2128             :      */
    2129          60 :     wordlen = 0;
    2130         404 :     while (isalpha((unsigned char) query[wordlen]))
    2131         344 :         wordlen += PQmblen(&query[wordlen], pset.encoding);
    2132             : 
    2133          60 :     if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
    2134          52 :         return true;
    2135             : 
    2136           8 :     if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
    2137           0 :         return true;
    2138             : 
    2139           8 :     return false;
    2140             : }
    2141             : 
    2142             : 
    2143             : /*
    2144             :  * Test if the current user is a database superuser.
    2145             :  *
    2146             :  * Note: this will correctly detect superuserness only with a protocol-3.0
    2147             :  * or newer backend; otherwise it will always say "false".
    2148             :  */
    2149             : bool
    2150          18 : is_superuser(void)
    2151             : {
    2152             :     const char *val;
    2153             : 
    2154          18 :     if (!pset.db)
    2155           0 :         return false;
    2156             : 
    2157          18 :     val = PQparameterStatus(pset.db, "is_superuser");
    2158             : 
    2159          18 :     if (val && strcmp(val, "on") == 0)
    2160          18 :         return true;
    2161             : 
    2162           0 :     return false;
    2163             : }
    2164             : 
    2165             : 
    2166             : /*
    2167             :  * Test if the current session uses standard string literals.
    2168             :  *
    2169             :  * Note: With a pre-protocol-3.0 connection this will always say "false",
    2170             :  * which should be the right answer.
    2171             :  */
    2172             : bool
    2173      301102 : standard_strings(void)
    2174             : {
    2175             :     const char *val;
    2176             : 
    2177      301102 :     if (!pset.db)
    2178           0 :         return false;
    2179             : 
    2180      301102 :     val = PQparameterStatus(pset.db, "standard_conforming_strings");
    2181             : 
    2182      301102 :     if (val && strcmp(val, "on") == 0)
    2183      300854 :         return true;
    2184             : 
    2185         248 :     return false;
    2186             : }
    2187             : 
    2188             : 
    2189             : /*
    2190             :  * Return the session user of the current connection.
    2191             :  *
    2192             :  * Note: this will correctly detect the session user only with a
    2193             :  * protocol-3.0 or newer backend; otherwise it will return the
    2194             :  * connection user.
    2195             :  */
    2196             : const char *
    2197           0 : session_username(void)
    2198             : {
    2199             :     const char *val;
    2200             : 
    2201           0 :     if (!pset.db)
    2202           0 :         return NULL;
    2203             : 
    2204           0 :     val = PQparameterStatus(pset.db, "session_authorization");
    2205           0 :     if (val)
    2206           0 :         return val;
    2207             :     else
    2208           0 :         return PQuser(pset.db);
    2209             : }
    2210             : 
    2211             : 
    2212             : /* expand_tilde
    2213             :  *
    2214             :  * substitute '~' with HOME or '~username' with username's home dir
    2215             :  *
    2216             :  */
    2217             : void
    2218          98 : expand_tilde(char **filename)
    2219             : {
    2220          98 :     if (!filename || !(*filename))
    2221           0 :         return;
    2222             : 
    2223             :     /*
    2224             :      * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
    2225             :      * for short versions of long file names, though the tilde is usually
    2226             :      * toward the end, not at the beginning.
    2227             :      */
    2228             : #ifndef WIN32
    2229             : 
    2230             :     /* try tilde expansion */
    2231          98 :     if (**filename == '~')
    2232             :     {
    2233             :         char       *fn;
    2234             :         char        oldp,
    2235             :                    *p;
    2236             :         struct passwd *pw;
    2237             :         char        home[MAXPGPATH];
    2238             : 
    2239           0 :         fn = *filename;
    2240           0 :         *home = '\0';
    2241             : 
    2242           0 :         p = fn + 1;
    2243           0 :         while (*p != '/' && *p != '\0')
    2244           0 :             p++;
    2245             : 
    2246           0 :         oldp = *p;
    2247           0 :         *p = '\0';
    2248             : 
    2249           0 :         if (*(fn + 1) == '\0')
    2250           0 :             get_home_path(home);    /* ~ or ~/ only */
    2251           0 :         else if ((pw = getpwnam(fn + 1)) != NULL)
    2252           0 :             strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
    2253             : 
    2254           0 :         *p = oldp;
    2255           0 :         if (strlen(home) != 0)
    2256             :         {
    2257             :             char       *newfn;
    2258             : 
    2259           0 :             newfn = psprintf("%s%s", home, p);
    2260           0 :             free(fn);
    2261           0 :             *filename = newfn;
    2262             :         }
    2263             :     }
    2264             : #endif
    2265             : }
    2266             : 
    2267             : /*
    2268             :  * Checks if connection string starts with either of the valid URI prefix
    2269             :  * designators.
    2270             :  *
    2271             :  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
    2272             :  *
    2273             :  * XXX This is a duplicate of the eponymous libpq function.
    2274             :  */
    2275             : static int
    2276          28 : uri_prefix_length(const char *connstr)
    2277             : {
    2278             :     /* The connection URI must start with either of the following designators: */
    2279             :     static const char uri_designator[] = "postgresql://";
    2280             :     static const char short_uri_designator[] = "postgres://";
    2281             : 
    2282          28 :     if (strncmp(connstr, uri_designator,
    2283             :                 sizeof(uri_designator) - 1) == 0)
    2284           0 :         return sizeof(uri_designator) - 1;
    2285             : 
    2286          28 :     if (strncmp(connstr, short_uri_designator,
    2287             :                 sizeof(short_uri_designator) - 1) == 0)
    2288           0 :         return sizeof(short_uri_designator) - 1;
    2289             : 
    2290          28 :     return 0;
    2291             : }
    2292             : 
    2293             : /*
    2294             :  * Recognized connection string either starts with a valid URI prefix or
    2295             :  * contains a "=" in it.
    2296             :  *
    2297             :  * Must be consistent with parse_connection_string: anything for which this
    2298             :  * returns true should at least look like it's parseable by that routine.
    2299             :  *
    2300             :  * XXX This is a duplicate of the eponymous libpq function.
    2301             :  */
    2302             : bool
    2303          28 : recognized_connection_string(const char *connstr)
    2304             : {
    2305          28 :     return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
    2306             : }

Generated by: LCOV version 1.13