LCOV - differential code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 75.9 % 1047 795 252 2 793 2
Current Date: 2026-08-27 14:31:44 +0300 Functions: 92.7 % 41 38 3 1 37
Baseline: lcov-20260827-baseline Branches: 64.9 % 818 531 287 531
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 93.1 % 29 27 2 27
(30,360] days: 82.4 % 34 28 6 2 26
(360..) days: 75.2 % 984 740 244 740
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(360..) days: 92.5 % 40 37 3 1 36
Branch coverage date bins:
(7,30] days: 90.0 % 20 18 2 18
(30,360] days: 62.5 % 24 15 9 15
(360..) days: 64.3 % 774 498 276 498

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*
                                  2                 :                :  * psql - the PostgreSQL interactive terminal
                                  3                 :                :  *
                                  4                 :                :  * Copyright (c) 2000-2026, 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 "mainloop.h"
                                 31                 :                : #include "portability/instr_time.h"
                                 32                 :                : #include "settings.h"
                                 33                 :                : 
                                 34                 :                : static bool DescribeQuery(const char *query, double *elapsed_msec);
                                 35                 :                : static int  ExecQueryAndProcessResults(const char *query,
                                 36                 :                :                                        double *elapsed_msec,
                                 37                 :                :                                        bool *svpt_gone_p,
                                 38                 :                :                                        int num_copy_from_stdin,
                                 39                 :                :                                        bool is_watch,
                                 40                 :                :                                        int min_rows,
                                 41                 :                :                                        const printQueryOpt *opt,
                                 42                 :                :                                        FILE *printQueryFout);
                                 43                 :                : static bool command_no_begin(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
 3920 tgl@sss.pgh.pa.us          58                 :CBC       10760 : openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
                                 59                 :                : {
 9793 bruce@momjian.us           60   [ +  +  -  + ]:          10760 :     if (!fname || fname[0] == '\0')
                                 61                 :                :     {
 3920 tgl@sss.pgh.pa.us          62                 :          10728 :         *fout = stdout;
                                 63                 :          10728 :         *is_pipe = false;
                                 64                 :                :     }
 9793 bruce@momjian.us           65         [ +  + ]:             32 :     else if (*fname == '|')
                                 66                 :                :     {
 1459 tgl@sss.pgh.pa.us          67                 :              4 :         fflush(NULL);
 3920                            68                 :              4 :         *fout = popen(fname + 1, "w");
                                 69                 :              4 :         *is_pipe = true;
                                 70                 :                :     }
                                 71                 :                :     else
                                 72                 :                :     {
                                 73                 :             28 :         *fout = fopen(fname, "w");
                                 74                 :             28 :         *is_pipe = false;
                                 75                 :                :     }
                                 76                 :                : 
                                 77         [ -  + ]:          10760 :     if (*fout == NULL)
                                 78                 :                :     {
 2705 peter@eisentraut.org       79                 :UBC           0 :         pg_log_error("%s: %m", fname);
 3920 tgl@sss.pgh.pa.us          80                 :              0 :         return false;
                                 81                 :                :     }
                                 82                 :                : 
 3920 tgl@sss.pgh.pa.us          83                 :CBC       10760 :     return true;
                                 84                 :                : }
                                 85                 :                : 
                                 86                 :                : /*
                                 87                 :                :  * Check if an output stream for \g needs to be opened, and if yes,
                                 88                 :                :  * open it and update the caller's gfile_fout and is_pipe state variables.
                                 89                 :                :  * Return true if OK, false if an error occurred.
                                 90                 :                :  */
                                 91                 :                : static bool
  873                            92                 :          96313 : SetupGOutput(FILE **gfile_fout, bool *is_pipe)
                                 93                 :                : {
                                 94                 :                :     /* If there is a \g file or program, and it's not already open, open it */
                                 95   [ +  +  +  + ]:          96313 :     if (pset.gfname != NULL && *gfile_fout == NULL)
                                 96                 :                :     {
                                 97         [ +  - ]:             20 :         if (openQueryOutputFile(pset.gfname, gfile_fout, is_pipe))
                                 98                 :                :         {
                                 99         [ +  + ]:             20 :             if (*is_pipe)
                                100                 :              4 :                 disable_sigpipe_trap();
                                101                 :                :         }
                                102                 :                :         else
  873 tgl@sss.pgh.pa.us         103                 :UBC           0 :             return false;
                                104                 :                :     }
  873 tgl@sss.pgh.pa.us         105                 :CBC       96313 :     return true;
                                106                 :                : }
                                107                 :                : 
                                108                 :                : /*
                                109                 :                :  * Close the output stream for \g, if we opened it.
                                110                 :                :  */
                                111                 :                : static void
                                112                 :         253817 : CloseGOutput(FILE *gfile_fout, bool is_pipe)
                                113                 :                : {
                                114         [ +  + ]:         253817 :     if (gfile_fout)
                                115                 :                :     {
                                116         [ +  + ]:             20 :         if (is_pipe)
                                117                 :                :         {
                                118                 :              4 :             SetShellResultVariables(pclose(gfile_fout));
                                119                 :              4 :             restore_sigpipe_trap();
                                120                 :                :         }
                                121                 :                :         else
                                122                 :             16 :             fclose(gfile_fout);
                                123                 :                :     }
                                124                 :         253817 : }
                                125                 :                : 
                                126                 :                : /*
                                127                 :                :  * Reset pset pipeline state
                                128                 :                :  */
                                129                 :                : static void
  552 michael@paquier.xyz       130                 :UBC           0 : pipelineReset(void)
                                131                 :                : {
                                132                 :              0 :     pset.piped_syncs = 0;
                                133                 :              0 :     pset.piped_commands = 0;
                                134                 :              0 :     pset.available_results = 0;
                                135                 :              0 :     pset.requested_results = 0;
                                136                 :              0 : }
                                137                 :                : 
                                138                 :                : /*
                                139                 :                :  * setQFout
                                140                 :                :  * -- handler for -o command line option and \o command
                                141                 :                :  *
                                142                 :                :  * On success, updates pset with the new output file and returns true.
                                143                 :                :  * On failure, returns false without changing pset state.
                                144                 :                :  */
                                145                 :                : bool
 3920 tgl@sss.pgh.pa.us         146                 :CBC       10740 : setQFout(const char *fname)
                                147                 :                : {
                                148                 :                :     FILE       *fout;
                                149                 :                :     bool        is_pipe;
                                150                 :                : 
                                151                 :                :     /* First make sure we can open the new output file/pipe */
                                152         [ -  + ]:          10740 :     if (!openQueryOutputFile(fname, &fout, &is_pipe))
 3920 tgl@sss.pgh.pa.us         153                 :UBC           0 :         return false;
                                154                 :                : 
                                155                 :                :     /* Close old file/pipe */
 3920 tgl@sss.pgh.pa.us         156   [ +  -  +  +  :CBC       10740 :     if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
                                              +  - ]
                                157                 :                :     {
                                158         [ -  + ]:             12 :         if (pset.queryFoutPipe)
 1239 tgl@sss.pgh.pa.us         159                 :UBC           0 :             SetShellResultVariables(pclose(pset.queryFout));
                                160                 :                :         else
 3920 tgl@sss.pgh.pa.us         161                 :CBC          12 :             fclose(pset.queryFout);
                                162                 :                :     }
                                163                 :                : 
                                164                 :          10740 :     pset.queryFout = fout;
                                165                 :          10740 :     pset.queryFoutPipe = is_pipe;
                                166                 :                : 
                                167                 :                :     /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
                                168                 :          10740 :     set_sigpipe_trap_state(is_pipe);
                                169                 :          10740 :     restore_sigpipe_trap();
                                170                 :                : 
                                171                 :          10740 :     return true;
                                172                 :                : }
                                173                 :                : 
                                174                 :                : 
                                175                 :                : /*
                                176                 :                :  * Variable-fetching callback for flex lexer
                                177                 :                :  *
                                178                 :                :  * If the specified variable exists, return its value as a string (malloc'd
                                179                 :                :  * and expected to be freed by the caller); else return NULL.
                                180                 :                :  *
                                181                 :                :  * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
                                182                 :                :  * escaped for the specified quoting requirement.  (Failure in escaping
                                183                 :                :  * should lead to printing an error and returning NULL.)
                                184                 :                :  *
                                185                 :                :  * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
                                186                 :                :  * In psql, passthrough points to a ConditionalStack, which we check to
                                187                 :                :  * determine whether variable expansion is allowed.
                                188                 :                :  */
                                189                 :                : char *
 3435                           190                 :           2932 : psql_get_variable(const char *varname, PsqlScanQuoteType quote,
                                191                 :                :                   void *passthrough)
                                192                 :                : {
                                193                 :           2932 :     char       *result = NULL;
                                194                 :                :     const char *value;
                                195                 :                : 
                                196                 :                :     /* In an inactive \if branch, suppress all variable substitutions */
 3437                           197   [ +  -  +  + ]:           2932 :     if (passthrough && !conditional_active((ConditionalStack) passthrough))
                                198                 :             48 :         return NULL;
                                199                 :                : 
 3814                           200                 :           2884 :     value = GetVariable(pset.vars, varname);
                                201         [ +  + ]:           2884 :     if (!value)
                                202                 :            333 :         return NULL;
                                203                 :                : 
 3435                           204   [ +  +  -  - ]:           2551 :     switch (quote)
                                205                 :                :     {
                                206                 :           1843 :         case PQUOTE_PLAIN:
                                207                 :           1843 :             result = pg_strdup(value);
                                208                 :           1843 :             break;
                                209                 :            708 :         case PQUOTE_SQL_LITERAL:
                                210                 :                :         case PQUOTE_SQL_IDENT:
                                211                 :                :             {
                                212                 :                :                 /*
                                213                 :                :                  * For these cases, we use libpq's quoting functions, which
                                214                 :                :                  * assume the string is in the connection's client encoding.
                                215                 :                :                  */
                                216                 :                :                 char       *escaped_value;
                                217                 :                : 
                                218         [ -  + ]:            708 :                 if (!pset.db)
                                219                 :                :                 {
 2705 peter@eisentraut.org      220                 :UBC           0 :                     pg_log_error("cannot escape without active connection");
 3435 tgl@sss.pgh.pa.us         221                 :              0 :                     return NULL;
                                222                 :                :                 }
                                223                 :                : 
 3435 tgl@sss.pgh.pa.us         224         [ +  + ]:CBC         708 :                 if (quote == PQUOTE_SQL_LITERAL)
                                225                 :                :                     escaped_value =
                                226                 :            687 :                         PQescapeLiteral(pset.db, value, strlen(value));
                                227                 :                :                 else
                                228                 :                :                     escaped_value =
                                229                 :             21 :                         PQescapeIdentifier(pset.db, value, strlen(value));
                                230                 :                : 
                                231         [ -  + ]:            708 :                 if (escaped_value == NULL)
                                232                 :                :                 {
 3435 tgl@sss.pgh.pa.us         233                 :UBC           0 :                     const char *error = PQerrorMessage(pset.db);
                                234                 :                : 
 2705 peter@eisentraut.org      235                 :              0 :                     pg_log_info("%s", error);
 3435 tgl@sss.pgh.pa.us         236                 :              0 :                     return NULL;
                                237                 :                :                 }
                                238                 :                : 
                                239                 :                :                 /*
                                240                 :                :                  * Rather than complicate the lexer's API with a notion of
                                241                 :                :                  * which free() routine to use, just pay the price of an extra
                                242                 :                :                  * strdup().
                                243                 :                :                  */
 3435 tgl@sss.pgh.pa.us         244                 :CBC         708 :                 result = pg_strdup(escaped_value);
                                245                 :            708 :                 PQfreemem(escaped_value);
                                246                 :            708 :                 break;
                                247                 :                :             }
 3435 tgl@sss.pgh.pa.us         248                 :UBC           0 :         case PQUOTE_SHELL_ARG:
                                249                 :                :             {
                                250                 :                :                 /*
                                251                 :                :                  * For this we use appendShellStringNoError, which is
                                252                 :                :                  * encoding-agnostic, which is fine since the shell probably
                                253                 :                :                  * is too.  In any case, the only special character is "'",
                                254                 :                :                  * which is not known to appear in valid multibyte characters.
                                255                 :                :                  */
                                256                 :                :                 PQExpBufferData buf;
                                257                 :                : 
                                258                 :              0 :                 initPQExpBuffer(&buf);
                                259         [ #  # ]:              0 :                 if (!appendShellStringNoError(&buf, value))
                                260                 :                :                 {
 2705 peter@eisentraut.org      261                 :              0 :                     pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
                                262                 :                :                                  value);
 3435 tgl@sss.pgh.pa.us         263                 :              0 :                     free(buf.data);
                                264                 :              0 :                     return NULL;
                                265                 :                :                 }
                                266                 :              0 :                 result = buf.data;
                                267                 :              0 :                 break;
                                268                 :                :             }
                                269                 :                : 
                                270                 :                :             /* No default: we want a compiler warning for missing cases */
                                271                 :                :     }
                                272                 :                : 
 3814 tgl@sss.pgh.pa.us         273                 :CBC        2551 :     return result;
                                274                 :                : }
                                275                 :                : 
                                276                 :                : 
                                277                 :                : /*
                                278                 :                :  * for backend Notice messages (INFO, WARNING, etc)
                                279                 :                :  */
                                280                 :                : void
 9633 bruce@momjian.us          281                 :          16433 : NoticeProcessor(void *arg, const char *message)
                                282                 :                : {
                                283                 :                :     (void) arg;                 /* not used */
 2705 peter@eisentraut.org      284                 :          16433 :     pg_log_info("%s", message);
 9718 peter_e@gmx.net           285                 :          16433 : }
                                286                 :                : 
                                287                 :                : 
                                288                 :                : 
                                289                 :                : /*
                                290                 :                :  * Code to support query cancellation
                                291                 :                :  *
                                292                 :                :  * Before we start a query, we enable the SIGINT signal catcher to send a
                                293                 :                :  * cancel request to the backend.
                                294                 :                :  *
                                295                 :                :  * SIGINT is supposed to abort all long-running psql operations, not only
                                296                 :                :  * database queries.  In most places, this is accomplished by checking
                                297                 :                :  * cancel_pressed during long-running loops.  However, that won't work when
                                298                 :                :  * blocked on user input (in readline() or fgets()).  In those places, we
                                299                 :                :  * set sigint_interrupt_enabled true while blocked, instructing the signal
                                300                 :                :  * catcher to longjmp through sigint_interrupt_jmp.  We assume readline and
                                301                 :                :  * fgets are coded to handle possible interruption.
                                302                 :                :  *
                                303                 :                :  * On Windows, currently this does not work, so control-C is less useful
                                304                 :                :  * there.
                                305                 :                :  */
                                306                 :                : volatile sig_atomic_t sigint_interrupt_enabled = false;
                                307                 :                : 
                                308                 :                : sigjmp_buf  sigint_interrupt_jmp;
                                309                 :                : 
                                310                 :                : static void
 2460 michael@paquier.xyz       311                 :              1 : psql_cancel_callback(void)
                                312                 :                : {
                                313                 :                : #ifndef WIN32
                                314                 :                :     /* if we are waiting for input, longjmp out of it */
 7379 tgl@sss.pgh.pa.us         315         [ -  + ]:              1 :     if (sigint_interrupt_enabled)
                                316                 :                :     {
 7379 tgl@sss.pgh.pa.us         317                 :UBC           0 :         sigint_interrupt_enabled = false;
                                318                 :              0 :         siglongjmp(sigint_interrupt_jmp, 1);
                                319                 :                :     }
                                320                 :                : #endif
                                321                 :                : 
                                322                 :                :     /* else, set cancel flag to stop any long-running loops */
 2445 michael@paquier.xyz       323                 :CBC           1 :     cancel_pressed = true;
 7971 tgl@sss.pgh.pa.us         324                 :              1 : }
                                325                 :                : 
                                326                 :                : void
 2460 michael@paquier.xyz       327                 :          10732 : psql_setup_cancel_handler(void)
                                328                 :                : {
                                329                 :          10732 :     setup_cancel_handler(psql_cancel_callback);
 7971 tgl@sss.pgh.pa.us         330                 :          10732 : }
                                331                 :                : 
                                332                 :                : 
                                333                 :                : /*
                                334                 :                :  * ConnectionUp
                                335                 :                :  *
                                336                 :                :  * Returns whether our backend connection is still there.
                                337                 :                :  */
                                338                 :                : static bool
 7991 neilc@samurai.com         339                 :         284737 : ConnectionUp(void)
                                340                 :                : {
 8561 bruce@momjian.us          341                 :         284737 :     return PQstatus(pset.db) != CONNECTION_BAD;
                                342                 :                : }
                                343                 :                : 
                                344                 :                : 
                                345                 :                : 
                                346                 :                : /*
                                347                 :                :  * CheckConnection
                                348                 :                :  *
                                349                 :                :  * Verify that we still have a good connection to the backend, and if not,
                                350                 :                :  * see if it can be restored.
                                351                 :                :  *
                                352                 :                :  * Returns true if either the connection was still there, or it could be
                                353                 :                :  * restored successfully; false otherwise.  If, however, there was no
                                354                 :                :  * connection and the session is non-interactive, this will exit the program
                                355                 :                :  * with a code of EXIT_BADCONN.
                                356                 :                :  */
                                357                 :                : static bool
 8424 tgl@sss.pgh.pa.us         358                 :         284557 : CheckConnection(void)
                                359                 :                : {
                                360                 :                :     bool        OK;
                                361                 :                : 
 8561 bruce@momjian.us          362                 :         284557 :     OK = ConnectionUp();
                                363         [ +  + ]:         284557 :     if (!OK)
                                364                 :                :     {
                                365         [ +  - ]:             12 :         if (!pset.cur_cmd_interactive)
                                366                 :                :         {
 1602 tgl@sss.pgh.pa.us         367                 :             12 :             pg_log_error("connection to server was lost");
 8561 bruce@momjian.us          368                 :             12 :             exit(EXIT_BADCONN);
                                369                 :                :         }
                                370                 :                : 
 2705 peter@eisentraut.org      371                 :UBC           0 :         fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
 8561 bruce@momjian.us          372                 :              0 :         PQreset(pset.db);
  552 michael@paquier.xyz       373                 :              0 :         pipelineReset();
 8561 bruce@momjian.us          374                 :              0 :         OK = ConnectionUp();
                                375         [ #  # ]:              0 :         if (!OK)
                                376                 :                :         {
 2705 peter@eisentraut.org      377                 :              0 :             fprintf(stderr, _("Failed.\n"));
                                378                 :                : 
                                379                 :                :             /*
                                380                 :                :              * Transition to having no connection; but stash away the failed
                                381                 :                :              * connection so that we can still refer to its parameters in a
                                382                 :                :              * later \connect attempt.  Keep the state cleanup here in sync
                                383                 :                :              * with do_connect().
                                384                 :                :              */
 2134 tgl@sss.pgh.pa.us         385         [ #  # ]:              0 :             if (pset.dead_conn)
                                386                 :              0 :                 PQfinish(pset.dead_conn);
                                387                 :              0 :             pset.dead_conn = pset.db;
 8561 bruce@momjian.us          388                 :              0 :             pset.db = NULL;
                                389                 :              0 :             ResetCancelConn();
 8461 tgl@sss.pgh.pa.us         390                 :              0 :             UnsyncVariables();
                                391                 :                :         }
                                392                 :                :         else
                                393                 :                :         {
 2705 peter@eisentraut.org      394                 :              0 :             fprintf(stderr, _("Succeeded.\n"));
                                395                 :                : 
                                396                 :                :             /*
                                397                 :                :              * Re-sync, just in case anything changed.  Keep this in sync with
                                398                 :                :              * do_connect().
                                399                 :                :              */
 2551 tgl@sss.pgh.pa.us         400                 :              0 :             SyncVariables();
                                401                 :              0 :             connection_warnings(false); /* Must be after SyncVariables */
                                402                 :                :         }
                                403                 :                :     }
                                404                 :                : 
 8561 bruce@momjian.us          405                 :CBC      284545 :     return OK;
                                406                 :                : }
                                407                 :                : 
                                408                 :                : 
                                409                 :                : 
                                410                 :                : 
                                411                 :                : /*
                                412                 :                :  * AcceptResult
                                413                 :                :  *
                                414                 :                :  * Checks whether a result is valid, giving an error message if necessary;
                                415                 :                :  * and ensures that the connection to the backend is still up.
                                416                 :                :  *
                                417                 :                :  * Returns true for valid result, false for error state.
                                418                 :                :  */
                                419                 :                : static bool
 1606 peter@eisentraut.org      420                 :         286379 : AcceptResult(const PGresult *result, bool show_error)
                                421                 :                : {
                                422                 :                :     bool        OK;
                                423                 :                : 
 8561 bruce@momjian.us          424         [ -  + ]:         286379 :     if (!result)
 8424 bruce@momjian.us          425                 :UBC           0 :         OK = false;
                                426                 :                :     else
 8424 bruce@momjian.us          427      [ +  +  + ]:CBC      286379 :         switch (PQresultStatus(result))
                                428                 :                :         {
                                429                 :         255671 :             case PGRES_COMMAND_OK:
                                430                 :                :             case PGRES_TUPLES_OK:
                                431                 :                :             case PGRES_TUPLES_CHUNK:
                                432                 :                :             case PGRES_EMPTY_QUERY:
                                433                 :                :             case PGRES_COPY_IN:
                                434                 :                :             case PGRES_COPY_OUT:
                                435                 :                :             case PGRES_PIPELINE_SYNC:
                                436                 :                :                 /* Fine, do nothing */
 5328 alvherre@alvh.no-ip.      437                 :         255671 :                 OK = true;
                                438                 :         255671 :                 break;
                                439                 :                : 
  552 michael@paquier.xyz       440                 :          30707 :             case PGRES_PIPELINE_ABORTED:
                                441                 :                :             case PGRES_BAD_RESPONSE:
                                442                 :                :             case PGRES_NONFATAL_ERROR:
                                443                 :                :             case PGRES_FATAL_ERROR:
 5328 alvherre@alvh.no-ip.      444                 :          30707 :                 OK = false;
 8424 bruce@momjian.us          445                 :          30707 :                 break;
                                446                 :                : 
                                447                 :              1 :             default:
                                448                 :              1 :                 OK = false;
 2705 peter@eisentraut.org      449                 :              1 :                 pg_log_error("unexpected PQresultStatus: %d",
                                450                 :                :                              PQresultStatus(result));
 8424 bruce@momjian.us          451                 :              1 :                 break;
                                452                 :                :         }
                                453                 :                : 
 1606 peter@eisentraut.org      454   [ +  +  +  + ]:         286379 :     if (!OK && show_error)
                                455                 :                :     {
 7623 bruce@momjian.us          456                 :              4 :         const char *error = PQerrorMessage(pset.db);
                                457                 :                : 
                                458         [ +  - ]:              4 :         if (strlen(error))
 2705 peter@eisentraut.org      459                 :              4 :             pg_log_info("%s", error);
                                460                 :                : 
 8424 tgl@sss.pgh.pa.us         461                 :              4 :         CheckConnection();
                                462                 :                :     }
                                463                 :                : 
 8561 bruce@momjian.us          464                 :         286379 :     return OK;
                                465                 :                : }
                                466                 :                : 
                                467                 :                : 
                                468                 :                : /*
                                469                 :                :  * Set special variables from a query result
                                470                 :                :  * - ERROR: true/false, whether an error occurred on this query
                                471                 :                :  * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
                                472                 :                :  * - ROW_COUNT: how many rows were returned or affected, or "0"
                                473                 :                :  * - LAST_ERROR_SQLSTATE: same for last error
                                474                 :                :  * - LAST_ERROR_MESSAGE: message of last error
                                475                 :                :  *
                                476                 :                :  * Note: current policy is to apply this only to the results of queries
                                477                 :                :  * entered by the user, not queries generated by slash commands.
                                478                 :                :  */
                                479                 :                : static void
 1659 peter@eisentraut.org      480                 :         253817 : SetResultVariables(PGresult *result, bool success)
                                481                 :                : {
 3271 tgl@sss.pgh.pa.us         482         [ +  + ]:         253817 :     if (success)
                                483                 :                :     {
 1659 peter@eisentraut.org      484                 :         222871 :         const char *ntuples = PQcmdTuples(result);
                                485                 :                : 
 3271 tgl@sss.pgh.pa.us         486                 :         222871 :         SetVariable(pset.vars, "ERROR", "false");
                                487                 :         222871 :         SetVariable(pset.vars, "SQLSTATE", "00000");
                                488         [ +  + ]:         222871 :         SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
                                489                 :                :     }
                                490                 :                :     else
                                491                 :                :     {
 1659 peter@eisentraut.org      492                 :          30946 :         const char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
                                493                 :          30946 :         const char *mesg = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
                                494                 :                : 
 3271 tgl@sss.pgh.pa.us         495                 :          30946 :         SetVariable(pset.vars, "ERROR", "true");
                                496                 :                : 
                                497                 :                :         /*
                                498                 :                :          * If there is no SQLSTATE code, use an empty string.  This can happen
                                499                 :                :          * for libpq-detected errors (e.g., lost connection, ENOMEM).
                                500                 :                :          */
                                501         [ +  + ]:          30946 :         if (code == NULL)
                                502                 :            106 :             code = "";
                                503                 :          30946 :         SetVariable(pset.vars, "SQLSTATE", code);
                                504                 :          30946 :         SetVariable(pset.vars, "ROW_COUNT", "0");
                                505                 :          30946 :         SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
                                506         [ +  + ]:          30946 :         SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
                                507                 :                :     }
                                508                 :         253817 : }
                                509                 :                : 
                                510                 :                : 
                                511                 :                : /*
                                512                 :                :  * Set special variables from a shell command result
                                513                 :                :  * - SHELL_ERROR: true/false, whether command returned exit code 0
                                514                 :                :  * - SHELL_EXIT_CODE: exit code according to shell conventions
                                515                 :                :  *
                                516                 :                :  * The argument is a wait status as returned by wait(2) or waitpid(2),
                                517                 :                :  * which also applies to pclose(3) and system(3).
                                518                 :                :  */
                                519                 :                : void
 1239                           520                 :              4 : SetShellResultVariables(int wait_result)
                                521                 :                : {
                                522                 :                :     char        buf[32];
                                523                 :                : 
                                524         [ +  - ]:              4 :     SetVariable(pset.vars, "SHELL_ERROR",
                                525                 :                :                 (wait_result == 0) ? "false" : "true");
                                526                 :              4 :     snprintf(buf, sizeof(buf), "%d", wait_result_to_exit_code(wait_result));
                                527                 :              4 :     SetVariable(pset.vars, "SHELL_EXIT_CODE", buf);
                                528                 :              4 : }
                                529                 :                : 
                                530                 :                : 
                                531                 :                : /*
                                532                 :                :  * Set special pipeline variables
                                533                 :                :  * - PIPELINE_SYNC_COUNT: The number of piped syncs
                                534                 :                :  * - PIPELINE_COMMAND_COUNT: The number of piped commands
                                535                 :                :  * - PIPELINE_RESULT_COUNT: The number of results available to read
                                536                 :                :  */
                                537                 :                : static void
  548 michael@paquier.xyz       538                 :         254810 : SetPipelineVariables(void)
                                539                 :                : {
                                540                 :                :     char        buf[32];
                                541                 :                : 
                                542                 :         254810 :     snprintf(buf, sizeof(buf), "%d", pset.piped_syncs);
                                543                 :         254810 :     SetVariable(pset.vars, "PIPELINE_SYNC_COUNT", buf);
                                544                 :         254810 :     snprintf(buf, sizeof(buf), "%d", pset.piped_commands);
                                545                 :         254810 :     SetVariable(pset.vars, "PIPELINE_COMMAND_COUNT", buf);
                                546                 :         254810 :     snprintf(buf, sizeof(buf), "%d", pset.available_results);
                                547                 :         254810 :     SetVariable(pset.vars, "PIPELINE_RESULT_COUNT", buf);
                                548                 :         254810 : }
                                549                 :                : 
                                550                 :                : 
                                551                 :                : /*
                                552                 :                :  * ClearOrSaveResult
                                553                 :                :  *
                                554                 :                :  * If the result represents an error, remember it for possible display by
                                555                 :                :  * \errverbose.  Otherwise, just PQclear() it.
                                556                 :                :  *
                                557                 :                :  * Note: current policy is to apply this to the results of all queries,
                                558                 :                :  * including "back door" queries, for debugging's sake.  It's OK to use
                                559                 :                :  * PQclear() directly on results known to not be error results, however.
                                560                 :                :  */
                                561                 :                : static void
 3798 tgl@sss.pgh.pa.us         562                 :         255621 : ClearOrSaveResult(PGresult *result)
                                563                 :                : {
                                564         [ +  + ]:         255621 :     if (result)
                                565                 :                :     {
                                566         [ +  + ]:         255100 :         switch (PQresultStatus(result))
                                567                 :                :         {
                                568                 :          30845 :             case PGRES_NONFATAL_ERROR:
                                569                 :                :             case PGRES_FATAL_ERROR:
 1516 peter@eisentraut.org      570                 :          30845 :                 PQclear(pset.last_error_result);
 3798 tgl@sss.pgh.pa.us         571                 :          30845 :                 pset.last_error_result = result;
                                572                 :          30845 :                 break;
                                573                 :                : 
                                574                 :         224255 :             default:
                                575                 :         224255 :                 PQclear(result);
                                576                 :         224255 :                 break;
                                577                 :                :         }
                                578                 :                :     }
                                579                 :         255621 : }
                                580                 :                : 
                                581                 :                : 
                                582                 :                : /*
                                583                 :                :  * Consume all results
                                584                 :                :  */
                                585                 :                : static void
 1606 peter@eisentraut.org      586                 :UBC           0 : ClearOrSaveAllResults(void)
                                587                 :                : {
                                588                 :                :     PGresult   *result;
                                589                 :                : 
                                590         [ #  # ]:              0 :     while ((result = PQgetResult(pset.db)) != NULL)
                                591                 :              0 :         ClearOrSaveResult(result);
                                592                 :              0 : }
                                593                 :                : 
                                594                 :                : 
                                595                 :                : /*
                                596                 :                :  * Print microtiming output.  Always print raw milliseconds; if the interval
                                597                 :                :  * is >= 1 second, also break it down into days/hours/minutes/seconds.
                                598                 :                :  */
                                599                 :                : static void
 3645 tgl@sss.pgh.pa.us         600                 :CBC           2 : PrintTiming(double elapsed_msec)
                                601                 :                : {
                                602                 :                :     double      seconds;
                                603                 :                :     double      minutes;
                                604                 :                :     double      hours;
                                605                 :                :     double      days;
                                606                 :                : 
                                607         [ +  - ]:              2 :     if (elapsed_msec < 1000.0)
                                608                 :                :     {
                                609                 :                :         /* This is the traditional (pre-v10) output format */
                                610                 :              2 :         printf(_("Time: %.3f ms\n"), elapsed_msec);
                                611                 :              2 :         return;
                                612                 :                :     }
                                613                 :                : 
                                614                 :                :     /*
                                615                 :                :      * Note: we could print just seconds, in a format like %06.3f, when the
                                616                 :                :      * total is less than 1min.  But that's hard to interpret unless we tack
                                617                 :                :      * on "s" or otherwise annotate it.  Forcing the display to include
                                618                 :                :      * minutes seems like a better solution.
                                619                 :                :      */
 3645 tgl@sss.pgh.pa.us         620                 :UBC           0 :     seconds = elapsed_msec / 1000.0;
                                621                 :              0 :     minutes = floor(seconds / 60.0);
                                622                 :              0 :     seconds -= 60.0 * minutes;
                                623         [ #  # ]:              0 :     if (minutes < 60.0)
                                624                 :                :     {
                                625                 :              0 :         printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
                                626                 :                :                elapsed_msec, (int) minutes, seconds);
                                627                 :              0 :         return;
                                628                 :                :     }
                                629                 :                : 
                                630                 :              0 :     hours = floor(minutes / 60.0);
                                631                 :              0 :     minutes -= 60.0 * hours;
                                632         [ #  # ]:              0 :     if (hours < 24.0)
                                633                 :                :     {
                                634                 :              0 :         printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
                                635                 :                :                elapsed_msec, (int) hours, (int) minutes, seconds);
                                636                 :              0 :         return;
                                637                 :                :     }
                                638                 :                : 
                                639                 :              0 :     days = floor(hours / 24.0);
                                640                 :              0 :     hours -= 24.0 * days;
                                641                 :              0 :     printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
                                642                 :                :            elapsed_msec, days, (int) hours, (int) minutes, seconds);
                                643                 :                : }
                                644                 :                : 
                                645                 :                : 
                                646                 :                : /*
                                647                 :                :  * PSQLexec
                                648                 :                :  *
                                649                 :                :  * This is the way to send "backdoor" queries (those not directly entered
                                650                 :                :  * by the user). It is subject to -E but not -e.
                                651                 :                :  *
                                652                 :                :  * Caller is responsible for handling the ensuing processing if a COPY
                                653                 :                :  * command is sent.
                                654                 :                :  *
                                655                 :                :  * Note: we don't bother to check PQclientEncoding; it is assumed that no
                                656                 :                :  * caller uses this path to issue "SET CLIENT_ENCODING".
                                657                 :                :  */
                                658                 :                : PGresult *
 4326 fujii@postgresql.org      659                 :CBC       30987 : PSQLexec(const char *query)
                                660                 :                : {
                                661                 :                :     PGresult   *res;
                                662                 :                : 
 9722 peter_e@gmx.net           663         [ -  + ]:          30987 :     if (!pset.db)
                                664                 :                :     {
 2705 peter@eisentraut.org      665                 :UBC           0 :         pg_log_error("You are currently not connected to a database.");
 9793 bruce@momjian.us          666                 :              0 :         return NULL;
                                667                 :                :     }
                                668                 :                : 
 7303 tgl@sss.pgh.pa.us         669         [ -  + ]:CBC       30987 :     if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
                                670                 :                :     {
  154 tgl@sss.pgh.pa.us         671                 :UBC           0 :         printf(_("/**** INTERNAL QUERY ****/\n"
                                672                 :                :                  "%s\n"
                                673                 :                :                  "/************************/\n\n"), query);
 9793 bruce@momjian.us          674                 :              0 :         fflush(stdout);
 7744                           675         [ #  # ]:              0 :         if (pset.logfile)
                                676                 :                :         {
 7632 peter_e@gmx.net           677                 :              0 :             fprintf(pset.logfile,
  154 tgl@sss.pgh.pa.us         678                 :              0 :                     _("/**** INTERNAL QUERY ****/\n"
                                679                 :                :                       "%s\n"
                                680                 :                :                       "/************************/\n\n"), query);
 7744 bruce@momjian.us          681                 :              0 :             fflush(pset.logfile);
                                682                 :                :         }
                                683                 :                : 
 7303 tgl@sss.pgh.pa.us         684         [ #  # ]:              0 :         if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
 8461                           685                 :              0 :             return NULL;
                                686                 :                :     }
                                687                 :                : 
 2460 michael@paquier.xyz       688                 :CBC       30987 :     SetCancelConn(pset.db);
                                689                 :                : 
 8461 tgl@sss.pgh.pa.us         690                 :          30987 :     res = PQexec(pset.db, query);
                                691                 :                : 
 7303                           692                 :          30987 :     ResetCancelConn();
                                693                 :                : 
 1606 peter@eisentraut.org      694         [ -  + ]:          30987 :     if (!AcceptResult(res, true))
                                695                 :                :     {
 3798 tgl@sss.pgh.pa.us         696                 :UBC           0 :         ClearOrSaveResult(res);
 8561 bruce@momjian.us          697                 :              0 :         res = NULL;
                                698                 :                :     }
                                699                 :                : 
 8561 bruce@momjian.us          700                 :CBC       30987 :     return res;
                                701                 :                : }
                                702                 :                : 
                                703                 :                : 
                                704                 :                : /*
                                705                 :                :  * PSQLexecWatch
                                706                 :                :  *
                                707                 :                :  * This function is used for \watch command to send the query to
                                708                 :                :  * the server and print out the result.
                                709                 :                :  *
                                710                 :                :  * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
                                711                 :                :  * e.g., because of the interrupt, -1 on error.
                                712                 :                :  */
                                713                 :                : int
 1094 dgustafsson@postgres      714                 :             77 : PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
                                715                 :                : {
 1780 peter@eisentraut.org      716                 :             77 :     bool        timing = pset.timing;
 4114 bruce@momjian.us          717                 :             77 :     double      elapsed_msec = 0;
                                718                 :                :     int         res;
                                719                 :                : 
 4375 fujii@postgresql.org      720         [ -  + ]:             77 :     if (!pset.db)
                                721                 :                :     {
 2705 peter@eisentraut.org      722                 :UBC           0 :         pg_log_error("You are currently not connected to a database.");
 4375 fujii@postgresql.org      723                 :              0 :         return 0;
                                724                 :                :     }
                                725                 :                : 
 2460 michael@paquier.xyz       726                 :CBC          77 :     SetCancelConn(pset.db);
                                727                 :                : 
   17 tgl@sss.pgh.pa.us         728                 :             77 :     res = ExecQueryAndProcessResults(query,
                                729                 :                :                                      &elapsed_msec, NULL,
                                730                 :                :                                      -1,
                                731                 :                :                                      true, min_rows,
                                732                 :                :                                      opt, printQueryFout);
                                733                 :                : 
 4375 fujii@postgresql.org      734                 :             75 :     ResetCancelConn();
                                735                 :                : 
                                736                 :                :     /* Possible microtiming output */
 1780 peter@eisentraut.org      737         [ -  + ]:             75 :     if (timing)
 3645 tgl@sss.pgh.pa.us         738                 :UBC           0 :         PrintTiming(elapsed_msec);
                                739                 :                : 
 1606 peter@eisentraut.org      740                 :CBC          75 :     return res;
                                741                 :                : }
                                742                 :                : 
                                743                 :                : 
                                744                 :                : /*
                                745                 :                :  * PrintNotifications: check for asynchronous notifications, and print them out
                                746                 :                :  */
                                747                 :                : static void
 8561 bruce@momjian.us          748                 :         254792 : PrintNotifications(void)
                                749                 :                : {
                                750                 :                :     PGnotify   *notify;
                                751                 :                : 
 2869 tgl@sss.pgh.pa.us         752                 :         254792 :     PQconsumeInput(pset.db);
                                753         [ +  + ]:         254794 :     while ((notify = PQnotifies(pset.db)) != NULL)
                                754                 :                :     {
                                755                 :                :         /* for backward compatibility, only show payload if nonempty */
 6036                           756         [ +  + ]:              2 :         if (notify->extra[0])
                                757                 :              1 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
                                758                 :                :                     notify->relname, notify->extra, notify->be_pid);
                                759                 :                :         else
                                760                 :              1 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
                                761                 :                :                     notify->relname, notify->be_pid);
 8561 bruce@momjian.us          762                 :              2 :         fflush(pset.queryFout);
 8381 tgl@sss.pgh.pa.us         763                 :              2 :         PQfreemem(notify);
 2869                           764                 :              2 :         PQconsumeInput(pset.db);
                                765                 :                :     }
 8561 bruce@momjian.us          766                 :         254792 : }
                                767                 :                : 
                                768                 :                : 
                                769                 :                : /*
                                770                 :                :  * PrintQueryTuples: assuming query result is OK, print its tuples
                                771                 :                :  *
                                772                 :                :  * We use the options given by opt unless that's NULL, in which case
                                773                 :                :  * we use pset.popt.
                                774                 :                :  *
                                775                 :                :  * Output is to printQueryFout unless that's NULL, in which case
                                776                 :                :  * we use pset.queryFout.
                                777                 :                :  *
                                778                 :                :  * Returns true if successful, false otherwise.
                                779                 :                :  */
                                780                 :                : static bool
 1424 tgl@sss.pgh.pa.us         781                 :          95553 : PrintQueryTuples(const PGresult *result, const printQueryOpt *opt,
                                782                 :                :                  FILE *printQueryFout)
                                783                 :                : {
 1659 peter@eisentraut.org      784                 :          95553 :     bool        ok = true;
 1424 tgl@sss.pgh.pa.us         785         [ +  + ]:          95553 :     FILE       *fout = printQueryFout ? printQueryFout : pset.queryFout;
                                786                 :                : 
                                787         [ +  + ]:          95553 :     printQuery(result, opt ? opt : &pset.popt, fout, false, pset.logfile);
                                788                 :          95553 :     fflush(fout);
                                789         [ -  + ]:          95553 :     if (ferror(fout))
                                790                 :                :     {
 1424 tgl@sss.pgh.pa.us         791                 :UBC           0 :         pg_log_error("could not print result table: %m");
                                792                 :              0 :         ok = false;
                                793                 :                :     }
                                794                 :                : 
 1659 peter@eisentraut.org      795                 :CBC       95553 :     return ok;
                                796                 :                : }
                                797                 :                : 
                                798                 :                : 
                                799                 :                : /*
                                800                 :                :  * StoreQueryTuple: assuming query result is OK, save data into variables
                                801                 :                :  *
                                802                 :                :  * Returns true if successful, false otherwise.
                                803                 :                :  */
                                804                 :                : static bool
 4954 tgl@sss.pgh.pa.us         805                 :            589 : StoreQueryTuple(const PGresult *result)
                                806                 :                : {
                                807                 :            589 :     bool        success = true;
                                808                 :                : 
                                809         [ +  + ]:            589 :     if (PQntuples(result) < 1)
                                810                 :                :     {
 2705 peter@eisentraut.org      811                 :             12 :         pg_log_error("no rows returned for \\gset");
 4954 tgl@sss.pgh.pa.us         812                 :             12 :         success = false;
                                813                 :                :     }
                                814         [ +  + ]:            577 :     else if (PQntuples(result) > 1)
                                815                 :                :     {
 2705 peter@eisentraut.org      816                 :              8 :         pg_log_error("more than one row returned for \\gset");
 4954 tgl@sss.pgh.pa.us         817                 :              8 :         success = false;
                                818                 :                :     }
                                819                 :                :     else
                                820                 :                :     {
                                821                 :                :         int         i;
                                822                 :                : 
                                823         [ +  + ]:           1256 :         for (i = 0; i < PQnfields(result); i++)
                                824                 :                :         {
                                825                 :            691 :             char       *colname = PQfname(result, i);
                                826                 :                :             char       *varname;
                                827                 :                :             char       *value;
                                828                 :                : 
                                829                 :                :             /* concatenate prefix and column name */
 4692                           830                 :            691 :             varname = psprintf("%s%s", pset.gset_prefix, colname);
                                831                 :                : 
 2117 noah@leadboat.com         832         [ +  + ]:            691 :             if (VariableHasHook(pset.vars, varname))
                                833                 :                :             {
                                834                 :              4 :                 pg_log_warning("attempt to \\gset into specially treated variable \"%s\" ignored",
                                835                 :                :                                varname);
                                836                 :              4 :                 continue;
                                837                 :                :             }
                                838                 :                : 
 4954 tgl@sss.pgh.pa.us         839         [ +  + ]:            687 :             if (!PQgetisnull(result, 0, i))
                                840                 :            679 :                 value = PQgetvalue(result, 0, i);
                                841                 :                :             else
                                842                 :                :             {
                                843                 :                :                 /* for NULL value, unset rather than set the variable */
                                844                 :              8 :                 value = NULL;
                                845                 :                :             }
                                846                 :                : 
                                847         [ +  + ]:            687 :             if (!SetVariable(pset.vars, varname, value))
                                848                 :                :             {
   57 peter@eisentraut.org      849                 :GNC           4 :                 pfree(varname);
 4954 tgl@sss.pgh.pa.us         850                 :CBC           4 :                 success = false;
                                851                 :              4 :                 break;
                                852                 :                :             }
                                853                 :                : 
   57 peter@eisentraut.org      854                 :GNC         683 :             pfree(varname);
                                855                 :                :         }
                                856                 :                :     }
                                857                 :                : 
 4954 tgl@sss.pgh.pa.us         858                 :CBC         589 :     return success;
                                859                 :                : }
                                860                 :                : 
                                861                 :                : 
                                862                 :                : /*
                                863                 :                :  * ExecQueryTuples: assuming query result is OK, execute each query
                                864                 :                :  * result field as a SQL statement
                                865                 :                :  *
                                866                 :                :  * Returns true if successful, false otherwise.
                                867                 :                :  */
                                868                 :                : static bool
 3797                           869                 :             29 : ExecQueryTuples(const PGresult *result)
                                870                 :                : {
                                871                 :             29 :     bool        success = true;
                                872                 :             29 :     int         nrows = PQntuples(result);
                                873                 :             29 :     int         ncolumns = PQnfields(result);
                                874                 :                :     int         r,
                                875                 :                :                 c;
                                876                 :                : 
                                877                 :                :     /*
                                878                 :                :      * We must turn off gexec_flag to avoid infinite recursion.
                                879                 :                :      */
                                880                 :             29 :     pset.gexec_flag = false;
                                881                 :                : 
                                882         [ +  + ]:            290 :     for (r = 0; r < nrows; r++)
                                883                 :                :     {
                                884         [ +  + ]:            534 :         for (c = 0; c < ncolumns; c++)
                                885                 :                :         {
                                886         [ +  + ]:            273 :             if (!PQgetisnull(result, r, c))
                                887                 :                :             {
                                888                 :            269 :                 const char *query = PQgetvalue(result, r, c);
                                889                 :                : 
                                890                 :                :                 /* Abandon execution if cancel_pressed */
 2445 michael@paquier.xyz       891         [ -  + ]:            269 :                 if (cancel_pressed)
 3797 tgl@sss.pgh.pa.us         892                 :UBC           0 :                     goto loop_exit;
                                893                 :                : 
                                894                 :                :                 /*
                                895                 :                :                  * ECHO_ALL mode should echo these queries, but SendQuery
                                896                 :                :                  * assumes that MainLoop did that, so we have to do it here.
                                897                 :                :                  */
 3797 tgl@sss.pgh.pa.us         898   [ +  +  +  - ]:CBC         269 :                 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
                                899                 :                :                 {
                                900                 :            264 :                     puts(query);
                                901                 :            264 :                     fflush(stdout);
                                902                 :                :                 }
                                903                 :                : 
   17                           904         [ +  + ]:            269 :                 if (!SendQuery(query, -1))
                                905                 :                :                 {
                                906                 :                :                     /* Error - abandon execution if ON_ERROR_STOP */
 3797                           907                 :              4 :                     success = false;
                                908         [ -  + ]:              4 :                     if (pset.on_error_stop)
 3797 tgl@sss.pgh.pa.us         909                 :UBC           0 :                         goto loop_exit;
                                910                 :                :                 }
                                911                 :                :             }
                                912                 :                :         }
                                913                 :                :     }
                                914                 :                : 
 3797 tgl@sss.pgh.pa.us         915                 :CBC          29 : loop_exit:
                                916                 :                : 
                                917                 :                :     /*
                                918                 :                :      * Restore state.  We know gexec_flag was on, else we'd not be here. (We
                                919                 :                :      * also know it'll get turned off at end of command, but that's not ours
                                920                 :                :      * to do here.)
                                921                 :                :      */
                                922                 :             29 :     pset.gexec_flag = true;
                                923                 :                : 
                                924                 :                :     /* Return true if all queries were successful */
                                925                 :             29 :     return success;
                                926                 :                : }
                                927                 :                : 
                                928                 :                : 
                                929                 :                : /*
                                930                 :                :  * Marshal the COPY data.  Either path will get the
                                931                 :                :  * connection out of its COPY state, then call PQresultStatus()
                                932                 :                :  * once and report any error.  Return whether all was ok.
                                933                 :                :  *
                                934                 :                :  * For COPY OUT, direct the output to copystream, or discard if that's NULL.
                                935                 :                :  * For COPY IN, read from copystream (which mustn't be NULL).
                                936                 :                :  *
                                937                 :                :  * Update *resultp if further processing is necessary; set to NULL otherwise.
                                938                 :                :  * Return a result when queryFout can safely output a result status: on COPY
                                939                 :                :  * IN, or on COPY OUT if written to something other than pset.queryFout.
                                940                 :                :  * Returning NULL prevents the command status from being printed, which we
                                941                 :                :  * want if the status line doesn't get taken as part of the COPY data.
                                942                 :                :  */
                                943                 :                : static bool
 1424                           944                 :           1127 : HandleCopyResult(PGresult **resultp, FILE *copystream)
                                945                 :                : {
                                946                 :                :     bool        success;
                                947                 :                :     PGresult   *copy_result;
 1609 peter@eisentraut.org      948                 :           1127 :     ExecStatusType result_status = PQresultStatus(*resultp);
                                949                 :                : 
                                950   [ +  +  -  + ]:           1127 :     Assert(result_status == PGRES_COPY_OUT ||
                                951                 :                :            result_status == PGRES_COPY_IN);
                                952                 :                : 
                                953                 :           1127 :     SetCancelConn(pset.db);
                                954                 :                : 
                                955         [ +  + ]:           1127 :     if (result_status == PGRES_COPY_OUT)
                                956                 :                :     {
                                957                 :            486 :         success = handleCopyOut(pset.db,
                                958                 :                :                                 copystream,
                                959                 :                :                                 &copy_result)
                                960   [ +  +  +  - ]:            486 :             && (copystream != NULL);
                                961                 :                : 
                                962                 :                :         /*
                                963                 :                :          * Suppress status printing if the report would go to the same place
                                964                 :                :          * as the COPY data just went.  Note this doesn't prevent error
                                965                 :                :          * reporting, since handleCopyOut did that.
                                966                 :                :          */
                                967         [ +  + ]:            486 :         if (copystream == pset.queryFout)
                                968                 :                :         {
                                969                 :            469 :             PQclear(copy_result);
                                970                 :            469 :             copy_result = NULL;
                                971                 :                :         }
                                972                 :                :     }
                                973                 :                :     else
                                974                 :                :     {
                                975                 :                :         /* COPY IN */
   17 tgl@sss.pgh.pa.us         976         [ -  + ]:            641 :         Assert(copystream);
 1609 peter@eisentraut.org      977                 :            641 :         success = handleCopyIn(pset.db,
                                978                 :                :                                copystream,
                                979                 :            641 :                                PQbinaryTuples(*resultp),
                                980                 :                :                                &copy_result);
                                981                 :                :     }
                                982                 :           1127 :     ResetCancelConn();
                                983                 :                : 
                                984                 :                :     /*
                                985                 :                :      * Replace the PGRES_COPY_OUT/IN result with COPY command's exit status,
                                986                 :                :      * or with NULL if we want to suppress printing anything.
                                987                 :                :      */
                                988                 :           1127 :     PQclear(*resultp);
                                989                 :           1127 :     *resultp = copy_result;
                                990                 :                : 
                                991                 :           1127 :     return success;
                                992                 :                : }
                                993                 :                : 
                                994                 :                : /*
                                995                 :                :  * PrintQueryStatus: report command status as required
                                996                 :                :  */
                                997                 :                : static void
 1606                           998                 :         223047 : PrintQueryStatus(PGresult *result, FILE *printQueryFout)
                                999                 :                : {
                               1000                 :                :     char        buf[16];
  871 tgl@sss.pgh.pa.us        1001                 :         223047 :     const char *cmdstatus = PQcmdStatus(result);
 1606 peter@eisentraut.org     1002         [ +  - ]:         223047 :     FILE       *fout = printQueryFout ? printQueryFout : pset.queryFout;
                               1003                 :                : 
                               1004                 :                :     /* Do nothing if it's a TUPLES_OK result that isn't from RETURNING */
  871 tgl@sss.pgh.pa.us        1005         [ +  + ]:         223047 :     if (PQresultStatus(result) == PGRES_TUPLES_OK)
                               1006                 :                :     {
                               1007         [ +  + ]:          96307 :         if (!(strncmp(cmdstatus, "INSERT", 6) == 0 ||
                               1008         [ +  + ]:          95781 :               strncmp(cmdstatus, "UPDATE", 6) == 0 ||
                               1009         [ +  + ]:          95414 :               strncmp(cmdstatus, "DELETE", 6) == 0 ||
                               1010         [ +  + ]:          95258 :               strncmp(cmdstatus, "MERGE", 5) == 0))
                               1011                 :          95146 :             return;
                               1012                 :                :     }
                               1013                 :                : 
 7303                          1014         [ +  + ]:         127901 :     if (!pset.quiet)
                               1015                 :                :     {
 7319                          1016         [ -  + ]:            620 :         if (pset.popt.topt.format == PRINT_HTML)
                               1017                 :                :         {
 1606 peter@eisentraut.org     1018                 :UBC           0 :             fputs("<p>", fout);
  871 tgl@sss.pgh.pa.us        1019                 :              0 :             html_escaped_print(cmdstatus, fout);
 1606 peter@eisentraut.org     1020                 :              0 :             fputs("</p>\n", fout);
                               1021                 :                :         }
                               1022                 :                :         else
  871 tgl@sss.pgh.pa.us        1023                 :CBC         620 :             fprintf(fout, "%s\n", cmdstatus);
 1424                          1024                 :            620 :         fflush(fout);
                               1025                 :                :     }
                               1026                 :                : 
 7319                          1027         [ -  + ]:         127901 :     if (pset.logfile)
  871 tgl@sss.pgh.pa.us        1028                 :UBC           0 :         fprintf(pset.logfile, "%s\n", cmdstatus);
                               1029                 :                : 
  261 peter@eisentraut.org     1030                 :CBC      127901 :     snprintf(buf, sizeof(buf), "%u", PQoidValue(result));
 7319 tgl@sss.pgh.pa.us        1031                 :         127901 :     SetVariable(pset.vars, "LASTOID", buf);
                               1032                 :                : }
                               1033                 :                : 
                               1034                 :                : 
                               1035                 :                : /*
                               1036                 :                :  * PrintQueryResult: print out (or store or execute) query result as required
                               1037                 :                :  *
                               1038                 :                :  * last is true if this is the last result of a command string.
                               1039                 :                :  * opt and printQueryFout are defined as for PrintQueryTuples.
                               1040                 :                :  * printStatusFout is where to send command status; NULL means pset.queryFout.
                               1041                 :                :  *
                               1042                 :                :  * Returns true if the query executed successfully, false otherwise.
                               1043                 :                :  */
                               1044                 :                : static bool
 1424                          1045                 :         223681 : PrintQueryResult(PGresult *result, bool last,
                               1046                 :                :                  const printQueryOpt *opt, FILE *printQueryFout,
                               1047                 :                :                  FILE *printStatusFout)
                               1048                 :                : {
                               1049                 :                :     bool        success;
                               1050                 :                : 
 1659 peter@eisentraut.org     1051         [ -  + ]:         223681 :     if (!result)
 8361 tgl@sss.pgh.pa.us        1052                 :UBC           0 :         return false;
                               1053                 :                : 
 1659 peter@eisentraut.org     1054   [ +  +  +  -  :CBC      223681 :     switch (PQresultStatus(result))
                                              -  - ]
                               1055                 :                :     {
 8361 tgl@sss.pgh.pa.us        1056                 :          96276 :         case PGRES_TUPLES_OK:
                               1057                 :                :             /* store or execute or print the data ... */
 1606 peter@eisentraut.org     1058   [ +  +  +  + ]:          96276 :             if (last && pset.gset_prefix)
 1659                          1059                 :            589 :                 success = StoreQueryTuple(result);
 1606                          1060   [ +  +  +  + ]:          95687 :             else if (last && pset.gexec_flag)
 1659                          1061                 :             29 :                 success = ExecQueryTuples(result);
 1606                          1062   [ +  +  +  + ]:          95658 :             else if (last && pset.crosstab_flag)
 1659                          1063                 :             96 :                 success = PrintResultInCrosstab(result);
 1606                          1064   [ +  +  +  + ]:          95562 :             else if (last || pset.show_all_results)
                               1065                 :          95553 :                 success = PrintQueryTuples(result, opt, printQueryFout);
                               1066                 :                :             else
                               1067                 :              9 :                 success = true;
                               1068                 :                : 
                               1069                 :                :             /*
                               1070                 :                :              * If it's INSERT/UPDATE/DELETE/MERGE RETURNING, also print
                               1071                 :                :              * status.
                               1072                 :                :              */
                               1073   [ +  +  +  + ]:          96276 :             if (last || pset.show_all_results)
  871 tgl@sss.pgh.pa.us        1074                 :          96267 :                 PrintQueryStatus(result, printStatusFout);
                               1075                 :                : 
 8361                          1076                 :          96276 :             break;
                               1077                 :                : 
 8424 bruce@momjian.us         1078                 :         126740 :         case PGRES_COMMAND_OK:
 1606 peter@eisentraut.org     1079   [ +  +  +  - ]:         126740 :             if (last || pset.show_all_results)
 1424 tgl@sss.pgh.pa.us        1080                 :         126740 :                 PrintQueryStatus(result, printStatusFout);
 7319                          1081                 :         126740 :             success = true;
                               1082                 :         126740 :             break;
                               1083                 :                : 
 8361                          1084                 :            665 :         case PGRES_EMPTY_QUERY:
                               1085                 :            665 :             success = true;
 8424 bruce@momjian.us         1086                 :            665 :             break;
                               1087                 :                : 
 8361 tgl@sss.pgh.pa.us        1088                 :UBC           0 :         case PGRES_COPY_OUT:
                               1089                 :                :         case PGRES_COPY_IN:
                               1090                 :                :             /* nothing to do here: already processed */
                               1091                 :              0 :             success = true;
 8424 bruce@momjian.us         1092                 :              0 :             break;
                               1093                 :                : 
  552 michael@paquier.xyz      1094                 :              0 :         case PGRES_PIPELINE_ABORTED:
                               1095                 :                :         case PGRES_BAD_RESPONSE:
                               1096                 :                :         case PGRES_NONFATAL_ERROR:
                               1097                 :                :         case PGRES_FATAL_ERROR:
 5328 alvherre@alvh.no-ip.     1098                 :              0 :             success = false;
                               1099                 :              0 :             break;
                               1100                 :                : 
 8561 bruce@momjian.us         1101                 :              0 :         default:
 5328 alvherre@alvh.no-ip.     1102                 :              0 :             success = false;
 2705 peter@eisentraut.org     1103                 :              0 :             pg_log_error("unexpected PQresultStatus: %d",
                               1104                 :                :                          PQresultStatus(result));
 8424 bruce@momjian.us         1105                 :              0 :             break;
                               1106                 :                :     }
                               1107                 :                : 
 8561 bruce@momjian.us         1108                 :CBC      223681 :     return success;
                               1109                 :                : }
                               1110                 :                : 
                               1111                 :                : /*
                               1112                 :                :  * SendQuery: send the query string to the backend
                               1113                 :                :  * (and print out result)
                               1114                 :                :  *
                               1115                 :                :  * Note: This is the "front door" way to send a query. That is, use it to
                               1116                 :                :  * send queries actually entered by the user. These queries will be subject to
                               1117                 :                :  * single step mode.
                               1118                 :                :  * To send "back door" queries (generated by slash commands, etc.) in a
                               1119                 :                :  * controlled way, use PSQLexec().
                               1120                 :                :  *
                               1121                 :                :  * In the most common case, the caller can determine whether the query
                               1122                 :                :  * includes any COPY FROM STDIN command(s); if so, pass the count of them.
                               1123                 :                :  * Otherwise pass num_copy_from_stdin == -1 and we'll compute it locally.
                               1124                 :                :  *
                               1125                 :                :  * Returns true if the query executed successfully, false otherwise.
                               1126                 :                :  */
                               1127                 :                : bool
   17 tgl@sss.pgh.pa.us        1128                 :         254806 : SendQuery(const char *query, int num_copy_from_stdin)
                               1129                 :                : {
 1780 peter@eisentraut.org     1130                 :         254806 :     bool        timing = pset.timing;
                               1131                 :                :     PGTransactionStatusType transaction_status;
 7303 tgl@sss.pgh.pa.us        1132                 :         254806 :     double      elapsed_msec = 0;
 4954                          1133                 :         254806 :     bool        OK = false;
                               1134                 :                :     int         i;
                               1135                 :         254806 :     bool        on_error_rollback_savepoint = false;
 1610 peter@eisentraut.org     1136                 :         254806 :     bool        svpt_gone = false;
                               1137                 :                : 
 8561 bruce@momjian.us         1138         [ -  + ]:         254806 :     if (!pset.db)
                               1139                 :                :     {
 2705 peter@eisentraut.org     1140                 :UBC           0 :         pg_log_error("You are currently not connected to a database.");
 4954 tgl@sss.pgh.pa.us        1141                 :              0 :         goto sendquery_cleanup;
                               1142                 :                :     }
                               1143                 :                : 
 7303 tgl@sss.pgh.pa.us        1144         [ -  + ]:CBC      254806 :     if (pset.singlestep)
                               1145                 :                :     {
                               1146                 :                :         char        buf[3];
                               1147                 :                : 
 3797 tgl@sss.pgh.pa.us        1148                 :UBC           0 :         fflush(stderr);
 1128 nathan@postgresql.or     1149                 :              0 :         printf(_("/**(Single step mode: verify command)******************************************/\n"
                               1150                 :                :                  "%s\n"
                               1151                 :                :                  "/**(press return to proceed or enter x and return to cancel)*******************/\n"),
                               1152                 :                :                query);
 8561 bruce@momjian.us         1153                 :              0 :         fflush(stdout);
                               1154         [ #  # ]:              0 :         if (fgets(buf, sizeof(buf), stdin) != NULL)
                               1155         [ #  # ]:              0 :             if (buf[0] == 'x')
 4954 tgl@sss.pgh.pa.us        1156                 :              0 :                 goto sendquery_cleanup;
 2445 michael@paquier.xyz      1157         [ #  # ]:              0 :         if (cancel_pressed)
 3797 tgl@sss.pgh.pa.us        1158                 :              0 :             goto sendquery_cleanup;
                               1159                 :                :     }
 7303 tgl@sss.pgh.pa.us        1160         [ +  + ]:CBC      254806 :     else if (pset.echo == PSQL_ECHO_QUERIES)
                               1161                 :                :     {
 8561 bruce@momjian.us         1162                 :             82 :         puts(query);
 8428                          1163                 :             82 :         fflush(stdout);
                               1164                 :                :     }
                               1165                 :                : 
 7744                          1166         [ -  + ]:         254806 :     if (pset.logfile)
                               1167                 :                :     {
 7632 peter_e@gmx.net          1168                 :UBC           0 :         fprintf(pset.logfile,
 1128 nathan@postgresql.or     1169                 :              0 :                 _("/******** QUERY *********/\n"
                               1170                 :                :                   "%s\n"
                               1171                 :                :                   "/************************/\n\n"), query);
 7744 bruce@momjian.us         1172                 :              0 :         fflush(pset.logfile);
                               1173                 :                :     }
                               1174                 :                : 
 2460 michael@paquier.xyz      1175                 :CBC      254806 :     SetCancelConn(pset.db);
                               1176                 :                : 
 7791 bruce@momjian.us         1177                 :         254806 :     transaction_status = PQtransactionStatus(pset.db);
                               1178                 :                : 
                               1179         [ +  + ]:         254806 :     if (transaction_status == PQTRANS_IDLE &&
 7303 tgl@sss.pgh.pa.us        1180         [ +  + ]:         226914 :         !pset.autocommit &&
 8011                          1181         [ +  + ]:             56 :         !command_no_begin(query))
                               1182                 :                :     {
                               1183                 :                :         PGresult   *result;
                               1184                 :                : 
 1659 peter@eisentraut.org     1185                 :             48 :         result = PQexec(pset.db, "BEGIN");
                               1186         [ -  + ]:             48 :         if (PQresultStatus(result) != PGRES_COMMAND_OK)
                               1187                 :                :         {
 2705 peter@eisentraut.org     1188                 :UBC           0 :             pg_log_info("%s", PQerrorMessage(pset.db));
 1659                          1189                 :              0 :             ClearOrSaveResult(result);
 4954 tgl@sss.pgh.pa.us        1190                 :              0 :             goto sendquery_cleanup;
                               1191                 :                :         }
 1659 peter@eisentraut.org     1192                 :CBC          48 :         ClearOrSaveResult(result);
 7646 bruce@momjian.us         1193                 :             48 :         transaction_status = PQtransactionStatus(pset.db);
                               1194                 :                :     }
                               1195                 :                : 
                               1196         [ +  + ]:         254806 :     if (transaction_status == PQTRANS_INTRANS &&
 7303 tgl@sss.pgh.pa.us        1197         [ +  + ]:          26321 :         pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
 7646 bruce@momjian.us         1198         [ +  - ]:            104 :         (pset.cur_cmd_interactive ||
 7303 tgl@sss.pgh.pa.us        1199         [ +  - ]:            104 :          pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
                               1200                 :                :     {
                               1201                 :                :         PGresult   *result;
                               1202                 :                : 
 1659 peter@eisentraut.org     1203                 :            104 :         result = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
                               1204         [ -  + ]:            104 :         if (PQresultStatus(result) != PGRES_COMMAND_OK)
                               1205                 :                :         {
 1715 tgl@sss.pgh.pa.us        1206                 :UBC           0 :             pg_log_info("%s", PQerrorMessage(pset.db));
 1659 peter@eisentraut.org     1207                 :              0 :             ClearOrSaveResult(result);
 1715 tgl@sss.pgh.pa.us        1208                 :              0 :             goto sendquery_cleanup;
                               1209                 :                :         }
 1659 peter@eisentraut.org     1210                 :CBC         104 :         ClearOrSaveResult(result);
 1715 tgl@sss.pgh.pa.us        1211                 :            104 :         on_error_rollback_savepoint = true;
                               1212                 :                :     }
                               1213                 :                : 
 3278                          1214         [ +  + ]:         254806 :     if (pset.gdesc_flag)
                               1215                 :                :     {
                               1216                 :                :         /* Describe query's result columns, without executing it */
                               1217                 :             57 :         OK = DescribeQuery(query, &elapsed_msec);
                               1218                 :                :     }
                               1219                 :                :     else
                               1220                 :                :     {
                               1221                 :                :         /* Default fetch-and-print mode */
   17                          1222                 :         254749 :         OK = (ExecQueryAndProcessResults(query,
                               1223                 :                :                                          &elapsed_msec, &svpt_gone,
                               1224                 :                :                                          num_copy_from_stdin,
                               1225                 :                :                                          false, 0,
                               1226                 :                :                                          NULL, NULL) > 0);
                               1227                 :                :     }
                               1228                 :                : 
 4431 fujii@postgresql.org     1229   [ +  +  +  + ]:         254792 :     if (!OK && pset.echo == PSQL_ECHO_ERRORS)
 2705 peter@eisentraut.org     1230                 :              4 :         pg_log_info("STATEMENT:  %s", query);
                               1231                 :                : 
                               1232                 :                :     /* If we made a temporary savepoint, possibly release/rollback */
 7791 bruce@momjian.us         1233         [ +  + ]:         254792 :     if (on_error_rollback_savepoint)
                               1234                 :                :     {
 5328 alvherre@alvh.no-ip.     1235                 :            104 :         const char *svptcmd = NULL;
                               1236                 :                : 
 7791 bruce@momjian.us         1237                 :            104 :         transaction_status = PQtransactionStatus(pset.db);
                               1238                 :                : 
 5328 alvherre@alvh.no-ip.     1239   [ +  +  +  - ]:            104 :         switch (transaction_status)
                               1240                 :                :         {
                               1241                 :             28 :             case PQTRANS_INERROR:
                               1242                 :                :                 /* We always rollback on an error */
                               1243                 :             28 :                 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
                               1244                 :             28 :                 break;
                               1245                 :                : 
                               1246                 :             28 :             case PQTRANS_IDLE:
                               1247                 :                :                 /* If they are no longer in a transaction, then do nothing */
                               1248                 :             28 :                 break;
                               1249                 :                : 
                               1250                 :             48 :             case PQTRANS_INTRANS:
                               1251                 :                : 
                               1252                 :                :                 /*
                               1253                 :                :                  * Release our savepoint, but do nothing if they are messing
                               1254                 :                :                  * with savepoints themselves
                               1255                 :                :                  */
 1610 peter@eisentraut.org     1256         [ +  + ]:             48 :                 if (!svpt_gone)
 5328 alvherre@alvh.no-ip.     1257                 :             44 :                     svptcmd = "RELEASE pg_psql_temporary_savepoint";
                               1258                 :             48 :                 break;
                               1259                 :                : 
 5328 alvherre@alvh.no-ip.     1260                 :UBC           0 :             case PQTRANS_ACTIVE:
                               1261                 :                :             case PQTRANS_UNKNOWN:
                               1262                 :                :             default:
                               1263                 :              0 :                 OK = false;
                               1264                 :                :                 /* PQTRANS_UNKNOWN is expected given a broken connection. */
 5286 rhaas@postgresql.org     1265   [ #  #  #  # ]:              0 :                 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
 2705 peter@eisentraut.org     1266                 :              0 :                     pg_log_error("unexpected transaction status (%d)",
                               1267                 :                :                                  transaction_status);
 5328 alvherre@alvh.no-ip.     1268                 :              0 :                 break;
                               1269                 :                :         }
                               1270                 :                : 
 6585 tgl@sss.pgh.pa.us        1271         [ +  + ]:CBC         104 :         if (svptcmd)
                               1272                 :                :         {
                               1273                 :                :             PGresult   *svptres;
                               1274                 :                : 
                               1275                 :             72 :             svptres = PQexec(pset.db, svptcmd);
                               1276         [ -  + ]:             72 :             if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
                               1277                 :                :             {
 2705 peter@eisentraut.org     1278                 :UBC           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
 3798 tgl@sss.pgh.pa.us        1279                 :              0 :                 ClearOrSaveResult(svptres);
 4954                          1280                 :              0 :                 OK = false;
                               1281                 :                : 
                               1282                 :              0 :                 goto sendquery_cleanup;
                               1283                 :                :             }
 7363 alvherre@alvh.no-ip.     1284                 :CBC          72 :             PQclear(svptres);
                               1285                 :                :         }
                               1286                 :                :     }
                               1287                 :                : 
                               1288                 :                :     /* Possible microtiming output */
 1780 peter@eisentraut.org     1289         [ +  + ]:         254792 :     if (timing)
 3645 tgl@sss.pgh.pa.us        1290                 :              2 :         PrintTiming(elapsed_msec);
                               1291                 :                : 
                               1292                 :                :     /* check for events that may occur during query execution */
                               1293                 :                : 
 8381                          1294   [ +  +  +  - ]:         254818 :     if (pset.encoding != PQclientEncoding(pset.db) &&
                               1295                 :             26 :         PQclientEncoding(pset.db) >= 0)
                               1296                 :                :     {
                               1297                 :                :         /* track effects of SET CLIENT_ENCODING */
                               1298                 :             26 :         pset.encoding = PQclientEncoding(pset.db);
                               1299                 :             26 :         pset.popt.topt.encoding = pset.encoding;
                               1300                 :             26 :         SetVariable(pset.vars, "ENCODING",
                               1301                 :                :                     pg_encoding_to_char(pset.encoding));
                               1302                 :                :     }
                               1303                 :                : 
 8561 bruce@momjian.us         1304                 :         254792 :     PrintNotifications();
                               1305                 :                : 
                               1306                 :                :     /* perform cleanup that should occur after any attempted query */
                               1307                 :                : 
 4954 tgl@sss.pgh.pa.us        1308                 :         254792 : sendquery_cleanup:
                               1309                 :                : 
                               1310                 :                :     /* global cancellation reset */
 1606 peter@eisentraut.org     1311                 :         254792 :     ResetCancelConn();
                               1312                 :                : 
                               1313                 :                :     /* reset \g's output-to-filename trigger */
 4954 tgl@sss.pgh.pa.us        1314         [ +  + ]:         254792 :     if (pset.gfname)
                               1315                 :                :     {
                               1316                 :             20 :         free(pset.gfname);
                               1317                 :             20 :         pset.gfname = NULL;
                               1318                 :                :     }
                               1319                 :                : 
                               1320                 :                :     /* restore print settings if \g changed them */
 2333                          1321         [ +  + ]:         254792 :     if (pset.gsavepopt)
                               1322                 :                :     {
                               1323                 :             94 :         restorePsetInfo(&pset.popt, pset.gsavepopt);
                               1324                 :             94 :         pset.gsavepopt = NULL;
                               1325                 :                :     }
                               1326                 :                : 
                               1327                 :                :     /* clean up after extended protocol queries */
  707 michael@paquier.xyz      1328                 :         254792 :     clean_extended_state();
                               1329                 :                : 
                               1330                 :                :     /* reset \gset trigger */
 4954 tgl@sss.pgh.pa.us        1331         [ +  + ]:         254792 :     if (pset.gset_prefix)
                               1332                 :                :     {
                               1333                 :            589 :         free(pset.gset_prefix);
                               1334                 :            589 :         pset.gset_prefix = NULL;
                               1335                 :                :     }
                               1336                 :                : 
                               1337                 :                :     /* reset \gdesc trigger */
 3278                          1338                 :         254792 :     pset.gdesc_flag = false;
                               1339                 :                : 
                               1340                 :                :     /* reset \gexec trigger */
 3797                          1341                 :         254792 :     pset.gexec_flag = false;
                               1342                 :                : 
                               1343                 :                :     /* reset \crosstabview trigger */
 3793 alvherre@alvh.no-ip.     1344                 :         254792 :     pset.crosstab_flag = false;
 3787 tgl@sss.pgh.pa.us        1345         [ +  + ]:        1273960 :     for (i = 0; i < lengthof(pset.ctv_args); i++)
                               1346                 :                :     {
                               1347                 :        1019168 :         pg_free(pset.ctv_args[i]);
                               1348                 :        1019168 :         pset.ctv_args[i] = NULL;
                               1349                 :                :     }
                               1350                 :                : 
 8561 bruce@momjian.us         1351                 :         254792 :     return OK;
                               1352                 :                : }
                               1353                 :                : 
                               1354                 :                : 
                               1355                 :                : /*
                               1356                 :                :  * DescribeQuery: describe the result columns of a query, without executing it
                               1357                 :                :  *
                               1358                 :                :  * Returns true if the operation executed successfully, false otherwise.
                               1359                 :                :  *
                               1360                 :                :  * If pset.timing is on, total query time (exclusive of result-printing) is
                               1361                 :                :  * stored into *elapsed_msec.
                               1362                 :                :  */
                               1363                 :                : static bool
 3278 tgl@sss.pgh.pa.us        1364                 :             57 : DescribeQuery(const char *query, double *elapsed_msec)
                               1365                 :                : {
 1780 peter@eisentraut.org     1366                 :             57 :     bool        timing = pset.timing;
                               1367                 :                :     PGresult   *result;
                               1368                 :                :     bool        OK;
                               1369                 :                :     instr_time  before,
                               1370                 :                :                 after;
                               1371                 :                : 
 3278 tgl@sss.pgh.pa.us        1372                 :             57 :     *elapsed_msec = 0;
                               1373                 :                : 
 1780 peter@eisentraut.org     1374         [ -  + ]:             57 :     if (timing)
 3278 tgl@sss.pgh.pa.us        1375                 :UBC           0 :         INSTR_TIME_SET_CURRENT(before);
                               1376                 :                :     else
 1315 andres@anarazel.de       1377                 :CBC          57 :         INSTR_TIME_SET_ZERO(before);
                               1378                 :                : 
                               1379                 :                :     /*
                               1380                 :                :      * To parse the query but not execute it, we prepare it, using the unnamed
                               1381                 :                :      * prepared statement.  This is invisible to psql users, since there's no
                               1382                 :                :      * way to access the unnamed prepared statement from psql user space. The
                               1383                 :                :      * next Parse or Query protocol message would overwrite the statement
                               1384                 :                :      * anyway.  (So there's no great need to clear it when done, which is a
                               1385                 :                :      * good thing because libpq provides no easy way to do that.)
                               1386                 :                :      */
 1659 peter@eisentraut.org     1387                 :             57 :     result = PQprepare(pset.db, "", query, 0, NULL);
                               1388         [ +  + ]:             57 :     if (PQresultStatus(result) != PGRES_COMMAND_OK)
                               1389                 :                :     {
 2705                          1390                 :             21 :         pg_log_info("%s", PQerrorMessage(pset.db));
 1659                          1391                 :             21 :         SetResultVariables(result, false);
                               1392                 :             21 :         ClearOrSaveResult(result);
 3278 tgl@sss.pgh.pa.us        1393                 :             21 :         return false;
                               1394                 :                :     }
 1659 peter@eisentraut.org     1395                 :             36 :     PQclear(result);
                               1396                 :                : 
                               1397                 :             36 :     result = PQdescribePrepared(pset.db, "");
 1606                          1398   [ +  -  +  - ]:             72 :     OK = AcceptResult(result, true) &&
 1659                          1399                 :             36 :         (PQresultStatus(result) == PGRES_COMMAND_OK);
                               1400   [ +  -  +  - ]:             36 :     if (OK && result)
                               1401                 :                :     {
                               1402         [ +  + ]:             36 :         if (PQnfields(result) > 0)
                               1403                 :                :         {
                               1404                 :                :             PQExpBufferData buf;
                               1405                 :                :             int         i;
                               1406                 :                : 
 3278 tgl@sss.pgh.pa.us        1407                 :             24 :             initPQExpBuffer(&buf);
                               1408                 :                : 
                               1409                 :             24 :             printfPQExpBuffer(&buf,
                               1410                 :                :                               "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
                               1411                 :                :                               "FROM (VALUES ",
                               1412                 :                :                               gettext_noop("Column"),
                               1413                 :                :                               gettext_noop("Type"));
                               1414                 :                : 
 1659 peter@eisentraut.org     1415         [ +  + ]:            108 :             for (i = 0; i < PQnfields(result); i++)
                               1416                 :                :             {
                               1417                 :                :                 const char *name;
                               1418                 :                :                 char       *escname;
                               1419                 :                : 
 3278 tgl@sss.pgh.pa.us        1420         [ +  + ]:             84 :                 if (i > 0)
  496 drowley@postgresql.o     1421                 :             60 :                     appendPQExpBufferChar(&buf, ',');
                               1422                 :                : 
 1659 peter@eisentraut.org     1423                 :             84 :                 name = PQfname(result, i);
 3278 tgl@sss.pgh.pa.us        1424                 :             84 :                 escname = PQescapeLiteral(pset.db, name, strlen(name));
                               1425                 :                : 
                               1426         [ -  + ]:             84 :                 if (escname == NULL)
                               1427                 :                :                 {
 2705 peter@eisentraut.org     1428                 :UBC           0 :                     pg_log_info("%s", PQerrorMessage(pset.db));
 1659                          1429                 :              0 :                     PQclear(result);
 3278 tgl@sss.pgh.pa.us        1430                 :              0 :                     termPQExpBuffer(&buf);
                               1431                 :              0 :                     return false;
                               1432                 :                :                 }
                               1433                 :                : 
 3278 tgl@sss.pgh.pa.us        1434                 :CBC          84 :                 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
                               1435                 :                :                                   escname,
                               1436                 :                :                                   PQftype(result, i),
                               1437                 :                :                                   PQfmod(result, i));
                               1438                 :                : 
                               1439                 :             84 :                 PQfreemem(escname);
                               1440                 :                :             }
                               1441                 :                : 
                               1442                 :             24 :             appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
 1659 peter@eisentraut.org     1443                 :             24 :             PQclear(result);
                               1444                 :                : 
                               1445                 :             24 :             result = PQexec(pset.db, buf.data);
 1606                          1446                 :             24 :             OK = AcceptResult(result, true);
                               1447                 :                : 
 1780                          1448         [ -  + ]:             24 :             if (timing)
                               1449                 :                :             {
 3278 tgl@sss.pgh.pa.us        1450                 :UBC           0 :                 INSTR_TIME_SET_CURRENT(after);
                               1451                 :              0 :                 INSTR_TIME_SUBTRACT(after, before);
                               1452                 :              0 :                 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
                               1453                 :                :             }
                               1454                 :                : 
 1659 peter@eisentraut.org     1455   [ +  -  +  - ]:CBC          24 :             if (OK && result)
 1424 tgl@sss.pgh.pa.us        1456                 :             24 :                 OK = PrintQueryResult(result, true, NULL, NULL, NULL);
                               1457                 :                : 
 3278                          1458                 :             24 :             termPQExpBuffer(&buf);
                               1459                 :                :         }
                               1460                 :                :         else
                               1461                 :             12 :             fprintf(pset.queryFout,
                               1462                 :             12 :                     _("The command has no result, or the result has no columns.\n"));
                               1463                 :                :     }
                               1464                 :                : 
 1659 peter@eisentraut.org     1465                 :             36 :     SetResultVariables(result, OK);
                               1466                 :             36 :     ClearOrSaveResult(result);
                               1467                 :                : 
 3278 tgl@sss.pgh.pa.us        1468                 :             36 :     return OK;
                               1469                 :                : }
                               1470                 :                : 
                               1471                 :                : /*
                               1472                 :                :  * Read and discard all results in an aborted pipeline.
                               1473                 :                :  *
                               1474                 :                :  * If a synchronisation point is found, we can stop discarding results as
                               1475                 :                :  * the pipeline will switch back to a clean state.  If no synchronisation
                               1476                 :                :  * point is available, we need to stop when there are no more pending
                               1477                 :                :  * results, otherwise, calling PQgetResult() would block.
                               1478                 :                :  */
                               1479                 :                : static PGresult *
  552 michael@paquier.xyz      1480                 :            108 : discardAbortedPipelineResults(void)
                               1481                 :                : {
                               1482                 :                :     for (;;)
                               1483                 :            196 :     {
                               1484                 :            304 :         PGresult   *res = PQgetResult(pset.db);
                               1485                 :            304 :         ExecStatusType result_status = PQresultStatus(res);
                               1486                 :                : 
                               1487         [ +  + ]:            304 :         if (result_status == PGRES_PIPELINE_SYNC)
                               1488                 :                :         {
                               1489                 :                :             /*
                               1490                 :                :              * Found a synchronisation point.  The sync counter is decremented
                               1491                 :                :              * by the caller.
                               1492                 :                :              */
                               1493                 :             52 :             return res;
                               1494                 :                :         }
  490                          1495   [ +  +  -  + ]:            252 :         else if (res != NULL && result_status == PGRES_FATAL_ERROR)
                               1496                 :                :         {
                               1497                 :                :             /*
                               1498                 :                :              * Found a FATAL error sent by the backend, and we cannot recover
                               1499                 :                :              * from this state.  Instead, return the last result and let the
                               1500                 :                :              * outer loop handle it.
                               1501                 :                :              */
                               1502                 :                :             PGresult   *fatal_res PG_USED_FOR_ASSERTS_ONLY;
                               1503                 :                : 
                               1504                 :                :             /*
                               1505                 :                :              * Fetch result to consume the end of the current query being
                               1506                 :                :              * processed.
                               1507                 :                :              */
  490 michael@paquier.xyz      1508                 :UBC           0 :             fatal_res = PQgetResult(pset.db);
                               1509         [ #  # ]:              0 :             Assert(fatal_res == NULL);
                               1510                 :              0 :             return res;
                               1511                 :                :         }
  552 michael@paquier.xyz      1512         [ +  + ]:CBC         252 :         else if (res == NULL)
                               1513                 :                :         {
                               1514                 :                :             /*
                               1515                 :                :              * A query was processed, decrement the counters.
                               1516                 :                :              *
                               1517                 :                :              * It is possible to get here with available_results == 0 when an
                               1518                 :                :              * error is generated by the Sync message processing itself. Such
                               1519                 :                :              * errors are not counted in available_results because they are
                               1520                 :                :              * not associated with a piped command.  In that case, skip the
                               1521                 :                :              * counter decrements and continue to find the Sync result.
                               1522                 :                :              *
                               1523                 :                :              * If the connection has been lost, there will never be any more
                               1524                 :                :              * results to read, so bail out.
                               1525                 :                :              */
   85                          1526         [ -  + ]:            180 :             if (!ConnectionUp())
   85 michael@paquier.xyz      1527                 :UBC           0 :                 return NULL;
   85 michael@paquier.xyz      1528         [ +  + ]:CBC         180 :             if (pset.available_results > 0)
                               1529                 :            152 :                 pset.available_results--;
                               1530         [ +  - ]:            180 :             if (pset.requested_results > 0)
                               1531                 :            180 :                 pset.requested_results--;
                               1532                 :                :         }
                               1533                 :                : 
  552                          1534         [ +  + ]:            252 :         if (pset.requested_results == 0)
                               1535                 :                :         {
                               1536                 :                :             /* We have read all the requested results, leave */
                               1537                 :             56 :             return res;
                               1538                 :                :         }
                               1539                 :                : 
                               1540   [ +  +  -  + ]:            196 :         if (pset.available_results == 0 && pset.piped_syncs == 0)
                               1541                 :                :         {
                               1542                 :                :             /*
                               1543                 :                :              * There are no more results to get and there is no
                               1544                 :                :              * synchronisation point to stop at.  This will leave the pipeline
                               1545                 :                :              * in an aborted state.
                               1546                 :                :              */
  552 michael@paquier.xyz      1547                 :UBC           0 :             return res;
                               1548                 :                :         }
                               1549                 :                : 
                               1550                 :                :         /*
                               1551                 :                :          * An aborted pipeline will have either NULL results or results in an
                               1552                 :                :          * PGRES_PIPELINE_ABORTED status.
                               1553                 :                :          */
  552 michael@paquier.xyz      1554   [ +  +  -  + ]:CBC         196 :         Assert(res == NULL || result_status == PGRES_PIPELINE_ABORTED);
                               1555                 :            196 :         PQclear(res);
                               1556                 :                :     }
                               1557                 :                : }
                               1558                 :                : 
                               1559                 :                : /*
                               1560                 :                :  * ExecQueryAndProcessResults: utility function for use by SendQuery()
                               1561                 :                :  * and PSQLexecWatch().
                               1562                 :                :  *
                               1563                 :                :  * Sends query and cycles through PGresult objects.
                               1564                 :                :  *
                               1565                 :                :  * If our command string contained a COPY FROM STDIN or COPY TO STDOUT, the
                               1566                 :                :  * PGresult associated with these commands must be processed by providing an
                               1567                 :                :  * input or output stream.  In that event, we'll marshal data for the COPY.
                               1568                 :                :  *
                               1569                 :                :  * For other commands, the results are processed normally, depending on their
                               1570                 :                :  * status and the status of a pipeline.
                               1571                 :                :  *
                               1572                 :                :  * When invoked from \watch, is_watch is true and min_rows is the value
                               1573                 :                :  * of that option, or 0 if it wasn't set.
                               1574                 :                :  *
                               1575                 :                :  * Returns 1 on complete success, 0 on interrupt and -1 or errors.  Possible
                               1576                 :                :  * failure modes include purely client-side problems; check the transaction
                               1577                 :                :  * status for the server-side opinion.
                               1578                 :                :  *
                               1579                 :                :  * Note that on a combined query, failure does not mean that nothing was
                               1580                 :                :  * committed.
                               1581                 :                :  */
                               1582                 :                : static int
 1424 tgl@sss.pgh.pa.us        1583                 :         254826 : ExecQueryAndProcessResults(const char *query,
                               1584                 :                :                            double *elapsed_msec, bool *svpt_gone_p,
                               1585                 :                :                            int num_copy_from_stdin,
                               1586                 :                :                            bool is_watch, int min_rows,
                               1587                 :                :                            const printQueryOpt *opt, FILE *printQueryFout)
                               1588                 :                : {
 1610 peter@eisentraut.org     1589                 :         254826 :     bool        timing = pset.timing;
  735 michael@paquier.xyz      1590                 :         254826 :     bool        success = false;
 1094 dgustafsson@postgres     1591                 :         254826 :     bool        return_early = false;
  552 michael@paquier.xyz      1592                 :         254826 :     bool        end_pipeline = false;
                               1593                 :                :     instr_time  before,
                               1594                 :                :                 after;
                               1595                 :                :     PGresult   *result;
 1424 tgl@sss.pgh.pa.us        1596                 :         254826 :     FILE       *gfile_fout = NULL;
                               1597                 :         254826 :     bool        gfile_is_pipe = false;
                               1598                 :                : 
 1610 peter@eisentraut.org     1599         [ +  + ]:         254826 :     if (timing)
                               1600                 :              2 :         INSTR_TIME_SET_CURRENT(before);
                               1601                 :                :     else
 1315 andres@anarazel.de       1602                 :         254824 :         INSTR_TIME_SET_ZERO(before);
                               1603                 :                : 
  735 michael@paquier.xyz      1604   [ +  +  +  +  :         254826 :     switch (pset.send_mode)
                                     +  +  +  +  +  
                                           +  +  - ]
                               1605                 :                :     {
                               1606                 :             25 :         case PSQL_SEND_EXTENDED_CLOSE:
                               1607                 :             25 :             success = PQsendClosePrepared(pset.db, pset.stmtName);
  552                          1608   [ +  -  +  + ]:             25 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1609                 :             12 :                 pset.piped_commands++;
  735                          1610                 :             25 :             break;
                               1611                 :             67 :         case PSQL_SEND_EXTENDED_PARSE:
                               1612                 :             67 :             success = PQsendPrepare(pset.db, pset.stmtName, query, 0, NULL);
  552                          1613   [ +  -  +  + ]:             67 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1614                 :             44 :                 pset.piped_commands++;
  735                          1615                 :             67 :             break;
                               1616                 :            492 :         case PSQL_SEND_EXTENDED_QUERY_PARAMS:
                               1617         [ -  + ]:            492 :             Assert(pset.stmtName == NULL);
                               1618                 :            984 :             success = PQsendQueryParams(pset.db, query,
                               1619                 :                :                                         pset.bind_nparams, NULL,
                               1620                 :            492 :                                         (const char *const *) pset.bind_params,
                               1621                 :                :                                         NULL, NULL, 0);
  552                          1622   [ +  -  +  + ]:            492 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1623                 :            433 :                 pset.piped_commands++;
  735                          1624                 :            492 :             break;
                               1625                 :             80 :         case PSQL_SEND_EXTENDED_QUERY_PREPARED:
                               1626         [ -  + ]:             80 :             Assert(pset.stmtName != NULL);
                               1627                 :            160 :             success = PQsendQueryPrepared(pset.db, pset.stmtName,
                               1628                 :                :                                           pset.bind_nparams,
                               1629                 :             80 :                                           (const char *const *) pset.bind_params,
                               1630                 :                :                                           NULL, NULL, 0);
  552                          1631   [ +  -  +  + ]:             80 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1632                 :             32 :                 pset.piped_commands++;
                               1633                 :             80 :             break;
                               1634                 :            225 :         case PSQL_SEND_START_PIPELINE_MODE:
                               1635                 :            225 :             success = PQenterPipelineMode(pset.db);
                               1636                 :            225 :             break;
                               1637                 :            225 :         case PSQL_SEND_END_PIPELINE_MODE:
                               1638                 :            225 :             success = PQpipelineSync(pset.db);
                               1639   [ +  +  +  - ]:            225 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1640                 :                :             {
                               1641                 :                :                 /*
                               1642                 :                :                  * End of the pipeline, all queued commands need to be
                               1643                 :                :                  * processed.
                               1644                 :                :                  */
                               1645                 :            221 :                 end_pipeline = true;
                               1646                 :            221 :                 pset.piped_syncs++;
                               1647                 :                : 
                               1648                 :                :                 /*
                               1649                 :                :                  * The server will send a ReadyForQuery after a Sync is
                               1650                 :                :                  * processed, flushing all the results back to the client.
                               1651                 :                :                  */
                               1652                 :            221 :                 pset.available_results += pset.piped_commands;
                               1653                 :            221 :                 pset.piped_commands = 0;
                               1654                 :                : 
                               1655                 :                :                 /* We want to read all results */
                               1656                 :            221 :                 pset.requested_results = pset.available_results + pset.piped_syncs;
                               1657                 :                :             }
                               1658                 :            225 :             break;
                               1659                 :             95 :         case PSQL_SEND_PIPELINE_SYNC:
                               1660                 :             95 :             success = PQsendPipelineSync(pset.db);
                               1661   [ +  -  +  - ]:             95 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1662                 :                :             {
                               1663                 :             95 :                 pset.piped_syncs++;
                               1664                 :                : 
                               1665                 :                :                 /*
                               1666                 :                :                  * The server will send a ReadyForQuery after a Sync is
                               1667                 :                :                  * processed, flushing all the results back to the client.
                               1668                 :                :                  */
                               1669                 :             95 :                 pset.available_results += pset.piped_commands;
                               1670                 :             95 :                 pset.piped_commands = 0;
                               1671                 :                :             }
                               1672                 :             95 :             break;
                               1673                 :             12 :         case PSQL_SEND_FLUSH:
                               1674                 :             12 :             success = PQflush(pset.db);
                               1675                 :             12 :             break;
                               1676                 :             44 :         case PSQL_SEND_FLUSH_REQUEST:
                               1677                 :             44 :             success = PQsendFlushRequest(pset.db);
                               1678   [ +  -  +  - ]:             44 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1679                 :                :             {
                               1680                 :                :                 /*
                               1681                 :                :                  * With the flush request, all commands in the pipeline are
                               1682                 :                :                  * pushed and the server will flush the results back to the
                               1683                 :                :                  * client, making them available.
                               1684                 :                :                  */
                               1685                 :             44 :                 pset.available_results += pset.piped_commands;
                               1686                 :             44 :                 pset.piped_commands = 0;
                               1687                 :                :             }
                               1688                 :             44 :             break;
                               1689                 :            124 :         case PSQL_SEND_GET_RESULTS:
                               1690   [ +  +  +  + ]:            124 :             if (pset.available_results == 0 && pset.piped_syncs == 0)
                               1691                 :                :             {
                               1692                 :                :                 /*
                               1693                 :                :                  * If no sync or flush request were sent, PQgetResult() would
                               1694                 :                :                  * block as there are no results available.  Forbid any
                               1695                 :                :                  * attempt to get pending results should we try to reach this
                               1696                 :                :                  * state.
                               1697                 :                :                  */
                               1698                 :             16 :                 pg_log_info("No pending results to get");
                               1699                 :             16 :                 success = false;
                               1700                 :             16 :                 pset.requested_results = 0;
                               1701                 :                :             }
                               1702                 :                :             else
                               1703                 :                :             {
                               1704                 :            108 :                 success = true;
                               1705                 :                : 
                               1706                 :                :                 /*
                               1707                 :                :                  * Cap requested_results to the maximum number of known
                               1708                 :                :                  * results.
                               1709                 :                :                  */
                               1710         [ +  + ]:            108 :                 if (pset.requested_results == 0 ||
                               1711         [ -  + ]:             44 :                     pset.requested_results > (pset.available_results + pset.piped_syncs))
                               1712                 :             64 :                     pset.requested_results = pset.available_results + pset.piped_syncs;
                               1713                 :                :             }
  735                          1714                 :            124 :             break;
                               1715                 :         253437 :         case PSQL_SEND_QUERY:
  526                          1716         [ +  + ]:         253437 :             if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1717                 :                :             {
                               1718                 :             76 :                 success = PQsendQueryParams(pset.db, query,
                               1719                 :                :                                             0, NULL, NULL, NULL, NULL, 0);
                               1720         [ +  - ]:             76 :                 if (success)
                               1721                 :             76 :                     pset.piped_commands++;
                               1722                 :                :             }
                               1723                 :                :             else
                               1724                 :         253361 :                 success = PQsendQuery(pset.db, query);
  735                          1725                 :         253437 :             break;
                               1726                 :                :     }
                               1727                 :                : 
 1606 peter@eisentraut.org     1728         [ +  + ]:         254826 :     if (!success)
                               1729                 :                :     {
                               1730                 :             32 :         const char *error = PQerrorMessage(pset.db);
                               1731                 :                : 
                               1732         [ +  + ]:             32 :         if (strlen(error))
                               1733                 :              4 :             pg_log_info("%s", error);
                               1734                 :                : 
                               1735                 :             32 :         CheckConnection();
                               1736                 :                : 
  548 michael@paquier.xyz      1737                 :             32 :         SetPipelineVariables();
                               1738                 :                : 
 1606 peter@eisentraut.org     1739                 :             32 :         return -1;
                               1740                 :                :     }
                               1741                 :                : 
  552 michael@paquier.xyz      1742   [ +  +  +  -  :         509259 :     if (pset.requested_results == 0 && !end_pipeline &&
                                              +  + ]
                               1743                 :         254465 :         PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1744                 :                :     {
                               1745                 :                :         /*
                               1746                 :                :          * We are in a pipeline and have not reached the pipeline end, or
                               1747                 :                :          * there was no request to read pipeline results.  Update the psql
                               1748                 :                :          * variables tracking the pipeline activity and exit.
                               1749                 :                :          */
  548                          1750                 :            961 :         SetPipelineVariables();
  552                          1751                 :            961 :         return 1;
                               1752                 :                :     }
                               1753                 :                : 
                               1754                 :                :     /*
                               1755                 :                :      * Fetch the result in chunks if FETCH_COUNT is set, except when:
                               1756                 :                :      *
                               1757                 :                :      * * SHOW_ALL_RESULTS is false, since that requires us to complete the
                               1758                 :                :      * query before we can tell if its results should be displayed.
                               1759                 :                :      *
                               1760                 :                :      * * We're doing \crosstab, which likewise needs to see all the rows at
                               1761                 :                :      * once.
                               1762                 :                :      *
                               1763                 :                :      * * We're doing \gexec: we must complete the data fetch to make the
                               1764                 :                :      * connection free for issuing the resulting commands.
                               1765                 :                :      *
                               1766                 :                :      * * We're doing \gset: only one result row is allowed anyway.
                               1767                 :                :      *
                               1768                 :                :      * * We're doing \watch: users probably don't want us to force use of the
                               1769                 :                :      * pager for that, plus chunking could break the min_rows check.
                               1770                 :                :      */
  873 tgl@sss.pgh.pa.us        1771   [ +  +  +  - ]:         253833 :     if (pset.fetch_count > 0 && pset.show_all_results &&
                               1772   [ +  -  +  + ]:             89 :         !pset.crosstab_flag && !pset.gexec_flag &&
                               1773   [ +  +  +  - ]:             85 :         !pset.gset_prefix && !is_watch)
                               1774                 :                :     {
                               1775         [ +  + ]:             69 :         if (!PQsetChunkedRowsMode(pset.db, pset.fetch_count))
                               1776                 :              4 :             pg_log_warning("fetching results in chunked mode failed");
                               1777                 :                :     }
                               1778                 :                : 
                               1779                 :                :     /*
                               1780                 :                :      * If SIGINT is sent while the query is processing, the interrupt will be
                               1781                 :                :      * consumed.  The user's intention, though, is to cancel the entire watch
                               1782                 :                :      * process, so detect a sent cancellation request and exit in this case.
                               1783                 :                :      */
 1606 peter@eisentraut.org     1784   [ +  +  -  + ]:         253833 :     if (is_watch && cancel_pressed)
                               1785                 :                :     {
 1606 peter@eisentraut.org     1786                 :UBC           0 :         ClearOrSaveAllResults();
                               1787                 :              0 :         return 0;
                               1788                 :                :     }
                               1789                 :                : 
                               1790                 :                :     /*
                               1791                 :                :      * If the caller didn't count the number of COPY FROM STDIN command(s) in
                               1792                 :                :      * the query string, we must do so now.
                               1793                 :                :      */
   17 tgl@sss.pgh.pa.us        1794         [ +  + ]:CBC      253833 :     if (num_copy_from_stdin < 0)
                               1795                 :                :     {
                               1796                 :                :         PsqlScanState scan_state;
                               1797                 :                :         PQExpBuffer query_buf;
                               1798                 :                :         promptStatus_t prompt_tmp;
                               1799                 :                :         PsqlScanResult scan_result;
                               1800                 :                : 
                               1801                 :           2099 :         scan_state = psql_scan_create(&psqlscan_callbacks);
                               1802                 :           2099 :         psql_scan_setup(scan_state, query, strlen(query),
                               1803                 :           2099 :                         pset.encoding, standard_strings());
                               1804                 :           2099 :         query_buf = createPQExpBuffer();
                               1805                 :                : 
                               1806                 :                :         /*
                               1807                 :                :          * A semicolon ends only one sub-command; keep scanning so that COPY
                               1808                 :                :          * FROM STDIN commands past the first semicolon are counted too.  The
                               1809                 :                :          * count accumulates in scan_state across the psql_scan() calls.
                               1810                 :                :          */
                               1811                 :                :         do
                               1812                 :                :         {
   13                          1813                 :           2889 :             scan_result = psql_scan(scan_state, query_buf, &prompt_tmp);
                               1814         [ +  + ]:           2889 :         } while (scan_result == PSCAN_SEMICOLON);
                               1815                 :                : 
                               1816                 :                :         /*
                               1817                 :                :          * We expect the result now to be PSCAN_EOL.  If it is PSCAN_BACKSLASH
                               1818                 :                :          * or PSCAN_INCOMPLETE, the server will get a parse error and refuse
                               1819                 :                :          * to execute any part of the command string, so don't expect any
                               1820                 :                :          * PGRES_COPY_IN results.  (This will mean that we don't attempt to
                               1821                 :                :          * discard any following data, but this seems consistent with the
                               1822                 :                :          * general contract of psql_scan_count_copy_from_stdin, which is that
                               1823                 :                :          * it only promises to count syntactically-valid COPY commands.)
                               1824                 :                :          */
                               1825         [ +  + ]:           2099 :         if (scan_result == PSCAN_EOL)
                               1826                 :           2082 :             num_copy_from_stdin = psql_scan_count_copy_from_stdin(scan_state);
                               1827                 :                :         else
                               1828                 :             17 :             num_copy_from_stdin = 0;
                               1829                 :                : 
   17                          1830                 :           2099 :         destroyPQExpBuffer(query_buf);
                               1831                 :           2099 :         psql_scan_destroy(scan_state);
                               1832                 :                :     }
                               1833                 :                : 
                               1834                 :                :     /* first result */
 1606 peter@eisentraut.org     1835                 :         253833 :     result = PQgetResult(pset.db);
 1094 dgustafsson@postgres     1836   [ +  +  +  - ]:         253833 :     if (min_rows > 0 && PQntuples(result) < min_rows)
                               1837                 :                :     {
                               1838                 :              1 :         return_early = true;
                               1839                 :                :     }
                               1840                 :                : 
 1606 peter@eisentraut.org     1841         [ +  + ]:         509145 :     while (result != NULL)
                               1842                 :                :     {
                               1843                 :                :         ExecStatusType result_status;
  873 tgl@sss.pgh.pa.us        1844                 :         255328 :         bool        is_chunked_result = false;
  552 michael@paquier.xyz      1845                 :         255328 :         PGresult   *next_result = NULL;
                               1846                 :                :         bool        last;
                               1847                 :                : 
 1606 peter@eisentraut.org     1848         [ +  + ]:         255328 :         if (!AcceptResult(result, false))
                               1849                 :          30692 :         {
                               1850                 :                :             /*
                               1851                 :                :              * Some error occurred, either a server-side failure or a failure
                               1852                 :                :              * to submit the command string.  Record that.
                               1853                 :                :              */
                               1854                 :          30704 :             const char *error = PQresultErrorMessage(result);
                               1855                 :                : 
                               1856         [ +  + ]:          30704 :             if (strlen(error))
                               1857                 :          30683 :                 pg_log_info("%s", error);
                               1858                 :                : 
                               1859                 :          30704 :             CheckConnection();
                               1860         [ +  + ]:          30692 :             if (!is_watch)
                               1861                 :          30690 :                 SetResultVariables(result, false);
                               1862                 :                : 
                               1863                 :                :             /* keep the result status before clearing it */
                               1864                 :          30692 :             result_status = PQresultStatus(result);
                               1865                 :          30692 :             ClearOrSaveResult(result);
                               1866                 :          30692 :             success = false;
                               1867                 :                : 
  552 michael@paquier.xyz      1868         [ +  + ]:          30692 :             if (result_status == PGRES_PIPELINE_ABORTED)
                               1869                 :             20 :                 pg_log_info("Pipeline aborted, command did not run");
                               1870                 :                : 
                               1871                 :                :             /*
                               1872                 :                :              * switch to next result
                               1873                 :                :              */
 1606 peter@eisentraut.org     1874   [ +  +  +  - ]:          30692 :             if (result_status == PGRES_COPY_BOTH ||
                               1875         [ -  + ]:          30691 :                 result_status == PGRES_COPY_OUT ||
                               1876                 :                :                 result_status == PGRES_COPY_IN)
                               1877                 :                :             {
                               1878                 :                :                 /*
                               1879                 :                :                  * For some obscure reason PQgetResult does *not* return a
                               1880                 :                :                  * NULL in copy cases despite the result having been cleared,
                               1881                 :                :                  * but keeps returning an "empty" result that we have to
                               1882                 :                :                  * ignore manually.
                               1883                 :                :                  */
                               1884                 :              1 :                 result = NULL;
                               1885                 :                :             }
  552 michael@paquier.xyz      1886   [ +  +  +  + ]:          30691 :             else if ((end_pipeline || pset.requested_results > 0)
                               1887         [ +  - ]:            108 :                      && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1888                 :                :             {
                               1889                 :                :                 /*
                               1890                 :                :                  * Error within a pipeline.  All commands are aborted until
                               1891                 :                :                  * the next synchronisation point.  We need to consume all the
                               1892                 :                :                  * results until this synchronisation point, or stop when
                               1893                 :                :                  * there are no more result to discard.
                               1894                 :                :                  *
                               1895                 :                :                  * Checking the pipeline status is necessary for the case
                               1896                 :                :                  * where the connection was reset.  The new connection is not
                               1897                 :                :                  * in any kind of pipeline state and thus has no result to
                               1898                 :                :                  * discard.
                               1899                 :                :                  */
                               1900                 :            108 :                 result = discardAbortedPipelineResults();
                               1901                 :                :             }
                               1902                 :                :             else
 1606 peter@eisentraut.org     1903                 :          30583 :                 result = PQgetResult(pset.db);
                               1904                 :                : 
                               1905                 :                :             /*
                               1906                 :                :              * Get current timing measure in case an error occurs
                               1907                 :                :              */
 1557                          1908         [ +  + ]:          30692 :             if (timing)
                               1909                 :                :             {
                               1910                 :              1 :                 INSTR_TIME_SET_CURRENT(after);
                               1911                 :              1 :                 INSTR_TIME_SUBTRACT(after, before);
                               1912                 :              1 :                 *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
                               1913                 :                :             }
                               1914                 :                : 
 1606                          1915                 :          30692 :             continue;
                               1916                 :                :         }
                               1917   [ +  +  +  + ]:         224624 :         else if (svpt_gone_p && !*svpt_gone_p)
                               1918                 :                :         {
                               1919                 :                :             /*
                               1920                 :                :              * Check if the user ran any command that would destroy our
                               1921                 :                :              * internal savepoint: If the user did COMMIT AND CHAIN, RELEASE
                               1922                 :                :              * or ROLLBACK, our savepoint is gone. If they issued a SAVEPOINT,
                               1923                 :                :              * releasing ours would remove theirs.
                               1924                 :                :              */
                               1925                 :         224490 :             const char *cmd = PQcmdStatus(result);
                               1926                 :                : 
                               1927                 :         669540 :             *svpt_gone_p = (strcmp(cmd, "COMMIT") == 0 ||
                               1928         [ +  + ]:         220560 :                             strcmp(cmd, "SAVEPOINT") == 0 ||
                               1929   [ +  +  +  + ]:         664787 :                             strcmp(cmd, "RELEASE") == 0 ||
                               1930         [ +  + ]:         444227 :                             strcmp(cmd, "ROLLBACK") == 0);
                               1931                 :                :         }
                               1932                 :                : 
                               1933                 :         224624 :         result_status = PQresultStatus(result);
                               1934                 :                : 
                               1935                 :                :         /* must handle COPY before changing the current result */
                               1936         [ -  + ]:         224624 :         Assert(result_status != PGRES_COPY_BOTH);
                               1937   [ +  +  +  + ]:         224624 :         if (result_status == PGRES_COPY_IN ||
                               1938                 :                :             result_status == PGRES_COPY_OUT)
                               1939                 :                :         {
 1424 tgl@sss.pgh.pa.us        1940                 :           1131 :             FILE       *copy_stream = NULL;
                               1941                 :                : 
  440 michael@paquier.xyz      1942         [ +  + ]:           1131 :             if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               1943                 :                :             {
                               1944                 :                :                 /*
                               1945                 :                :                  * Running COPY within a pipeline can break the protocol
                               1946                 :                :                  * synchronisation in multiple ways, and psql shows its limits
                               1947                 :                :                  * when it comes to tracking this information.
                               1948                 :                :                  *
                               1949                 :                :                  * While in COPY mode, the backend process ignores additional
                               1950                 :                :                  * Sync messages and will not send the matching ReadyForQuery
                               1951                 :                :                  * expected by the frontend.
                               1952                 :                :                  *
                               1953                 :                :                  * Additionally, libpq automatically sends a Sync with the
                               1954                 :                :                  * Copy message, creating an unexpected synchronisation point.
                               1955                 :                :                  * A failure during COPY would leave the pipeline in an
                               1956                 :                :                  * aborted state while the backend would be in a clean state,
                               1957                 :                :                  * ready to process commands.
                               1958                 :                :                  *
                               1959                 :                :                  * Improving those issues would require modifications in how
                               1960                 :                :                  * libpq handles pipelines and COPY.  Hence, for the time
                               1961                 :                :                  * being, we forbid the use of COPY within a pipeline,
                               1962                 :                :                  * aborting the connection to avoid an inconsistent state on
                               1963                 :                :                  * psql side if trying to use a COPY command.
                               1964                 :                :                  */
                               1965                 :              4 :                 pg_log_info("COPY in a pipeline is not supported, aborting connection");
  449                          1966                 :              4 :                 exit(EXIT_BADCONN);
                               1967                 :                :             }
                               1968                 :                : 
                               1969                 :                :             /* Select data source or sink. */
 1424 tgl@sss.pgh.pa.us        1970         [ +  + ]:           1127 :             if (result_status == PGRES_COPY_OUT)
                               1971                 :                :             {
                               1972                 :                :                 /*
                               1973                 :                :                  * For COPY OUT, direct the output to the default place
                               1974                 :                :                  * (probably a pager pipe) for \watch, or to pset.copyStream
                               1975                 :                :                  * for \copy, otherwise to pset.gfname if that's set,
                               1976                 :                :                  * otherwise to pset.queryFout.
                               1977                 :                :                  */
                               1978         [ -  + ]:            486 :                 if (is_watch)
                               1979                 :                :                 {
                               1980                 :                :                     /* invoked by \watch */
 1424 tgl@sss.pgh.pa.us        1981         [ #  # ]:UBC           0 :                     copy_stream = printQueryFout ? printQueryFout : pset.queryFout;
                               1982                 :                :                 }
 1424 tgl@sss.pgh.pa.us        1983         [ +  + ]:CBC         486 :                 else if (pset.copyStream)
                               1984                 :                :                 {
                               1985                 :                :                     /* invoked by \copy */
                               1986                 :             36 :                     copy_stream = pset.copyStream;
                               1987                 :                :                 }
                               1988         [ +  + ]:            450 :                 else if (pset.gfname)
                               1989                 :                :                 {
                               1990                 :                :                     /* COPY followed by \g filename or \g |program */
  873                          1991                 :             17 :                     success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
                               1992         [ +  - ]:             17 :                     if (gfile_fout)
 1424                          1993                 :             17 :                         copy_stream = gfile_fout;
                               1994                 :                :                 }
                               1995                 :                :                 else
                               1996                 :                :                 {
                               1997                 :                :                     /* fall back to the generic query output stream */
                               1998                 :            433 :                     copy_stream = pset.queryFout;
                               1999                 :                :                 }
                               2000                 :                :             }
                               2001                 :                :             else
                               2002                 :                :             {
   17                          2003         [ -  + ]:            641 :                 if (num_copy_from_stdin <= 0)
                               2004                 :                :                 {
                               2005                 :                :                     /*
                               2006                 :                :                      * We didn't send a COPY FROM STDIN command.  The server
                               2007                 :                :                      * is broken or possibly malicious.  Report and quit.  (We
                               2008                 :                :                      * could instead send an empty COPY response, but it's not
                               2009                 :                :                      * clear that that's a better behavior; it would make it
                               2010                 :                :                      * harder to diagnose any such problem.)
                               2011                 :                :                      */
   17 tgl@sss.pgh.pa.us        2012                 :UBC           0 :                     pg_log_info("unexpected COPY_IN result, aborting connection");
                               2013                 :              0 :                     exit(EXIT_BADCONN);
                               2014                 :                :                 }
                               2015                 :                :                 /* Keep track of the number of remaining copy operations */
   17 tgl@sss.pgh.pa.us        2016                 :CBC         641 :                 num_copy_from_stdin--;
                               2017                 :                : 
                               2018                 :                :                 /*
                               2019                 :                :                  * For COPY IN, read from pset.copyStream if \copy set that,
                               2020                 :                :                  * otherwise from the current command source.
                               2021                 :                :                  */
                               2022         [ +  + ]:            641 :                 if (pset.copyStream)
                               2023                 :             47 :                     copy_stream = pset.copyStream;
                               2024                 :                :                 else
                               2025                 :            594 :                     copy_stream = pset.cur_cmd_source;
                               2026                 :                :             }
                               2027                 :                : 
                               2028                 :                :             /*
                               2029                 :                :              * Even if the output stream could not be opened, we call
                               2030                 :                :              * HandleCopyResult() with a NULL output stream to collect and
                               2031                 :                :              * discard the COPY data.
                               2032                 :                :              */
 1424                          2033                 :           1127 :             success &= HandleCopyResult(&result, copy_stream);
                               2034                 :                :         }
                               2035                 :                : 
                               2036                 :                :         /* If we have a chunked result, collect and print all chunks */
  873                          2037         [ +  + ]:         224620 :         if (result_status == PGRES_TUPLES_CHUNK)
                               2038                 :                :         {
  871                          2039         [ +  - ]:             44 :             FILE       *tuples_fout = printQueryFout ? printQueryFout : pset.queryFout;
                               2040         [ -  + ]:             44 :             printQueryOpt my_popt = opt ? *opt : pset.popt;
  873                          2041                 :             44 :             int64       total_tuples = 0;
                               2042                 :             44 :             bool        is_pager = false;
                               2043                 :             44 :             int         flush_error = 0;
                               2044                 :                : 
                               2045                 :                :             /* initialize print options for partial table output */
                               2046                 :             44 :             my_popt.topt.start_table = true;
                               2047                 :             44 :             my_popt.topt.stop_table = false;
                               2048                 :             44 :             my_popt.topt.prior_records = 0;
                               2049                 :                : 
                               2050                 :                :             /* open \g file if needed */
                               2051                 :             44 :             success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
                               2052         [ -  + ]:             44 :             if (gfile_fout)
  873 tgl@sss.pgh.pa.us        2053                 :UBC           0 :                 tuples_fout = gfile_fout;
                               2054                 :                : 
                               2055                 :                :             /* force use of pager for any chunked resultset going to stdout */
  873 tgl@sss.pgh.pa.us        2056   [ +  -  +  - ]:CBC          44 :             if (success && tuples_fout == stdout)
                               2057                 :                :             {
                               2058                 :             44 :                 tuples_fout = PageOutput(INT_MAX, &(my_popt.topt));
                               2059                 :             44 :                 is_pager = true;
                               2060                 :                :             }
                               2061                 :                : 
                               2062                 :                :             do
                               2063                 :                :             {
                               2064                 :                :                 /*
                               2065                 :                :                  * Display the current chunk of results, unless the output
                               2066                 :                :                  * stream stopped working or we got canceled.  We skip use of
                               2067                 :                :                  * PrintQueryResult and go directly to printQuery, so that we
                               2068                 :                :                  * can pass the correct is_pager value and because we don't
                               2069                 :                :                  * want PrintQueryStatus to happen yet.  Above, we rejected
                               2070                 :                :                  * use of chunking for all cases in which PrintQueryResult
                               2071                 :                :                  * would send the result to someplace other than printQuery.
                               2072                 :                :                  */
                               2073   [ +  -  +  -  :             60 :                 if (success && !flush_error && !cancel_pressed)
                                              +  - ]
                               2074                 :                :                 {
                               2075                 :             60 :                     printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
                               2076                 :             60 :                     flush_error = fflush(tuples_fout);
                               2077                 :                :                 }
                               2078                 :                : 
                               2079                 :                :                 /* after the first result set, disallow header decoration */
                               2080                 :             60 :                 my_popt.topt.start_table = false;
                               2081                 :                : 
                               2082                 :                :                 /* count tuples before dropping the result */
                               2083                 :             60 :                 my_popt.topt.prior_records += PQntuples(result);
                               2084                 :             60 :                 total_tuples += PQntuples(result);
                               2085                 :                : 
                               2086                 :             60 :                 ClearOrSaveResult(result);
                               2087                 :                : 
                               2088                 :                :                 /* get the next result, loop if it's PGRES_TUPLES_CHUNK */
                               2089                 :             60 :                 result = PQgetResult(pset.db);
                               2090         [ +  + ]:             60 :             } while (PQresultStatus(result) == PGRES_TUPLES_CHUNK);
                               2091                 :                : 
                               2092                 :                :             /* We expect an empty PGRES_TUPLES_OK, else there's a problem */
                               2093         [ +  + ]:             44 :             if (PQresultStatus(result) == PGRES_TUPLES_OK)
                               2094                 :                :             {
                               2095                 :                :                 char        buf[32];
                               2096                 :                : 
                               2097         [ -  + ]:             40 :                 Assert(PQntuples(result) == 0);
                               2098                 :                : 
                               2099                 :                :                 /* Display the footer using the empty result */
                               2100   [ +  -  +  -  :             40 :                 if (success && !flush_error && !cancel_pressed)
                                              +  - ]
                               2101                 :                :                 {
                               2102                 :             40 :                     my_popt.topt.stop_table = true;
                               2103                 :             40 :                     printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
                               2104                 :             40 :                     fflush(tuples_fout);
                               2105                 :                :                 }
                               2106                 :                : 
                               2107         [ +  - ]:             40 :                 if (is_pager)
                               2108                 :             40 :                     ClosePager(tuples_fout);
                               2109                 :                : 
                               2110                 :                :                 /*
                               2111                 :                :                  * It's possible the data is from a RETURNING clause, in which
                               2112                 :                :                  * case we need to print query status.
                               2113                 :                :                  */
  871                          2114                 :             40 :                 PrintQueryStatus(result, printQueryFout);
                               2115                 :                : 
                               2116                 :                :                 /*
                               2117                 :                :                  * We must do a fake SetResultVariables(), since we don't have
                               2118                 :                :                  * a PGresult corresponding to the whole query.
                               2119                 :                :                  */
  873                          2120                 :             40 :                 SetVariable(pset.vars, "ERROR", "false");
                               2121                 :             40 :                 SetVariable(pset.vars, "SQLSTATE", "00000");
                               2122                 :             40 :                 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
                               2123                 :             40 :                 SetVariable(pset.vars, "ROW_COUNT", buf);
                               2124                 :                :                 /* Prevent SetResultVariables call below */
                               2125                 :             40 :                 is_chunked_result = true;
                               2126                 :                : 
                               2127                 :                :                 /* Clear the empty result so it isn't printed below */
                               2128                 :             40 :                 ClearOrSaveResult(result);
                               2129                 :             40 :                 result = NULL;
                               2130                 :                :             }
                               2131                 :                :             else
                               2132                 :                :             {
                               2133                 :                :                 /* Probably an error report, so close the pager and print it */
                               2134         [ +  - ]:              4 :                 if (is_pager)
                               2135                 :              4 :                     ClosePager(tuples_fout);
                               2136                 :                : 
                               2137                 :              4 :                 success &= AcceptResult(result, true);
                               2138                 :                :                 /* SetResultVariables and ClearOrSaveResult happen below */
                               2139                 :                :             }
                               2140                 :                :         }
                               2141                 :                : 
  552 michael@paquier.xyz      2142         [ +  + ]:         224620 :         if (result_status == PGRES_PIPELINE_SYNC)
                               2143                 :                :         {
                               2144                 :                :             /*
                               2145                 :                :              * Sync response, decrease the sync and requested_results
                               2146                 :                :              * counters.  Guard against underflow: an error during Sync
                               2147                 :                :              * processing on the server can cause the client-side counter to
                               2148                 :                :              * drift.
                               2149                 :                :              */
   85                          2150         [ +  - ]:            289 :             if (pset.piped_syncs > 0)
                               2151                 :            289 :                 pset.piped_syncs--;
                               2152         [ +  - ]:            289 :             if (pset.requested_results > 0)
                               2153                 :            289 :                 pset.requested_results--;
                               2154                 :                : 
                               2155                 :                :             /*
                               2156                 :                :              * After a synchronisation point, reset success state to print
                               2157                 :                :              * possible successful results that will be processed after this.
                               2158                 :                :              */
  552                          2159                 :            289 :             success = true;
                               2160                 :                : 
                               2161                 :                :             /*
                               2162                 :                :              * If all syncs were processed and pipeline end was requested,
                               2163                 :                :              * exit pipeline mode.
                               2164                 :                :              */
                               2165   [ +  +  +  + ]:            289 :             if (end_pipeline && pset.piped_syncs == 0)
                               2166                 :            197 :                 success &= PQexitPipelineMode(pset.db);
                               2167                 :                :         }
                               2168   [ +  +  +  - ]:         224331 :         else if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF &&
                               2169                 :                :                  result_status != PGRES_PIPELINE_SYNC)
                               2170                 :                :         {
                               2171                 :                :             /*
                               2172                 :                :              * In a pipeline with a non-sync response?  Decrease the result
                               2173                 :                :              * counters.
                               2174                 :                :              */
   85                          2175         [ +  + ]:            442 :             if (pset.available_results > 0)
                               2176                 :            438 :                 pset.available_results--;
                               2177         [ +  - ]:            442 :             if (pset.requested_results > 0)
                               2178                 :            442 :                 pset.requested_results--;
                               2179                 :                :         }
                               2180                 :                : 
                               2181                 :                :         /*
                               2182                 :                :          * Check PQgetResult() again.  In the typical case of a single-command
                               2183                 :                :          * string, it will return NULL.  Otherwise, we'll have other results
                               2184                 :                :          * to process.  We need to do that to check whether this is the last.
                               2185                 :                :          */
  552                          2186         [ +  + ]:         224620 :         if (PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
                               2187                 :         224086 :             next_result = PQgetResult(pset.db);
                               2188                 :                :         else
                               2189                 :                :         {
                               2190                 :                :             /*
                               2191                 :                :              * In pipeline mode, a NULL result indicates the end of the
                               2192                 :                :              * current query being processed.  Call PQgetResult() once to
                               2193                 :                :              * consume this state.
                               2194                 :                :              */
                               2195         [ +  + ]:            534 :             if (result_status != PGRES_PIPELINE_SYNC)
                               2196                 :                :             {
                               2197                 :            442 :                 next_result = PQgetResult(pset.db);
                               2198         [ -  + ]:            442 :                 Assert(next_result == NULL);
                               2199                 :                :             }
                               2200                 :                : 
                               2201                 :                :             /* Now, we can get the next result in the pipeline. */
                               2202         [ +  + ]:            534 :             if (pset.requested_results > 0)
                               2203                 :            462 :                 next_result = PQgetResult(pset.db);
                               2204                 :                :         }
                               2205                 :                : 
 1606 peter@eisentraut.org     2206                 :         224620 :         last = (next_result == NULL);
                               2207                 :                : 
                               2208                 :                :         /*
                               2209                 :                :          * Update current timing measure.
                               2210                 :                :          *
                               2211                 :                :          * It will include the display of previous results, if any. This
                               2212                 :                :          * cannot be helped because the server goes on processing further
                               2213                 :                :          * queries anyway while the previous ones are being displayed. The
                               2214                 :                :          * parallel execution of the client display hides the server time when
                               2215                 :                :          * it is shorter.
                               2216                 :                :          *
                               2217                 :                :          * With combined queries, timing must be understood as an upper bound
                               2218                 :                :          * of the time spent processing them.
                               2219                 :                :          */
 1557                          2220         [ +  + ]:         224620 :         if (timing)
                               2221                 :                :         {
 1606                          2222                 :              1 :             INSTR_TIME_SET_CURRENT(after);
                               2223                 :              1 :             INSTR_TIME_SUBTRACT(after, before);
                               2224                 :              1 :             *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
                               2225                 :                :         }
                               2226                 :                : 
                               2227                 :                :         /*
                               2228                 :                :          * This may or may not print something depending on settings.
                               2229                 :                :          *
                               2230                 :                :          * A pipeline sync will have a non-NULL result but does not have
                               2231                 :                :          * anything to print, thus ignore results in this case.
                               2232                 :                :          */
  552 michael@paquier.xyz      2233   [ +  +  +  + ]:         224620 :         if (result != NULL && result_status != PGRES_PIPELINE_SYNC)
                               2234                 :                :         {
                               2235                 :                :             /*
                               2236                 :                :              * If results need to be printed into the file specified by \g,
                               2237                 :                :              * open it, unless we already did.  Note that when pset.gfname is
                               2238                 :                :              * set, the passed-in value of printQueryFout is not used for
                               2239                 :                :              * tuple output, but it's still used for status output.
                               2240                 :                :              */
 1424 tgl@sss.pgh.pa.us        2241                 :         223822 :             FILE       *tuples_fout = printQueryFout;
                               2242                 :                : 
  873                          2243         [ +  + ]:         223822 :             if (PQresultStatus(result) == PGRES_TUPLES_OK)
                               2244                 :          96252 :                 success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
                               2245         [ +  + ]:         223822 :             if (gfile_fout)
 1424                          2246                 :             38 :                 tuples_fout = gfile_fout;
  873                          2247         [ +  + ]:         223822 :             if (success)
 1424                          2248                 :         223657 :                 success &= PrintQueryResult(result, last, opt,
                               2249                 :                :                                             tuples_fout, printQueryFout);
                               2250                 :                :         }
                               2251                 :                : 
                               2252                 :                :         /* set variables from last result, unless dealt with elsewhere */
  873                          2253   [ +  +  +  +  :         224620 :         if (last && !is_watch && !is_chunked_result)
                                              +  + ]
 1060 michael@paquier.xyz      2254                 :         223070 :             SetResultVariables(result, success);
                               2255                 :                : 
 1606 peter@eisentraut.org     2256                 :         224620 :         ClearOrSaveResult(result);
                               2257                 :         224620 :         result = next_result;
                               2258                 :                : 
  552 michael@paquier.xyz      2259   [ -  +  -  - ]:         224620 :         if (cancel_pressed && PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
                               2260                 :                :         {
                               2261                 :                :             /*
                               2262                 :                :              * Outside of a pipeline, drop the next result, as well as any
                               2263                 :                :              * others not yet read.
                               2264                 :                :              *
                               2265                 :                :              * Within a pipeline, we can let the outer loop handle this as an
                               2266                 :                :              * aborted pipeline, which will discard then all the results.
                               2267                 :                :              */
  871 tgl@sss.pgh.pa.us        2268                 :UBC           0 :             ClearOrSaveResult(result);
 1606 peter@eisentraut.org     2269                 :              0 :             ClearOrSaveAllResults();
                               2270                 :              0 :             break;
                               2271                 :                :         }
                               2272                 :                :     }
                               2273                 :                : 
                               2274                 :                :     /* close \g file if we opened it */
  873 tgl@sss.pgh.pa.us        2275                 :CBC      253817 :     CloseGOutput(gfile_fout, gfile_is_pipe);
                               2276                 :                : 
  552 michael@paquier.xyz      2277         [ +  + ]:         253817 :     if (end_pipeline)
                               2278                 :                :     {
                               2279                 :                :         /*
                               2280                 :                :          * Reset available/requested results.  Normally these are already 0,
                               2281                 :                :          * but an error generated by a Sync processing itself can leave some
                               2282                 :                :          * of them behind.  Consume them before exiting pipeline mode.
                               2283                 :                :          */
   85                          2284         [ +  + ]:            237 :         while (pset.piped_syncs > 0)
                               2285                 :                :         {
                               2286                 :                :             PGresult   *remaining;
                               2287                 :                : 
                               2288                 :             20 :             remaining = PQgetResult(pset.db);
                               2289                 :                : 
                               2290         [ -  + ]:             20 :             if (remaining == NULL)
                               2291                 :                :             {
   85 michael@paquier.xyz      2292         [ #  # ]:UBC           0 :                 if (!ConnectionUp())
                               2293                 :              0 :                     break;
                               2294                 :              0 :                 continue;
                               2295                 :                :             }
   85 michael@paquier.xyz      2296         [ +  - ]:CBC          20 :             if (PQresultStatus(remaining) == PGRES_PIPELINE_SYNC)
                               2297                 :             20 :                 pset.piped_syncs--;
                               2298                 :             20 :             PQclear(remaining);
                               2299                 :                :         }
                               2300                 :            217 :         pset.piped_syncs = 0;
                               2301                 :            217 :         pset.piped_commands = 0;
                               2302                 :            217 :         pset.available_results = 0;
                               2303                 :            217 :         pset.requested_results = 0;
                               2304                 :                : 
                               2305         [ +  + ]:            217 :         if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
                               2306                 :             20 :             PQexitPipelineMode(pset.db);
                               2307                 :                :     }
  552                          2308         [ -  + ]:         253817 :     Assert(pset.requested_results == 0);
                               2309                 :                : 
  548                          2310                 :         253817 :     SetPipelineVariables();
                               2311                 :                : 
                               2312                 :                :     /* may need this to recover from conn loss during COPY */
 1606 peter@eisentraut.org     2313         [ -  + ]:         253817 :     if (!CheckConnection())
 1606 peter@eisentraut.org     2314                 :UBC           0 :         return -1;
                               2315                 :                : 
                               2316                 :                :     /*
                               2317                 :                :      * If we were expecting COPY ... FROM STDIN, and we didn't get
                               2318                 :                :      * PGRES_COPY_IN (presumably because the COPY failed server-side), and the
                               2319                 :                :      * data is supposed to come from the current command source, we must eat
                               2320                 :                :      * up the data in order to stay in sync with the command file's contents.
                               2321                 :                :      * Repeat for the number of unfulfilled COPY commands.
                               2322                 :                :      */
   17 tgl@sss.pgh.pa.us        2323         [ +  + ]:CBC      254122 :     while (num_copy_from_stdin > 0)
                               2324                 :                :     {
                               2325         [ +  + ]:            305 :         if (pset.copyStream == NULL ||
                               2326         [ +  + ]:              5 :             pset.copyStream == pset.cur_cmd_source)
                               2327                 :            304 :             (void) handleCopyIn(NULL,   /* no connection */
                               2328                 :                :                                 pset.cur_cmd_source,
                               2329                 :                :                                 false,  /* XXX assume not binary */
                               2330                 :                :                                 NULL);  /* no result */
                               2331                 :            305 :         num_copy_from_stdin--;
                               2332                 :                :     }
                               2333                 :                : 
 1094 dgustafsson@postgres     2334   [ +  +  +  + ]:         253817 :     if (cancel_pressed || return_early)
                               2335                 :              2 :         return 0;
                               2336                 :                : 
                               2337         [ +  + ]:         253815 :     return success ? 1 : -1;
                               2338                 :                : }
                               2339                 :                : 
                               2340                 :                : 
                               2341                 :                : /*
                               2342                 :                :  * Advance the given char pointer over white space and SQL comments.
                               2343                 :                :  */
                               2344                 :                : static const char *
 8011 tgl@sss.pgh.pa.us        2345                 :             72 : skip_white_space(const char *query)
                               2346                 :                : {
 7621 bruce@momjian.us         2347                 :             72 :     int         cnestlevel = 0; /* slash-star comment nest level */
                               2348                 :                : 
 8461 tgl@sss.pgh.pa.us        2349         [ +  - ]:             88 :     while (*query)
                               2350                 :                :     {
 1907                          2351                 :             88 :         int         mblen = PQmblenBounded(query, pset.encoding);
                               2352                 :                : 
                               2353                 :                :         /*
                               2354                 :                :          * Note: we assume the encoding is a superset of ASCII, so that for
                               2355                 :                :          * example "query[0] == '/'" is meaningful.  However, we do NOT assume
                               2356                 :                :          * that the second and subsequent bytes of a multibyte character
                               2357                 :                :          * couldn't look like ASCII characters; so it is critical to advance
                               2358                 :                :          * by mblen, not 1, whenever we haven't exactly identified the
                               2359                 :                :          * character we are skipping over.
                               2360                 :                :          */
 8461                          2361         [ +  + ]:             88 :         if (isspace((unsigned char) *query))
 8011                          2362                 :             16 :             query += mblen;
                               2363   [ -  +  -  - ]:             72 :         else if (query[0] == '/' && query[1] == '*')
                               2364                 :                :         {
 8011 tgl@sss.pgh.pa.us        2365                 :UBC           0 :             cnestlevel++;
 8461                          2366                 :              0 :             query += 2;
                               2367                 :                :         }
 8011 tgl@sss.pgh.pa.us        2368   [ -  +  -  -  :CBC          72 :         else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
                                              -  - ]
                               2369                 :                :         {
 8011 tgl@sss.pgh.pa.us        2370                 :UBC           0 :             cnestlevel--;
                               2371                 :              0 :             query += 2;
                               2372                 :                :         }
 8011 tgl@sss.pgh.pa.us        2373   [ +  -  -  +  :CBC          72 :         else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
                                              -  - ]
                               2374                 :                :         {
 8461 tgl@sss.pgh.pa.us        2375                 :UBC           0 :             query += 2;
                               2376                 :                : 
                               2377                 :                :             /*
                               2378                 :                :              * We have to skip to end of line since any slash-star inside the
                               2379                 :                :              * -- comment does NOT start a slash-star comment.
                               2380                 :                :              */
                               2381         [ #  # ]:              0 :             while (*query)
                               2382                 :                :             {
 8011                          2383         [ #  # ]:              0 :                 if (*query == '\n')
                               2384                 :                :                 {
                               2385                 :              0 :                     query++;
 8461                          2386                 :              0 :                     break;
                               2387                 :                :                 }
 1907                          2388                 :              0 :                 query += PQmblenBounded(query, pset.encoding);
                               2389                 :                :             }
                               2390                 :                :         }
 8011 tgl@sss.pgh.pa.us        2391         [ -  + ]:CBC          72 :         else if (cnestlevel > 0)
 8011 tgl@sss.pgh.pa.us        2392                 :UBC           0 :             query += mblen;
                               2393                 :                :         else
 8461 tgl@sss.pgh.pa.us        2394                 :CBC          72 :             break;              /* found first token */
                               2395                 :                :     }
                               2396                 :                : 
 8011                          2397                 :             72 :     return query;
                               2398                 :                : }
                               2399                 :                : 
                               2400                 :                : 
                               2401                 :                : /*
                               2402                 :                :  * Check whether a command is one of those for which we should NOT start
                               2403                 :                :  * a new transaction block (ie, send a preceding BEGIN).
                               2404                 :                :  *
                               2405                 :                :  * These include the transaction control statements themselves, plus
                               2406                 :                :  * certain statements that the backend disallows inside transaction blocks.
                               2407                 :                :  */
                               2408                 :                : static bool
                               2409                 :             56 : command_no_begin(const char *query)
                               2410                 :                : {
                               2411                 :                :     int         wordlen;
                               2412                 :                : 
                               2413                 :                :     /*
                               2414                 :                :      * First we must advance over any whitespace and comments.
                               2415                 :                :      */
                               2416                 :             56 :     query = skip_white_space(query);
                               2417                 :                : 
                               2418                 :                :     /*
                               2419                 :                :      * Check word length (since "beginx" is not "begin").
                               2420                 :                :      */
 8461                          2421                 :             56 :     wordlen = 0;
                               2422         [ +  + ]:            376 :     while (isalpha((unsigned char) query[wordlen]))
 1907                          2423                 :            320 :         wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2424                 :                : 
                               2425                 :                :     /*
                               2426                 :                :      * Transaction control commands.  These should include every keyword that
                               2427                 :                :      * gives rise to a TransactionStmt in the backend grammar, except for the
                               2428                 :                :      * savepoint-related commands.
                               2429                 :                :      *
                               2430                 :                :      * (We assume that START must be START TRANSACTION, since there is
                               2431                 :                :      * presently no other "START foo" command.)
                               2432                 :                :      */
 8011                          2433   [ +  +  -  + ]:             56 :     if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
 8011 tgl@sss.pgh.pa.us        2434                 :UBC           0 :         return true;
 8147 tgl@sss.pgh.pa.us        2435   [ +  +  +  - ]:CBC          56 :     if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
 8461                          2436                 :              8 :         return true;
 8011                          2437   [ -  +  -  - ]:             48 :     if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
 8011 tgl@sss.pgh.pa.us        2438                 :UBC           0 :         return true;
 8147 tgl@sss.pgh.pa.us        2439   [ +  +  -  + ]:CBC          48 :     if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
 8461 tgl@sss.pgh.pa.us        2440                 :UBC           0 :         return true;
 8011 tgl@sss.pgh.pa.us        2441   [ -  +  -  - ]:CBC          48 :     if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
 8461 tgl@sss.pgh.pa.us        2442                 :UBC           0 :         return true;
 8011 tgl@sss.pgh.pa.us        2443   [ -  +  -  - ]:CBC          48 :     if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
 8461 tgl@sss.pgh.pa.us        2444                 :UBC           0 :         return true;
 7741 tgl@sss.pgh.pa.us        2445   [ -  +  -  - ]:CBC          48 :     if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
                               2446                 :                :     {
                               2447                 :                :         /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
 7741 tgl@sss.pgh.pa.us        2448                 :UBC           0 :         query += wordlen;
                               2449                 :                : 
                               2450                 :              0 :         query = skip_white_space(query);
                               2451                 :                : 
                               2452                 :              0 :         wordlen = 0;
                               2453         [ #  # ]:              0 :         while (isalpha((unsigned char) query[wordlen]))
 1907                          2454                 :              0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2455                 :                : 
 7741                          2456   [ #  #  #  # ]:              0 :         if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
                               2457                 :              0 :             return true;
                               2458                 :              0 :         return false;
                               2459                 :                :     }
                               2460                 :                : 
                               2461                 :                :     /*
                               2462                 :                :      * Commands not allowed within transactions.  The statements checked for
                               2463                 :                :      * here should be exactly those that call PreventInTransactionBlock() in
                               2464                 :                :      * the backend.
                               2465                 :                :      */
 8011 tgl@sss.pgh.pa.us        2466   [ +  +  -  + ]:CBC          48 :     if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
 8461 tgl@sss.pgh.pa.us        2467                 :UBC           0 :         return true;
 8011 tgl@sss.pgh.pa.us        2468   [ -  +  -  - ]:CBC          48 :     if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
                               2469                 :                :     {
                               2470                 :                :         /* CLUSTER with any arguments is allowed in transactions */
 7307 tgl@sss.pgh.pa.us        2471                 :UBC           0 :         query += wordlen;
                               2472                 :                : 
                               2473                 :              0 :         query = skip_white_space(query);
                               2474                 :                : 
                               2475         [ #  # ]:              0 :         if (isalpha((unsigned char) query[0]))
                               2476                 :              0 :             return false;       /* has additional words */
                               2477                 :              0 :         return true;            /* it's CLUSTER without arguments */
                               2478                 :                :     }
                               2479                 :                : 
 7307 tgl@sss.pgh.pa.us        2480   [ +  +  +  + ]:CBC          48 :     if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
                               2481                 :                :     {
                               2482                 :              8 :         query += wordlen;
                               2483                 :                : 
                               2484                 :              8 :         query = skip_white_space(query);
                               2485                 :                : 
                               2486                 :              8 :         wordlen = 0;
                               2487         [ +  + ]:             48 :         while (isalpha((unsigned char) query[wordlen]))
 1907                          2488                 :             40 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2489                 :                : 
 7307                          2490   [ -  +  -  - ]:              8 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
 7307 tgl@sss.pgh.pa.us        2491                 :UBC           0 :             return true;
 7307 tgl@sss.pgh.pa.us        2492   [ -  +  -  - ]:CBC           8 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
 7307 tgl@sss.pgh.pa.us        2493                 :UBC           0 :             return true;
                               2494                 :                : 
                               2495                 :                :         /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
 7307 tgl@sss.pgh.pa.us        2496   [ -  +  -  - ]:CBC           8 :         if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
                               2497                 :                :         {
 7307 tgl@sss.pgh.pa.us        2498                 :UBC           0 :             query += wordlen;
                               2499                 :                : 
                               2500                 :              0 :             query = skip_white_space(query);
                               2501                 :                : 
                               2502                 :              0 :             wordlen = 0;
                               2503         [ #  # ]:              0 :             while (isalpha((unsigned char) query[wordlen]))
 1907                          2504                 :              0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2505                 :                :         }
                               2506                 :                : 
 7307 tgl@sss.pgh.pa.us        2507   [ +  -  -  + ]:CBC           8 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
                               2508                 :                :         {
 7307 tgl@sss.pgh.pa.us        2509                 :UBC           0 :             query += wordlen;
                               2510                 :                : 
                               2511                 :              0 :             query = skip_white_space(query);
                               2512                 :                : 
                               2513                 :              0 :             wordlen = 0;
                               2514         [ #  # ]:              0 :             while (isalpha((unsigned char) query[wordlen]))
 1907                          2515                 :              0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2516                 :                : 
 7307                          2517   [ #  #  #  # ]:              0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
                               2518                 :              0 :                 return true;
                               2519                 :                :         }
                               2520                 :                : 
 7307 tgl@sss.pgh.pa.us        2521                 :CBC           8 :         return false;
                               2522                 :                :     }
                               2523                 :                : 
 4439 fujii@postgresql.org     2524   [ -  +  -  - ]:             40 :     if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
                               2525                 :                :     {
 4439 fujii@postgresql.org     2526                 :UBC           0 :         query += wordlen;
                               2527                 :                : 
                               2528                 :              0 :         query = skip_white_space(query);
                               2529                 :                : 
                               2530                 :              0 :         wordlen = 0;
                               2531         [ #  # ]:              0 :         while (isalpha((unsigned char) query[wordlen]))
 1907 tgl@sss.pgh.pa.us        2532                 :              0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2533                 :                : 
                               2534                 :                :         /* ALTER SYSTEM isn't allowed in xacts */
 4439 fujii@postgresql.org     2535   [ #  #  #  # ]:              0 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
                               2536                 :              0 :             return true;
                               2537                 :                : 
                               2538                 :              0 :         return false;
                               2539                 :                :     }
                               2540                 :                : 
                               2541                 :                :     /*
                               2542                 :                :      * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
                               2543                 :                :      * aren't really valid commands so we don't care much. The other four
                               2544                 :                :      * possible matches are correct.
                               2545                 :                :      */
 7307 tgl@sss.pgh.pa.us        2546   [ +  +  -  +  :CBC          40 :     if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
                                              -  + ]
 8011 tgl@sss.pgh.pa.us        2547         [ #  # ]:UBC           0 :         (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
                               2548                 :                :     {
 8011 tgl@sss.pgh.pa.us        2549                 :CBC           4 :         query += wordlen;
                               2550                 :                : 
                               2551                 :              4 :         query = skip_white_space(query);
                               2552                 :                : 
                               2553                 :              4 :         wordlen = 0;
                               2554         [ +  + ]:             24 :         while (isalpha((unsigned char) query[wordlen]))
 1907                          2555                 :             20 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2556                 :                : 
 8011                          2557   [ -  +  -  - ]:              4 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
 8011 tgl@sss.pgh.pa.us        2558                 :UBC           0 :             return true;
 7736 tgl@sss.pgh.pa.us        2559   [ -  +  -  - ]:CBC           4 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
 7736 tgl@sss.pgh.pa.us        2560                 :UBC           0 :             return true;
 8011 tgl@sss.pgh.pa.us        2561   [ -  +  -  - ]:CBC           4 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
 8011 tgl@sss.pgh.pa.us        2562                 :UBC           0 :             return true;
 2708 peter@eisentraut.org     2563   [ +  -  +  -  :CBC           8 :         if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
                                              +  - ]
                               2564                 :              4 :                              pg_strncasecmp(query, "table", 5) == 0))
                               2565                 :                :         {
                               2566                 :              4 :             query += wordlen;
                               2567                 :              4 :             query = skip_white_space(query);
                               2568                 :              4 :             wordlen = 0;
                               2569         [ +  + ]:             16 :             while (isalpha((unsigned char) query[wordlen]))
 1907 tgl@sss.pgh.pa.us        2570                 :             12 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2571                 :                : 
                               2572                 :                :             /*
                               2573                 :                :              * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
                               2574                 :                :              * xacts.
                               2575                 :                :              */
 2708 peter@eisentraut.org     2576   [ -  +  -  - ]:              4 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
 2708 peter@eisentraut.org     2577                 :UBC           0 :                 return true;
                               2578                 :                :         }
                               2579                 :                : 
                               2580                 :                :         /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
 4179 bruce@momjian.us         2581   [ -  +  -  - ]:CBC           4 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
                               2582                 :                :         {
 4179 bruce@momjian.us         2583                 :UBC           0 :             query += wordlen;
                               2584                 :                : 
                               2585                 :              0 :             query = skip_white_space(query);
                               2586                 :                : 
                               2587                 :              0 :             wordlen = 0;
                               2588         [ #  # ]:              0 :             while (isalpha((unsigned char) query[wordlen]))
 1907 tgl@sss.pgh.pa.us        2589                 :              0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2590                 :                : 
 4179 bruce@momjian.us         2591   [ #  #  #  # ]:              0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
                               2592                 :              0 :                 return true;
                               2593                 :                : 
                               2594                 :              0 :             return false;
                               2595                 :                :         }
                               2596                 :                : 
 5812 tgl@sss.pgh.pa.us        2597                 :CBC           4 :         return false;
                               2598                 :                :     }
                               2599                 :                : 
                               2600                 :                :     /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
      itagaki.takahiro@gma     2601   [ -  +  -  - ]:             36 :     if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
                               2602                 :                :     {
 5812 itagaki.takahiro@gma     2603                 :UBC           0 :         query += wordlen;
                               2604                 :                : 
                               2605                 :              0 :         query = skip_white_space(query);
                               2606                 :                : 
                               2607                 :              0 :         wordlen = 0;
                               2608         [ #  # ]:              0 :         while (isalpha((unsigned char) query[wordlen]))
 1907 tgl@sss.pgh.pa.us        2609                 :              0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
                               2610                 :                : 
 5812 itagaki.takahiro@gma     2611   [ #  #  #  # ]:              0 :         if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
                               2612                 :              0 :             return true;
      tgl@sss.pgh.pa.us        2613                 :              0 :         return false;
                               2614                 :                :     }
                               2615                 :                : 
 8461 tgl@sss.pgh.pa.us        2616                 :CBC          36 :     return false;
                               2617                 :                : }
                               2618                 :                : 
                               2619                 :                : 
                               2620                 :                : /*
                               2621                 :                :  * Test if the current user is a database superuser.
                               2622                 :                :  */
                               2623                 :                : bool
                               2624                 :             72 : is_superuser(void)
                               2625                 :                : {
                               2626                 :                :     const char *val;
                               2627                 :                : 
                               2628         [ -  + ]:             72 :     if (!pset.db)
 8461 tgl@sss.pgh.pa.us        2629                 :UBC           0 :         return false;
                               2630                 :                : 
 8461 tgl@sss.pgh.pa.us        2631                 :CBC          72 :     val = PQparameterStatus(pset.db, "is_superuser");
                               2632                 :                : 
                               2633   [ +  -  +  - ]:             72 :     if (val && strcmp(val, "on") == 0)
                               2634                 :             72 :         return true;
                               2635                 :                : 
 8461 tgl@sss.pgh.pa.us        2636                 :UBC           0 :     return false;
                               2637                 :                : }
                               2638                 :                : 
                               2639                 :                : 
                               2640                 :                : /*
                               2641                 :                :  * Test if the current session uses standard string literals.
                               2642                 :                :  */
                               2643                 :                : bool
 7479 bruce@momjian.us         2644                 :CBC      528817 : standard_strings(void)
                               2645                 :                : {
                               2646                 :                :     const char *val;
                               2647                 :                : 
                               2648         [ -  + ]:         528817 :     if (!pset.db)
 7479 bruce@momjian.us         2649                 :UBC           0 :         return false;
                               2650                 :                : 
 7479 bruce@momjian.us         2651                 :CBC      528817 :     val = PQparameterStatus(pset.db, "standard_conforming_strings");
                               2652                 :                : 
                               2653   [ +  -  +  - ]:         528817 :     if (val && strcmp(val, "on") == 0)
                               2654                 :         528817 :         return true;
                               2655                 :                : 
 7479 bruce@momjian.us         2656                 :UBC           0 :     return false;
                               2657                 :                : }
                               2658                 :                : 
                               2659                 :                : 
                               2660                 :                : /*
                               2661                 :                :  * Return the session user of the current connection.
                               2662                 :                :  */
                               2663                 :                : const char *
 8394 peter_e@gmx.net          2664                 :              0 : session_username(void)
                               2665                 :                : {
                               2666                 :                :     const char *val;
                               2667                 :                : 
                               2668         [ #  # ]:              0 :     if (!pset.db)
                               2669                 :              0 :         return NULL;
                               2670                 :                : 
                               2671                 :              0 :     val = PQparameterStatus(pset.db, "session_authorization");
                               2672         [ #  # ]:              0 :     if (val)
                               2673                 :              0 :         return val;
                               2674                 :                :     else
                               2675                 :              0 :         return PQuser(pset.db);
                               2676                 :                : }
                               2677                 :                : 
                               2678                 :                : /*
                               2679                 :                :  * Return the value of option for keyword in the current connection.
                               2680                 :                :  *
                               2681                 :                :  * The caller is responsible for freeing the result value allocated.
                               2682                 :                :  */
                               2683                 :                : char *
  414 michael@paquier.xyz      2684                 :CBC       21908 : get_conninfo_value(const char *keyword)
                               2685                 :                : {
                               2686                 :                :     PQconninfoOption *opts;
                               2687                 :          21908 :     PQconninfoOption *serviceopt = NULL;
                               2688                 :          21908 :     char       *res = NULL;
                               2689                 :                : 
                               2690         [ -  + ]:          21908 :     if (pset.db == NULL)
  414 michael@paquier.xyz      2691                 :UBC           0 :         return NULL;
                               2692                 :                : 
  414 michael@paquier.xyz      2693                 :CBC       21908 :     opts = PQconninfo(pset.db);
                               2694         [ -  + ]:          21908 :     if (opts == NULL)
  414 michael@paquier.xyz      2695                 :UBC           0 :         return NULL;
                               2696                 :                : 
  414 michael@paquier.xyz      2697         [ +  - ]:CBC       32862 :     for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
                               2698                 :                :     {
                               2699         [ +  + ]:          32862 :         if (strcmp(opt->keyword, keyword) == 0)
                               2700                 :                :         {
                               2701                 :          21908 :             serviceopt = opt;
                               2702                 :          21908 :             break;
                               2703                 :                :         }
                               2704                 :                :     }
                               2705                 :                : 
                               2706                 :                :     /* Take a copy of the value, as it is freed by PQconninfoFree(). */
                               2707   [ +  -  +  + ]:          21908 :     if (serviceopt && serviceopt->val != NULL)
                               2708                 :             24 :         res = pg_strdup(serviceopt->val);
                               2709                 :          21908 :     PQconninfoFree(opts);
                               2710                 :                : 
                               2711                 :          21908 :     return res;
                               2712                 :                : }
                               2713                 :                : 
                               2714                 :                : /*
                               2715                 :                :  * expand_tilde
                               2716                 :                :  *
                               2717                 :                :  * substitute '~' with HOME or '~username' with username's home dir
                               2718                 :                :  *
                               2719                 :                :  */
                               2720                 :                : void
 8266 bruce@momjian.us         2721                 :            107 : expand_tilde(char **filename)
                               2722                 :                : {
                               2723   [ +  -  +  + ]:            107 :     if (!filename || !(*filename))
 4893                          2724                 :             12 :         return;
                               2725                 :                : 
                               2726                 :                :     /*
                               2727                 :                :      * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
                               2728                 :                :      * for short versions of long file names, though the tilde is usually
                               2729                 :                :      * toward the end, not at the beginning.
                               2730                 :                :      */
                               2731                 :                : #ifndef WIN32
                               2732                 :                : 
                               2733                 :                :     /* try tilde expansion */
 8266                          2734         [ -  + ]:             95 :     if (**filename == '~')
                               2735                 :                :     {
                               2736                 :                :         char       *fn;
                               2737                 :                :         char        oldp,
                               2738                 :                :                    *p;
                               2739                 :                :         struct passwd *pw;
                               2740                 :                :         char        home[MAXPGPATH];
                               2741                 :                : 
 8266 bruce@momjian.us         2742                 :UBC           0 :         fn = *filename;
 8044                          2743                 :              0 :         *home = '\0';
                               2744                 :                : 
 8266                          2745                 :              0 :         p = fn + 1;
                               2746   [ #  #  #  # ]:              0 :         while (*p != '/' && *p != '\0')
                               2747                 :              0 :             p++;
                               2748                 :                : 
                               2749                 :              0 :         oldp = *p;
                               2750                 :              0 :         *p = '\0';
                               2751                 :                : 
                               2752         [ #  # ]:              0 :         if (*(fn + 1) == '\0')
 7748                          2753                 :              0 :             get_home_path(home);    /* ~ or ~/ only */
 8266                          2754         [ #  # ]:              0 :         else if ((pw = getpwnam(fn + 1)) != NULL)
 6860                          2755                 :              0 :             strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
                               2756                 :                : 
 8266                          2757                 :              0 :         *p = oldp;
 8044                          2758         [ #  # ]:              0 :         if (strlen(home) != 0)
                               2759                 :                :         {
                               2760                 :                :             char       *newfn;
                               2761                 :                : 
 4692 tgl@sss.pgh.pa.us        2762                 :              0 :             newfn = psprintf("%s%s", home, p);
 8266 bruce@momjian.us         2763                 :              0 :             free(fn);
                               2764                 :              0 :             *filename = newfn;
                               2765                 :                :         }
                               2766                 :                :     }
                               2767                 :                : #endif
                               2768                 :                : }
                               2769                 :                : 
                               2770                 :                : /*
                               2771                 :                :  * Checks if connection string starts with either of the valid URI prefix
                               2772                 :                :  * designators.
                               2773                 :                :  *
                               2774                 :                :  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
                               2775                 :                :  *
                               2776                 :                :  * XXX This is a duplicate of the eponymous libpq function.
                               2777                 :                :  */
                               2778                 :                : static int
 4165 alvherre@alvh.no-ip.     2779                 :CBC          17 : uri_prefix_length(const char *connstr)
                               2780                 :                : {
                               2781                 :                :     /* The connection URI must start with either of the following designators: */
                               2782                 :                :     static const char uri_designator[] = "postgresql://";
                               2783                 :                :     static const char short_uri_designator[] = "postgres://";
                               2784                 :                : 
                               2785         [ -  + ]:             17 :     if (strncmp(connstr, uri_designator,
                               2786                 :                :                 sizeof(uri_designator) - 1) == 0)
 4165 alvherre@alvh.no-ip.     2787                 :UBC           0 :         return sizeof(uri_designator) - 1;
                               2788                 :                : 
 4165 alvherre@alvh.no-ip.     2789         [ -  + ]:CBC          17 :     if (strncmp(connstr, short_uri_designator,
                               2790                 :                :                 sizeof(short_uri_designator) - 1) == 0)
 4165 alvherre@alvh.no-ip.     2791                 :UBC           0 :         return sizeof(short_uri_designator) - 1;
                               2792                 :                : 
 4165 alvherre@alvh.no-ip.     2793                 :CBC          17 :     return 0;
                               2794                 :                : }
                               2795                 :                : 
                               2796                 :                : /*
                               2797                 :                :  * Reset state related to extended query protocol
                               2798                 :                :  *
                               2799                 :                :  * Clean up any state related to bind parameters, statement name and
                               2800                 :                :  * PSQL_SEND_MODE.  This needs to be called after processing a query or when
                               2801                 :                :  * running a new meta-command that uses the extended query protocol, like
                               2802                 :                :  * \parse, \bind, etc.
                               2803                 :                :  */
                               2804                 :                : void
  707 michael@paquier.xyz      2805                 :         255588 : clean_extended_state(void)
                               2806                 :                : {
                               2807                 :                :     int         i;
                               2808                 :                : 
                               2809   [ +  +  +  +  :         255588 :     switch (pset.send_mode)
                                                 - ]
                               2810                 :                :     {
  429                          2811                 :             25 :         case PSQL_SEND_EXTENDED_CLOSE:  /* \close_prepared */
  707                          2812                 :             25 :             free(pset.stmtName);
                               2813                 :             25 :             break;
                               2814                 :             67 :         case PSQL_SEND_EXTENDED_PARSE:  /* \parse */
                               2815                 :             67 :             free(pset.stmtName);
                               2816                 :             67 :             break;
                               2817                 :            628 :         case PSQL_SEND_EXTENDED_QUERY_PARAMS:   /* \bind */
                               2818                 :                :         case PSQL_SEND_EXTENDED_QUERY_PREPARED: /* \bind_named */
                               2819         [ +  + ]:           1175 :             for (i = 0; i < pset.bind_nparams; i++)
                               2820                 :            547 :                 free(pset.bind_params[i]);
                               2821                 :            628 :             free(pset.bind_params);
                               2822                 :            628 :             free(pset.stmtName);
                               2823                 :            628 :             pset.bind_params = NULL;
                               2824                 :            628 :             break;
                               2825                 :         254868 :         case PSQL_SEND_QUERY:
                               2826                 :                :         case PSQL_SEND_START_PIPELINE_MODE: /* \startpipeline */
                               2827                 :                :         case PSQL_SEND_END_PIPELINE_MODE:   /* \endpipeline */
                               2828                 :                :         case PSQL_SEND_PIPELINE_SYNC:   /* \syncpipeline */
                               2829                 :                :         case PSQL_SEND_FLUSH:   /* \flush */
                               2830                 :                :         case PSQL_SEND_GET_RESULTS: /* \getresults */
                               2831                 :                :         case PSQL_SEND_FLUSH_REQUEST:   /* \flushrequest */
                               2832                 :         254868 :             break;
                               2833                 :                :     }
                               2834                 :                : 
                               2835                 :         255588 :     pset.stmtName = NULL;
                               2836                 :         255588 :     pset.send_mode = PSQL_SEND_QUERY;
                               2837                 :         255588 : }
                               2838                 :                : 
                               2839                 :                : /*
                               2840                 :                :  * Recognized connection string either starts with a valid URI prefix or
                               2841                 :                :  * contains a "=" in it.
                               2842                 :                :  *
                               2843                 :                :  * Must be consistent with parse_connection_string: anything for which this
                               2844                 :                :  * returns true should at least look like it's parseable by that routine.
                               2845                 :                :  *
                               2846                 :                :  * XXX This is a duplicate of the eponymous libpq function.
                               2847                 :                :  */
                               2848                 :                : bool
 4165 alvherre@alvh.no-ip.     2849                 :             17 : recognized_connection_string(const char *connstr)
                               2850                 :                : {
                               2851   [ +  -  +  + ]:             17 :     return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
                               2852                 :                : }
        

Generated by: LCOV version 2.0-1