LCOV - code coverage report
Current view: top level - src/bin/psql - command.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1137 2041 55.7 %
Date: 2020-05-29 01:06:25 Functions: 82 94 87.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * psql - the PostgreSQL interactive terminal
       3             :  *
       4             :  * Copyright (c) 2000-2020, PostgreSQL Global Development Group
       5             :  *
       6             :  * src/bin/psql/command.c
       7             :  */
       8             : #include "postgres_fe.h"
       9             : 
      10             : #include <ctype.h>
      11             : #include <time.h>
      12             : #include <pwd.h>
      13             : #ifndef WIN32
      14             : #include <sys/stat.h>         /* for stat() */
      15             : #include <fcntl.h>                /* open() flags */
      16             : #include <unistd.h>               /* for geteuid(), getpid(), stat() */
      17             : #else
      18             : #include <win32.h>
      19             : #include <io.h>
      20             : #include <fcntl.h>
      21             : #include <direct.h>
      22             : #include <sys/stat.h>         /* for stat() */
      23             : #endif
      24             : 
      25             : #include "catalog/pg_class_d.h"
      26             : #include "command.h"
      27             : #include "common.h"
      28             : #include "common/logging.h"
      29             : #include "copy.h"
      30             : #include "crosstabview.h"
      31             : #include "describe.h"
      32             : #include "fe_utils/cancel.h"
      33             : #include "fe_utils/print.h"
      34             : #include "fe_utils/string_utils.h"
      35             : #include "help.h"
      36             : #include "input.h"
      37             : #include "large_obj.h"
      38             : #include "libpq-fe.h"
      39             : #include "mainloop.h"
      40             : #include "portability/instr_time.h"
      41             : #include "pqexpbuffer.h"
      42             : #include "psqlscanslash.h"
      43             : #include "settings.h"
      44             : #include "variables.h"
      45             : 
      46             : /*
      47             :  * Editable database object types.
      48             :  */
      49             : typedef enum EditableObjectType
      50             : {
      51             :     EditableFunction,
      52             :     EditableView
      53             : } EditableObjectType;
      54             : 
      55             : /* local function declarations */
      56             : static backslashResult exec_command(const char *cmd,
      57             :                                     PsqlScanState scan_state,
      58             :                                     ConditionalStack cstack,
      59             :                                     PQExpBuffer query_buf,
      60             :                                     PQExpBuffer previous_buf);
      61             : static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch);
      62             : static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch);
      63             : static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch);
      64             : static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch,
      65             :                                        const char *cmd);
      66             : static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch);
      67             : static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch);
      68             : static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch);
      69             : static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch);
      70             : static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch,
      71             :                                       const char *cmd);
      72             : static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch,
      73             :                                          PQExpBuffer query_buf, PQExpBuffer previous_buf);
      74             : static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
      75             :                                           PQExpBuffer query_buf, bool is_func);
      76             : static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch,
      77             :                                          const char *cmd);
      78             : static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
      79             :                                          PQExpBuffer query_buf);
      80             : static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
      81             :                                          PQExpBuffer query_buf);
      82             : static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
      83             :                                           PQExpBuffer query_buf);
      84             : static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch);
      85             : static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch);
      86             : static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch);
      87             : static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch,
      88             :                                       const char *cmd);
      89             : static backslashResult process_command_g_options(char *first_option,
      90             :                                                  PsqlScanState scan_state,
      91             :                                                  bool active_branch,
      92             :                                                  const char *cmd);
      93             : static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch);
      94             : static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch);
      95             : static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch);
      96             : static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch);
      97             : static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch);
      98             : static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch,
      99             :                                             const char *cmd);
     100             : static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
     101             :                                        PQExpBuffer query_buf);
     102             : static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch,
     103             :                                          const char *cmd);
     104             : static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch,
     105             :                                        const char *cmd);
     106             : static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch);
     107             : static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch,
     108             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     109             : static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch);
     110             : static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch,
     111             :                                            const char *cmd);
     112             : static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch);
     113             : static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch);
     114             : static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch,
     115             :                                           PQExpBuffer query_buf);
     116             : static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch);
     117             : static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch);
     118             : static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch,
     119             :                                            const char *cmd);
     120             : static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
     121             :                                           const char *cmd, bool is_func);
     122             : static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch);
     123             : static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch);
     124             : static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch);
     125             : static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch,
     126             :                                           const char *cmd);
     127             : static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch,
     128             :                                           const char *cmd,
     129             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     130             : static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch,
     131             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     132             : static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch);
     133             : static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch);
     134             : static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch);
     135             : static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch);
     136             : static char *read_connect_arg(PsqlScanState scan_state);
     137             : static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state);
     138             : static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name);
     139             : static void ignore_boolean_expression(PsqlScanState scan_state);
     140             : static void ignore_slash_options(PsqlScanState scan_state);
     141             : static void ignore_slash_filepipe(PsqlScanState scan_state);
     142             : static void ignore_slash_whole_line(PsqlScanState scan_state);
     143             : static bool is_branching_command(const char *cmd);
     144             : static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
     145             :                                   PQExpBuffer query_buf);
     146             : static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
     147             :                                PQExpBuffer query_buf);
     148             : static void copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf);
     149             : static bool do_connect(enum trivalue reuse_previous_specification,
     150             :                        char *dbname, char *user, char *host, char *port);
     151             : static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
     152             :                     int lineno, bool *edited);
     153             : static bool do_shell(const char *command);
     154             : static bool do_watch(PQExpBuffer query_buf, double sleep);
     155             : static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
     156             :                               Oid *obj_oid);
     157             : static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
     158             :                                   PQExpBuffer buf);
     159             : static int  strip_lineno_from_objdesc(char *obj);
     160             : static int  count_lines_in_buf(PQExpBuffer buf);
     161             : static void print_with_linenumbers(FILE *output, char *lines,
     162             :                                    const char *header_keyword);
     163             : static void minimal_error_message(PGresult *res);
     164             : 
     165             : static void printSSLInfo(void);
     166             : static void printGSSInfo(void);
     167             : static bool printPsetInfo(const char *param, printQueryOpt *popt);
     168             : static char *pset_value_string(const char *param, printQueryOpt *popt);
     169             : 
     170             : #ifdef WIN32
     171             : static void checkWin32Codepage(void);
     172             : #endif
     173             : 
     174             : 
     175             : 
     176             : /*----------
     177             :  * HandleSlashCmds:
     178             :  *
     179             :  * Handles all the different commands that start with '\'.
     180             :  * Ordinarily called by MainLoop().
     181             :  *
     182             :  * scan_state is a lexer working state that is set to continue scanning
     183             :  * just after the '\'.  The lexer is advanced past the command and all
     184             :  * arguments on return.
     185             :  *
     186             :  * cstack is the current \if stack state.  This will be examined, and
     187             :  * possibly modified by conditional commands.
     188             :  *
     189             :  * query_buf contains the query-so-far, which may be modified by
     190             :  * execution of the backslash command (for example, \r clears it).
     191             :  *
     192             :  * previous_buf contains the query most recently sent to the server
     193             :  * (empty if none yet).  This should not be modified here, but some
     194             :  * commands copy its content into query_buf.
     195             :  *
     196             :  * query_buf and previous_buf will be NULL when executing a "-c"
     197             :  * command-line option.
     198             :  *
     199             :  * Returns a status code indicating what action is desired, see command.h.
     200             :  *----------
     201             :  */
     202             : 
     203             : backslashResult
     204        5422 : HandleSlashCmds(PsqlScanState scan_state,
     205             :                 ConditionalStack cstack,
     206             :                 PQExpBuffer query_buf,
     207             :                 PQExpBuffer previous_buf)
     208             : {
     209             :     backslashResult status;
     210             :     char       *cmd;
     211             :     char       *arg;
     212             : 
     213             :     Assert(scan_state != NULL);
     214             :     Assert(cstack != NULL);
     215             : 
     216             :     /* Parse off the command name */
     217        5422 :     cmd = psql_scan_slash_command(scan_state);
     218             : 
     219             :     /* And try to execute it */
     220        5422 :     status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
     221             : 
     222        5422 :     if (status == PSQL_CMD_UNKNOWN)
     223             :     {
     224           4 :         pg_log_error("invalid command \\%s", cmd);
     225           4 :         if (pset.cur_cmd_interactive)
     226           0 :             pg_log_info("Try \\? for help.");
     227           4 :         status = PSQL_CMD_ERROR;
     228             :     }
     229             : 
     230        5422 :     if (status != PSQL_CMD_ERROR)
     231             :     {
     232             :         /*
     233             :          * Eat any remaining arguments after a valid command.  We want to
     234             :          * suppress evaluation of backticks in this situation, so transiently
     235             :          * push an inactive conditional-stack entry.
     236             :          */
     237        5328 :         bool        active_branch = conditional_active(cstack);
     238             : 
     239        5328 :         conditional_stack_push(cstack, IFSTATE_IGNORED);
     240        5348 :         while ((arg = psql_scan_slash_option(scan_state,
     241             :                                              OT_NORMAL, NULL, false)))
     242             :         {
     243          20 :             if (active_branch)
     244          20 :                 pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
     245          20 :             free(arg);
     246             :         }
     247        5328 :         conditional_stack_pop(cstack);
     248             :     }
     249             :     else
     250             :     {
     251             :         /* silently throw away rest of line after an erroneous command */
     252         100 :         while ((arg = psql_scan_slash_option(scan_state,
     253             :                                              OT_WHOLE_LINE, NULL, false)))
     254           6 :             free(arg);
     255             :     }
     256             : 
     257             :     /* if there is a trailing \\, swallow it */
     258        5422 :     psql_scan_slash_command_end(scan_state);
     259             : 
     260        5422 :     free(cmd);
     261             : 
     262             :     /* some commands write to queryFout, so make sure output is sent */
     263        5422 :     fflush(pset.queryFout);
     264             : 
     265        5422 :     return status;
     266             : }
     267             : 
     268             : 
     269             : /*
     270             :  * Subroutine to actually try to execute a backslash command.
     271             :  *
     272             :  * The typical "success" result code is PSQL_CMD_SKIP_LINE, although some
     273             :  * commands return something else.  Failure results are PSQL_CMD_ERROR,
     274             :  * unless PSQL_CMD_UNKNOWN is more appropriate.
     275             :  */
     276             : static backslashResult
     277        5422 : exec_command(const char *cmd,
     278             :              PsqlScanState scan_state,
     279             :              ConditionalStack cstack,
     280             :              PQExpBuffer query_buf,
     281             :              PQExpBuffer previous_buf)
     282             : {
     283             :     backslashResult status;
     284        5422 :     bool        active_branch = conditional_active(cstack);
     285             : 
     286             :     /*
     287             :      * In interactive mode, warn when we're ignoring a command within a false
     288             :      * \if-branch.  But we continue on, so as to parse and discard the right
     289             :      * amount of parameter text.  Each individual backslash command subroutine
     290             :      * is responsible for doing nothing after discarding appropriate
     291             :      * arguments, if !active_branch.
     292             :      */
     293        5422 :     if (pset.cur_cmd_interactive && !active_branch &&
     294           0 :         !is_branching_command(cmd))
     295             :     {
     296           0 :         pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
     297             :                        cmd);
     298             :     }
     299             : 
     300        5422 :     if (strcmp(cmd, "a") == 0)
     301          28 :         status = exec_command_a(scan_state, active_branch);
     302        5394 :     else if (strcmp(cmd, "C") == 0)
     303           4 :         status = exec_command_C(scan_state, active_branch);
     304        5390 :     else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
     305         168 :         status = exec_command_connect(scan_state, active_branch);
     306        5222 :     else if (strcmp(cmd, "cd") == 0)
     307           4 :         status = exec_command_cd(scan_state, active_branch, cmd);
     308        5218 :     else if (strcmp(cmd, "conninfo") == 0)
     309           4 :         status = exec_command_conninfo(scan_state, active_branch);
     310        5214 :     else if (pg_strcasecmp(cmd, "copy") == 0)
     311         130 :         status = exec_command_copy(scan_state, active_branch);
     312        5084 :     else if (strcmp(cmd, "copyright") == 0)
     313           4 :         status = exec_command_copyright(scan_state, active_branch);
     314        5080 :     else if (strcmp(cmd, "crosstabview") == 0)
     315          92 :         status = exec_command_crosstabview(scan_state, active_branch);
     316        4988 :     else if (cmd[0] == 'd')
     317        2292 :         status = exec_command_d(scan_state, active_branch, cmd);
     318        2696 :     else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
     319           4 :         status = exec_command_edit(scan_state, active_branch,
     320             :                                    query_buf, previous_buf);
     321        2692 :     else if (strcmp(cmd, "ef") == 0)
     322           4 :         status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
     323        2688 :     else if (strcmp(cmd, "ev") == 0)
     324           4 :         status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
     325        2684 :     else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
     326        2296 :              strcmp(cmd, "warn") == 0)
     327         396 :         status = exec_command_echo(scan_state, active_branch, cmd);
     328        2288 :     else if (strcmp(cmd, "elif") == 0)
     329          32 :         status = exec_command_elif(scan_state, cstack, query_buf);
     330        2256 :     else if (strcmp(cmd, "else") == 0)
     331          84 :         status = exec_command_else(scan_state, cstack, query_buf);
     332        2172 :     else if (strcmp(cmd, "endif") == 0)
     333          92 :         status = exec_command_endif(scan_state, cstack, query_buf);
     334        2080 :     else if (strcmp(cmd, "encoding") == 0)
     335           4 :         status = exec_command_encoding(scan_state, active_branch);
     336        2076 :     else if (strcmp(cmd, "errverbose") == 0)
     337           4 :         status = exec_command_errverbose(scan_state, active_branch);
     338        2072 :     else if (strcmp(cmd, "f") == 0)
     339           4 :         status = exec_command_f(scan_state, active_branch);
     340        2068 :     else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
     341          80 :         status = exec_command_g(scan_state, active_branch, cmd);
     342        1988 :     else if (strcmp(cmd, "gdesc") == 0)
     343          40 :         status = exec_command_gdesc(scan_state, active_branch);
     344        1948 :     else if (strcmp(cmd, "gexec") == 0)
     345          24 :         status = exec_command_gexec(scan_state, active_branch);
     346        1924 :     else if (strcmp(cmd, "gset") == 0)
     347         152 :         status = exec_command_gset(scan_state, active_branch);
     348        1772 :     else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
     349           4 :         status = exec_command_help(scan_state, active_branch);
     350        1768 :     else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
     351           4 :         status = exec_command_html(scan_state, active_branch);
     352        1764 :     else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
     353        1760 :              strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
     354           8 :         status = exec_command_include(scan_state, active_branch, cmd);
     355        1756 :     else if (strcmp(cmd, "if") == 0)
     356          96 :         status = exec_command_if(scan_state, cstack, query_buf);
     357        1660 :     else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
     358        1656 :              strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
     359           4 :         status = exec_command_list(scan_state, active_branch, cmd);
     360        1656 :     else if (strncmp(cmd, "lo_", 3) == 0)
     361          32 :         status = exec_command_lo(scan_state, active_branch, cmd);
     362        1624 :     else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
     363           4 :         status = exec_command_out(scan_state, active_branch);
     364        1620 :     else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
     365          28 :         status = exec_command_print(scan_state, active_branch,
     366             :                                     query_buf, previous_buf);
     367        1592 :     else if (strcmp(cmd, "password") == 0)
     368           4 :         status = exec_command_password(scan_state, active_branch);
     369        1588 :     else if (strcmp(cmd, "prompt") == 0)
     370           4 :         status = exec_command_prompt(scan_state, active_branch, cmd);
     371        1584 :     else if (strcmp(cmd, "pset") == 0)
     372        1140 :         status = exec_command_pset(scan_state, active_branch);
     373         444 :     else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
     374          26 :         status = exec_command_quit(scan_state, active_branch);
     375         418 :     else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
     376          26 :         status = exec_command_reset(scan_state, active_branch, query_buf);
     377         392 :     else if (strcmp(cmd, "s") == 0)
     378           4 :         status = exec_command_s(scan_state, active_branch);
     379         388 :     else if (strcmp(cmd, "set") == 0)
     380         236 :         status = exec_command_set(scan_state, active_branch);
     381         152 :     else if (strcmp(cmd, "setenv") == 0)
     382           4 :         status = exec_command_setenv(scan_state, active_branch, cmd);
     383         148 :     else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
     384           4 :         status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
     385         144 :     else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
     386           8 :         status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
     387         136 :     else if (strcmp(cmd, "t") == 0)
     388          44 :         status = exec_command_t(scan_state, active_branch);
     389          92 :     else if (strcmp(cmd, "T") == 0)
     390           4 :         status = exec_command_T(scan_state, active_branch);
     391          88 :     else if (strcmp(cmd, "timing") == 0)
     392           4 :         status = exec_command_timing(scan_state, active_branch);
     393          84 :     else if (strcmp(cmd, "unset") == 0)
     394          26 :         status = exec_command_unset(scan_state, active_branch, cmd);
     395          58 :     else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
     396           8 :         status = exec_command_write(scan_state, active_branch, cmd,
     397             :                                     query_buf, previous_buf);
     398          50 :     else if (strcmp(cmd, "watch") == 0)
     399           4 :         status = exec_command_watch(scan_state, active_branch,
     400             :                                     query_buf, previous_buf);
     401          46 :     else if (strcmp(cmd, "x") == 0)
     402          22 :         status = exec_command_x(scan_state, active_branch);
     403          24 :     else if (strcmp(cmd, "z") == 0)
     404          12 :         status = exec_command_z(scan_state, active_branch);
     405          12 :     else if (strcmp(cmd, "!") == 0)
     406           4 :         status = exec_command_shell_escape(scan_state, active_branch);
     407           8 :     else if (strcmp(cmd, "?") == 0)
     408           4 :         status = exec_command_slash_command_help(scan_state, active_branch);
     409             :     else
     410           4 :         status = PSQL_CMD_UNKNOWN;
     411             : 
     412             :     /*
     413             :      * All the commands that return PSQL_CMD_SEND want to execute previous_buf
     414             :      * if query_buf is empty.  For convenience we implement that here, not in
     415             :      * the individual command subroutines.
     416             :      */
     417        5422 :     if (status == PSQL_CMD_SEND)
     418         368 :         copy_previous_query(query_buf, previous_buf);
     419             : 
     420        5422 :     return status;
     421             : }
     422             : 
     423             : 
     424             : /*
     425             :  * \a -- toggle field alignment
     426             :  *
     427             :  * This makes little sense but we keep it around.
     428             :  */
     429             : static backslashResult
     430          28 : exec_command_a(PsqlScanState scan_state, bool active_branch)
     431             : {
     432          28 :     bool        success = true;
     433             : 
     434          28 :     if (active_branch)
     435             :     {
     436          24 :         if (pset.popt.topt.format != PRINT_ALIGNED)
     437          12 :             success = do_pset("format", "aligned", &pset.popt, pset.quiet);
     438             :         else
     439          12 :             success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
     440             :     }
     441             : 
     442          28 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     443             : }
     444             : 
     445             : /*
     446             :  * \C -- override table title (formerly change HTML caption)
     447             :  */
     448             : static backslashResult
     449           4 : exec_command_C(PsqlScanState scan_state, bool active_branch)
     450             : {
     451           4 :     bool        success = true;
     452             : 
     453           4 :     if (active_branch)
     454             :     {
     455           0 :         char       *opt = psql_scan_slash_option(scan_state,
     456             :                                                  OT_NORMAL, NULL, true);
     457             : 
     458           0 :         success = do_pset("title", opt, &pset.popt, pset.quiet);
     459           0 :         free(opt);
     460             :     }
     461             :     else
     462           4 :         ignore_slash_options(scan_state);
     463             : 
     464           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     465             : }
     466             : 
     467             : /*
     468             :  * \c or \connect -- connect to database using the specified parameters.
     469             :  *
     470             :  * \c [-reuse-previous=BOOL] dbname user host port
     471             :  *
     472             :  * Specifying a parameter as '-' is equivalent to omitting it.  Examples:
     473             :  *
     474             :  * \c - - hst       Connect to current database on current port of
     475             :  *                  host "hst" as current user.
     476             :  * \c - usr - prt   Connect to current database on port "prt" of current host
     477             :  *                  as user "usr".
     478             :  * \c dbs           Connect to database "dbs" on current port of current host
     479             :  *                  as current user.
     480             :  */
     481             : static backslashResult
     482         168 : exec_command_connect(PsqlScanState scan_state, bool active_branch)
     483             : {
     484         168 :     bool        success = true;
     485             : 
     486         168 :     if (active_branch)
     487             :     {
     488             :         static const char prefix[] = "-reuse-previous=";
     489             :         char       *opt1,
     490             :                    *opt2,
     491             :                    *opt3,
     492             :                    *opt4;
     493         164 :         enum trivalue reuse_previous = TRI_DEFAULT;
     494             : 
     495         164 :         opt1 = read_connect_arg(scan_state);
     496         164 :         if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
     497             :         {
     498             :             bool        on_off;
     499             : 
     500          16 :             success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
     501             :                                         "-reuse-previous",
     502             :                                         &on_off);
     503          16 :             if (success)
     504             :             {
     505          16 :                 reuse_previous = on_off ? TRI_YES : TRI_NO;
     506          16 :                 free(opt1);
     507          16 :                 opt1 = read_connect_arg(scan_state);
     508             :             }
     509             :         }
     510             : 
     511         164 :         if (success)            /* give up if reuse_previous was invalid */
     512             :         {
     513         164 :             opt2 = read_connect_arg(scan_state);
     514         164 :             opt3 = read_connect_arg(scan_state);
     515         164 :             opt4 = read_connect_arg(scan_state);
     516             : 
     517         164 :             success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
     518             : 
     519         164 :             free(opt2);
     520         164 :             free(opt3);
     521         164 :             free(opt4);
     522             :         }
     523         164 :         free(opt1);
     524             :     }
     525             :     else
     526           4 :         ignore_slash_options(scan_state);
     527             : 
     528         168 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     529             : }
     530             : 
     531             : /*
     532             :  * \cd -- change directory
     533             :  */
     534             : static backslashResult
     535           4 : exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
     536             : {
     537           4 :     bool        success = true;
     538             : 
     539           4 :     if (active_branch)
     540             :     {
     541           0 :         char       *opt = psql_scan_slash_option(scan_state,
     542             :                                                  OT_NORMAL, NULL, true);
     543             :         char       *dir;
     544             : 
     545           0 :         if (opt)
     546           0 :             dir = opt;
     547             :         else
     548             :         {
     549             : #ifndef WIN32
     550             :             struct passwd *pw;
     551           0 :             uid_t       user_id = geteuid();
     552             : 
     553           0 :             errno = 0;          /* clear errno before call */
     554           0 :             pw = getpwuid(user_id);
     555           0 :             if (!pw)
     556             :             {
     557           0 :                 pg_log_error("could not get home directory for user ID %ld: %s",
     558             :                              (long) user_id,
     559             :                              errno ? strerror(errno) : _("user does not exist"));
     560           0 :                 exit(EXIT_FAILURE);
     561             :             }
     562           0 :             dir = pw->pw_dir;
     563             : #else                           /* WIN32 */
     564             : 
     565             :             /*
     566             :              * On Windows, 'cd' without arguments prints the current
     567             :              * directory, so if someone wants to code this here instead...
     568             :              */
     569             :             dir = "/";
     570             : #endif                          /* WIN32 */
     571             :         }
     572             : 
     573           0 :         if (chdir(dir) == -1)
     574             :         {
     575           0 :             pg_log_error("\\%s: could not change directory to \"%s\": %m",
     576             :                          cmd, dir);
     577           0 :             success = false;
     578             :         }
     579             : 
     580           0 :         if (opt)
     581           0 :             free(opt);
     582             :     }
     583             :     else
     584           4 :         ignore_slash_options(scan_state);
     585             : 
     586           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     587             : }
     588             : 
     589             : /*
     590             :  * \conninfo -- display information about the current connection
     591             :  */
     592             : static backslashResult
     593           4 : exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
     594             : {
     595           4 :     if (active_branch)
     596             :     {
     597           0 :         char       *db = PQdb(pset.db);
     598             : 
     599           0 :         if (db == NULL)
     600           0 :             printf(_("You are currently not connected to a database.\n"));
     601             :         else
     602             :         {
     603           0 :             char       *host = PQhost(pset.db);
     604           0 :             char       *hostaddr = PQhostaddr(pset.db);
     605             : 
     606             :             /*
     607             :              * If the host is an absolute path, the connection is via socket
     608             :              * unless overridden by hostaddr
     609             :              */
     610           0 :             if (is_absolute_path(host))
     611             :             {
     612           0 :                 if (hostaddr && *hostaddr)
     613           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
     614             :                            db, PQuser(pset.db), hostaddr, PQport(pset.db));
     615             :                 else
     616           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
     617             :                            db, PQuser(pset.db), host, PQport(pset.db));
     618             :             }
     619             :             else
     620             :             {
     621           0 :                 if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
     622           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
     623             :                            db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
     624             :                 else
     625           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
     626             :                            db, PQuser(pset.db), host, PQport(pset.db));
     627             :             }
     628           0 :             printSSLInfo();
     629           0 :             printGSSInfo();
     630             :         }
     631             :     }
     632             : 
     633           4 :     return PSQL_CMD_SKIP_LINE;
     634             : }
     635             : 
     636             : /*
     637             :  * \copy -- run a COPY command
     638             :  */
     639             : static backslashResult
     640         130 : exec_command_copy(PsqlScanState scan_state, bool active_branch)
     641             : {
     642         130 :     bool        success = true;
     643             : 
     644         130 :     if (active_branch)
     645             :     {
     646         126 :         char       *opt = psql_scan_slash_option(scan_state,
     647             :                                                  OT_WHOLE_LINE, NULL, false);
     648             : 
     649         126 :         success = do_copy(opt);
     650         126 :         free(opt);
     651             :     }
     652             :     else
     653           4 :         ignore_slash_whole_line(scan_state);
     654             : 
     655         130 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     656             : }
     657             : 
     658             : /*
     659             :  * \copyright -- print copyright notice
     660             :  */
     661             : static backslashResult
     662           4 : exec_command_copyright(PsqlScanState scan_state, bool active_branch)
     663             : {
     664           4 :     if (active_branch)
     665           0 :         print_copyright();
     666             : 
     667           4 :     return PSQL_CMD_SKIP_LINE;
     668             : }
     669             : 
     670             : /*
     671             :  * \crosstabview -- execute a query and display results in crosstab
     672             :  */
     673             : static backslashResult
     674          92 : exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
     675             : {
     676          92 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     677             : 
     678          92 :     if (active_branch)
     679             :     {
     680             :         int         i;
     681             : 
     682         440 :         for (i = 0; i < lengthof(pset.ctv_args); i++)
     683         352 :             pset.ctv_args[i] = psql_scan_slash_option(scan_state,
     684             :                                                       OT_NORMAL, NULL, true);
     685          88 :         pset.crosstab_flag = true;
     686          88 :         status = PSQL_CMD_SEND;
     687             :     }
     688             :     else
     689           4 :         ignore_slash_options(scan_state);
     690             : 
     691          92 :     return status;
     692             : }
     693             : 
     694             : /*
     695             :  * \d* commands
     696             :  */
     697             : static backslashResult
     698        2292 : exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
     699             : {
     700        2292 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     701        2292 :     bool        success = true;
     702             : 
     703        2292 :     if (active_branch)
     704             :     {
     705             :         char       *pattern;
     706             :         bool        show_verbose,
     707             :                     show_system;
     708             : 
     709             :         /* We don't do SQLID reduction on the pattern yet */
     710        2288 :         pattern = psql_scan_slash_option(scan_state,
     711             :                                          OT_NORMAL, NULL, true);
     712             : 
     713        2288 :         show_verbose = strchr(cmd, '+') ? true : false;
     714        2288 :         show_system = strchr(cmd, 'S') ? true : false;
     715             : 
     716        2288 :         switch (cmd[1])
     717             :         {
     718        1788 :             case '\0':
     719             :             case '+':
     720             :             case 'S':
     721        1788 :                 if (pattern)
     722        1788 :                     success = describeTableDetails(pattern, show_verbose, show_system);
     723             :                 else
     724             :                     /* standard listing of interesting things */
     725           0 :                     success = listTables("tvmsE", NULL, show_verbose, show_system);
     726        1788 :                 break;
     727          64 :             case 'A':
     728          40 :                 {
     729          64 :                     char       *pattern2 = NULL;
     730             : 
     731          64 :                     if (pattern && cmd[2] != '\0' && cmd[2] != '+')
     732          28 :                         pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
     733             : 
     734          64 :                     switch (cmd[2])
     735             :                     {
     736          36 :                         case '\0':
     737             :                         case '+':
     738          36 :                             success = describeAccessMethods(pattern, show_verbose);
     739          36 :                             break;
     740           4 :                         case 'c':
     741           4 :                             success = listOperatorClasses(pattern, pattern2, show_verbose);
     742           4 :                             break;
     743           8 :                         case 'f':
     744           8 :                             success = listOperatorFamilies(pattern, pattern2, show_verbose);
     745           8 :                             break;
     746           8 :                         case 'o':
     747           8 :                             success = listOpFamilyOperators(pattern, pattern2, show_verbose);
     748           8 :                             break;
     749           8 :                         case 'p':
     750           8 :                             success = listOpFamilyProcedures(pattern, pattern2);
     751           8 :                             break;
     752           0 :                         default:
     753           0 :                             status = PSQL_CMD_UNKNOWN;
     754           0 :                             break;
     755             :                     }
     756             : 
     757          64 :                     if (pattern2)
     758          24 :                         free(pattern2);
     759             :                 }
     760          64 :                 break;
     761           4 :             case 'a':
     762           4 :                 success = describeAggregates(pattern, show_verbose, show_system);
     763           4 :                 break;
     764           0 :             case 'b':
     765           0 :                 success = describeTablespaces(pattern, show_verbose);
     766           0 :                 break;
     767           0 :             case 'c':
     768           0 :                 success = listConversions(pattern, show_verbose, show_system);
     769           0 :                 break;
     770           0 :             case 'C':
     771           0 :                 success = listCasts(pattern, show_verbose);
     772           0 :                 break;
     773           0 :             case 'd':
     774           0 :                 if (strncmp(cmd, "ddp", 3) == 0)
     775           0 :                     success = listDefaultACLs(pattern);
     776             :                 else
     777           0 :                     success = objectDescription(pattern, show_system);
     778           0 :                 break;
     779           0 :             case 'D':
     780           0 :                 success = listDomains(pattern, show_verbose, show_system);
     781           0 :                 break;
     782         100 :             case 'f':           /* function subsystem */
     783         100 :                 switch (cmd[2])
     784             :                 {
     785         100 :                     case '\0':
     786             :                     case '+':
     787             :                     case 'S':
     788             :                     case 'a':
     789             :                     case 'n':
     790             :                     case 'p':
     791             :                     case 't':
     792             :                     case 'w':
     793         100 :                         success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
     794         100 :                         break;
     795           0 :                     default:
     796           0 :                         status = PSQL_CMD_UNKNOWN;
     797           0 :                         break;
     798             :                 }
     799         100 :                 break;
     800           0 :             case 'g':
     801             :                 /* no longer distinct from \du */
     802           0 :                 success = describeRoles(pattern, show_verbose, show_system);
     803           0 :                 break;
     804           0 :             case 'l':
     805           0 :                 success = do_lo_list();
     806           0 :                 break;
     807           0 :             case 'L':
     808           0 :                 success = listLanguages(pattern, show_verbose, show_system);
     809           0 :                 break;
     810           0 :             case 'n':
     811           0 :                 success = listSchemas(pattern, show_verbose, show_system);
     812           0 :                 break;
     813           8 :             case 'o':
     814           8 :                 success = describeOperators(pattern, show_verbose, show_system);
     815           8 :                 break;
     816           0 :             case 'O':
     817           0 :                 success = listCollations(pattern, show_verbose, show_system);
     818           0 :                 break;
     819          16 :             case 'p':
     820          16 :                 success = permissionsList(pattern);
     821          16 :                 break;
     822          44 :             case 'P':
     823             :                 {
     824          44 :                     switch (cmd[2])
     825             :                     {
     826          44 :                         case '\0':
     827             :                         case '+':
     828             :                         case 't':
     829             :                         case 'i':
     830             :                         case 'n':
     831          44 :                             success = listPartitionedTables(&cmd[2], pattern, show_verbose);
     832          44 :                             break;
     833           0 :                         default:
     834           0 :                             status = PSQL_CMD_UNKNOWN;
     835           0 :                             break;
     836             :                     }
     837             :                 }
     838          44 :                 break;
     839          14 :             case 'T':
     840          14 :                 success = describeTypes(pattern, show_verbose, show_system);
     841          14 :                 break;
     842           4 :             case 't':
     843             :             case 'v':
     844             :             case 'm':
     845             :             case 'i':
     846             :             case 's':
     847             :             case 'E':
     848           4 :                 success = listTables(&cmd[1], pattern, show_verbose, show_system);
     849           4 :                 break;
     850           2 :             case 'r':
     851           2 :                 if (cmd[2] == 'd' && cmd[3] == 's')
     852           2 :                 {
     853           2 :                     char       *pattern2 = NULL;
     854             : 
     855           2 :                     if (pattern)
     856           0 :                         pattern2 = psql_scan_slash_option(scan_state,
     857             :                                                           OT_NORMAL, NULL, true);
     858           2 :                     success = listDbRoleSettings(pattern, pattern2);
     859             : 
     860           2 :                     if (pattern2)
     861           0 :                         free(pattern2);
     862             :                 }
     863             :                 else
     864           0 :                     status = PSQL_CMD_UNKNOWN;
     865           2 :                 break;
     866          68 :             case 'R':
     867          68 :                 switch (cmd[2])
     868             :                 {
     869          48 :                     case 'p':
     870          48 :                         if (show_verbose)
     871          32 :                             success = describePublications(pattern);
     872             :                         else
     873          16 :                             success = listPublications(pattern);
     874          48 :                         break;
     875          20 :                     case 's':
     876          20 :                         success = describeSubscriptions(pattern, show_verbose);
     877          20 :                         break;
     878           0 :                     default:
     879           0 :                         status = PSQL_CMD_UNKNOWN;
     880             :                 }
     881          68 :                 break;
     882           0 :             case 'u':
     883           0 :                 success = describeRoles(pattern, show_verbose, show_system);
     884           0 :                 break;
     885           0 :             case 'F':           /* text search subsystem */
     886           0 :                 switch (cmd[2])
     887             :                 {
     888           0 :                     case '\0':
     889             :                     case '+':
     890           0 :                         success = listTSConfigs(pattern, show_verbose);
     891           0 :                         break;
     892           0 :                     case 'p':
     893           0 :                         success = listTSParsers(pattern, show_verbose);
     894           0 :                         break;
     895           0 :                     case 'd':
     896           0 :                         success = listTSDictionaries(pattern, show_verbose);
     897           0 :                         break;
     898           0 :                     case 't':
     899           0 :                         success = listTSTemplates(pattern, show_verbose);
     900           0 :                         break;
     901           0 :                     default:
     902           0 :                         status = PSQL_CMD_UNKNOWN;
     903           0 :                         break;
     904             :                 }
     905           0 :                 break;
     906         164 :             case 'e':           /* SQL/MED subsystem */
     907         164 :                 switch (cmd[2])
     908             :                 {
     909          48 :                     case 's':
     910          48 :                         success = listForeignServers(pattern, show_verbose);
     911          48 :                         break;
     912          40 :                     case 'u':
     913          40 :                         success = listUserMappings(pattern, show_verbose);
     914          40 :                         break;
     915          60 :                     case 'w':
     916          60 :                         success = listForeignDataWrappers(pattern, show_verbose);
     917          60 :                         break;
     918          16 :                     case 't':
     919          16 :                         success = listForeignTables(pattern, show_verbose);
     920          16 :                         break;
     921           0 :                     default:
     922           0 :                         status = PSQL_CMD_UNKNOWN;
     923           0 :                         break;
     924             :                 }
     925         164 :                 break;
     926          12 :             case 'x':           /* Extensions */
     927          12 :                 if (show_verbose)
     928          12 :                     success = listExtensionContents(pattern);
     929             :                 else
     930           0 :                     success = listExtensions(pattern);
     931          12 :                 break;
     932           0 :             case 'y':           /* Event Triggers */
     933           0 :                 success = listEventTriggers(pattern, show_verbose);
     934           0 :                 break;
     935           0 :             default:
     936           0 :                 status = PSQL_CMD_UNKNOWN;
     937             :         }
     938             : 
     939        2288 :         if (pattern)
     940        2058 :             free(pattern);
     941             :     }
     942             :     else
     943           4 :         ignore_slash_options(scan_state);
     944             : 
     945        2292 :     if (!success)
     946          18 :         status = PSQL_CMD_ERROR;
     947             : 
     948        2292 :     return status;
     949             : }
     950             : 
     951             : /*
     952             :  * \e or \edit -- edit the current query buffer, or edit a file and
     953             :  * make it the query buffer
     954             :  */
     955             : static backslashResult
     956           4 : exec_command_edit(PsqlScanState scan_state, bool active_branch,
     957             :                   PQExpBuffer query_buf, PQExpBuffer previous_buf)
     958             : {
     959           4 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     960             : 
     961           4 :     if (active_branch)
     962             :     {
     963           0 :         if (!query_buf)
     964             :         {
     965           0 :             pg_log_error("no query buffer");
     966           0 :             status = PSQL_CMD_ERROR;
     967             :         }
     968             :         else
     969             :         {
     970             :             char       *fname;
     971           0 :             char       *ln = NULL;
     972           0 :             int         lineno = -1;
     973             : 
     974           0 :             fname = psql_scan_slash_option(scan_state,
     975             :                                            OT_NORMAL, NULL, true);
     976           0 :             if (fname)
     977             :             {
     978             :                 /* try to get separate lineno arg */
     979           0 :                 ln = psql_scan_slash_option(scan_state,
     980             :                                             OT_NORMAL, NULL, true);
     981           0 :                 if (ln == NULL)
     982             :                 {
     983             :                     /* only one arg; maybe it is lineno not fname */
     984           0 :                     if (fname[0] &&
     985           0 :                         strspn(fname, "0123456789") == strlen(fname))
     986             :                     {
     987             :                         /* all digits, so assume it is lineno */
     988           0 :                         ln = fname;
     989           0 :                         fname = NULL;
     990             :                     }
     991             :                 }
     992             :             }
     993           0 :             if (ln)
     994             :             {
     995           0 :                 lineno = atoi(ln);
     996           0 :                 if (lineno < 1)
     997             :                 {
     998           0 :                     pg_log_error("invalid line number: %s", ln);
     999           0 :                     status = PSQL_CMD_ERROR;
    1000             :                 }
    1001             :             }
    1002           0 :             if (status != PSQL_CMD_ERROR)
    1003             :             {
    1004           0 :                 expand_tilde(&fname);
    1005           0 :                 if (fname)
    1006           0 :                     canonicalize_path(fname);
    1007             : 
    1008             :                 /* If query_buf is empty, recall previous query for editing */
    1009           0 :                 copy_previous_query(query_buf, previous_buf);
    1010             : 
    1011           0 :                 if (do_edit(fname, query_buf, lineno, NULL))
    1012           0 :                     status = PSQL_CMD_NEWEDIT;
    1013             :                 else
    1014           0 :                     status = PSQL_CMD_ERROR;
    1015             :             }
    1016           0 :             if (fname)
    1017           0 :                 free(fname);
    1018           0 :             if (ln)
    1019           0 :                 free(ln);
    1020             :         }
    1021             :     }
    1022             :     else
    1023           4 :         ignore_slash_options(scan_state);
    1024             : 
    1025           4 :     return status;
    1026             : }
    1027             : 
    1028             : /*
    1029             :  * \ef/\ev -- edit the named function/view, or
    1030             :  * present a blank CREATE FUNCTION/VIEW template if no argument is given
    1031             :  */
    1032             : static backslashResult
    1033           8 : exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
    1034             :                    PQExpBuffer query_buf, bool is_func)
    1035             : {
    1036           8 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1037             : 
    1038           8 :     if (active_branch)
    1039             :     {
    1040           0 :         char       *obj_desc = psql_scan_slash_option(scan_state,
    1041             :                                                       OT_WHOLE_LINE,
    1042             :                                                       NULL, true);
    1043           0 :         int         lineno = -1;
    1044             : 
    1045           0 :         if (pset.sversion < (is_func ? 80400 : 70400))
    1046             :         {
    1047             :             char        sverbuf[32];
    1048             : 
    1049           0 :             formatPGVersionNumber(pset.sversion, false,
    1050             :                                   sverbuf, sizeof(sverbuf));
    1051           0 :             if (is_func)
    1052           0 :                 pg_log_error("The server (version %s) does not support editing function source.",
    1053             :                              sverbuf);
    1054             :             else
    1055           0 :                 pg_log_error("The server (version %s) does not support editing view definitions.",
    1056             :                              sverbuf);
    1057           0 :             status = PSQL_CMD_ERROR;
    1058             :         }
    1059           0 :         else if (!query_buf)
    1060             :         {
    1061           0 :             pg_log_error("no query buffer");
    1062           0 :             status = PSQL_CMD_ERROR;
    1063             :         }
    1064             :         else
    1065             :         {
    1066           0 :             Oid         obj_oid = InvalidOid;
    1067           0 :             EditableObjectType eot = is_func ? EditableFunction : EditableView;
    1068             : 
    1069           0 :             lineno = strip_lineno_from_objdesc(obj_desc);
    1070           0 :             if (lineno == 0)
    1071             :             {
    1072             :                 /* error already reported */
    1073           0 :                 status = PSQL_CMD_ERROR;
    1074             :             }
    1075           0 :             else if (!obj_desc)
    1076             :             {
    1077             :                 /* set up an empty command to fill in */
    1078           0 :                 resetPQExpBuffer(query_buf);
    1079           0 :                 if (is_func)
    1080           0 :                     appendPQExpBufferStr(query_buf,
    1081             :                                          "CREATE FUNCTION ( )\n"
    1082             :                                          " RETURNS \n"
    1083             :                                          " LANGUAGE \n"
    1084             :                                          " -- common options:  IMMUTABLE  STABLE  STRICT  SECURITY DEFINER\n"
    1085             :                                          "AS $function$\n"
    1086             :                                          "\n$function$\n");
    1087             :                 else
    1088           0 :                     appendPQExpBufferStr(query_buf,
    1089             :                                          "CREATE VIEW  AS\n"
    1090             :                                          " SELECT \n"
    1091             :                                          "  -- something...\n");
    1092             :             }
    1093           0 :             else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
    1094             :             {
    1095             :                 /* error already reported */
    1096           0 :                 status = PSQL_CMD_ERROR;
    1097             :             }
    1098           0 :             else if (!get_create_object_cmd(eot, obj_oid, query_buf))
    1099             :             {
    1100             :                 /* error already reported */
    1101           0 :                 status = PSQL_CMD_ERROR;
    1102             :             }
    1103           0 :             else if (is_func && lineno > 0)
    1104             :             {
    1105             :                 /*
    1106             :                  * lineno "1" should correspond to the first line of the
    1107             :                  * function body.  We expect that pg_get_functiondef() will
    1108             :                  * emit that on a line beginning with "AS ", and that there
    1109             :                  * can be no such line before the real start of the function
    1110             :                  * body.  Increment lineno by the number of lines before that
    1111             :                  * line, so that it becomes relative to the first line of the
    1112             :                  * function definition.
    1113             :                  */
    1114           0 :                 const char *lines = query_buf->data;
    1115             : 
    1116           0 :                 while (*lines != '\0')
    1117             :                 {
    1118           0 :                     if (strncmp(lines, "AS ", 3) == 0)
    1119           0 :                         break;
    1120           0 :                     lineno++;
    1121             :                     /* find start of next line */
    1122           0 :                     lines = strchr(lines, '\n');
    1123           0 :                     if (!lines)
    1124           0 :                         break;
    1125           0 :                     lines++;
    1126             :                 }
    1127             :             }
    1128             :         }
    1129             : 
    1130           0 :         if (status != PSQL_CMD_ERROR)
    1131             :         {
    1132           0 :             bool        edited = false;
    1133             : 
    1134           0 :             if (!do_edit(NULL, query_buf, lineno, &edited))
    1135           0 :                 status = PSQL_CMD_ERROR;
    1136           0 :             else if (!edited)
    1137           0 :                 puts(_("No changes"));
    1138             :             else
    1139           0 :                 status = PSQL_CMD_NEWEDIT;
    1140             :         }
    1141             : 
    1142           0 :         if (obj_desc)
    1143           0 :             free(obj_desc);
    1144             :     }
    1145             :     else
    1146           8 :         ignore_slash_whole_line(scan_state);
    1147             : 
    1148           8 :     return status;
    1149             : }
    1150             : 
    1151             : /*
    1152             :  * \echo, \qecho, and \warn -- echo arguments to stdout, query output, or stderr
    1153             :  */
    1154             : static backslashResult
    1155         396 : exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1156             : {
    1157         396 :     if (active_branch)
    1158             :     {
    1159             :         char       *value;
    1160             :         char        quoted;
    1161         304 :         bool        no_newline = false;
    1162         304 :         bool        first = true;
    1163             :         FILE       *fout;
    1164             : 
    1165         304 :         if (strcmp(cmd, "qecho") == 0)
    1166           8 :             fout = pset.queryFout;
    1167         296 :         else if (strcmp(cmd, "warn") == 0)
    1168           8 :             fout = stderr;
    1169             :         else
    1170         288 :             fout = stdout;
    1171             : 
    1172         884 :         while ((value = psql_scan_slash_option(scan_state,
    1173             :                                                OT_NORMAL, &quoted, false)))
    1174             :         {
    1175         580 :             if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
    1176           4 :                 no_newline = true;
    1177             :             else
    1178             :             {
    1179         576 :                 if (first)
    1180         304 :                     first = false;
    1181             :                 else
    1182         272 :                     fputc(' ', fout);
    1183         576 :                 fputs(value, fout);
    1184             :             }
    1185         580 :             free(value);
    1186             :         }
    1187         304 :         if (!no_newline)
    1188         300 :             fputs("\n", fout);
    1189             :     }
    1190             :     else
    1191          92 :         ignore_slash_options(scan_state);
    1192             : 
    1193         396 :     return PSQL_CMD_SKIP_LINE;
    1194             : }
    1195             : 
    1196             : /*
    1197             :  * \encoding -- set/show client side encoding
    1198             :  */
    1199             : static backslashResult
    1200           4 : exec_command_encoding(PsqlScanState scan_state, bool active_branch)
    1201             : {
    1202           4 :     if (active_branch)
    1203             :     {
    1204           0 :         char       *encoding = psql_scan_slash_option(scan_state,
    1205             :                                                       OT_NORMAL, NULL, false);
    1206             : 
    1207           0 :         if (!encoding)
    1208             :         {
    1209             :             /* show encoding */
    1210           0 :             puts(pg_encoding_to_char(pset.encoding));
    1211             :         }
    1212             :         else
    1213             :         {
    1214             :             /* set encoding */
    1215           0 :             if (PQsetClientEncoding(pset.db, encoding) == -1)
    1216           0 :                 pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
    1217             :             else
    1218             :             {
    1219             :                 /* save encoding info into psql internal data */
    1220           0 :                 pset.encoding = PQclientEncoding(pset.db);
    1221           0 :                 pset.popt.topt.encoding = pset.encoding;
    1222           0 :                 SetVariable(pset.vars, "ENCODING",
    1223             :                             pg_encoding_to_char(pset.encoding));
    1224             :             }
    1225           0 :             free(encoding);
    1226             :         }
    1227             :     }
    1228             :     else
    1229           4 :         ignore_slash_options(scan_state);
    1230             : 
    1231           4 :     return PSQL_CMD_SKIP_LINE;
    1232             : }
    1233             : 
    1234             : /*
    1235             :  * \errverbose -- display verbose message from last failed query
    1236             :  */
    1237             : static backslashResult
    1238           4 : exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
    1239             : {
    1240           4 :     if (active_branch)
    1241             :     {
    1242           0 :         if (pset.last_error_result)
    1243             :         {
    1244             :             char       *msg;
    1245             : 
    1246           0 :             msg = PQresultVerboseErrorMessage(pset.last_error_result,
    1247             :                                               PQERRORS_VERBOSE,
    1248             :                                               PQSHOW_CONTEXT_ALWAYS);
    1249           0 :             if (msg)
    1250             :             {
    1251           0 :                 pg_log_error("%s", msg);
    1252           0 :                 PQfreemem(msg);
    1253             :             }
    1254             :             else
    1255           0 :                 puts(_("out of memory"));
    1256             :         }
    1257             :         else
    1258           0 :             puts(_("There is no previous error."));
    1259             :     }
    1260             : 
    1261           4 :     return PSQL_CMD_SKIP_LINE;
    1262             : }
    1263             : 
    1264             : /*
    1265             :  * \f -- change field separator
    1266             :  */
    1267             : static backslashResult
    1268           4 : exec_command_f(PsqlScanState scan_state, bool active_branch)
    1269             : {
    1270           4 :     bool        success = true;
    1271             : 
    1272           4 :     if (active_branch)
    1273             :     {
    1274           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1275             :                                                    OT_NORMAL, NULL, false);
    1276             : 
    1277           0 :         success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
    1278           0 :         free(fname);
    1279             :     }
    1280             :     else
    1281           4 :         ignore_slash_options(scan_state);
    1282             : 
    1283           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1284             : }
    1285             : 
    1286             : /*
    1287             :  * \g  [(pset-option[=pset-value] ...)] [filename/shell-command]
    1288             :  * \gx [(pset-option[=pset-value] ...)] [filename/shell-command]
    1289             :  *
    1290             :  * Send the current query.  If pset options are specified, they are made
    1291             :  * active just for this query.  If a filename or pipe command is given,
    1292             :  * the query output goes there.  \gx implicitly sets "expanded=on" along
    1293             :  * with any other pset options that are specified.
    1294             :  */
    1295             : static backslashResult
    1296          80 : exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1297             : {
    1298          80 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1299             :     char       *fname;
    1300             : 
    1301             :     /*
    1302             :      * Because the option processing for this is fairly complicated, we do it
    1303             :      * and then decide whether the branch is active.
    1304             :      */
    1305          80 :     fname = psql_scan_slash_option(scan_state,
    1306             :                                    OT_FILEPIPE, NULL, false);
    1307             : 
    1308          80 :     if (fname && fname[0] == '(')
    1309             :     {
    1310             :         /* Consume pset options through trailing ')' ... */
    1311           8 :         status = process_command_g_options(fname + 1, scan_state,
    1312             :                                            active_branch, cmd);
    1313           8 :         free(fname);
    1314             :         /* ... and again attempt to scan the filename. */
    1315           8 :         fname = psql_scan_slash_option(scan_state,
    1316             :                                        OT_FILEPIPE, NULL, false);
    1317             :     }
    1318             : 
    1319          80 :     if (status == PSQL_CMD_SKIP_LINE && active_branch)
    1320             :     {
    1321          72 :         if (!fname)
    1322          72 :             pset.gfname = NULL;
    1323             :         else
    1324             :         {
    1325           0 :             expand_tilde(&fname);
    1326           0 :             pset.gfname = pg_strdup(fname);
    1327             :         }
    1328          72 :         if (strcmp(cmd, "gx") == 0)
    1329             :         {
    1330             :             /* save settings if not done already, then force expanded=on */
    1331          20 :             if (pset.gsavepopt == NULL)
    1332          16 :                 pset.gsavepopt = savePsetInfo(&pset.popt);
    1333          20 :             pset.popt.topt.expanded = 1;
    1334             :         }
    1335          72 :         status = PSQL_CMD_SEND;
    1336             :     }
    1337             : 
    1338          80 :     free(fname);
    1339             : 
    1340          80 :     return status;
    1341             : }
    1342             : 
    1343             : /*
    1344             :  * Process parenthesized pset options for \g
    1345             :  *
    1346             :  * Note: okay to modify first_option, but not to free it; caller does that
    1347             :  */
    1348             : static backslashResult
    1349           8 : process_command_g_options(char *first_option, PsqlScanState scan_state,
    1350             :                           bool active_branch, const char *cmd)
    1351             : {
    1352           8 :     bool        success = true;
    1353           8 :     bool        found_r_paren = false;
    1354             : 
    1355             :     do
    1356             :     {
    1357             :         char       *option;
    1358             :         size_t      optlen;
    1359             : 
    1360             :         /* If not first time through, collect a new option */
    1361          12 :         if (first_option)
    1362           8 :             option = first_option;
    1363             :         else
    1364             :         {
    1365           4 :             option = psql_scan_slash_option(scan_state,
    1366             :                                             OT_NORMAL, NULL, false);
    1367           4 :             if (!option)
    1368             :             {
    1369           0 :                 if (active_branch)
    1370             :                 {
    1371           0 :                     pg_log_error("\\%s: missing right parenthesis", cmd);
    1372           0 :                     success = false;
    1373             :                 }
    1374           0 :                 break;
    1375             :             }
    1376             :         }
    1377             : 
    1378             :         /* Check for terminating right paren, and remove it from string */
    1379          12 :         optlen = strlen(option);
    1380          12 :         if (optlen > 0 && option[optlen - 1] == ')')
    1381             :         {
    1382           8 :             option[--optlen] = '\0';
    1383           8 :             found_r_paren = true;
    1384             :         }
    1385             : 
    1386             :         /* If there was anything besides parentheses, parse/execute it */
    1387          12 :         if (optlen > 0)
    1388             :         {
    1389             :             /* We can have either "name" or "name=value" */
    1390          12 :             char       *valptr = strchr(option, '=');
    1391             : 
    1392          12 :             if (valptr)
    1393          12 :                 *valptr++ = '\0';
    1394          12 :             if (active_branch)
    1395             :             {
    1396             :                 /* save settings if not done already, then apply option */
    1397          12 :                 if (pset.gsavepopt == NULL)
    1398           8 :                     pset.gsavepopt = savePsetInfo(&pset.popt);
    1399          12 :                 success &= do_pset(option, valptr, &pset.popt, true);
    1400             :             }
    1401             :         }
    1402             : 
    1403             :         /* Clean up after this option.  We should not free first_option. */
    1404          12 :         if (first_option)
    1405           8 :             first_option = NULL;
    1406             :         else
    1407           4 :             free(option);
    1408          12 :     } while (!found_r_paren);
    1409             : 
    1410             :     /* If we failed after already changing some options, undo side-effects */
    1411           8 :     if (!success && active_branch && pset.gsavepopt)
    1412             :     {
    1413           0 :         restorePsetInfo(&pset.popt, pset.gsavepopt);
    1414           0 :         pset.gsavepopt = NULL;
    1415             :     }
    1416             : 
    1417           8 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1418             : }
    1419             : 
    1420             : /*
    1421             :  * \gdesc -- describe query result
    1422             :  */
    1423             : static backslashResult
    1424          40 : exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
    1425             : {
    1426          40 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1427             : 
    1428          40 :     if (active_branch)
    1429             :     {
    1430          40 :         pset.gdesc_flag = true;
    1431          40 :         status = PSQL_CMD_SEND;
    1432             :     }
    1433             : 
    1434          40 :     return status;
    1435             : }
    1436             : 
    1437             : /*
    1438             :  * \gexec -- send query and execute each field of result
    1439             :  */
    1440             : static backslashResult
    1441          24 : exec_command_gexec(PsqlScanState scan_state, bool active_branch)
    1442             : {
    1443          24 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1444             : 
    1445          24 :     if (active_branch)
    1446             :     {
    1447          20 :         pset.gexec_flag = true;
    1448          20 :         status = PSQL_CMD_SEND;
    1449             :     }
    1450             : 
    1451          24 :     return status;
    1452             : }
    1453             : 
    1454             : /*
    1455             :  * \gset [prefix] -- send query and store result into variables
    1456             :  */
    1457             : static backslashResult
    1458         152 : exec_command_gset(PsqlScanState scan_state, bool active_branch)
    1459             : {
    1460         152 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1461             : 
    1462         152 :     if (active_branch)
    1463             :     {
    1464         148 :         char       *prefix = psql_scan_slash_option(scan_state,
    1465             :                                                     OT_NORMAL, NULL, false);
    1466             : 
    1467         148 :         if (prefix)
    1468          28 :             pset.gset_prefix = prefix;
    1469             :         else
    1470             :         {
    1471             :             /* we must set a non-NULL prefix to trigger storing */
    1472         120 :             pset.gset_prefix = pg_strdup("");
    1473             :         }
    1474             :         /* gset_prefix is freed later */
    1475         148 :         status = PSQL_CMD_SEND;
    1476             :     }
    1477             :     else
    1478           4 :         ignore_slash_options(scan_state);
    1479             : 
    1480         152 :     return status;
    1481             : }
    1482             : 
    1483             : /*
    1484             :  * \help [topic] -- print help about SQL commands
    1485             :  */
    1486             : static backslashResult
    1487           4 : exec_command_help(PsqlScanState scan_state, bool active_branch)
    1488             : {
    1489           4 :     if (active_branch)
    1490             :     {
    1491           0 :         char       *opt = psql_scan_slash_option(scan_state,
    1492             :                                                  OT_WHOLE_LINE, NULL, false);
    1493             :         size_t      len;
    1494             : 
    1495             :         /* strip any trailing spaces and semicolons */
    1496           0 :         if (opt)
    1497             :         {
    1498           0 :             len = strlen(opt);
    1499           0 :             while (len > 0 &&
    1500           0 :                    (isspace((unsigned char) opt[len - 1])
    1501           0 :                     || opt[len - 1] == ';'))
    1502           0 :                 opt[--len] = '\0';
    1503             :         }
    1504             : 
    1505           0 :         helpSQL(opt, pset.popt.topt.pager);
    1506           0 :         free(opt);
    1507             :     }
    1508             :     else
    1509           4 :         ignore_slash_whole_line(scan_state);
    1510             : 
    1511           4 :     return PSQL_CMD_SKIP_LINE;
    1512             : }
    1513             : 
    1514             : /*
    1515             :  * \H and \html -- toggle HTML formatting
    1516             :  */
    1517             : static backslashResult
    1518           4 : exec_command_html(PsqlScanState scan_state, bool active_branch)
    1519             : {
    1520           4 :     bool        success = true;
    1521             : 
    1522           4 :     if (active_branch)
    1523             :     {
    1524           0 :         if (pset.popt.topt.format != PRINT_HTML)
    1525           0 :             success = do_pset("format", "html", &pset.popt, pset.quiet);
    1526             :         else
    1527           0 :             success = do_pset("format", "aligned", &pset.popt, pset.quiet);
    1528             :     }
    1529             : 
    1530           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1531             : }
    1532             : 
    1533             : /*
    1534             :  * \i and \ir -- include a file
    1535             :  */
    1536             : static backslashResult
    1537           8 : exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1538             : {
    1539           8 :     bool        success = true;
    1540             : 
    1541           8 :     if (active_branch)
    1542             :     {
    1543           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1544             :                                                    OT_NORMAL, NULL, true);
    1545             : 
    1546           0 :         if (!fname)
    1547             :         {
    1548           0 :             pg_log_error("\\%s: missing required argument", cmd);
    1549           0 :             success = false;
    1550             :         }
    1551             :         else
    1552             :         {
    1553             :             bool        include_relative;
    1554             : 
    1555           0 :             include_relative = (strcmp(cmd, "ir") == 0
    1556           0 :                                 || strcmp(cmd, "include_relative") == 0);
    1557           0 :             expand_tilde(&fname);
    1558           0 :             success = (process_file(fname, include_relative) == EXIT_SUCCESS);
    1559           0 :             free(fname);
    1560             :         }
    1561             :     }
    1562             :     else
    1563           8 :         ignore_slash_options(scan_state);
    1564             : 
    1565           8 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1566             : }
    1567             : 
    1568             : /*
    1569             :  * \if <expr> -- beginning of an \if..\endif block
    1570             :  *
    1571             :  * <expr> is parsed as a boolean expression.  Invalid expressions will emit a
    1572             :  * warning and be treated as false.  Statements that follow a false expression
    1573             :  * will be parsed but ignored.  Note that in the case where an \if statement
    1574             :  * is itself within an inactive section of a block, then the entire inner
    1575             :  * \if..\endif block will be parsed but ignored.
    1576             :  */
    1577             : static backslashResult
    1578          96 : exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
    1579             :                 PQExpBuffer query_buf)
    1580             : {
    1581          96 :     if (conditional_active(cstack))
    1582             :     {
    1583             :         /*
    1584             :          * First, push a new active stack entry; this ensures that the lexer
    1585             :          * will perform variable substitution and backtick evaluation while
    1586             :          * scanning the expression.  (That should happen anyway, since we know
    1587             :          * we're in an active outer branch, but let's be sure.)
    1588             :          */
    1589          92 :         conditional_stack_push(cstack, IFSTATE_TRUE);
    1590             : 
    1591             :         /* Remember current query state in case we need to restore later */
    1592          92 :         save_query_text_state(scan_state, cstack, query_buf);
    1593             : 
    1594             :         /*
    1595             :          * Evaluate the expression; if it's false, change to inactive state.
    1596             :          */
    1597          92 :         if (!is_true_boolean_expression(scan_state, "\\if expression"))
    1598          44 :             conditional_stack_poke(cstack, IFSTATE_FALSE);
    1599             :     }
    1600             :     else
    1601             :     {
    1602             :         /*
    1603             :          * We're within an inactive outer branch, so this entire \if block
    1604             :          * will be ignored.  We don't want to evaluate the expression, so push
    1605             :          * the "ignored" stack state before scanning it.
    1606             :          */
    1607           4 :         conditional_stack_push(cstack, IFSTATE_IGNORED);
    1608             : 
    1609             :         /* Remember current query state in case we need to restore later */
    1610           4 :         save_query_text_state(scan_state, cstack, query_buf);
    1611             : 
    1612           4 :         ignore_boolean_expression(scan_state);
    1613             :     }
    1614             : 
    1615          96 :     return PSQL_CMD_SKIP_LINE;
    1616             : }
    1617             : 
    1618             : /*
    1619             :  * \elif <expr> -- alternative branch in an \if..\endif block
    1620             :  *
    1621             :  * <expr> is evaluated the same as in \if <expr>.
    1622             :  */
    1623             : static backslashResult
    1624          32 : exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
    1625             :                   PQExpBuffer query_buf)
    1626             : {
    1627          32 :     bool        success = true;
    1628             : 
    1629          32 :     switch (conditional_stack_peek(cstack))
    1630             :     {
    1631           4 :         case IFSTATE_TRUE:
    1632             : 
    1633             :             /*
    1634             :              * Just finished active branch of this \if block.  Update saved
    1635             :              * state so we will keep whatever data was put in query_buf by the
    1636             :              * active branch.
    1637             :              */
    1638           4 :             save_query_text_state(scan_state, cstack, query_buf);
    1639             : 
    1640             :             /*
    1641             :              * Discard \elif expression and ignore the rest until \endif.
    1642             :              * Switch state before reading expression to ensure proper lexer
    1643             :              * behavior.
    1644             :              */
    1645           4 :             conditional_stack_poke(cstack, IFSTATE_IGNORED);
    1646           4 :             ignore_boolean_expression(scan_state);
    1647           4 :             break;
    1648          16 :         case IFSTATE_FALSE:
    1649             : 
    1650             :             /*
    1651             :              * Discard any query text added by the just-skipped branch.
    1652             :              */
    1653          16 :             discard_query_text(scan_state, cstack, query_buf);
    1654             : 
    1655             :             /*
    1656             :              * Have not yet found a true expression in this \if block, so this
    1657             :              * might be the first.  We have to change state before examining
    1658             :              * the expression, or the lexer won't do the right thing.
    1659             :              */
    1660          16 :             conditional_stack_poke(cstack, IFSTATE_TRUE);
    1661          16 :             if (!is_true_boolean_expression(scan_state, "\\elif expression"))
    1662          12 :                 conditional_stack_poke(cstack, IFSTATE_FALSE);
    1663          16 :             break;
    1664           4 :         case IFSTATE_IGNORED:
    1665             : 
    1666             :             /*
    1667             :              * Discard any query text added by the just-skipped branch.
    1668             :              */
    1669           4 :             discard_query_text(scan_state, cstack, query_buf);
    1670             : 
    1671             :             /*
    1672             :              * Skip expression and move on.  Either the \if block already had
    1673             :              * an active section, or whole block is being skipped.
    1674             :              */
    1675           4 :             ignore_boolean_expression(scan_state);
    1676           4 :             break;
    1677           4 :         case IFSTATE_ELSE_TRUE:
    1678             :         case IFSTATE_ELSE_FALSE:
    1679           4 :             pg_log_error("\\elif: cannot occur after \\else");
    1680           4 :             success = false;
    1681           4 :             break;
    1682           4 :         case IFSTATE_NONE:
    1683             :             /* no \if to elif from */
    1684           4 :             pg_log_error("\\elif: no matching \\if");
    1685           4 :             success = false;
    1686           4 :             break;
    1687             :     }
    1688             : 
    1689          32 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1690             : }
    1691             : 
    1692             : /*
    1693             :  * \else -- final alternative in an \if..\endif block
    1694             :  *
    1695             :  * Statements within an \else branch will only be executed if
    1696             :  * all previous \if and \elif expressions evaluated to false
    1697             :  * and the block was not itself being ignored.
    1698             :  */
    1699             : static backslashResult
    1700          84 : exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
    1701             :                   PQExpBuffer query_buf)
    1702             : {
    1703          84 :     bool        success = true;
    1704             : 
    1705          84 :     switch (conditional_stack_peek(cstack))
    1706             :     {
    1707          40 :         case IFSTATE_TRUE:
    1708             : 
    1709             :             /*
    1710             :              * Just finished active branch of this \if block.  Update saved
    1711             :              * state so we will keep whatever data was put in query_buf by the
    1712             :              * active branch.
    1713             :              */
    1714          40 :             save_query_text_state(scan_state, cstack, query_buf);
    1715             : 
    1716             :             /* Now skip the \else branch */
    1717          40 :             conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
    1718          40 :             break;
    1719          28 :         case IFSTATE_FALSE:
    1720             : 
    1721             :             /*
    1722             :              * Discard any query text added by the just-skipped branch.
    1723             :              */
    1724          28 :             discard_query_text(scan_state, cstack, query_buf);
    1725             : 
    1726             :             /*
    1727             :              * We've not found any true \if or \elif expression, so execute
    1728             :              * the \else branch.
    1729             :              */
    1730          28 :             conditional_stack_poke(cstack, IFSTATE_ELSE_TRUE);
    1731          28 :             break;
    1732           8 :         case IFSTATE_IGNORED:
    1733             : 
    1734             :             /*
    1735             :              * Discard any query text added by the just-skipped branch.
    1736             :              */
    1737           8 :             discard_query_text(scan_state, cstack, query_buf);
    1738             : 
    1739             :             /*
    1740             :              * Either we previously processed the active branch of this \if,
    1741             :              * or the whole \if block is being skipped.  Either way, skip the
    1742             :              * \else branch.
    1743             :              */
    1744           8 :             conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
    1745           8 :             break;
    1746           4 :         case IFSTATE_ELSE_TRUE:
    1747             :         case IFSTATE_ELSE_FALSE:
    1748           4 :             pg_log_error("\\else: cannot occur after \\else");
    1749           4 :             success = false;
    1750           4 :             break;
    1751           4 :         case IFSTATE_NONE:
    1752             :             /* no \if to else from */
    1753           4 :             pg_log_error("\\else: no matching \\if");
    1754           4 :             success = false;
    1755           4 :             break;
    1756             :     }
    1757             : 
    1758          84 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1759             : }
    1760             : 
    1761             : /*
    1762             :  * \endif -- ends an \if...\endif block
    1763             :  */
    1764             : static backslashResult
    1765          92 : exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
    1766             :                    PQExpBuffer query_buf)
    1767             : {
    1768          92 :     bool        success = true;
    1769             : 
    1770          92 :     switch (conditional_stack_peek(cstack))
    1771             :     {
    1772          28 :         case IFSTATE_TRUE:
    1773             :         case IFSTATE_ELSE_TRUE:
    1774             :             /* Close the \if block, keeping the query text */
    1775          28 :             success = conditional_stack_pop(cstack);
    1776             :             Assert(success);
    1777          28 :             break;
    1778          60 :         case IFSTATE_FALSE:
    1779             :         case IFSTATE_IGNORED:
    1780             :         case IFSTATE_ELSE_FALSE:
    1781             : 
    1782             :             /*
    1783             :              * Discard any query text added by the just-skipped branch.
    1784             :              */
    1785          60 :             discard_query_text(scan_state, cstack, query_buf);
    1786             : 
    1787             :             /* Close the \if block */
    1788          60 :             success = conditional_stack_pop(cstack);
    1789             :             Assert(success);
    1790          60 :             break;
    1791           4 :         case IFSTATE_NONE:
    1792             :             /* no \if to end */
    1793           4 :             pg_log_error("\\endif: no matching \\if");
    1794           4 :             success = false;
    1795           4 :             break;
    1796             :     }
    1797             : 
    1798          92 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1799             : }
    1800             : 
    1801             : /*
    1802             :  * \l -- list databases
    1803             :  */
    1804             : static backslashResult
    1805           4 : exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1806             : {
    1807           4 :     bool        success = true;
    1808             : 
    1809           4 :     if (active_branch)
    1810             :     {
    1811             :         char       *pattern;
    1812             :         bool        show_verbose;
    1813             : 
    1814           0 :         pattern = psql_scan_slash_option(scan_state,
    1815             :                                          OT_NORMAL, NULL, true);
    1816             : 
    1817           0 :         show_verbose = strchr(cmd, '+') ? true : false;
    1818             : 
    1819           0 :         success = listAllDbs(pattern, show_verbose);
    1820             : 
    1821           0 :         if (pattern)
    1822           0 :             free(pattern);
    1823             :     }
    1824             :     else
    1825           4 :         ignore_slash_options(scan_state);
    1826             : 
    1827           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1828             : }
    1829             : 
    1830             : /*
    1831             :  * \lo_* -- large object operations
    1832             :  */
    1833             : static backslashResult
    1834          32 : exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1835             : {
    1836          32 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1837          32 :     bool        success = true;
    1838             : 
    1839          32 :     if (active_branch)
    1840             :     {
    1841             :         char       *opt1,
    1842             :                    *opt2;
    1843             : 
    1844          28 :         opt1 = psql_scan_slash_option(scan_state,
    1845             :                                       OT_NORMAL, NULL, true);
    1846          28 :         opt2 = psql_scan_slash_option(scan_state,
    1847             :                                       OT_NORMAL, NULL, true);
    1848             : 
    1849          28 :         if (strcmp(cmd + 3, "export") == 0)
    1850             :         {
    1851           4 :             if (!opt2)
    1852             :             {
    1853           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1854           0 :                 success = false;
    1855             :             }
    1856             :             else
    1857             :             {
    1858           4 :                 expand_tilde(&opt2);
    1859           4 :                 success = do_lo_export(opt1, opt2);
    1860             :             }
    1861             :         }
    1862             : 
    1863          24 :         else if (strcmp(cmd + 3, "import") == 0)
    1864             :         {
    1865          12 :             if (!opt1)
    1866             :             {
    1867           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1868           0 :                 success = false;
    1869             :             }
    1870             :             else
    1871             :             {
    1872          12 :                 expand_tilde(&opt1);
    1873          12 :                 success = do_lo_import(opt1, opt2);
    1874             :             }
    1875             :         }
    1876             : 
    1877          12 :         else if (strcmp(cmd + 3, "list") == 0)
    1878           0 :             success = do_lo_list();
    1879             : 
    1880          12 :         else if (strcmp(cmd + 3, "unlink") == 0)
    1881             :         {
    1882          12 :             if (!opt1)
    1883             :             {
    1884           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1885           0 :                 success = false;
    1886             :             }
    1887             :             else
    1888          12 :                 success = do_lo_unlink(opt1);
    1889             :         }
    1890             : 
    1891             :         else
    1892           0 :             status = PSQL_CMD_UNKNOWN;
    1893             : 
    1894          28 :         free(opt1);
    1895          28 :         free(opt2);
    1896             :     }
    1897             :     else
    1898           4 :         ignore_slash_options(scan_state);
    1899             : 
    1900          32 :     if (!success)
    1901           2 :         status = PSQL_CMD_ERROR;
    1902             : 
    1903          32 :     return status;
    1904             : }
    1905             : 
    1906             : /*
    1907             :  * \o -- set query output
    1908             :  */
    1909             : static backslashResult
    1910           4 : exec_command_out(PsqlScanState scan_state, bool active_branch)
    1911             : {
    1912           4 :     bool        success = true;
    1913             : 
    1914           4 :     if (active_branch)
    1915             :     {
    1916           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1917             :                                                    OT_FILEPIPE, NULL, true);
    1918             : 
    1919           0 :         expand_tilde(&fname);
    1920           0 :         success = setQFout(fname);
    1921           0 :         free(fname);
    1922             :     }
    1923             :     else
    1924           4 :         ignore_slash_filepipe(scan_state);
    1925             : 
    1926           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1927             : }
    1928             : 
    1929             : /*
    1930             :  * \p -- print the current query buffer
    1931             :  */
    1932             : static backslashResult
    1933          28 : exec_command_print(PsqlScanState scan_state, bool active_branch,
    1934             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    1935             : {
    1936          28 :     if (active_branch)
    1937             :     {
    1938             :         /*
    1939             :          * We want to print the same thing \g would execute, but not to change
    1940             :          * the query buffer state; so we can't use copy_previous_query().
    1941             :          * Also, beware of possibility that buffer pointers are NULL.
    1942             :          */
    1943          24 :         if (query_buf && query_buf->len > 0)
    1944          12 :             puts(query_buf->data);
    1945          12 :         else if (previous_buf && previous_buf->len > 0)
    1946          12 :             puts(previous_buf->data);
    1947           0 :         else if (!pset.quiet)
    1948           0 :             puts(_("Query buffer is empty."));
    1949          24 :         fflush(stdout);
    1950             :     }
    1951             : 
    1952          28 :     return PSQL_CMD_SKIP_LINE;
    1953             : }
    1954             : 
    1955             : /*
    1956             :  * \password -- set user password
    1957             :  */
    1958             : static backslashResult
    1959           4 : exec_command_password(PsqlScanState scan_state, bool active_branch)
    1960             : {
    1961           4 :     bool        success = true;
    1962             : 
    1963           4 :     if (active_branch)
    1964             :     {
    1965           0 :         char       *opt0 = psql_scan_slash_option(scan_state,
    1966             :                                                   OT_SQLID, NULL, true);
    1967             :         char        pw1[100];
    1968             :         char        pw2[100];
    1969             : 
    1970           0 :         simple_prompt("Enter new password: ", pw1, sizeof(pw1), false);
    1971           0 :         simple_prompt("Enter it again: ", pw2, sizeof(pw2), false);
    1972             : 
    1973           0 :         if (strcmp(pw1, pw2) != 0)
    1974             :         {
    1975           0 :             pg_log_error("Passwords didn't match.");
    1976           0 :             success = false;
    1977             :         }
    1978             :         else
    1979             :         {
    1980             :             char       *user;
    1981             :             char       *encrypted_password;
    1982             : 
    1983           0 :             if (opt0)
    1984           0 :                 user = opt0;
    1985             :             else
    1986           0 :                 user = PQuser(pset.db);
    1987             : 
    1988           0 :             encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
    1989             : 
    1990           0 :             if (!encrypted_password)
    1991             :             {
    1992           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
    1993           0 :                 success = false;
    1994             :             }
    1995             :             else
    1996             :             {
    1997             :                 PQExpBufferData buf;
    1998             :                 PGresult   *res;
    1999             : 
    2000           0 :                 initPQExpBuffer(&buf);
    2001           0 :                 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
    2002             :                                   fmtId(user));
    2003           0 :                 appendStringLiteralConn(&buf, encrypted_password, pset.db);
    2004           0 :                 res = PSQLexec(buf.data);
    2005           0 :                 termPQExpBuffer(&buf);
    2006           0 :                 if (!res)
    2007           0 :                     success = false;
    2008             :                 else
    2009           0 :                     PQclear(res);
    2010           0 :                 PQfreemem(encrypted_password);
    2011             :             }
    2012             :         }
    2013             : 
    2014           0 :         if (opt0)
    2015           0 :             free(opt0);
    2016             :     }
    2017             :     else
    2018           4 :         ignore_slash_options(scan_state);
    2019             : 
    2020           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2021             : }
    2022             : 
    2023             : /*
    2024             :  * \prompt -- prompt and set variable
    2025             :  */
    2026             : static backslashResult
    2027           4 : exec_command_prompt(PsqlScanState scan_state, bool active_branch,
    2028             :                     const char *cmd)
    2029             : {
    2030           4 :     bool        success = true;
    2031             : 
    2032           4 :     if (active_branch)
    2033             :     {
    2034             :         char       *opt,
    2035           0 :                    *prompt_text = NULL;
    2036             :         char       *arg1,
    2037             :                    *arg2;
    2038             : 
    2039           0 :         arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
    2040           0 :         arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
    2041             : 
    2042           0 :         if (!arg1)
    2043             :         {
    2044           0 :             pg_log_error("\\%s: missing required argument", cmd);
    2045           0 :             success = false;
    2046             :         }
    2047             :         else
    2048             :         {
    2049             :             char       *result;
    2050             : 
    2051           0 :             if (arg2)
    2052             :             {
    2053           0 :                 prompt_text = arg1;
    2054           0 :                 opt = arg2;
    2055             :             }
    2056             :             else
    2057           0 :                 opt = arg1;
    2058             : 
    2059           0 :             if (!pset.inputfile)
    2060             :             {
    2061           0 :                 result = (char *) pg_malloc(4096);
    2062           0 :                 simple_prompt(prompt_text, result, 4096, true);
    2063             :             }
    2064             :             else
    2065             :             {
    2066           0 :                 if (prompt_text)
    2067             :                 {
    2068           0 :                     fputs(prompt_text, stdout);
    2069           0 :                     fflush(stdout);
    2070             :                 }
    2071           0 :                 result = gets_fromFile(stdin);
    2072           0 :                 if (!result)
    2073             :                 {
    2074           0 :                     pg_log_error("\\%s: could not read value for variable",
    2075             :                                  cmd);
    2076           0 :                     success = false;
    2077             :                 }
    2078             :             }
    2079             : 
    2080           0 :             if (result &&
    2081           0 :                 !SetVariable(pset.vars, opt, result))
    2082           0 :                 success = false;
    2083             : 
    2084           0 :             if (result)
    2085           0 :                 free(result);
    2086           0 :             if (prompt_text)
    2087           0 :                 free(prompt_text);
    2088           0 :             free(opt);
    2089             :         }
    2090             :     }
    2091             :     else
    2092           4 :         ignore_slash_options(scan_state);
    2093             : 
    2094           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2095             : }
    2096             : 
    2097             : /*
    2098             :  * \pset -- set printing parameters
    2099             :  */
    2100             : static backslashResult
    2101        1140 : exec_command_pset(PsqlScanState scan_state, bool active_branch)
    2102             : {
    2103        1140 :     bool        success = true;
    2104             : 
    2105        1140 :     if (active_branch)
    2106             :     {
    2107        1132 :         char       *opt0 = psql_scan_slash_option(scan_state,
    2108             :                                                   OT_NORMAL, NULL, false);
    2109        1132 :         char       *opt1 = psql_scan_slash_option(scan_state,
    2110             :                                                   OT_NORMAL, NULL, false);
    2111             : 
    2112        1132 :         if (!opt0)
    2113             :         {
    2114             :             /* list all variables */
    2115             : 
    2116             :             int         i;
    2117             :             static const char *const my_list[] = {
    2118             :                 "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
    2119             :                 "fieldsep_zero", "footer", "format", "linestyle", "null",
    2120             :                 "numericlocale", "pager", "pager_min_lines",
    2121             :                 "recordsep", "recordsep_zero",
    2122             :                 "tableattr", "title", "tuples_only",
    2123             :                 "unicode_border_linestyle",
    2124             :                 "unicode_column_linestyle",
    2125             :                 "unicode_header_linestyle",
    2126             :                 NULL
    2127             :             };
    2128             : 
    2129          88 :             for (i = 0; my_list[i] != NULL; i++)
    2130             :             {
    2131          84 :                 char       *val = pset_value_string(my_list[i], &pset.popt);
    2132             : 
    2133          84 :                 printf("%-24s %s\n", my_list[i], val);
    2134          84 :                 free(val);
    2135             :             }
    2136             : 
    2137           4 :             success = true;
    2138             :         }
    2139             :         else
    2140        1128 :             success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
    2141             : 
    2142        1132 :         free(opt0);
    2143        1132 :         free(opt1);
    2144             :     }
    2145             :     else
    2146           8 :         ignore_slash_options(scan_state);
    2147             : 
    2148        1140 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2149             : }
    2150             : 
    2151             : /*
    2152             :  * \q or \quit -- exit psql
    2153             :  */
    2154             : static backslashResult
    2155          26 : exec_command_quit(PsqlScanState scan_state, bool active_branch)
    2156             : {
    2157          26 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2158             : 
    2159          26 :     if (active_branch)
    2160          10 :         status = PSQL_CMD_TERMINATE;
    2161             : 
    2162          26 :     return status;
    2163             : }
    2164             : 
    2165             : /*
    2166             :  * \r -- reset (clear) the query buffer
    2167             :  */
    2168             : static backslashResult
    2169          26 : exec_command_reset(PsqlScanState scan_state, bool active_branch,
    2170             :                    PQExpBuffer query_buf)
    2171             : {
    2172          26 :     if (active_branch)
    2173             :     {
    2174          22 :         resetPQExpBuffer(query_buf);
    2175          22 :         psql_scan_reset(scan_state);
    2176          22 :         if (!pset.quiet)
    2177          10 :             puts(_("Query buffer reset (cleared)."));
    2178             :     }
    2179             : 
    2180          26 :     return PSQL_CMD_SKIP_LINE;
    2181             : }
    2182             : 
    2183             : /*
    2184             :  * \s -- save history in a file or show it on the screen
    2185             :  */
    2186             : static backslashResult
    2187           4 : exec_command_s(PsqlScanState scan_state, bool active_branch)
    2188             : {
    2189           4 :     bool        success = true;
    2190             : 
    2191           4 :     if (active_branch)
    2192             :     {
    2193           0 :         char       *fname = psql_scan_slash_option(scan_state,
    2194             :                                                    OT_NORMAL, NULL, true);
    2195             : 
    2196           0 :         expand_tilde(&fname);
    2197           0 :         success = printHistory(fname, pset.popt.topt.pager);
    2198           0 :         if (success && !pset.quiet && fname)
    2199           0 :             printf(_("Wrote history to file \"%s\".\n"), fname);
    2200           0 :         if (!fname)
    2201           0 :             putchar('\n');
    2202           0 :         free(fname);
    2203             :     }
    2204             :     else
    2205           4 :         ignore_slash_options(scan_state);
    2206             : 
    2207           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2208             : }
    2209             : 
    2210             : /*
    2211             :  * \set -- set variable
    2212             :  */
    2213             : static backslashResult
    2214         236 : exec_command_set(PsqlScanState scan_state, bool active_branch)
    2215             : {
    2216         236 :     bool        success = true;
    2217             : 
    2218         236 :     if (active_branch)
    2219             :     {
    2220         232 :         char       *opt0 = psql_scan_slash_option(scan_state,
    2221             :                                                   OT_NORMAL, NULL, false);
    2222             : 
    2223         232 :         if (!opt0)
    2224             :         {
    2225             :             /* list all variables */
    2226           0 :             PrintVariables(pset.vars);
    2227           0 :             success = true;
    2228             :         }
    2229             :         else
    2230             :         {
    2231             :             /*
    2232             :              * Set variable to the concatenation of the arguments.
    2233             :              */
    2234             :             char       *newval;
    2235             :             char       *opt;
    2236             : 
    2237         232 :             opt = psql_scan_slash_option(scan_state,
    2238             :                                          OT_NORMAL, NULL, false);
    2239         232 :             newval = pg_strdup(opt ? opt : "");
    2240         232 :             free(opt);
    2241             : 
    2242         232 :             while ((opt = psql_scan_slash_option(scan_state,
    2243             :                                                  OT_NORMAL, NULL, false)))
    2244             :             {
    2245           0 :                 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
    2246           0 :                 strcat(newval, opt);
    2247           0 :                 free(opt);
    2248             :             }
    2249             : 
    2250         232 :             if (!SetVariable(pset.vars, opt0, newval))
    2251          16 :                 success = false;
    2252             : 
    2253         232 :             free(newval);
    2254             :         }
    2255         232 :         free(opt0);
    2256             :     }
    2257             :     else
    2258           4 :         ignore_slash_options(scan_state);
    2259             : 
    2260         236 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2261             : }
    2262             : 
    2263             : /*
    2264             :  * \setenv -- set environment variable
    2265             :  */
    2266             : static backslashResult
    2267           4 : exec_command_setenv(PsqlScanState scan_state, bool active_branch,
    2268             :                     const char *cmd)
    2269             : {
    2270           4 :     bool        success = true;
    2271             : 
    2272           4 :     if (active_branch)
    2273             :     {
    2274           0 :         char       *envvar = psql_scan_slash_option(scan_state,
    2275             :                                                     OT_NORMAL, NULL, false);
    2276           0 :         char       *envval = psql_scan_slash_option(scan_state,
    2277             :                                                     OT_NORMAL, NULL, false);
    2278             : 
    2279           0 :         if (!envvar)
    2280             :         {
    2281           0 :             pg_log_error("\\%s: missing required argument", cmd);
    2282           0 :             success = false;
    2283             :         }
    2284           0 :         else if (strchr(envvar, '=') != NULL)
    2285             :         {
    2286           0 :             pg_log_error("\\%s: environment variable name must not contain \"=\"",
    2287             :                          cmd);
    2288           0 :             success = false;
    2289             :         }
    2290           0 :         else if (!envval)
    2291             :         {
    2292             :             /* No argument - unset the environment variable */
    2293           0 :             unsetenv(envvar);
    2294           0 :             success = true;
    2295             :         }
    2296             :         else
    2297             :         {
    2298             :             /* Set variable to the value of the next argument */
    2299             :             char       *newval;
    2300             : 
    2301           0 :             newval = psprintf("%s=%s", envvar, envval);
    2302           0 :             putenv(newval);
    2303           0 :             success = true;
    2304             : 
    2305             :             /*
    2306             :              * Do not free newval here, it will screw up the environment if
    2307             :              * you do. See putenv man page for details. That means we leak a
    2308             :              * bit of memory here, but not enough to worry about.
    2309             :              */
    2310             :         }
    2311           0 :         free(envvar);
    2312           0 :         free(envval);
    2313             :     }
    2314             :     else
    2315           4 :         ignore_slash_options(scan_state);
    2316             : 
    2317           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2318             : }
    2319             : 
    2320             : /*
    2321             :  * \sf/\sv -- show a function/view's source code
    2322             :  */
    2323             : static backslashResult
    2324          12 : exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
    2325             :                    const char *cmd, bool is_func)
    2326             : {
    2327          12 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2328             : 
    2329          12 :     if (active_branch)
    2330             :     {
    2331           4 :         bool        show_linenumbers = (strchr(cmd, '+') != NULL);
    2332             :         PQExpBuffer buf;
    2333             :         char       *obj_desc;
    2334           4 :         Oid         obj_oid = InvalidOid;
    2335           4 :         EditableObjectType eot = is_func ? EditableFunction : EditableView;
    2336             : 
    2337           4 :         buf = createPQExpBuffer();
    2338           4 :         obj_desc = psql_scan_slash_option(scan_state,
    2339             :                                           OT_WHOLE_LINE, NULL, true);
    2340           4 :         if (pset.sversion < (is_func ? 80400 : 70400))
    2341             :         {
    2342             :             char        sverbuf[32];
    2343             : 
    2344           0 :             formatPGVersionNumber(pset.sversion, false,
    2345             :                                   sverbuf, sizeof(sverbuf));
    2346           0 :             if (is_func)
    2347           0 :                 pg_log_error("The server (version %s) does not support showing function source.",
    2348             :                              sverbuf);
    2349             :             else
    2350           0 :                 pg_log_error("The server (version %s) does not support showing view definitions.",
    2351             :                              sverbuf);
    2352           0 :             status = PSQL_CMD_ERROR;
    2353             :         }
    2354           4 :         else if (!obj_desc)
    2355             :         {
    2356           0 :             if (is_func)
    2357           0 :                 pg_log_error("function name is required");
    2358             :             else
    2359           0 :                 pg_log_error("view name is required");
    2360           0 :             status = PSQL_CMD_ERROR;
    2361             :         }
    2362           4 :         else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
    2363             :         {
    2364             :             /* error already reported */
    2365           0 :             status = PSQL_CMD_ERROR;
    2366             :         }
    2367           4 :         else if (!get_create_object_cmd(eot, obj_oid, buf))
    2368             :         {
    2369             :             /* error already reported */
    2370           0 :             status = PSQL_CMD_ERROR;
    2371             :         }
    2372             :         else
    2373             :         {
    2374             :             FILE       *output;
    2375             :             bool        is_pager;
    2376             : 
    2377             :             /* Select output stream: stdout, pager, or file */
    2378           4 :             if (pset.queryFout == stdout)
    2379             :             {
    2380             :                 /* count lines in function to see if pager is needed */
    2381           4 :                 int         lineno = count_lines_in_buf(buf);
    2382             : 
    2383           4 :                 output = PageOutput(lineno, &(pset.popt.topt));
    2384           4 :                 is_pager = true;
    2385             :             }
    2386             :             else
    2387             :             {
    2388             :                 /* use previously set output file, without pager */
    2389           0 :                 output = pset.queryFout;
    2390           0 :                 is_pager = false;
    2391             :             }
    2392             : 
    2393           4 :             if (show_linenumbers)
    2394             :             {
    2395             :                 /*
    2396             :                  * For functions, lineno "1" should correspond to the first
    2397             :                  * line of the function body.  We expect that
    2398             :                  * pg_get_functiondef() will emit that on a line beginning
    2399             :                  * with "AS ", and that there can be no such line before the
    2400             :                  * real start of the function body.
    2401             :                  */
    2402           0 :                 print_with_linenumbers(output, buf->data,
    2403             :                                        is_func ? "AS " : NULL);
    2404             :             }
    2405             :             else
    2406             :             {
    2407             :                 /* just send the definition to output */
    2408           4 :                 fputs(buf->data, output);
    2409             :             }
    2410             : 
    2411           4 :             if (is_pager)
    2412           4 :                 ClosePager(output);
    2413             :         }
    2414             : 
    2415           4 :         if (obj_desc)
    2416           4 :             free(obj_desc);
    2417           4 :         destroyPQExpBuffer(buf);
    2418             :     }
    2419             :     else
    2420           8 :         ignore_slash_whole_line(scan_state);
    2421             : 
    2422          12 :     return status;
    2423             : }
    2424             : 
    2425             : /*
    2426             :  * \t -- turn off table headers and row count
    2427             :  */
    2428             : static backslashResult
    2429          44 : exec_command_t(PsqlScanState scan_state, bool active_branch)
    2430             : {
    2431          44 :     bool        success = true;
    2432             : 
    2433          44 :     if (active_branch)
    2434             :     {
    2435          40 :         char       *opt = psql_scan_slash_option(scan_state,
    2436             :                                                  OT_NORMAL, NULL, true);
    2437             : 
    2438          40 :         success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
    2439          40 :         free(opt);
    2440             :     }
    2441             :     else
    2442           4 :         ignore_slash_options(scan_state);
    2443             : 
    2444          44 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2445             : }
    2446             : 
    2447             : /*
    2448             :  * \T -- define html <table ...> attributes
    2449             :  */
    2450             : static backslashResult
    2451           4 : exec_command_T(PsqlScanState scan_state, bool active_branch)
    2452             : {
    2453           4 :     bool        success = true;
    2454             : 
    2455           4 :     if (active_branch)
    2456             :     {
    2457           0 :         char       *value = psql_scan_slash_option(scan_state,
    2458             :                                                    OT_NORMAL, NULL, false);
    2459             : 
    2460           0 :         success = do_pset("tableattr", value, &pset.popt, pset.quiet);
    2461           0 :         free(value);
    2462             :     }
    2463             :     else
    2464           4 :         ignore_slash_options(scan_state);
    2465             : 
    2466           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2467             : }
    2468             : 
    2469             : /*
    2470             :  * \timing -- enable/disable timing of queries
    2471             :  */
    2472             : static backslashResult
    2473           4 : exec_command_timing(PsqlScanState scan_state, bool active_branch)
    2474             : {
    2475           4 :     bool        success = true;
    2476             : 
    2477           4 :     if (active_branch)
    2478             :     {
    2479           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2480             :                                                  OT_NORMAL, NULL, false);
    2481             : 
    2482           0 :         if (opt)
    2483           0 :             success = ParseVariableBool(opt, "\\timing", &pset.timing);
    2484             :         else
    2485           0 :             pset.timing = !pset.timing;
    2486           0 :         if (!pset.quiet)
    2487             :         {
    2488           0 :             if (pset.timing)
    2489           0 :                 puts(_("Timing is on."));
    2490             :             else
    2491           0 :                 puts(_("Timing is off."));
    2492             :         }
    2493           0 :         free(opt);
    2494             :     }
    2495             :     else
    2496           4 :         ignore_slash_options(scan_state);
    2497             : 
    2498           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2499             : }
    2500             : 
    2501             : /*
    2502             :  * \unset -- unset variable
    2503             :  */
    2504             : static backslashResult
    2505          26 : exec_command_unset(PsqlScanState scan_state, bool active_branch,
    2506             :                    const char *cmd)
    2507             : {
    2508          26 :     bool        success = true;
    2509             : 
    2510          26 :     if (active_branch)
    2511             :     {
    2512          22 :         char       *opt = psql_scan_slash_option(scan_state,
    2513             :                                                  OT_NORMAL, NULL, false);
    2514             : 
    2515          22 :         if (!opt)
    2516             :         {
    2517           0 :             pg_log_error("\\%s: missing required argument", cmd);
    2518           0 :             success = false;
    2519             :         }
    2520          22 :         else if (!SetVariable(pset.vars, opt, NULL))
    2521           0 :             success = false;
    2522             : 
    2523          22 :         free(opt);
    2524             :     }
    2525             :     else
    2526           4 :         ignore_slash_options(scan_state);
    2527             : 
    2528          26 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2529             : }
    2530             : 
    2531             : /*
    2532             :  * \w -- write query buffer to file
    2533             :  */
    2534             : static backslashResult
    2535           8 : exec_command_write(PsqlScanState scan_state, bool active_branch,
    2536             :                    const char *cmd,
    2537             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2538             : {
    2539           8 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2540             : 
    2541           8 :     if (active_branch)
    2542             :     {
    2543           0 :         char       *fname = psql_scan_slash_option(scan_state,
    2544             :                                                    OT_FILEPIPE, NULL, true);
    2545           0 :         FILE       *fd = NULL;
    2546           0 :         bool        is_pipe = false;
    2547             : 
    2548           0 :         if (!query_buf)
    2549             :         {
    2550           0 :             pg_log_error("no query buffer");
    2551           0 :             status = PSQL_CMD_ERROR;
    2552             :         }
    2553             :         else
    2554             :         {
    2555           0 :             if (!fname)
    2556             :             {
    2557           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    2558           0 :                 status = PSQL_CMD_ERROR;
    2559             :             }
    2560             :             else
    2561             :             {
    2562           0 :                 expand_tilde(&fname);
    2563           0 :                 if (fname[0] == '|')
    2564             :                 {
    2565           0 :                     is_pipe = true;
    2566           0 :                     disable_sigpipe_trap();
    2567           0 :                     fd = popen(&fname[1], "w");
    2568             :                 }
    2569             :                 else
    2570             :                 {
    2571           0 :                     canonicalize_path(fname);
    2572           0 :                     fd = fopen(fname, "w");
    2573             :                 }
    2574           0 :                 if (!fd)
    2575             :                 {
    2576           0 :                     pg_log_error("%s: %m", fname);
    2577           0 :                     status = PSQL_CMD_ERROR;
    2578             :                 }
    2579             :             }
    2580             :         }
    2581             : 
    2582           0 :         if (fd)
    2583             :         {
    2584             :             int         result;
    2585             : 
    2586             :             /*
    2587             :              * We want to print the same thing \g would execute, but not to
    2588             :              * change the query buffer state; so we can't use
    2589             :              * copy_previous_query().  Also, beware of possibility that buffer
    2590             :              * pointers are NULL.
    2591             :              */
    2592           0 :             if (query_buf && query_buf->len > 0)
    2593           0 :                 fprintf(fd, "%s\n", query_buf->data);
    2594           0 :             else if (previous_buf && previous_buf->len > 0)
    2595           0 :                 fprintf(fd, "%s\n", previous_buf->data);
    2596             : 
    2597           0 :             if (is_pipe)
    2598           0 :                 result = pclose(fd);
    2599             :             else
    2600           0 :                 result = fclose(fd);
    2601             : 
    2602           0 :             if (result == EOF)
    2603             :             {
    2604           0 :                 pg_log_error("%s: %m", fname);
    2605           0 :                 status = PSQL_CMD_ERROR;
    2606             :             }
    2607             :         }
    2608             : 
    2609           0 :         if (is_pipe)
    2610           0 :             restore_sigpipe_trap();
    2611             : 
    2612           0 :         free(fname);
    2613             :     }
    2614             :     else
    2615           8 :         ignore_slash_filepipe(scan_state);
    2616             : 
    2617           8 :     return status;
    2618             : }
    2619             : 
    2620             : /*
    2621             :  * \watch -- execute a query every N seconds
    2622             :  */
    2623             : static backslashResult
    2624           4 : exec_command_watch(PsqlScanState scan_state, bool active_branch,
    2625             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2626             : {
    2627           4 :     bool        success = true;
    2628             : 
    2629           4 :     if (active_branch)
    2630             :     {
    2631           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2632             :                                                  OT_NORMAL, NULL, true);
    2633           0 :         double      sleep = 2;
    2634             : 
    2635             :         /* Convert optional sleep-length argument */
    2636           0 :         if (opt)
    2637             :         {
    2638           0 :             sleep = strtod(opt, NULL);
    2639           0 :             if (sleep <= 0)
    2640           0 :                 sleep = 1;
    2641           0 :             free(opt);
    2642             :         }
    2643             : 
    2644             :         /* If query_buf is empty, recall and execute previous query */
    2645           0 :         copy_previous_query(query_buf, previous_buf);
    2646             : 
    2647           0 :         success = do_watch(query_buf, sleep);
    2648             : 
    2649             :         /* Reset the query buffer as though for \r */
    2650           0 :         resetPQExpBuffer(query_buf);
    2651           0 :         psql_scan_reset(scan_state);
    2652             :     }
    2653             :     else
    2654           4 :         ignore_slash_options(scan_state);
    2655             : 
    2656           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2657             : }
    2658             : 
    2659             : /*
    2660             :  * \x -- set or toggle expanded table representation
    2661             :  */
    2662             : static backslashResult
    2663          22 : exec_command_x(PsqlScanState scan_state, bool active_branch)
    2664             : {
    2665          22 :     bool        success = true;
    2666             : 
    2667          22 :     if (active_branch)
    2668             :     {
    2669          18 :         char       *opt = psql_scan_slash_option(scan_state,
    2670             :                                                  OT_NORMAL, NULL, true);
    2671             : 
    2672          18 :         success = do_pset("expanded", opt, &pset.popt, pset.quiet);
    2673          18 :         free(opt);
    2674             :     }
    2675             :     else
    2676           4 :         ignore_slash_options(scan_state);
    2677             : 
    2678          22 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2679             : }
    2680             : 
    2681             : /*
    2682             :  * \z -- list table privileges (equivalent to \dp)
    2683             :  */
    2684             : static backslashResult
    2685          12 : exec_command_z(PsqlScanState scan_state, bool active_branch)
    2686             : {
    2687          12 :     bool        success = true;
    2688             : 
    2689          12 :     if (active_branch)
    2690             :     {
    2691           8 :         char       *pattern = psql_scan_slash_option(scan_state,
    2692             :                                                      OT_NORMAL, NULL, true);
    2693             : 
    2694           8 :         success = permissionsList(pattern);
    2695           8 :         if (pattern)
    2696           8 :             free(pattern);
    2697             :     }
    2698             :     else
    2699           4 :         ignore_slash_options(scan_state);
    2700             : 
    2701          12 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2702             : }
    2703             : 
    2704             : /*
    2705             :  * \! -- execute shell command
    2706             :  */
    2707             : static backslashResult
    2708           4 : exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
    2709             : {
    2710           4 :     bool        success = true;
    2711             : 
    2712           4 :     if (active_branch)
    2713             :     {
    2714           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2715             :                                                  OT_WHOLE_LINE, NULL, false);
    2716             : 
    2717           0 :         success = do_shell(opt);
    2718           0 :         free(opt);
    2719             :     }
    2720             :     else
    2721           4 :         ignore_slash_whole_line(scan_state);
    2722             : 
    2723           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2724             : }
    2725             : 
    2726             : /*
    2727             :  * \? -- print help about backslash commands
    2728             :  */
    2729             : static backslashResult
    2730           4 : exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
    2731             : {
    2732           4 :     if (active_branch)
    2733             :     {
    2734           0 :         char       *opt0 = psql_scan_slash_option(scan_state,
    2735             :                                                   OT_NORMAL, NULL, false);
    2736             : 
    2737           0 :         if (!opt0 || strcmp(opt0, "commands") == 0)
    2738           0 :             slashUsage(pset.popt.topt.pager);
    2739           0 :         else if (strcmp(opt0, "options") == 0)
    2740           0 :             usage(pset.popt.topt.pager);
    2741           0 :         else if (strcmp(opt0, "variables") == 0)
    2742           0 :             helpVariables(pset.popt.topt.pager);
    2743             :         else
    2744           0 :             slashUsage(pset.popt.topt.pager);
    2745             : 
    2746           0 :         if (opt0)
    2747           0 :             free(opt0);
    2748             :     }
    2749             :     else
    2750           4 :         ignore_slash_options(scan_state);
    2751             : 
    2752           4 :     return PSQL_CMD_SKIP_LINE;
    2753             : }
    2754             : 
    2755             : 
    2756             : /*
    2757             :  * Read and interpret an argument to the \connect slash command.
    2758             :  *
    2759             :  * Returns a malloc'd string, or NULL if no/empty argument.
    2760             :  */
    2761             : static char *
    2762         672 : read_connect_arg(PsqlScanState scan_state)
    2763             : {
    2764             :     char       *result;
    2765             :     char        quote;
    2766             : 
    2767             :     /*
    2768             :      * Ideally we should treat the arguments as SQL identifiers.  But for
    2769             :      * backwards compatibility with 7.2 and older pg_dump files, we have to
    2770             :      * take unquoted arguments verbatim (don't downcase them). For now,
    2771             :      * double-quoted arguments may be stripped of double quotes (as if SQL
    2772             :      * identifiers).  By 7.4 or so, pg_dump files can be expected to
    2773             :      * double-quote all mixed-case \connect arguments, and then we can get rid
    2774             :      * of OT_SQLIDHACK.
    2775             :      */
    2776         672 :     result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
    2777             : 
    2778         672 :     if (!result)
    2779         524 :         return NULL;
    2780             : 
    2781         148 :     if (quote)
    2782          18 :         return result;
    2783             : 
    2784         130 :     if (*result == '\0' || strcmp(result, "-") == 0)
    2785             :     {
    2786         104 :         free(result);
    2787         104 :         return NULL;
    2788             :     }
    2789             : 
    2790          26 :     return result;
    2791             : }
    2792             : 
    2793             : /*
    2794             :  * Read a boolean expression, return it as a PQExpBuffer string.
    2795             :  *
    2796             :  * Note: anything more or less than one token will certainly fail to be
    2797             :  * parsed by ParseVariableBool, so we don't worry about complaining here.
    2798             :  * This routine's return data structure will need to be rethought anyway
    2799             :  * to support likely future extensions such as "\if defined VARNAME".
    2800             :  */
    2801             : static PQExpBuffer
    2802         120 : gather_boolean_expression(PsqlScanState scan_state)
    2803             : {
    2804         120 :     PQExpBuffer exp_buf = createPQExpBuffer();
    2805         120 :     int         num_options = 0;
    2806             :     char       *value;
    2807             : 
    2808             :     /* collect all arguments for the conditional command into exp_buf */
    2809         248 :     while ((value = psql_scan_slash_option(scan_state,
    2810             :                                            OT_NORMAL, NULL, false)) != NULL)
    2811             :     {
    2812             :         /* add spaces between tokens */
    2813         128 :         if (num_options > 0)
    2814           8 :             appendPQExpBufferChar(exp_buf, ' ');
    2815         128 :         appendPQExpBufferStr(exp_buf, value);
    2816         128 :         num_options++;
    2817         128 :         free(value);
    2818             :     }
    2819             : 
    2820         120 :     return exp_buf;
    2821             : }
    2822             : 
    2823             : /*
    2824             :  * Read a boolean expression, return true if the expression
    2825             :  * was a valid boolean expression that evaluated to true.
    2826             :  * Otherwise return false.
    2827             :  *
    2828             :  * Note: conditional stack's top state must be active, else lexer will
    2829             :  * fail to expand variables and backticks.
    2830             :  */
    2831             : static bool
    2832         108 : is_true_boolean_expression(PsqlScanState scan_state, const char *name)
    2833             : {
    2834         108 :     PQExpBuffer buf = gather_boolean_expression(scan_state);
    2835         108 :     bool        value = false;
    2836         108 :     bool        success = ParseVariableBool(buf->data, name, &value);
    2837             : 
    2838         108 :     destroyPQExpBuffer(buf);
    2839         108 :     return success && value;
    2840             : }
    2841             : 
    2842             : /*
    2843             :  * Read a boolean expression, but do nothing with it.
    2844             :  *
    2845             :  * Note: conditional stack's top state must be INACTIVE, else lexer will
    2846             :  * expand variables and backticks, which we do not want here.
    2847             :  */
    2848             : static void
    2849          12 : ignore_boolean_expression(PsqlScanState scan_state)
    2850             : {
    2851          12 :     PQExpBuffer buf = gather_boolean_expression(scan_state);
    2852             : 
    2853          12 :     destroyPQExpBuffer(buf);
    2854          12 : }
    2855             : 
    2856             : /*
    2857             :  * Read and discard "normal" slash command options.
    2858             :  *
    2859             :  * This should be used for inactive-branch processing of any slash command
    2860             :  * that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
    2861             :  * We don't need to worry about exactly how many it would eat, since the
    2862             :  * cleanup logic in HandleSlashCmds would silently discard any extras anyway.
    2863             :  */
    2864             : static void
    2865         204 : ignore_slash_options(PsqlScanState scan_state)
    2866             : {
    2867             :     char       *arg;
    2868             : 
    2869         488 :     while ((arg = psql_scan_slash_option(scan_state,
    2870             :                                          OT_NORMAL, NULL, false)) != NULL)
    2871         284 :         free(arg);
    2872         204 : }
    2873             : 
    2874             : /*
    2875             :  * Read and discard FILEPIPE slash command argument.
    2876             :  *
    2877             :  * This *MUST* be used for inactive-branch processing of any slash command
    2878             :  * that takes an OT_FILEPIPE option.  Otherwise we might consume a different
    2879             :  * amount of option text in active and inactive cases.
    2880             :  */
    2881             : static void
    2882          12 : ignore_slash_filepipe(PsqlScanState scan_state)
    2883             : {
    2884          12 :     char       *arg = psql_scan_slash_option(scan_state,
    2885             :                                              OT_FILEPIPE, NULL, false);
    2886             : 
    2887          12 :     if (arg)
    2888          12 :         free(arg);
    2889          12 : }
    2890             : 
    2891             : /*
    2892             :  * Read and discard whole-line slash command argument.
    2893             :  *
    2894             :  * This *MUST* be used for inactive-branch processing of any slash command
    2895             :  * that takes an OT_WHOLE_LINE option.  Otherwise we might consume a different
    2896             :  * amount of option text in active and inactive cases.
    2897             :  */
    2898             : static void
    2899          28 : ignore_slash_whole_line(PsqlScanState scan_state)
    2900             : {
    2901          28 :     char       *arg = psql_scan_slash_option(scan_state,
    2902             :                                              OT_WHOLE_LINE, NULL, false);
    2903             : 
    2904          28 :     if (arg)
    2905          24 :         free(arg);
    2906          28 : }
    2907             : 
    2908             : /*
    2909             :  * Return true if the command given is a branching command.
    2910             :  */
    2911             : static bool
    2912           0 : is_branching_command(const char *cmd)
    2913             : {
    2914           0 :     return (strcmp(cmd, "if") == 0 ||
    2915           0 :             strcmp(cmd, "elif") == 0 ||
    2916           0 :             strcmp(cmd, "else") == 0 ||
    2917           0 :             strcmp(cmd, "endif") == 0);
    2918             : }
    2919             : 
    2920             : /*
    2921             :  * Prepare to possibly restore query buffer to its current state
    2922             :  * (cf. discard_query_text).
    2923             :  *
    2924             :  * We need to remember the length of the query buffer, and the lexer's
    2925             :  * notion of the parenthesis nesting depth.
    2926             :  */
    2927             : static void
    2928         140 : save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
    2929             :                       PQExpBuffer query_buf)
    2930             : {
    2931         140 :     if (query_buf)
    2932         140 :         conditional_stack_set_query_len(cstack, query_buf->len);
    2933         140 :     conditional_stack_set_paren_depth(cstack,
    2934             :                                       psql_scan_get_paren_depth(scan_state));
    2935         140 : }
    2936             : 
    2937             : /*
    2938             :  * Discard any query text absorbed during an inactive conditional branch.
    2939             :  *
    2940             :  * We must discard data that was appended to query_buf during an inactive
    2941             :  * \if branch.  We don't have to do anything there if there's no query_buf.
    2942             :  *
    2943             :  * Also, reset the lexer state to the same paren depth there was before.
    2944             :  * (The rest of its state doesn't need attention, since we could not be
    2945             :  * inside a comment or literal or partial token.)
    2946             :  */
    2947             : static void
    2948         116 : discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
    2949             :                    PQExpBuffer query_buf)
    2950             : {
    2951         116 :     if (query_buf)
    2952             :     {
    2953         116 :         int         new_len = conditional_stack_get_query_len(cstack);
    2954             : 
    2955             :         Assert(new_len >= 0 && new_len <= query_buf->len);
    2956         116 :         query_buf->len = new_len;
    2957         116 :         query_buf->data[new_len] = '\0';
    2958             :     }
    2959         116 :     psql_scan_set_paren_depth(scan_state,
    2960             :                               conditional_stack_get_paren_depth(cstack));
    2961         116 : }
    2962             : 
    2963             : /*
    2964             :  * If query_buf is empty, copy previous_buf into it.
    2965             :  *
    2966             :  * This is used by various slash commands for which re-execution of a
    2967             :  * previous query is a common usage.  For convenience, we allow the
    2968             :  * case of query_buf == NULL (and do nothing).
    2969             :  */
    2970             : static void
    2971         368 : copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2972             : {
    2973         368 :     if (query_buf && query_buf->len == 0)
    2974          48 :         appendPQExpBufferStr(query_buf, previous_buf->data);
    2975         368 : }
    2976             : 
    2977             : /*
    2978             :  * Ask the user for a password; 'username' is the username the
    2979             :  * password is for, if one has been explicitly specified. Returns a
    2980             :  * malloc'd string.
    2981             :  */
    2982             : static char *
    2983           0 : prompt_for_password(const char *username)
    2984             : {
    2985             :     char        buf[100];
    2986             : 
    2987           0 :     if (username == NULL || username[0] == '\0')
    2988           0 :         simple_prompt("Password: ", buf, sizeof(buf), false);
    2989             :     else
    2990             :     {
    2991             :         char       *prompt_text;
    2992             : 
    2993           0 :         prompt_text = psprintf(_("Password for user %s: "), username);
    2994           0 :         simple_prompt(prompt_text, buf, sizeof(buf), false);
    2995           0 :         free(prompt_text);
    2996             :     }
    2997           0 :     return pg_strdup(buf);
    2998             : }
    2999             : 
    3000             : static bool
    3001          48 : param_is_newly_set(const char *old_val, const char *new_val)
    3002             : {
    3003          48 :     if (new_val == NULL)
    3004           0 :         return false;
    3005             : 
    3006          48 :     if (old_val == NULL || strcmp(old_val, new_val) != 0)
    3007           0 :         return true;
    3008             : 
    3009          48 :     return false;
    3010             : }
    3011             : 
    3012             : /* return whether the connection has 'hostaddr' in its conninfo */
    3013             : static bool
    3014         164 : has_hostaddr(PGconn *conn)
    3015             : {
    3016         164 :     bool        used = false;
    3017         164 :     PQconninfoOption *ciopt = PQconninfo(conn);
    3018             : 
    3019        6068 :     for (PQconninfoOption *p = ciopt; p->keyword != NULL; p++)
    3020             :     {
    3021        5904 :         if (strcmp(p->keyword, "hostaddr") == 0 && p->val != NULL)
    3022             :         {
    3023           0 :             used = true;
    3024           0 :             break;
    3025             :         }
    3026             :     }
    3027             : 
    3028         164 :     PQconninfoFree(ciopt);
    3029         164 :     return used;
    3030             : }
    3031             : 
    3032             : /*
    3033             :  * do_connect -- handler for \connect
    3034             :  *
    3035             :  * Connects to a database with given parameters. Absent an established
    3036             :  * connection, all parameters are required. Given -reuse-previous=off or a
    3037             :  * connection string without -reuse-previous=on, NULL values will pass through
    3038             :  * to PQconnectdbParams(), so the libpq defaults will be used. Otherwise, NULL
    3039             :  * values will be replaced with the ones in the current connection.
    3040             :  *
    3041             :  * In interactive mode, if connection fails with the given parameters,
    3042             :  * the old connection will be kept.
    3043             :  */
    3044             : static bool
    3045         164 : do_connect(enum trivalue reuse_previous_specification,
    3046             :            char *dbname, char *user, char *host, char *port)
    3047             : {
    3048         164 :     PGconn     *o_conn = pset.db,
    3049             :                *n_conn;
    3050         164 :     char       *password = NULL;
    3051         164 :     char       *hostaddr = NULL;
    3052             :     bool        keep_password;
    3053             :     bool        has_connection_string;
    3054             :     bool        reuse_previous;
    3055             :     PQExpBufferData connstr;
    3056             : 
    3057         164 :     if (!o_conn && (!dbname || !user || !host || !port))
    3058             :     {
    3059             :         /*
    3060             :          * We don't know the supplied connection parameters and don't want to
    3061             :          * connect to the wrong database by using defaults, so require all
    3062             :          * parameters to be specified.
    3063             :          */
    3064           0 :         pg_log_error("All connection parameters must be supplied because no "
    3065             :                      "database connection exists");
    3066           0 :         return false;
    3067             :     }
    3068             : 
    3069         164 :     has_connection_string = dbname ?
    3070         164 :         recognized_connection_string(dbname) : false;
    3071         164 :     switch (reuse_previous_specification)
    3072             :     {
    3073          16 :         case TRI_YES:
    3074          16 :             reuse_previous = true;
    3075          16 :             break;
    3076           0 :         case TRI_NO:
    3077           0 :             reuse_previous = false;
    3078           0 :             break;
    3079         148 :         default:
    3080         148 :             reuse_previous = !has_connection_string;
    3081         148 :             break;
    3082             :     }
    3083             : 
    3084             :     /* If the old connection does not exist, there is nothing to reuse. */
    3085         164 :     if (!o_conn)
    3086           0 :         reuse_previous = false;
    3087             : 
    3088             :     /* Silently ignore arguments subsequent to a connection string. */
    3089         164 :     if (has_connection_string)
    3090             :     {
    3091          16 :         user = NULL;
    3092          16 :         host = NULL;
    3093          16 :         port = NULL;
    3094             :     }
    3095             : 
    3096             :     /*
    3097             :      * Grab missing values from the old connection.  If we grab host (or host
    3098             :      * is the same as before) and hostaddr was set, grab that too.
    3099             :      */
    3100         164 :     if (reuse_previous)
    3101             :     {
    3102         164 :         if (!user)
    3103         164 :             user = PQuser(o_conn);
    3104         164 :         if (host && strcmp(host, PQhost(o_conn)) == 0 &&
    3105           0 :             has_hostaddr(o_conn))
    3106             :         {
    3107           0 :             hostaddr = PQhostaddr(o_conn);
    3108             :         }
    3109         164 :         if (!host)
    3110             :         {
    3111         164 :             host = PQhost(o_conn);
    3112         164 :             if (has_hostaddr(o_conn))
    3113           0 :                 hostaddr = PQhostaddr(o_conn);
    3114             :         }
    3115         164 :         if (!port)
    3116         164 :             port = PQport(o_conn);
    3117             :     }
    3118             : 
    3119             :     /*
    3120             :      * Any change in the parameters read above makes us discard the password.
    3121             :      * We also discard it if we're to use a conninfo rather than the
    3122             :      * positional syntax.
    3123             :      */
    3124         164 :     if (has_connection_string)
    3125          16 :         keep_password = false;
    3126             :     else
    3127         148 :         keep_password =
    3128         148 :             (user && PQuser(o_conn) && strcmp(user, PQuser(o_conn)) == 0) &&
    3129         444 :             (host && PQhost(o_conn) && strcmp(host, PQhost(o_conn)) == 0) &&
    3130         148 :             (port && PQport(o_conn) && strcmp(port, PQport(o_conn)) == 0);
    3131             : 
    3132             :     /*
    3133             :      * Grab missing dbname from old connection.  No password discard if this
    3134             :      * changes: passwords aren't (usually) database-specific.
    3135             :      */
    3136         164 :     if (!dbname && reuse_previous)
    3137             :     {
    3138         136 :         initPQExpBuffer(&connstr);
    3139         136 :         appendPQExpBufferStr(&connstr, "dbname=");
    3140         136 :         appendConnStrVal(&connstr, PQdb(o_conn));
    3141         136 :         dbname = connstr.data;
    3142             :         /* has_connection_string=true would be a dead store */
    3143             :     }
    3144             :     else
    3145          28 :         connstr.data = NULL;
    3146             : 
    3147             :     /*
    3148             :      * If the user asked to be prompted for a password, ask for one now. If
    3149             :      * not, use the password from the old connection, provided the username
    3150             :      * etc have not changed. Otherwise, try to connect without a password
    3151             :      * first, and then ask for a password if needed.
    3152             :      *
    3153             :      * XXX: this behavior leads to spurious connection attempts recorded in
    3154             :      * the postmaster's log.  But libpq offers no API that would let us obtain
    3155             :      * a password and then continue with the first connection attempt.
    3156             :      */
    3157         164 :     if (pset.getPassword == TRI_YES)
    3158             :     {
    3159             :         /*
    3160             :          * If a connstring or URI is provided, we can't be sure we know which
    3161             :          * username will be used, since we haven't parsed that argument yet.
    3162             :          * Don't risk issuing a misleading prompt.  As in startup.c, it does
    3163             :          * not seem worth working harder, since this getPassword option is
    3164             :          * normally only used in noninteractive cases.
    3165             :          */
    3166           0 :         password = prompt_for_password(has_connection_string ? NULL : user);
    3167             :     }
    3168         164 :     else if (o_conn && keep_password)
    3169             :     {
    3170         148 :         password = PQpass(o_conn);
    3171         148 :         if (password && *password)
    3172           0 :             password = pg_strdup(password);
    3173             :         else
    3174         148 :             password = NULL;
    3175             :     }
    3176             : 
    3177             :     while (true)
    3178           0 :     {
    3179             : #define PARAMS_ARRAY_SIZE   9
    3180         164 :         const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
    3181         164 :         const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
    3182         164 :         int         paramnum = -1;
    3183             : 
    3184         164 :         keywords[++paramnum] = "host";
    3185         164 :         values[paramnum] = host;
    3186         164 :         if (hostaddr && *hostaddr)
    3187             :         {
    3188           0 :             keywords[++paramnum] = "hostaddr";
    3189           0 :             values[paramnum] = hostaddr;
    3190             :         }
    3191         164 :         keywords[++paramnum] = "port";
    3192         164 :         values[paramnum] = port;
    3193         164 :         keywords[++paramnum] = "user";
    3194         164 :         values[paramnum] = user;
    3195             : 
    3196             :         /*
    3197             :          * Position in the array matters when the dbname is a connection
    3198             :          * string, because settings in a connection string override earlier
    3199             :          * array entries only.  Thus, user= in the connection string always
    3200             :          * takes effect, but client_encoding= often will not.
    3201             :          *
    3202             :          * If you change this code, also change the initial-connection code in
    3203             :          * main().  For no good reason, a connection string password= takes
    3204             :          * precedence in main() but not here.
    3205             :          */
    3206         164 :         keywords[++paramnum] = "dbname";
    3207         164 :         values[paramnum] = dbname;
    3208         164 :         keywords[++paramnum] = "password";
    3209         164 :         values[paramnum] = password;
    3210         164 :         keywords[++paramnum] = "fallback_application_name";
    3211         164 :         values[paramnum] = pset.progname;
    3212         164 :         keywords[++paramnum] = "client_encoding";
    3213         164 :         values[paramnum] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
    3214             : 
    3215             :         /* add array terminator */
    3216         164 :         keywords[++paramnum] = NULL;
    3217         164 :         values[paramnum] = NULL;
    3218             : 
    3219         164 :         n_conn = PQconnectdbParams(keywords, values, true);
    3220             : 
    3221         164 :         pg_free(keywords);
    3222         164 :         pg_free(values);
    3223             : 
    3224             :         /* We can immediately discard the password -- no longer needed */
    3225         164 :         if (password)
    3226           0 :             pg_free(password);
    3227             : 
    3228         164 :         if (PQstatus(n_conn) == CONNECTION_OK)
    3229         164 :             break;
    3230             : 
    3231             :         /*
    3232             :          * Connection attempt failed; either retry the connection attempt with
    3233             :          * a new password, or give up.
    3234             :          */
    3235           0 :         if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
    3236             :         {
    3237             :             /*
    3238             :              * Prompt for password using the username we actually connected
    3239             :              * with --- it might've come out of "dbname" rather than "user".
    3240             :              */
    3241           0 :             password = prompt_for_password(PQuser(n_conn));
    3242           0 :             PQfinish(n_conn);
    3243           0 :             continue;
    3244             :         }
    3245             : 
    3246             :         /*
    3247             :          * Failed to connect to the database. In interactive mode, keep the
    3248             :          * previous connection to the DB; in scripting mode, close our
    3249             :          * previous connection as well.
    3250             :          */
    3251           0 :         if (pset.cur_cmd_interactive)
    3252             :         {
    3253           0 :             pg_log_info("%s", PQerrorMessage(n_conn));
    3254             : 
    3255             :             /* pset.db is left unmodified */
    3256           0 :             if (o_conn)
    3257           0 :                 pg_log_info("Previous connection kept");
    3258             :         }
    3259             :         else
    3260             :         {
    3261           0 :             pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
    3262           0 :             if (o_conn)
    3263             :             {
    3264             :                 /*
    3265             :                  * Transition to having no connection.  Keep this bit in sync
    3266             :                  * with CheckConnection().
    3267             :                  */
    3268           0 :                 PQfinish(o_conn);
    3269           0 :                 pset.db = NULL;
    3270           0 :                 ResetCancelConn();
    3271           0 :                 UnsyncVariables();
    3272             :             }
    3273             :         }
    3274             : 
    3275           0 :         PQfinish(n_conn);
    3276           0 :         if (connstr.data)
    3277           0 :             termPQExpBuffer(&connstr);
    3278           0 :         return false;
    3279             :     }
    3280         164 :     if (connstr.data)
    3281         136 :         termPQExpBuffer(&connstr);
    3282             : 
    3283             :     /*
    3284             :      * Replace the old connection with the new one, and update
    3285             :      * connection-dependent variables.  Keep the resynchronization logic in
    3286             :      * sync with CheckConnection().
    3287             :      */
    3288         164 :     PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
    3289         164 :     pset.db = n_conn;
    3290         164 :     SyncVariables();
    3291         164 :     connection_warnings(false); /* Must be after SyncVariables */
    3292             : 
    3293             :     /* Tell the user about the new connection */
    3294         164 :     if (!pset.quiet)
    3295             :     {
    3296          48 :         if (!o_conn ||
    3297          48 :             param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
    3298          24 :             param_is_newly_set(PQport(o_conn), PQport(pset.db)))
    3299           0 :         {
    3300           0 :             char       *host = PQhost(pset.db);
    3301           0 :             char       *hostaddr = PQhostaddr(pset.db);
    3302             : 
    3303             :             /*
    3304             :              * If the host is an absolute path, the connection is via socket
    3305             :              * unless overridden by hostaddr
    3306             :              */
    3307           0 :             if (is_absolute_path(host))
    3308             :             {
    3309           0 :                 if (hostaddr && *hostaddr)
    3310           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
    3311             :                            PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
    3312             :                 else
    3313           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
    3314             :                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
    3315             :             }
    3316             :             else
    3317             :             {
    3318           0 :                 if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
    3319           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
    3320             :                            PQdb(pset.db), PQuser(pset.db), host, hostaddr, PQport(pset.db));
    3321             :                 else
    3322           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
    3323             :                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
    3324             :             }
    3325             :         }
    3326             :         else
    3327          24 :             printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
    3328             :                    PQdb(pset.db), PQuser(pset.db));
    3329             :     }
    3330             : 
    3331         164 :     if (o_conn)
    3332         164 :         PQfinish(o_conn);
    3333         164 :     return true;
    3334             : }
    3335             : 
    3336             : 
    3337             : void
    3338         166 : connection_warnings(bool in_startup)
    3339             : {
    3340         166 :     if (!pset.quiet && !pset.notty)
    3341             :     {
    3342           2 :         int         client_ver = PG_VERSION_NUM;
    3343             :         char        cverbuf[32];
    3344             :         char        sverbuf[32];
    3345             : 
    3346           2 :         if (pset.sversion != client_ver)
    3347             :         {
    3348             :             const char *server_version;
    3349             : 
    3350             :             /* Try to get full text form, might include "devel" etc */
    3351           0 :             server_version = PQparameterStatus(pset.db, "server_version");
    3352             :             /* Otherwise fall back on pset.sversion */
    3353           0 :             if (!server_version)
    3354             :             {
    3355           0 :                 formatPGVersionNumber(pset.sversion, true,
    3356             :                                       sverbuf, sizeof(sverbuf));
    3357           0 :                 server_version = sverbuf;
    3358             :             }
    3359             : 
    3360           0 :             printf(_("%s (%s, server %s)\n"),
    3361             :                    pset.progname, PG_VERSION, server_version);
    3362             :         }
    3363             :         /* For version match, only print psql banner on startup. */
    3364           2 :         else if (in_startup)
    3365           2 :             printf("%s (%s)\n", pset.progname, PG_VERSION);
    3366             : 
    3367           2 :         if (pset.sversion / 100 > client_ver / 100)
    3368           0 :             printf(_("WARNING: %s major version %s, server major version %s.\n"
    3369             :                      "         Some psql features might not work.\n"),
    3370             :                    pset.progname,
    3371             :                    formatPGVersionNumber(client_ver, false,
    3372             :                                          cverbuf, sizeof(cverbuf)),
    3373             :                    formatPGVersionNumber(pset.sversion, false,
    3374             :                                          sverbuf, sizeof(sverbuf)));
    3375             : 
    3376             : #ifdef WIN32
    3377             :         if (in_startup)
    3378             :             checkWin32Codepage();
    3379             : #endif
    3380           2 :         printSSLInfo();
    3381           2 :         printGSSInfo();
    3382             :     }
    3383         166 : }
    3384             : 
    3385             : 
    3386             : /*
    3387             :  * printSSLInfo
    3388             :  *
    3389             :  * Prints information about the current SSL connection, if SSL is in use
    3390             :  */
    3391             : static void
    3392           2 : printSSLInfo(void)
    3393             : {
    3394             :     const char *protocol;
    3395             :     const char *cipher;
    3396             :     const char *bits;
    3397             :     const char *compression;
    3398             : 
    3399           2 :     if (!PQsslInUse(pset.db))
    3400           2 :         return;                 /* no SSL */
    3401             : 
    3402           0 :     protocol = PQsslAttribute(pset.db, "protocol");
    3403           0 :     cipher = PQsslAttribute(pset.db, "cipher");
    3404           0 :     bits = PQsslAttribute(pset.db, "key_bits");
    3405           0 :     compression = PQsslAttribute(pset.db, "compression");
    3406             : 
    3407           0 :     printf(_("SSL connection (protocol: %s, cipher: %s, bits: %s, compression: %s)\n"),
    3408             :            protocol ? protocol : _("unknown"),
    3409             :            cipher ? cipher : _("unknown"),
    3410             :            bits ? bits : _("unknown"),
    3411             :            (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"));
    3412             : }
    3413             : 
    3414             : /*
    3415             :  * printGSSInfo
    3416             :  *
    3417             :  * Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
    3418             :  */
    3419             : static void
    3420           2 : printGSSInfo(void)
    3421             : {
    3422           2 :     if (!PQgssEncInUse(pset.db))
    3423           2 :         return;                 /* no GSSAPI encryption in use */
    3424             : 
    3425           0 :     printf(_("GSSAPI-encrypted connection\n"));
    3426             : }
    3427             : 
    3428             : 
    3429             : /*
    3430             :  * checkWin32Codepage
    3431             :  *
    3432             :  * Prints a warning when win32 console codepage differs from Windows codepage
    3433             :  */
    3434             : #ifdef WIN32
    3435             : static void
    3436             : checkWin32Codepage(void)
    3437             : {
    3438             :     unsigned int wincp,
    3439             :                 concp;
    3440             : 
    3441             :     wincp = GetACP();
    3442             :     concp = GetConsoleCP();
    3443             :     if (wincp != concp)
    3444             :     {
    3445             :         printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
    3446             :                  "         8-bit characters might not work correctly. See psql reference\n"
    3447             :                  "         page \"Notes for Windows users\" for details.\n"),
    3448             :                concp, wincp);
    3449             :     }
    3450             : }
    3451             : #endif
    3452             : 
    3453             : 
    3454             : /*
    3455             :  * SyncVariables
    3456             :  *
    3457             :  * Make psql's internal variables agree with connection state upon
    3458             :  * establishing a new connection.
    3459             :  */
    3460             : void
    3461        4810 : SyncVariables(void)
    3462             : {
    3463             :     char        vbuf[32];
    3464             :     const char *server_version;
    3465             : 
    3466             :     /* get stuff from connection */
    3467        4810 :     pset.encoding = PQclientEncoding(pset.db);
    3468        4810 :     pset.popt.topt.encoding = pset.encoding;
    3469        4810 :     pset.sversion = PQserverVersion(pset.db);
    3470             : 
    3471        4810 :     SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
    3472        4810 :     SetVariable(pset.vars, "USER", PQuser(pset.db));
    3473        4810 :     SetVariable(pset.vars, "HOST", PQhost(pset.db));
    3474        4810 :     SetVariable(pset.vars, "PORT", PQport(pset.db));
    3475        4810 :     SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
    3476             : 
    3477             :     /* this bit should match connection_warnings(): */
    3478             :     /* Try to get full text form of version, might include "devel" etc */
    3479        4810 :     server_version = PQparameterStatus(pset.db, "server_version");
    3480             :     /* Otherwise fall back on pset.sversion */
    3481        4810 :     if (!server_version)
    3482             :     {
    3483           0 :         formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
    3484           0 :         server_version = vbuf;
    3485             :     }
    3486        4810 :     SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
    3487             : 
    3488        4810 :     snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
    3489        4810 :     SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
    3490             : 
    3491             :     /* send stuff to it, too */
    3492        4810 :     PQsetErrorVerbosity(pset.db, pset.verbosity);
    3493        4810 :     PQsetErrorContextVisibility(pset.db, pset.show_context);
    3494        4810 : }
    3495             : 
    3496             : /*
    3497             :  * UnsyncVariables
    3498             :  *
    3499             :  * Clear variables that should be not be set when there is no connection.
    3500             :  */
    3501             : void
    3502           0 : UnsyncVariables(void)
    3503             : {
    3504           0 :     SetVariable(pset.vars, "DBNAME", NULL);
    3505           0 :     SetVariable(pset.vars, "USER", NULL);
    3506           0 :     SetVariable(pset.vars, "HOST", NULL);
    3507           0 :     SetVariable(pset.vars, "PORT", NULL);
    3508           0 :     SetVariable(pset.vars, "ENCODING", NULL);
    3509           0 :     SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
    3510           0 :     SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
    3511           0 : }
    3512             : 
    3513             : 
    3514             : /*
    3515             :  * do_edit -- handler for \e
    3516             :  *
    3517             :  * If you do not specify a filename, the current query buffer will be copied
    3518             :  * into a temporary one.
    3519             :  */
    3520             : static bool
    3521           0 : editFile(const char *fname, int lineno)
    3522             : {
    3523             :     const char *editorName;
    3524           0 :     const char *editor_lineno_arg = NULL;
    3525             :     char       *sys;
    3526             :     int         result;
    3527             : 
    3528             :     Assert(fname != NULL);
    3529             : 
    3530             :     /* Find an editor to use */
    3531           0 :     editorName = getenv("PSQL_EDITOR");
    3532           0 :     if (!editorName)
    3533           0 :         editorName = getenv("EDITOR");
    3534           0 :     if (!editorName)
    3535           0 :         editorName = getenv("VISUAL");
    3536           0 :     if (!editorName)
    3537           0 :         editorName = DEFAULT_EDITOR;
    3538             : 
    3539             :     /* Get line number argument, if we need it. */
    3540           0 :     if (lineno > 0)
    3541             :     {
    3542           0 :         editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
    3543             : #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
    3544           0 :         if (!editor_lineno_arg)
    3545           0 :             editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
    3546             : #endif
    3547           0 :         if (!editor_lineno_arg)
    3548             :         {
    3549           0 :             pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
    3550           0 :             return false;
    3551             :         }
    3552             :     }
    3553             : 
    3554             :     /*
    3555             :      * On Unix the EDITOR value should *not* be quoted, since it might include
    3556             :      * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
    3557             :      * if necessary.  But this policy is not very workable on Windows, due to
    3558             :      * severe brain damage in their command shell plus the fact that standard
    3559             :      * program paths include spaces.
    3560             :      */
    3561             : #ifndef WIN32
    3562           0 :     if (lineno > 0)
    3563           0 :         sys = psprintf("exec %s %s%d '%s'",
    3564             :                        editorName, editor_lineno_arg, lineno, fname);
    3565             :     else
    3566           0 :         sys = psprintf("exec %s '%s'",
    3567             :                        editorName, fname);
    3568             : #else
    3569             :     if (lineno > 0)
    3570             :         sys = psprintf("\"%s\" %s%d \"%s\"",
    3571             :                        editorName, editor_lineno_arg, lineno, fname);
    3572             :     else
    3573             :         sys = psprintf("\"%s\" \"%s\"",
    3574             :                        editorName, fname);
    3575             : #endif
    3576           0 :     result = system(sys);
    3577           0 :     if (result == -1)
    3578           0 :         pg_log_error("could not start editor \"%s\"", editorName);
    3579           0 :     else if (result == 127)
    3580           0 :         pg_log_error("could not start /bin/sh");
    3581           0 :     free(sys);
    3582             : 
    3583           0 :     return result == 0;
    3584             : }
    3585             : 
    3586             : 
    3587             : /* call this one */
    3588             : static bool
    3589           0 : do_edit(const char *filename_arg, PQExpBuffer query_buf,
    3590             :         int lineno, bool *edited)
    3591             : {
    3592             :     char        fnametmp[MAXPGPATH];
    3593           0 :     FILE       *stream = NULL;
    3594             :     const char *fname;
    3595           0 :     bool        error = false;
    3596             :     int         fd;
    3597             : 
    3598             :     struct stat before,
    3599             :                 after;
    3600             : 
    3601           0 :     if (filename_arg)
    3602           0 :         fname = filename_arg;
    3603             :     else
    3604             :     {
    3605             :         /* make a temp file to edit */
    3606             : #ifndef WIN32
    3607           0 :         const char *tmpdir = getenv("TMPDIR");
    3608             : 
    3609           0 :         if (!tmpdir)
    3610           0 :             tmpdir = "/tmp";
    3611             : #else
    3612             :         char        tmpdir[MAXPGPATH];
    3613             :         int         ret;
    3614             : 
    3615             :         ret = GetTempPath(MAXPGPATH, tmpdir);
    3616             :         if (ret == 0 || ret > MAXPGPATH)
    3617             :         {
    3618             :             pg_log_error("could not locate temporary directory: %s",
    3619             :                          !ret ? strerror(errno) : "");
    3620             :             return false;
    3621             :         }
    3622             : 
    3623             :         /*
    3624             :          * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
    3625             :          * current directory to the supplied path unless we use only
    3626             :          * backslashes, so we do that.
    3627             :          */
    3628             : #endif
    3629             : #ifndef WIN32
    3630           0 :         snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
    3631           0 :                  "/", (int) getpid());
    3632             : #else
    3633             :         snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
    3634             :                  "" /* trailing separator already present */ , (int) getpid());
    3635             : #endif
    3636             : 
    3637           0 :         fname = (const char *) fnametmp;
    3638             : 
    3639           0 :         fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
    3640           0 :         if (fd != -1)
    3641           0 :             stream = fdopen(fd, "w");
    3642             : 
    3643           0 :         if (fd == -1 || !stream)
    3644             :         {
    3645           0 :             pg_log_error("could not open temporary file \"%s\": %m", fname);
    3646           0 :             error = true;
    3647             :         }
    3648             :         else
    3649             :         {
    3650           0 :             unsigned int ql = query_buf->len;
    3651             : 
    3652             :             /* force newline-termination of what we send to editor */
    3653           0 :             if (ql > 0 && query_buf->data[ql - 1] != '\n')
    3654             :             {
    3655           0 :                 appendPQExpBufferChar(query_buf, '\n');
    3656           0 :                 ql++;
    3657             :             }
    3658             : 
    3659           0 :             if (fwrite(query_buf->data, 1, ql, stream) != ql)
    3660             :             {
    3661           0 :                 pg_log_error("%s: %m", fname);
    3662             : 
    3663           0 :                 if (fclose(stream) != 0)
    3664           0 :                     pg_log_error("%s: %m", fname);
    3665             : 
    3666           0 :                 if (remove(fname) != 0)
    3667           0 :                     pg_log_error("%s: %m", fname);
    3668             : 
    3669           0 :                 error = true;
    3670             :             }
    3671           0 :             else if (fclose(stream) != 0)
    3672             :             {
    3673           0 :                 pg_log_error("%s: %m", fname);
    3674           0 :                 if (remove(fname) != 0)
    3675           0 :                     pg_log_error("%s: %m", fname);
    3676           0 :                 error = true;
    3677             :             }
    3678             :         }
    3679             :     }
    3680             : 
    3681           0 :     if (!error && stat(fname, &before) != 0)
    3682             :     {
    3683           0 :         pg_log_error("%s: %m", fname);
    3684           0 :         error = true;
    3685             :     }
    3686             : 
    3687             :     /* call editor */
    3688           0 :     if (!error)
    3689           0 :         error = !editFile(fname, lineno);
    3690             : 
    3691           0 :     if (!error && stat(fname, &after) != 0)
    3692             :     {
    3693           0 :         pg_log_error("%s: %m", fname);
    3694           0 :         error = true;
    3695             :     }
    3696             : 
    3697           0 :     if (!error && before.st_mtime != after.st_mtime)
    3698             :     {
    3699           0 :         stream = fopen(fname, PG_BINARY_R);
    3700           0 :         if (!stream)
    3701             :         {
    3702           0 :             pg_log_error("%s: %m", fname);
    3703           0 :             error = true;
    3704             :         }
    3705             :         else
    3706             :         {
    3707             :             /* read file back into query_buf */
    3708             :             char        line[1024];
    3709             : 
    3710           0 :             resetPQExpBuffer(query_buf);
    3711           0 :             while (fgets(line, sizeof(line), stream) != NULL)
    3712           0 :                 appendPQExpBufferStr(query_buf, line);
    3713             : 
    3714           0 :             if (ferror(stream))
    3715             :             {
    3716           0 :                 pg_log_error("%s: %m", fname);
    3717           0 :                 error = true;
    3718             :             }
    3719           0 :             else if (edited)
    3720             :             {
    3721           0 :                 *edited = true;
    3722             :             }
    3723             : 
    3724           0 :             fclose(stream);
    3725             :         }
    3726             :     }
    3727             : 
    3728             :     /* remove temp file */
    3729           0 :     if (!filename_arg)
    3730             :     {
    3731           0 :         if (remove(fname) == -1)
    3732             :         {
    3733           0 :             pg_log_error("%s: %m", fname);
    3734           0 :             error = true;
    3735             :         }
    3736             :     }
    3737             : 
    3738           0 :     return !error;
    3739             : }
    3740             : 
    3741             : 
    3742             : 
    3743             : /*
    3744             :  * process_file
    3745             :  *
    3746             :  * Reads commands from filename and passes them to the main processing loop.
    3747             :  * Handler for \i and \ir, but can be used for other things as well.  Returns
    3748             :  * MainLoop() error code.
    3749             :  *
    3750             :  * If use_relative_path is true and filename is not an absolute path, then open
    3751             :  * the file from where the currently processed file (if any) is located.
    3752             :  */
    3753             : int
    3754        3500 : process_file(char *filename, bool use_relative_path)
    3755             : {
    3756             :     FILE       *fd;
    3757             :     int         result;
    3758             :     char       *oldfilename;
    3759             :     char        relpath[MAXPGPATH];
    3760             : 
    3761        3500 :     if (!filename)
    3762             :     {
    3763        1402 :         fd = stdin;
    3764        1402 :         filename = NULL;
    3765             :     }
    3766        2098 :     else if (strcmp(filename, "-") != 0)
    3767             :     {
    3768           6 :         canonicalize_path(filename);
    3769             : 
    3770             :         /*
    3771             :          * If we were asked to resolve the pathname relative to the location
    3772             :          * of the currently executing script, and there is one, and this is a
    3773             :          * relative pathname, then prepend all but the last pathname component
    3774             :          * of the current script to this pathname.
    3775             :          */
    3776           6 :         if (use_relative_path && pset.inputfile &&
    3777           0 :             !is_absolute_path(filename) && !has_drive_prefix(filename))
    3778             :         {
    3779           0 :             strlcpy(relpath, pset.inputfile, sizeof(relpath));
    3780           0 :             get_parent_directory(relpath);
    3781           0 :             join_path_components(relpath, relpath, filename);
    3782           0 :             canonicalize_path(relpath);
    3783             : 
    3784           0 :             filename = relpath;
    3785             :         }
    3786             : 
    3787           6 :         fd = fopen(filename, PG_BINARY_R);
    3788             : 
    3789           6 :         if (!fd)
    3790             :         {
    3791           0 :             pg_log_error("%s: %m", filename);
    3792           0 :             return EXIT_FAILURE;
    3793             :         }
    3794             :     }
    3795             :     else
    3796             :     {
    3797        2092 :         fd = stdin;
    3798        2092 :         filename = "<stdin>";   /* for future error messages */
    3799             :     }
    3800             : 
    3801        3500 :     oldfilename = pset.inputfile;
    3802        3500 :     pset.inputfile = filename;
    3803             : 
    3804        3500 :     pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
    3805             : 
    3806        3500 :     result = MainLoop(fd);
    3807             : 
    3808        3494 :     if (fd != stdin)
    3809           6 :         fclose(fd);
    3810             : 
    3811        3494 :     pset.inputfile = oldfilename;
    3812             : 
    3813        3494 :     pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
    3814             : 
    3815        3494 :     return result;
    3816             : }
    3817             : 
    3818             : 
    3819             : 
    3820             : static const char *
    3821           4 : _align2string(enum printFormat in)
    3822             : {
    3823           4 :     switch (in)
    3824             :     {
    3825           0 :         case PRINT_NOTHING:
    3826           0 :             return "nothing";
    3827             :             break;
    3828           4 :         case PRINT_ALIGNED:
    3829           4 :             return "aligned";
    3830             :             break;
    3831           0 :         case PRINT_ASCIIDOC:
    3832           0 :             return "asciidoc";
    3833             :             break;
    3834           0 :         case PRINT_CSV:
    3835           0 :             return "csv";
    3836             :             break;
    3837           0 :         case PRINT_HTML:
    3838           0 :             return "html";
    3839             :             break;
    3840           0 :         case PRINT_LATEX:
    3841           0 :             return "latex";
    3842             :             break;
    3843           0 :         case PRINT_LATEX_LONGTABLE:
    3844           0 :             return "latex-longtable";
    3845             :             break;
    3846           0 :         case PRINT_TROFF_MS:
    3847           0 :             return "troff-ms";
    3848             :             break;
    3849           0 :         case PRINT_UNALIGNED:
    3850           0 :             return "unaligned";
    3851             :             break;
    3852           0 :         case PRINT_WRAPPED:
    3853           0 :             return "wrapped";
    3854             :             break;
    3855             :     }
    3856           0 :     return "unknown";
    3857             : }
    3858             : 
    3859             : /*
    3860             :  * Parse entered Unicode linestyle.  If ok, update *linestyle and return
    3861             :  * true, else return false.
    3862             :  */
    3863             : static bool
    3864           0 : set_unicode_line_style(const char *value, size_t vallen,
    3865             :                        unicode_linestyle *linestyle)
    3866             : {
    3867           0 :     if (pg_strncasecmp("single", value, vallen) == 0)
    3868           0 :         *linestyle = UNICODE_LINESTYLE_SINGLE;
    3869           0 :     else if (pg_strncasecmp("double", value, vallen) == 0)
    3870           0 :         *linestyle = UNICODE_LINESTYLE_DOUBLE;
    3871             :     else
    3872           0 :         return false;
    3873           0 :     return true;
    3874             : }
    3875             : 
    3876             : static const char *
    3877          12 : _unicode_linestyle2string(int linestyle)
    3878             : {
    3879          12 :     switch (linestyle)
    3880             :     {
    3881          12 :         case UNICODE_LINESTYLE_SINGLE:
    3882          12 :             return "single";
    3883             :             break;
    3884           0 :         case UNICODE_LINESTYLE_DOUBLE:
    3885           0 :             return "double";
    3886             :             break;
    3887             :     }
    3888           0 :     return "unknown";
    3889             : }
    3890             : 
    3891             : /*
    3892             :  * do_pset
    3893             :  *
    3894             :  * Performs the assignment "param = value", where value could be NULL;
    3895             :  * for some params that has an effect such as inversion, for others
    3896             :  * it does nothing.
    3897             :  *
    3898             :  * Adjusts the state of the formatting options at *popt.  (In practice that
    3899             :  * is always pset.popt, but maybe someday it could be different.)
    3900             :  *
    3901             :  * If successful and quiet is false, then invokes printPsetInfo() to report
    3902             :  * the change.
    3903             :  *
    3904             :  * Returns true if successful, else false (eg for invalid param or value).
    3905             :  */
    3906             : bool
    3907        1226 : do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
    3908             : {
    3909        1226 :     size_t      vallen = 0;
    3910             : 
    3911             :     Assert(param != NULL);
    3912             : 
    3913        1226 :     if (value)
    3914        1164 :         vallen = strlen(value);
    3915             : 
    3916             :     /* set format */
    3917        1226 :     if (strcmp(param, "format") == 0)
    3918             :     {
    3919             :         static const struct fmt
    3920             :         {
    3921             :             const char *name;
    3922             :             enum printFormat number;
    3923             :         }           formats[] =
    3924             :         {
    3925             :             /* remember to update error message below when adding more */
    3926             :             {"aligned", PRINT_ALIGNED},
    3927             :             {"asciidoc", PRINT_ASCIIDOC},
    3928             :             {"csv", PRINT_CSV},
    3929             :             {"html", PRINT_HTML},
    3930             :             {"latex", PRINT_LATEX},
    3931             :             {"troff-ms", PRINT_TROFF_MS},
    3932             :             {"unaligned", PRINT_UNALIGNED},
    3933             :             {"wrapped", PRINT_WRAPPED}
    3934             :         };
    3935             : 
    3936         404 :         if (!value)
    3937             :             ;
    3938             :         else
    3939             :         {
    3940         404 :             int         match_pos = -1;
    3941             : 
    3942        3608 :             for (int i = 0; i < lengthof(formats); i++)
    3943             :             {
    3944        3208 :                 if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
    3945             :                 {
    3946         404 :                     if (match_pos < 0)
    3947         400 :                         match_pos = i;
    3948             :                     else
    3949             :                     {
    3950           4 :                         pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
    3951             :                                      value,
    3952             :                                      formats[match_pos].name, formats[i].name);
    3953           4 :                         return false;
    3954             :                     }
    3955             :                 }
    3956             :             }
    3957         400 :             if (match_pos >= 0)
    3958         396 :                 popt->topt.format = formats[match_pos].number;
    3959           4 :             else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
    3960             :             {
    3961             :                 /*
    3962             :                  * We must treat latex-longtable specially because latex is a
    3963             :                  * prefix of it; if both were in the table above, we'd think
    3964             :                  * "latex" is ambiguous.
    3965             :                  */
    3966           4 :                 popt->topt.format = PRINT_LATEX_LONGTABLE;
    3967             :             }
    3968             :             else
    3969             :             {
    3970           0 :                 pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
    3971           0 :                 return false;
    3972             :             }
    3973             :         }
    3974             :     }
    3975             : 
    3976             :     /* set table line style */
    3977         822 :     else if (strcmp(param, "linestyle") == 0)
    3978             :     {
    3979          20 :         if (!value)
    3980             :             ;
    3981          20 :         else if (pg_strncasecmp("ascii", value, vallen) == 0)
    3982          12 :             popt->topt.line_style = &pg_asciiformat;
    3983           8 :         else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
    3984           8 :             popt->topt.line_style = &pg_asciiformat_old;
    3985           0 :         else if (pg_strncasecmp("unicode", value, vallen) == 0)
    3986           0 :             popt->topt.line_style = &pg_utf8format;
    3987             :         else
    3988             :         {
    3989           0 :             pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
    3990           0 :             return false;
    3991             :         }
    3992             :     }
    3993             : 
    3994             :     /* set unicode border line style */
    3995         802 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    3996             :     {
    3997           0 :         if (!value)
    3998             :             ;
    3999           0 :         else if (set_unicode_line_style(value, vallen,
    4000             :                                         &popt->topt.unicode_border_linestyle))
    4001           0 :             refresh_utf8format(&(popt->topt));
    4002             :         else
    4003             :         {
    4004           0 :             pg_log_error("\\pset: allowed Unicode border line styles are single, double");
    4005           0 :             return false;
    4006             :         }
    4007             :     }
    4008             : 
    4009             :     /* set unicode column line style */
    4010         802 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    4011             :     {
    4012           0 :         if (!value)
    4013             :             ;
    4014           0 :         else if (set_unicode_line_style(value, vallen,
    4015             :                                         &popt->topt.unicode_column_linestyle))
    4016           0 :             refresh_utf8format(&(popt->topt));
    4017             :         else
    4018             :         {
    4019           0 :             pg_log_error("\\pset: allowed Unicode column line styles are single, double");
    4020           0 :             return false;
    4021             :         }
    4022             :     }
    4023             : 
    4024             :     /* set unicode header line style */
    4025         802 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    4026             :     {
    4027           0 :         if (!value)
    4028             :             ;
    4029           0 :         else if (set_unicode_line_style(value, vallen,
    4030             :                                         &popt->topt.unicode_header_linestyle))
    4031           0 :             refresh_utf8format(&(popt->topt));
    4032             :         else
    4033             :         {
    4034           0 :             pg_log_error("\\pset: allowed Unicode header line styles are single, double");
    4035           0 :             return false;
    4036             :         }
    4037             :     }
    4038             : 
    4039             :     /* set border style/width */
    4040         802 :     else if (strcmp(param, "border") == 0)
    4041             :     {
    4042         268 :         if (value)
    4043         268 :             popt->topt.border = atoi(value);
    4044             :     }
    4045             : 
    4046             :     /* set expanded/vertical mode */
    4047         534 :     else if (strcmp(param, "x") == 0 ||
    4048         534 :              strcmp(param, "expanded") == 0 ||
    4049         346 :              strcmp(param, "vertical") == 0)
    4050             :     {
    4051         376 :         if (value && pg_strcasecmp(value, "auto") == 0)
    4052           0 :             popt->topt.expanded = 2;
    4053         188 :         else if (value)
    4054             :         {
    4055             :             bool        on_off;
    4056             : 
    4057         170 :             if (ParseVariableBool(value, NULL, &on_off))
    4058         170 :                 popt->topt.expanded = on_off ? 1 : 0;
    4059             :             else
    4060             :             {
    4061           0 :                 PsqlVarEnumError(param, value, "on, off, auto");
    4062           0 :                 return false;
    4063             :             }
    4064             :         }
    4065             :         else
    4066          18 :             popt->topt.expanded = !popt->topt.expanded;
    4067             :     }
    4068             : 
    4069             :     /* field separator for CSV format */
    4070         346 :     else if (strcmp(param, "csv_fieldsep") == 0)
    4071             :     {
    4072          40 :         if (value)
    4073             :         {
    4074             :             /* CSV separator has to be a one-byte character */
    4075          40 :             if (strlen(value) != 1)
    4076             :             {
    4077          12 :                 pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
    4078          12 :                 return false;
    4079             :             }
    4080          28 :             if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
    4081             :             {
    4082          12 :                 pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
    4083          12 :                 return false;
    4084             :             }
    4085          16 :             popt->topt.csvFieldSep[0] = value[0];
    4086             :         }
    4087             :     }
    4088             : 
    4089             :     /* locale-aware numeric output */
    4090         306 :     else if (strcmp(param, "numericlocale") == 0)
    4091             :     {
    4092           8 :         if (value)
    4093           8 :             return ParseVariableBool(value, param, &popt->topt.numericLocale);
    4094             :         else
    4095           0 :             popt->topt.numericLocale = !popt->topt.numericLocale;
    4096             :     }
    4097             : 
    4098             :     /* null display */
    4099         298 :     else if (strcmp(param, "null") == 0)
    4100             :     {
    4101          42 :         if (value)
    4102             :         {
    4103          38 :             free(popt->nullPrint);
    4104          38 :             popt->nullPrint = pg_strdup(value);
    4105             :         }
    4106             :     }
    4107             : 
    4108             :     /* field separator for unaligned text */
    4109         256 :     else if (strcmp(param, "fieldsep") == 0)
    4110             :     {
    4111           4 :         if (value)
    4112             :         {
    4113           4 :             free(popt->topt.fieldSep.separator);
    4114           4 :             popt->topt.fieldSep.separator = pg_strdup(value);
    4115           4 :             popt->topt.fieldSep.separator_zero = false;
    4116             :         }
    4117             :     }
    4118             : 
    4119         252 :     else if (strcmp(param, "fieldsep_zero") == 0)
    4120             :     {
    4121           0 :         free(popt->topt.fieldSep.separator);
    4122           0 :         popt->topt.fieldSep.separator = NULL;
    4123           0 :         popt->topt.fieldSep.separator_zero = true;
    4124             :     }
    4125             : 
    4126             :     /* record separator for unaligned text */
    4127         252 :     else if (strcmp(param, "recordsep") == 0)
    4128             :     {
    4129           0 :         if (value)
    4130             :         {
    4131           0 :             free(popt->topt.recordSep.separator);
    4132           0 :             popt->topt.recordSep.separator = pg_strdup(value);
    4133           0 :             popt->topt.recordSep.separator_zero = false;
    4134             :         }
    4135             :     }
    4136             : 
    4137         252 :     else if (strcmp(param, "recordsep_zero") == 0)
    4138             :     {
    4139           0 :         free(popt->topt.recordSep.separator);
    4140           0 :         popt->topt.recordSep.separator = NULL;
    4141           0 :         popt->topt.recordSep.separator_zero = true;
    4142             :     }
    4143             : 
    4144             :     /* toggle between full and tuples-only format */
    4145         252 :     else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
    4146             :     {
    4147         184 :         if (value)
    4148         160 :             return ParseVariableBool(value, param, &popt->topt.tuples_only);
    4149             :         else
    4150          24 :             popt->topt.tuples_only = !popt->topt.tuples_only;
    4151             :     }
    4152             : 
    4153             :     /* set title override */
    4154          68 :     else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
    4155             :     {
    4156           4 :         free(popt->title);
    4157           8 :         if (!value)
    4158           0 :             popt->title = NULL;
    4159             :         else
    4160           4 :             popt->title = pg_strdup(value);
    4161             :     }
    4162             : 
    4163             :     /* set HTML table tag options */
    4164          64 :     else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
    4165             :     {
    4166          32 :         free(popt->topt.tableAttr);
    4167          64 :         if (!value)
    4168          16 :             popt->topt.tableAttr = NULL;
    4169             :         else
    4170          16 :             popt->topt.tableAttr = pg_strdup(value);
    4171             :     }
    4172             : 
    4173             :     /* toggle use of pager */
    4174          32 :     else if (strcmp(param, "pager") == 0)
    4175             :     {
    4176           0 :         if (value && pg_strcasecmp(value, "always") == 0)
    4177           0 :             popt->topt.pager = 2;
    4178           0 :         else if (value)
    4179             :         {
    4180             :             bool        on_off;
    4181             : 
    4182           0 :             if (!ParseVariableBool(value, NULL, &on_off))
    4183             :             {
    4184           0 :                 PsqlVarEnumError(param, value, "on, off, always");
    4185           0 :                 return false;
    4186             :             }
    4187           0 :             popt->topt.pager = on_off ? 1 : 0;
    4188             :         }
    4189           0 :         else if (popt->topt.pager == 1)
    4190           0 :             popt->topt.pager = 0;
    4191             :         else
    4192           0 :             popt->topt.pager = 1;
    4193             :     }
    4194             : 
    4195             :     /* set minimum lines for pager use */
    4196          32 :     else if (strcmp(param, "pager_min_lines") == 0)
    4197             :     {
    4198           0 :         if (value)
    4199           0 :             popt->topt.pager_min_lines = atoi(value);
    4200             :     }
    4201             : 
    4202             :     /* disable "(x rows)" footer */
    4203          32 :     else if (strcmp(param, "footer") == 0)
    4204             :     {
    4205           0 :         if (value)
    4206           0 :             return ParseVariableBool(value, param, &popt->topt.default_footer);
    4207             :         else
    4208           0 :             popt->topt.default_footer = !popt->topt.default_footer;
    4209             :     }
    4210             : 
    4211             :     /* set border style/width */
    4212          32 :     else if (strcmp(param, "columns") == 0)
    4213             :     {
    4214          32 :         if (value)
    4215          32 :             popt->topt.columns = atoi(value);
    4216             :     }
    4217             :     else
    4218             :     {
    4219           0 :         pg_log_error("\\pset: unknown option: %s", param);
    4220           0 :         return false;
    4221             :     }
    4222             : 
    4223        1030 :     if (!quiet)
    4224           0 :         printPsetInfo(param, &pset.popt);
    4225             : 
    4226        1030 :     return true;
    4227             : }
    4228             : 
    4229             : /*
    4230             :  * printPsetInfo: print the state of the "param" formatting parameter in popt.
    4231             :  */
    4232             : static bool
    4233           0 : printPsetInfo(const char *param, printQueryOpt *popt)
    4234             : {
    4235             :     Assert(param != NULL);
    4236             : 
    4237             :     /* show border style/width */
    4238           0 :     if (strcmp(param, "border") == 0)
    4239           0 :         printf(_("Border style is %d.\n"), popt->topt.border);
    4240             : 
    4241             :     /* show the target width for the wrapped format */
    4242           0 :     else if (strcmp(param, "columns") == 0)
    4243             :     {
    4244           0 :         if (!popt->topt.columns)
    4245           0 :             printf(_("Target width is unset.\n"));
    4246             :         else
    4247           0 :             printf(_("Target width is %d.\n"), popt->topt.columns);
    4248             :     }
    4249             : 
    4250             :     /* show expanded/vertical mode */
    4251           0 :     else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
    4252             :     {
    4253           0 :         if (popt->topt.expanded == 1)
    4254           0 :             printf(_("Expanded display is on.\n"));
    4255           0 :         else if (popt->topt.expanded == 2)
    4256           0 :             printf(_("Expanded display is used automatically.\n"));
    4257             :         else
    4258           0 :             printf(_("Expanded display is off.\n"));
    4259             :     }
    4260             : 
    4261             :     /* show field separator for CSV format */
    4262           0 :     else if (strcmp(param, "csv_fieldsep") == 0)
    4263             :     {
    4264           0 :         printf(_("Field separator for CSV is \"%s\".\n"),
    4265             :                popt->topt.csvFieldSep);
    4266             :     }
    4267             : 
    4268             :     /* show field separator for unaligned text */
    4269           0 :     else if (strcmp(param, "fieldsep") == 0)
    4270             :     {
    4271           0 :         if (popt->topt.fieldSep.separator_zero)
    4272           0 :             printf(_("Field separator is zero byte.\n"));
    4273             :         else
    4274           0 :             printf(_("Field separator is \"%s\".\n"),
    4275             :                    popt->topt.fieldSep.separator);
    4276             :     }
    4277             : 
    4278           0 :     else if (strcmp(param, "fieldsep_zero") == 0)
    4279             :     {
    4280           0 :         printf(_("Field separator is zero byte.\n"));
    4281             :     }
    4282             : 
    4283             :     /* show disable "(x rows)" footer */
    4284           0 :     else if (strcmp(param, "footer") == 0)
    4285             :     {
    4286           0 :         if (popt->topt.default_footer)
    4287           0 :             printf(_("Default footer is on.\n"));
    4288             :         else
    4289           0 :             printf(_("Default footer is off.\n"));
    4290             :     }
    4291             : 
    4292             :     /* show format */
    4293           0 :     else if (strcmp(param, "format") == 0)
    4294             :     {
    4295           0 :         printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
    4296             :     }
    4297             : 
    4298             :     /* show table line style */
    4299           0 :     else if (strcmp(param, "linestyle") == 0)
    4300             :     {
    4301           0 :         printf(_("Line style is %s.\n"),
    4302             :                get_line_style(&popt->topt)->name);
    4303             :     }
    4304             : 
    4305             :     /* show null display */
    4306           0 :     else if (strcmp(param, "null") == 0)
    4307             :     {
    4308           0 :         printf(_("Null display is \"%s\".\n"),
    4309             :                popt->nullPrint ? popt->nullPrint : "");
    4310             :     }
    4311             : 
    4312             :     /* show locale-aware numeric output */
    4313           0 :     else if (strcmp(param, "numericlocale") == 0)
    4314             :     {
    4315           0 :         if (popt->topt.numericLocale)
    4316           0 :             printf(_("Locale-adjusted numeric output is on.\n"));
    4317             :         else
    4318           0 :             printf(_("Locale-adjusted numeric output is off.\n"));
    4319             :     }
    4320             : 
    4321             :     /* show toggle use of pager */
    4322           0 :     else if (strcmp(param, "pager") == 0)
    4323             :     {
    4324           0 :         if (popt->topt.pager == 1)
    4325           0 :             printf(_("Pager is used for long output.\n"));
    4326           0 :         else if (popt->topt.pager == 2)
    4327           0 :             printf(_("Pager is always used.\n"));
    4328             :         else
    4329           0 :             printf(_("Pager usage is off.\n"));
    4330             :     }
    4331             : 
    4332             :     /* show minimum lines for pager use */
    4333           0 :     else if (strcmp(param, "pager_min_lines") == 0)
    4334             :     {
    4335           0 :         printf(ngettext("Pager won't be used for less than %d line.\n",
    4336             :                         "Pager won't be used for less than %d lines.\n",
    4337             :                         popt->topt.pager_min_lines),
    4338             :                popt->topt.pager_min_lines);
    4339             :     }
    4340             : 
    4341             :     /* show record separator for unaligned text */
    4342           0 :     else if (strcmp(param, "recordsep") == 0)
    4343             :     {
    4344           0 :         if (popt->topt.recordSep.separator_zero)
    4345           0 :             printf(_("Record separator is zero byte.\n"));
    4346           0 :         else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
    4347           0 :             printf(_("Record separator is <newline>.\n"));
    4348             :         else
    4349           0 :             printf(_("Record separator is \"%s\".\n"),
    4350             :                    popt->topt.recordSep.separator);
    4351             :     }
    4352             : 
    4353           0 :     else if (strcmp(param, "recordsep_zero") == 0)
    4354             :     {
    4355           0 :         printf(_("Record separator is zero byte.\n"));
    4356             :     }
    4357             : 
    4358             :     /* show HTML table tag options */
    4359           0 :     else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
    4360             :     {
    4361           0 :         if (popt->topt.tableAttr)
    4362           0 :             printf(_("Table attributes are \"%s\".\n"),
    4363             :                    popt->topt.tableAttr);
    4364             :         else
    4365           0 :             printf(_("Table attributes unset.\n"));
    4366             :     }
    4367             : 
    4368             :     /* show title override */
    4369           0 :     else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
    4370             :     {
    4371           0 :         if (popt->title)
    4372           0 :             printf(_("Title is \"%s\".\n"), popt->title);
    4373             :         else
    4374           0 :             printf(_("Title is unset.\n"));
    4375             :     }
    4376             : 
    4377             :     /* show toggle between full and tuples-only format */
    4378           0 :     else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
    4379             :     {
    4380           0 :         if (popt->topt.tuples_only)
    4381           0 :             printf(_("Tuples only is on.\n"));
    4382             :         else
    4383           0 :             printf(_("Tuples only is off.\n"));
    4384             :     }
    4385             : 
    4386             :     /* Unicode style formatting */
    4387           0 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    4388             :     {
    4389           0 :         printf(_("Unicode border line style is \"%s\".\n"),
    4390             :                _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
    4391             :     }
    4392             : 
    4393           0 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    4394             :     {
    4395           0 :         printf(_("Unicode column line style is \"%s\".\n"),
    4396             :                _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
    4397             :     }
    4398             : 
    4399           0 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    4400             :     {
    4401           0 :         printf(_("Unicode header line style is \"%s\".\n"),
    4402             :                _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
    4403             :     }
    4404             : 
    4405             :     else
    4406             :     {
    4407           0 :         pg_log_error("\\pset: unknown option: %s", param);
    4408           0 :         return false;
    4409             :     }
    4410             : 
    4411           0 :     return true;
    4412             : }
    4413             : 
    4414             : /*
    4415             :  * savePsetInfo: make a malloc'd copy of the data in *popt.
    4416             :  *
    4417             :  * Possibly this should be somewhere else, but it's a bit specific to psql.
    4418             :  */
    4419             : printQueryOpt *
    4420          24 : savePsetInfo(const printQueryOpt *popt)
    4421             : {
    4422             :     printQueryOpt *save;
    4423             : 
    4424          24 :     save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
    4425             : 
    4426             :     /* Flat-copy all the scalar fields, then duplicate sub-structures. */
    4427          24 :     memcpy(save, popt, sizeof(printQueryOpt));
    4428             : 
    4429             :     /* topt.line_style points to const data that need not be duplicated */
    4430          24 :     if (popt->topt.fieldSep.separator)
    4431          24 :         save->topt.fieldSep.separator = pg_strdup(popt->topt.fieldSep.separator);
    4432          24 :     if (popt->topt.recordSep.separator)
    4433          24 :         save->topt.recordSep.separator = pg_strdup(popt->topt.recordSep.separator);
    4434          24 :     if (popt->topt.tableAttr)
    4435           0 :         save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
    4436          24 :     if (popt->nullPrint)
    4437           0 :         save->nullPrint = pg_strdup(popt->nullPrint);
    4438          24 :     if (popt->title)
    4439           0 :         save->title = pg_strdup(popt->title);
    4440             : 
    4441             :     /*
    4442             :      * footers and translate_columns are never set in psql's print settings,
    4443             :      * so we needn't write code to duplicate them.
    4444             :      */
    4445             :     Assert(popt->footers == NULL);
    4446             :     Assert(popt->translate_columns == NULL);
    4447             : 
    4448          24 :     return save;
    4449             : }
    4450             : 
    4451             : /*
    4452             :  * restorePsetInfo: restore *popt from the previously-saved copy *save,
    4453             :  * then free *save.
    4454             :  */
    4455             : void
    4456          24 : restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
    4457             : {
    4458             :     /* Free all the old data we're about to overwrite the pointers to. */
    4459             : 
    4460             :     /* topt.line_style points to const data that need not be duplicated */
    4461          24 :     if (popt->topt.fieldSep.separator)
    4462          24 :         free(popt->topt.fieldSep.separator);
    4463          24 :     if (popt->topt.recordSep.separator)
    4464          24 :         free(popt->topt.recordSep.separator);
    4465          24 :     if (popt->topt.tableAttr)
    4466           0 :         free(popt->topt.tableAttr);
    4467          24 :     if (popt->nullPrint)
    4468           0 :         free(popt->nullPrint);
    4469          24 :     if (popt->title)
    4470           4 :         free(popt->title);
    4471             : 
    4472             :     /*
    4473             :      * footers and translate_columns are never set in psql's print settings,
    4474             :      * so we needn't write code to duplicate them.
    4475             :      */
    4476             :     Assert(popt->footers == NULL);
    4477             :     Assert(popt->translate_columns == NULL);
    4478             : 
    4479             :     /* Now we may flat-copy all the fields, including pointers. */
    4480          24 :     memcpy(popt, save, sizeof(printQueryOpt));
    4481             : 
    4482             :     /* Lastly, free "save" ... but its sub-structures now belong to popt. */
    4483          24 :     free(save);
    4484          24 : }
    4485             : 
    4486             : static const char *
    4487          24 : pset_bool_string(bool val)
    4488             : {
    4489          24 :     return val ? "on" : "off";
    4490             : }
    4491             : 
    4492             : 
    4493             : static char *
    4494          16 : pset_quoted_string(const char *str)
    4495             : {
    4496          16 :     char       *ret = pg_malloc(strlen(str) * 2 + 3);
    4497          16 :     char       *r = ret;
    4498             : 
    4499          16 :     *r++ = '\'';
    4500             : 
    4501          28 :     for (; *str; str++)
    4502             :     {
    4503          12 :         if (*str == '\n')
    4504             :         {
    4505           4 :             *r++ = '\\';
    4506           4 :             *r++ = 'n';
    4507             :         }
    4508           8 :         else if (*str == '\'')
    4509             :         {
    4510           0 :             *r++ = '\\';
    4511           0 :             *r++ = '\'';
    4512             :         }
    4513             :         else
    4514           8 :             *r++ = *str;
    4515             :     }
    4516             : 
    4517          16 :     *r++ = '\'';
    4518          16 :     *r = '\0';
    4519             : 
    4520          16 :     return ret;
    4521             : }
    4522             : 
    4523             : 
    4524             : /*
    4525             :  * Return a malloc'ed string for the \pset value.
    4526             :  *
    4527             :  * Note that for some string parameters, print.c distinguishes between unset
    4528             :  * and empty string, but for others it doesn't.  This function should produce
    4529             :  * output that produces the correct setting when fed back into \pset.
    4530             :  */
    4531             : static char *
    4532          84 : pset_value_string(const char *param, printQueryOpt *popt)
    4533             : {
    4534             :     Assert(param != NULL);
    4535             : 
    4536          84 :     if (strcmp(param, "border") == 0)
    4537           4 :         return psprintf("%d", popt->topt.border);
    4538          80 :     else if (strcmp(param, "columns") == 0)
    4539           4 :         return psprintf("%d", popt->topt.columns);
    4540          76 :     else if (strcmp(param, "csv_fieldsep") == 0)
    4541           4 :         return pset_quoted_string(popt->topt.csvFieldSep);
    4542          72 :     else if (strcmp(param, "expanded") == 0)
    4543           8 :         return pstrdup(popt->topt.expanded == 2
    4544             :                        ? "auto"
    4545           4 :                        : pset_bool_string(popt->topt.expanded));
    4546          68 :     else if (strcmp(param, "fieldsep") == 0)
    4547           4 :         return pset_quoted_string(popt->topt.fieldSep.separator
    4548             :                                   ? popt->topt.fieldSep.separator
    4549             :                                   : "");
    4550          64 :     else if (strcmp(param, "fieldsep_zero") == 0)
    4551           4 :         return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
    4552          60 :     else if (strcmp(param, "footer") == 0)
    4553           4 :         return pstrdup(pset_bool_string(popt->topt.default_footer));
    4554          56 :     else if (strcmp(param, "format") == 0)
    4555           4 :         return psprintf("%s", _align2string(popt->topt.format));
    4556          52 :     else if (strcmp(param, "linestyle") == 0)
    4557           4 :         return psprintf("%s", get_line_style(&popt->topt)->name);
    4558          48 :     else if (strcmp(param, "null") == 0)
    4559           4 :         return pset_quoted_string(popt->nullPrint
    4560             :                                   ? popt->nullPrint
    4561             :                                   : "");
    4562          44 :     else if (strcmp(param, "numericlocale") == 0)
    4563           4 :         return pstrdup(pset_bool_string(popt->topt.numericLocale));
    4564          40 :     else if (strcmp(param, "pager") == 0)
    4565           4 :         return psprintf("%d", popt->topt.pager);
    4566          36 :     else if (strcmp(param, "pager_min_lines") == 0)
    4567           4 :         return psprintf("%d", popt->topt.pager_min_lines);
    4568          32 :     else if (strcmp(param, "recordsep") == 0)
    4569           4 :         return pset_quoted_string(popt->topt.recordSep.separator
    4570             :                                   ? popt->topt.recordSep.separator
    4571             :                                   : "");
    4572          28 :     else if (strcmp(param, "recordsep_zero") == 0)
    4573           4 :         return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
    4574          24 :     else if (strcmp(param, "tableattr") == 0)
    4575           4 :         return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
    4576          20 :     else if (strcmp(param, "title") == 0)
    4577           4 :         return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
    4578          16 :     else if (strcmp(param, "tuples_only") == 0)
    4579           4 :         return pstrdup(pset_bool_string(popt->topt.tuples_only));
    4580          12 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    4581           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
    4582           8 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    4583           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
    4584           4 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    4585           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
    4586             :     else
    4587           0 :         return pstrdup("ERROR");
    4588             : }
    4589             : 
    4590             : 
    4591             : 
    4592             : #ifndef WIN32
    4593             : #define DEFAULT_SHELL "/bin/sh"
    4594             : #else
    4595             : /*
    4596             :  *  CMD.EXE is in different places in different Win32 releases so we
    4597             :  *  have to rely on the path to find it.
    4598             :  */
    4599             : #define DEFAULT_SHELL "cmd.exe"
    4600             : #endif
    4601             : 
    4602             : static bool
    4603           0 : do_shell(const char *command)
    4604             : {
    4605             :     int         result;
    4606             : 
    4607           0 :     if (!command)
    4608             :     {
    4609             :         char       *sys;
    4610             :         const char *shellName;
    4611             : 
    4612           0 :         shellName = getenv("SHELL");
    4613             : #ifdef WIN32
    4614             :         if (shellName == NULL)
    4615             :             shellName = getenv("COMSPEC");
    4616             : #endif
    4617           0 :         if (shellName == NULL)
    4618           0 :             shellName = DEFAULT_SHELL;
    4619             : 
    4620             :         /* See EDITOR handling comment for an explanation */
    4621             : #ifndef WIN32
    4622           0 :         sys = psprintf("exec %s", shellName);
    4623             : #else
    4624             :         sys = psprintf("\"%s\"", shellName);
    4625             : #endif
    4626           0 :         result = system(sys);
    4627           0 :         free(sys);
    4628             :     }
    4629             :     else
    4630           0 :         result = system(command);
    4631             : 
    4632           0 :     if (result == 127 || result == -1)
    4633             :     {
    4634           0 :         pg_log_error("\\!: failed");
    4635           0 :         return false;
    4636             :     }
    4637           0 :     return true;
    4638             : }
    4639             : 
    4640             : /*
    4641             :  * do_watch -- handler for \watch
    4642             :  *
    4643             :  * We break this out of exec_command to avoid having to plaster "volatile"
    4644             :  * onto a bunch of exec_command's variables to silence stupider compilers.
    4645             :  */
    4646             : static bool
    4647           0 : do_watch(PQExpBuffer query_buf, double sleep)
    4648             : {
    4649           0 :     long        sleep_ms = (long) (sleep * 1000);
    4650           0 :     printQueryOpt myopt = pset.popt;
    4651             :     const char *strftime_fmt;
    4652             :     const char *user_title;
    4653             :     char       *title;
    4654             :     int         title_len;
    4655           0 :     int         res = 0;
    4656             : 
    4657           0 :     if (!query_buf || query_buf->len <= 0)
    4658             :     {
    4659           0 :         pg_log_error("\\watch cannot be used with an empty query");
    4660           0 :         return false;
    4661             :     }
    4662             : 
    4663             :     /*
    4664             :      * Choose format for timestamps.  We might eventually make this a \pset
    4665             :      * option.  In the meantime, using a variable for the format suppresses
    4666             :      * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
    4667             :      */
    4668           0 :     strftime_fmt = "%c";
    4669             : 
    4670             :     /*
    4671             :      * Set up rendering options, in particular, disable the pager, because
    4672             :      * nobody wants to be prompted while watching the output of 'watch'.
    4673             :      */
    4674           0 :     myopt.topt.pager = 0;
    4675             : 
    4676             :     /*
    4677             :      * If there's a title in the user configuration, make sure we have room
    4678             :      * for it in the title buffer.  Allow 128 bytes for the timestamp plus 128
    4679             :      * bytes for the rest.
    4680             :      */
    4681           0 :     user_title = myopt.title;
    4682           0 :     title_len = (user_title ? strlen(user_title) : 0) + 256;
    4683           0 :     title = pg_malloc(title_len);
    4684             : 
    4685             :     for (;;)
    4686           0 :     {
    4687             :         time_t      timer;
    4688             :         char        timebuf[128];
    4689             :         long        i;
    4690             : 
    4691             :         /*
    4692             :          * Prepare title for output.  Note that we intentionally include a
    4693             :          * newline at the end of the title; this is somewhat historical but it
    4694             :          * makes for reasonably nicely formatted output in simple cases.
    4695             :          */
    4696           0 :         timer = time(NULL);
    4697           0 :         strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
    4698             : 
    4699           0 :         if (user_title)
    4700           0 :             snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
    4701             :                      user_title, timebuf, sleep);
    4702             :         else
    4703           0 :             snprintf(title, title_len, _("%s (every %gs)\n"),
    4704             :                      timebuf, sleep);
    4705           0 :         myopt.title = title;
    4706             : 
    4707             :         /* Run the query and print out the results */
    4708           0 :         res = PSQLexecWatch(query_buf->data, &myopt);
    4709             : 
    4710             :         /*
    4711             :          * PSQLexecWatch handles the case where we can no longer repeat the
    4712             :          * query, and returns 0 or -1.
    4713             :          */
    4714           0 :         if (res <= 0)
    4715           0 :             break;
    4716             : 
    4717             :         /*
    4718             :          * Set up cancellation of 'watch' via SIGINT.  We redo this each time
    4719             :          * through the loop since it's conceivable something inside
    4720             :          * PSQLexecWatch could change sigint_interrupt_jmp.
    4721             :          */
    4722           0 :         if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
    4723           0 :             break;
    4724             : 
    4725             :         /*
    4726             :          * Enable 'watch' cancellations and wait a while before running the
    4727             :          * query again.  Break the sleep into short intervals (at most 1s)
    4728             :          * since pg_usleep isn't interruptible on some platforms.
    4729             :          */
    4730           0 :         sigint_interrupt_enabled = true;
    4731           0 :         i = sleep_ms;
    4732           0 :         while (i > 0)
    4733             :         {
    4734           0 :             long        s = Min(i, 1000L);
    4735             : 
    4736           0 :             pg_usleep(s * 1000L);
    4737           0 :             if (cancel_pressed)
    4738           0 :                 break;
    4739           0 :             i -= s;
    4740             :         }
    4741           0 :         sigint_interrupt_enabled = false;
    4742             :     }
    4743             : 
    4744           0 :     pg_free(title);
    4745           0 :     return (res >= 0);
    4746             : }
    4747             : 
    4748             : /*
    4749             :  * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
    4750             :  * returns true unless we have ECHO_HIDDEN_NOEXEC.
    4751             :  */
    4752             : static bool
    4753           8 : echo_hidden_command(const char *query)
    4754             : {
    4755           8 :     if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
    4756             :     {
    4757           0 :         printf(_("********* QUERY **********\n"
    4758             :                  "%s\n"
    4759             :                  "**************************\n\n"), query);
    4760           0 :         fflush(stdout);
    4761           0 :         if (pset.logfile)
    4762             :         {
    4763           0 :             fprintf(pset.logfile,
    4764           0 :                     _("********* QUERY **********\n"
    4765             :                       "%s\n"
    4766             :                       "**************************\n\n"), query);
    4767           0 :             fflush(pset.logfile);
    4768             :         }
    4769             : 
    4770           0 :         if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
    4771           0 :             return false;
    4772             :     }
    4773           8 :     return true;
    4774             : }
    4775             : 
    4776             : /*
    4777             :  * Look up the object identified by obj_type and desc.  If successful,
    4778             :  * store its OID in *obj_oid and return true, else return false.
    4779             :  *
    4780             :  * Note that we'll fail if the object doesn't exist OR if there are multiple
    4781             :  * matching candidates OR if there's something syntactically wrong with the
    4782             :  * object description; unfortunately it can be hard to tell the difference.
    4783             :  */
    4784             : static bool
    4785           4 : lookup_object_oid(EditableObjectType obj_type, const char *desc,
    4786             :                   Oid *obj_oid)
    4787             : {
    4788           4 :     bool        result = true;
    4789           4 :     PQExpBuffer query = createPQExpBuffer();
    4790             :     PGresult   *res;
    4791             : 
    4792           4 :     switch (obj_type)
    4793             :     {
    4794           0 :         case EditableFunction:
    4795             : 
    4796             :             /*
    4797             :              * We have a function description, e.g. "x" or "x(int)".  Issue a
    4798             :              * query to retrieve the function's OID using a cast to regproc or
    4799             :              * regprocedure (as appropriate).
    4800             :              */
    4801           0 :             appendPQExpBufferStr(query, "SELECT ");
    4802           0 :             appendStringLiteralConn(query, desc, pset.db);
    4803           0 :             appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
    4804           0 :                               strchr(desc, '(') ? "regprocedure" : "regproc");
    4805           0 :             break;
    4806             : 
    4807           4 :         case EditableView:
    4808             : 
    4809             :             /*
    4810             :              * Convert view name (possibly schema-qualified) to OID.  Note:
    4811             :              * this code doesn't check if the relation is actually a view.
    4812             :              * We'll detect that in get_create_object_cmd().
    4813             :              */
    4814           4 :             appendPQExpBufferStr(query, "SELECT ");
    4815           4 :             appendStringLiteralConn(query, desc, pset.db);
    4816           4 :             appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
    4817           4 :             break;
    4818             :     }
    4819             : 
    4820           4 :     if (!echo_hidden_command(query->data))
    4821             :     {
    4822           0 :         destroyPQExpBuffer(query);
    4823           0 :         return false;
    4824             :     }
    4825           4 :     res = PQexec(pset.db, query->data);
    4826           4 :     if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
    4827           4 :         *obj_oid = atooid(PQgetvalue(res, 0, 0));
    4828             :     else
    4829             :     {
    4830           0 :         minimal_error_message(res);
    4831           0 :         result = false;
    4832             :     }
    4833             : 
    4834           4 :     PQclear(res);
    4835           4 :     destroyPQExpBuffer(query);
    4836             : 
    4837           4 :     return result;
    4838             : }
    4839             : 
    4840             : /*
    4841             :  * Construct a "CREATE OR REPLACE ..." command that describes the specified
    4842             :  * database object.  If successful, the result is stored in buf.
    4843             :  */
    4844             : static bool
    4845           4 : get_create_object_cmd(EditableObjectType obj_type, Oid oid,
    4846             :                       PQExpBuffer buf)
    4847             : {
    4848           4 :     bool        result = true;
    4849           4 :     PQExpBuffer query = createPQExpBuffer();
    4850             :     PGresult   *res;
    4851             : 
    4852           4 :     switch (obj_type)
    4853             :     {
    4854           0 :         case EditableFunction:
    4855           0 :             printfPQExpBuffer(query,
    4856             :                               "SELECT pg_catalog.pg_get_functiondef(%u)",
    4857             :                               oid);
    4858           0 :             break;
    4859             : 
    4860           4 :         case EditableView:
    4861             : 
    4862             :             /*
    4863             :              * pg_get_viewdef() just prints the query, so we must prepend
    4864             :              * CREATE for ourselves.  We must fully qualify the view name to
    4865             :              * ensure the right view gets replaced.  Also, check relation kind
    4866             :              * to be sure it's a view.
    4867             :              *
    4868             :              * Starting with 9.2, views may have reloptions (security_barrier)
    4869             :              * and from 9.4 onwards they may also have WITH [LOCAL|CASCADED]
    4870             :              * CHECK OPTION.  These are not part of the view definition
    4871             :              * returned by pg_get_viewdef() and so need to be retrieved
    4872             :              * separately.  Materialized views (introduced in 9.3) may have
    4873             :              * arbitrary storage parameter reloptions.
    4874             :              */
    4875           4 :             if (pset.sversion >= 90400)
    4876             :             {
    4877           4 :                 printfPQExpBuffer(query,
    4878             :                                   "SELECT nspname, relname, relkind, "
    4879             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4880             :                                   "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
    4881             :                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
    4882             :                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
    4883             :                                   "FROM pg_catalog.pg_class c "
    4884             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4885             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4886             :                                   oid);
    4887             :             }
    4888           0 :             else if (pset.sversion >= 90200)
    4889             :             {
    4890           0 :                 printfPQExpBuffer(query,
    4891             :                                   "SELECT nspname, relname, relkind, "
    4892             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4893             :                                   "c.reloptions AS reloptions, "
    4894             :                                   "NULL AS checkoption "
    4895             :                                   "FROM pg_catalog.pg_class c "
    4896             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4897             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4898             :                                   oid);
    4899             :             }
    4900             :             else
    4901             :             {
    4902           0 :                 printfPQExpBuffer(query,
    4903             :                                   "SELECT nspname, relname, relkind, "
    4904             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4905             :                                   "NULL AS reloptions, "
    4906             :                                   "NULL AS checkoption "
    4907             :                                   "FROM pg_catalog.pg_class c "
    4908             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4909             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4910             :                                   oid);
    4911             :             }
    4912           4 :             break;
    4913             :     }
    4914             : 
    4915           4 :     if (!echo_hidden_command(query->data))
    4916             :     {
    4917           0 :         destroyPQExpBuffer(query);
    4918           0 :         return false;
    4919             :     }
    4920           4 :     res = PQexec(pset.db, query->data);
    4921           4 :     if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
    4922             :     {
    4923           4 :         resetPQExpBuffer(buf);
    4924           4 :         switch (obj_type)
    4925             :         {
    4926           0 :             case EditableFunction:
    4927           0 :                 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
    4928           0 :                 break;
    4929             : 
    4930           4 :             case EditableView:
    4931             :                 {
    4932           4 :                     char       *nspname = PQgetvalue(res, 0, 0);
    4933           4 :                     char       *relname = PQgetvalue(res, 0, 1);
    4934           4 :                     char       *relkind = PQgetvalue(res, 0, 2);
    4935           4 :                     char       *viewdef = PQgetvalue(res, 0, 3);
    4936           4 :                     char       *reloptions = PQgetvalue(res, 0, 4);
    4937           4 :                     char       *checkoption = PQgetvalue(res, 0, 5);
    4938             : 
    4939             :                     /*
    4940             :                      * If the backend ever supports CREATE OR REPLACE
    4941             :                      * MATERIALIZED VIEW, allow that here; but as of today it
    4942             :                      * does not, so editing a matview definition in this way
    4943             :                      * is impossible.
    4944             :                      */
    4945           4 :                     switch (relkind[0])
    4946             :                     {
    4947             : #ifdef NOT_USED
    4948             :                         case RELKIND_MATVIEW:
    4949             :                             appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
    4950             :                             break;
    4951             : #endif
    4952           4 :                         case RELKIND_VIEW:
    4953           4 :                             appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
    4954           4 :                             break;
    4955           0 :                         default:
    4956           0 :                             pg_log_error("\"%s.%s\" is not a view",
    4957             :                                          nspname, relname);
    4958           0 :                             result = false;
    4959           0 :                             break;
    4960             :                     }
    4961           4 :                     appendPQExpBuffer(buf, "%s.", fmtId(nspname));
    4962           4 :                     appendPQExpBufferStr(buf, fmtId(relname));
    4963             : 
    4964             :                     /* reloptions, if not an empty array "{}" */
    4965           4 :                     if (reloptions != NULL && strlen(reloptions) > 2)
    4966             :                     {
    4967           0 :                         appendPQExpBufferStr(buf, "\n WITH (");
    4968           0 :                         if (!appendReloptionsArray(buf, reloptions, "",
    4969             :                                                    pset.encoding,
    4970           0 :                                                    standard_strings()))
    4971             :                         {
    4972           0 :                             pg_log_error("could not parse reloptions array");
    4973           0 :                             result = false;
    4974             :                         }
    4975           0 :                         appendPQExpBufferChar(buf, ')');
    4976             :                     }
    4977             : 
    4978             :                     /* View definition from pg_get_viewdef (a SELECT query) */
    4979           4 :                     appendPQExpBuffer(buf, " AS\n%s", viewdef);
    4980             : 
    4981             :                     /* Get rid of the semicolon that pg_get_viewdef appends */
    4982           4 :                     if (buf->len > 0 && buf->data[buf->len - 1] == ';')
    4983           4 :                         buf->data[--(buf->len)] = '\0';
    4984             : 
    4985             :                     /* WITH [LOCAL|CASCADED] CHECK OPTION */
    4986           4 :                     if (checkoption && checkoption[0] != '\0')
    4987           0 :                         appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
    4988             :                                           checkoption);
    4989             :                 }
    4990           4 :                 break;
    4991             :         }
    4992             :         /* Make sure result ends with a newline */
    4993           8 :         if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
    4994           4 :             appendPQExpBufferChar(buf, '\n');
    4995             :     }
    4996             :     else
    4997             :     {
    4998           0 :         minimal_error_message(res);
    4999           0 :         result = false;
    5000             :     }
    5001             : 
    5002           4 :     PQclear(res);
    5003           4 :     destroyPQExpBuffer(query);
    5004             : 
    5005           4 :     return result;
    5006             : }
    5007             : 
    5008             : /*
    5009             :  * If the given argument of \ef or \ev ends with a line number, delete the line
    5010             :  * number from the argument string and return it as an integer.  (We need
    5011             :  * this kluge because we're too lazy to parse \ef's function or \ev's view
    5012             :  * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
    5013             :  *
    5014             :  * Returns -1 if no line number is present, 0 on error, or a positive value
    5015             :  * on success.
    5016             :  */
    5017             : static int
    5018           0 : strip_lineno_from_objdesc(char *obj)
    5019             : {
    5020             :     char       *c;
    5021             :     int         lineno;
    5022             : 
    5023           0 :     if (!obj || obj[0] == '\0')
    5024           0 :         return -1;
    5025             : 
    5026           0 :     c = obj + strlen(obj) - 1;
    5027             : 
    5028             :     /*
    5029             :      * This business of parsing backwards is dangerous as can be in a
    5030             :      * multibyte environment: there is no reason to believe that we are
    5031             :      * looking at the first byte of a character, nor are we necessarily
    5032             :      * working in a "safe" encoding.  Fortunately the bitpatterns we are
    5033             :      * looking for are unlikely to occur as non-first bytes, but beware of
    5034             :      * trying to expand the set of cases that can be recognized.  We must
    5035             :      * guard the <ctype.h> macros by using isascii() first, too.
    5036             :      */
    5037             : 
    5038             :     /* skip trailing whitespace */
    5039           0 :     while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
    5040           0 :         c--;
    5041             : 
    5042             :     /* must have a digit as last non-space char */
    5043           0 :     if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
    5044           0 :         return -1;
    5045             : 
    5046             :     /* find start of digit string */
    5047           0 :     while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
    5048           0 :         c--;
    5049             : 
    5050             :     /* digits must be separated from object name by space or closing paren */
    5051             :     /* notice also that we are not allowing an empty object name ... */
    5052           0 :     if (c == obj || !isascii((unsigned char) *c) ||
    5053           0 :         !(isspace((unsigned char) *c) || *c == ')'))
    5054           0 :         return -1;
    5055             : 
    5056             :     /* parse digit string */
    5057           0 :     c++;
    5058           0 :     lineno = atoi(c);
    5059           0 :     if (lineno < 1)
    5060             :     {
    5061           0 :         pg_log_error("invalid line number: %s", c);
    5062           0 :         return 0;
    5063             :     }
    5064             : 
    5065             :     /* strip digit string from object name */
    5066           0 :     *c = '\0';
    5067             : 
    5068           0 :     return lineno;
    5069             : }
    5070             : 
    5071             : /*
    5072             :  * Count number of lines in the buffer.
    5073             :  * This is used to test if pager is needed or not.
    5074             :  */
    5075             : static int
    5076           4 : count_lines_in_buf(PQExpBuffer buf)
    5077             : {
    5078           4 :     int         lineno = 0;
    5079           4 :     const char *lines = buf->data;
    5080             : 
    5081          52 :     while (*lines != '\0')
    5082             :     {
    5083          48 :         lineno++;
    5084             :         /* find start of next line */
    5085          48 :         lines = strchr(lines, '\n');
    5086          48 :         if (!lines)
    5087           0 :             break;
    5088          48 :         lines++;
    5089             :     }
    5090             : 
    5091           4 :     return lineno;
    5092             : }
    5093             : 
    5094             : /*
    5095             :  * Write text at *lines to output with line numbers.
    5096             :  *
    5097             :  * If header_keyword isn't NULL, then line 1 should be the first line beginning
    5098             :  * with header_keyword; lines before that are unnumbered.
    5099             :  *
    5100             :  * Caution: this scribbles on *lines.
    5101             :  */
    5102             : static void
    5103           0 : print_with_linenumbers(FILE *output, char *lines,
    5104             :                        const char *header_keyword)
    5105             : {
    5106           0 :     bool        in_header = (header_keyword != NULL);
    5107           0 :     size_t      header_sz = in_header ? strlen(header_keyword) : 0;
    5108           0 :     int         lineno = 0;
    5109             : 
    5110           0 :     while (*lines != '\0')
    5111             :     {
    5112             :         char       *eol;
    5113             : 
    5114           0 :         if (in_header && strncmp(lines, header_keyword, header_sz) == 0)
    5115           0 :             in_header = false;
    5116             : 
    5117             :         /* increment lineno only for body's lines */
    5118           0 :         if (!in_header)
    5119           0 :             lineno++;
    5120             : 
    5121             :         /* find and mark end of current line */
    5122           0 :         eol = strchr(lines, '\n');
    5123           0 :         if (eol != NULL)
    5124           0 :             *eol = '\0';
    5125             : 
    5126             :         /* show current line as appropriate */
    5127           0 :         if (in_header)
    5128           0 :             fprintf(output, "        %s\n", lines);
    5129             :         else
    5130           0 :             fprintf(output, "%-7d %s\n", lineno, lines);
    5131             : 
    5132             :         /* advance to next line, if any */
    5133           0 :         if (eol == NULL)
    5134           0 :             break;
    5135           0 :         lines = ++eol;
    5136             :     }
    5137           0 : }
    5138             : 
    5139             : /*
    5140             :  * Report just the primary error; this is to avoid cluttering the output
    5141             :  * with, for instance, a redisplay of the internally generated query
    5142             :  */
    5143             : static void
    5144           0 : minimal_error_message(PGresult *res)
    5145             : {
    5146             :     PQExpBuffer msg;
    5147             :     const char *fld;
    5148             : 
    5149           0 :     msg = createPQExpBuffer();
    5150             : 
    5151           0 :     fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
    5152           0 :     if (fld)
    5153           0 :         printfPQExpBuffer(msg, "%s:  ", fld);
    5154             :     else
    5155           0 :         printfPQExpBuffer(msg, "ERROR:  ");
    5156           0 :     fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
    5157           0 :     if (fld)
    5158           0 :         appendPQExpBufferStr(msg, fld);
    5159             :     else
    5160           0 :         appendPQExpBufferStr(msg, "(not available)");
    5161           0 :     appendPQExpBufferChar(msg, '\n');
    5162             : 
    5163           0 :     pg_log_error("%s", msg->data);
    5164             : 
    5165           0 :     destroyPQExpBuffer(msg);
    5166           0 : }

Generated by: LCOV version 1.13