LCOV - code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 653 910 71.8 %
Date: 2024-03-29 07:11:49 Functions: 34 36 94.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14