LCOV - code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 525 903 58.1 %
Date: 2021-12-04 22:09:09 Functions: 30 33 90.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14