~ubuntu-branches/ubuntu/hardy/postgresql-8.4/hardy-backports

« back to all changes in this revision

Viewing changes to src/backend/tcop/postgres.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-03-20 12:00:13 UTC
  • Revision ID: james.westby@ubuntu.com-20090320120013-hogj7egc5mjncc5g
Tags: upstream-8.4~0cvs20090328
ImportĀ upstreamĀ versionĀ 8.4~0cvs20090328

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*-------------------------------------------------------------------------
 
2
 *
 
3
 * postgres.c
 
4
 *        POSTGRES C Backend Interface
 
5
 *
 
6
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
 
7
 * Portions Copyright (c) 1994, Regents of the University of California
 
8
 *
 
9
 *
 
10
 * IDENTIFICATION
 
11
 *        $PostgreSQL$
 
12
 *
 
13
 * NOTES
 
14
 *        this is the "main" module of the postgres backend and
 
15
 *        hence the main module of the "traffic cop".
 
16
 *
 
17
 *-------------------------------------------------------------------------
 
18
 */
 
19
 
 
20
#include "postgres.h"
 
21
 
 
22
#include <time.h>
 
23
#include <unistd.h>
 
24
#include <signal.h>
 
25
#include <fcntl.h>
 
26
#include <sys/socket.h>
 
27
#ifdef HAVE_SYS_SELECT_H
 
28
#include <sys/select.h>
 
29
#endif
 
30
#ifdef HAVE_SYS_RESOURCE_H
 
31
#include <sys/time.h>
 
32
#include <sys/resource.h>
 
33
#endif
 
34
#ifdef HAVE_GETOPT_H
 
35
#include <getopt.h>
 
36
#endif
 
37
 
 
38
#ifndef HAVE_GETRUSAGE
 
39
#include "rusagestub.h"
 
40
#endif
 
41
 
 
42
#include "access/printtup.h"
 
43
#include "access/xact.h"
 
44
#include "catalog/pg_type.h"
 
45
#include "commands/async.h"
 
46
#include "commands/prepare.h"
 
47
#include "libpq/libpq.h"
 
48
#include "libpq/pqformat.h"
 
49
#include "libpq/pqsignal.h"
 
50
#include "miscadmin.h"
 
51
#include "nodes/print.h"
 
52
#include "optimizer/planner.h"
 
53
#include "pgstat.h"
 
54
#include "pg_trace.h"
 
55
#include "parser/analyze.h"
 
56
#include "parser/parser.h"
 
57
#include "postmaster/autovacuum.h"
 
58
#include "rewrite/rewriteHandler.h"
 
59
#include "storage/bufmgr.h"
 
60
#include "storage/ipc.h"
 
61
#include "storage/proc.h"
 
62
#include "storage/sinval.h"
 
63
#include "tcop/fastpath.h"
 
64
#include "tcop/pquery.h"
 
65
#include "tcop/tcopprot.h"
 
66
#include "tcop/utility.h"
 
67
#include "utils/flatfiles.h"
 
68
#include "utils/lsyscache.h"
 
69
#include "utils/memutils.h"
 
70
#include "utils/ps_status.h"
 
71
#include "utils/snapmgr.h"
 
72
#include "mb/pg_wchar.h"
 
73
 
 
74
 
 
75
extern int      optind;
 
76
extern char *optarg;
 
77
 
 
78
/* ----------------
 
79
 *              global variables
 
80
 * ----------------
 
81
 */
 
82
const char *debug_query_string; /* client-supplied query string */
 
83
 
 
84
/* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
 
85
CommandDest whereToSendOutput = DestDebug;
 
86
 
 
87
/* flag for logging end of session */
 
88
bool            Log_disconnections = false;
 
89
 
 
90
int                     log_statement = LOGSTMT_NONE;
 
91
 
 
92
/* GUC variable for maximum stack depth (measured in kilobytes) */
 
93
int                     max_stack_depth = 100;
 
94
 
 
95
/* wait N seconds to allow attach from a debugger */
 
96
int                     PostAuthDelay = 0;
 
97
 
 
98
 
 
99
 
 
100
/* ----------------
 
101
 *              private variables
 
102
 * ----------------
 
103
 */
 
104
 
 
105
/* max_stack_depth converted to bytes for speed of checking */
 
106
static long max_stack_depth_bytes = 100 * 1024L;
 
107
 
 
108
/*
 
109
 * Stack base pointer -- initialized by PostgresMain. This is not static
 
110
 * so that PL/Java can modify it.
 
111
 */
 
112
char       *stack_base_ptr = NULL;
 
113
 
 
114
 
 
115
/*
 
116
 * Flag to mark SIGHUP. Whenever the main loop comes around it
 
117
 * will reread the configuration file. (Better than doing the
 
118
 * reading in the signal handler, ey?)
 
119
 */
 
120
static volatile sig_atomic_t got_SIGHUP = false;
 
121
 
 
122
/*
 
123
 * Flag to keep track of whether we have started a transaction.
 
124
 * For extended query protocol this has to be remembered across messages.
 
125
 */
 
126
static bool xact_started = false;
 
127
 
 
128
/*
 
129
 * Flag to indicate that we are doing the outer loop's read-from-client,
 
130
 * as opposed to any random read from client that might happen within
 
131
 * commands like COPY FROM STDIN.
 
132
 */
 
133
static bool DoingCommandRead = false;
 
134
 
 
135
/*
 
136
 * Flags to implement skip-till-Sync-after-error behavior for messages of
 
137
 * the extended query protocol.
 
138
 */
 
139
static bool doing_extended_query_message = false;
 
140
static bool ignore_till_sync = false;
 
141
 
 
142
/*
 
143
 * If an unnamed prepared statement exists, it's stored here.
 
144
 * We keep it separate from the hashtable kept by commands/prepare.c
 
145
 * in order to reduce overhead for short-lived queries.
 
146
 */
 
147
static CachedPlanSource *unnamed_stmt_psrc = NULL;
 
148
 
 
149
/* workspace for building a new unnamed statement in */
 
150
static MemoryContext unnamed_stmt_context = NULL;
 
151
 
 
152
 
 
153
static bool EchoQuery = false;  /* default don't echo */
 
154
 
 
155
/*
 
156
 * people who want to use EOF should #define DONTUSENEWLINE in
 
157
 * tcop/tcopdebug.h
 
158
 */
 
159
#ifndef TCOP_DONTUSENEWLINE
 
160
static int      UseNewLine = 1;         /* Use newlines query delimiters (the default) */
 
161
#else
 
162
static int      UseNewLine = 0;         /* Use EOF as query delimiters */
 
163
#endif   /* TCOP_DONTUSENEWLINE */
 
164
 
 
165
 
 
166
/* ----------------------------------------------------------------
 
167
 *              decls for routines only used in this file
 
168
 * ----------------------------------------------------------------
 
169
 */
 
170
static int      InteractiveBackend(StringInfo inBuf);
 
171
static int      interactive_getc(void);
 
172
static int      SocketBackend(StringInfo inBuf);
 
173
static int      ReadCommand(StringInfo inBuf);
 
174
static List *pg_rewrite_query(Query *query);
 
175
static bool check_log_statement(List *stmt_list);
 
176
static int      errdetail_execute(List *raw_parsetree_list);
 
177
static int      errdetail_params(ParamListInfo params);
 
178
static void start_xact_command(void);
 
179
static void finish_xact_command(void);
 
180
static bool IsTransactionExitStmt(Node *parsetree);
 
181
static bool IsTransactionExitStmtList(List *parseTrees);
 
182
static bool IsTransactionStmtList(List *parseTrees);
 
183
static void drop_unnamed_stmt(void);
 
184
static void SigHupHandler(SIGNAL_ARGS);
 
185
static void log_disconnections(int code, Datum arg);
 
186
 
 
187
 
 
188
/* ----------------------------------------------------------------
 
189
 *              routines to obtain user input
 
190
 * ----------------------------------------------------------------
 
191
 */
 
192
 
 
193
/* ----------------
 
194
 *      InteractiveBackend() is called for user interactive connections
 
195
 *
 
196
 *      the string entered by the user is placed in its parameter inBuf,
 
197
 *      and we act like a Q message was received.
 
198
 *
 
199
 *      EOF is returned if end-of-file input is seen; time to shut down.
 
200
 * ----------------
 
201
 */
 
202
 
 
203
static int
 
204
InteractiveBackend(StringInfo inBuf)
 
205
{
 
206
        int                     c;                              /* character read from getc() */
 
207
        bool            end = false;    /* end-of-input flag */
 
208
        bool            backslashSeen = false;  /* have we seen a \ ? */
 
209
 
 
210
        /*
 
211
         * display a prompt and obtain input from the user
 
212
         */
 
213
        printf("backend> ");
 
214
        fflush(stdout);
 
215
 
 
216
        resetStringInfo(inBuf);
 
217
 
 
218
        if (UseNewLine)
 
219
        {
 
220
                /*
 
221
                 * if we are using \n as a delimiter, then read characters until the
 
222
                 * \n.
 
223
                 */
 
224
                while ((c = interactive_getc()) != EOF)
 
225
                {
 
226
                        if (c == '\n')
 
227
                        {
 
228
                                if (backslashSeen)
 
229
                                {
 
230
                                        /* discard backslash from inBuf */
 
231
                                        inBuf->data[--inBuf->len] = '\0';
 
232
                                        backslashSeen = false;
 
233
                                        continue;
 
234
                                }
 
235
                                else
 
236
                                {
 
237
                                        /* keep the newline character */
 
238
                                        appendStringInfoChar(inBuf, '\n');
 
239
                                        break;
 
240
                                }
 
241
                        }
 
242
                        else if (c == '\\')
 
243
                                backslashSeen = true;
 
244
                        else
 
245
                                backslashSeen = false;
 
246
 
 
247
                        appendStringInfoChar(inBuf, (char) c);
 
248
                }
 
249
 
 
250
                if (c == EOF)
 
251
                        end = true;
 
252
        }
 
253
        else
 
254
        {
 
255
                /*
 
256
                 * otherwise read characters until EOF.
 
257
                 */
 
258
                while ((c = interactive_getc()) != EOF)
 
259
                        appendStringInfoChar(inBuf, (char) c);
 
260
 
 
261
                /* No input before EOF signal means time to quit. */
 
262
                if (inBuf->len == 0)
 
263
                        end = true;
 
264
        }
 
265
 
 
266
        if (end)
 
267
                return EOF;
 
268
 
 
269
        /*
 
270
         * otherwise we have a user query so process it.
 
271
         */
 
272
 
 
273
        /* Add '\0' to make it look the same as message case. */
 
274
        appendStringInfoChar(inBuf, (char) '\0');
 
275
 
 
276
        /*
 
277
         * if the query echo flag was given, print the query..
 
278
         */
 
279
        if (EchoQuery)
 
280
                printf("statement: %s\n", inBuf->data);
 
281
        fflush(stdout);
 
282
 
 
283
        return 'Q';
 
284
}
 
285
 
 
286
/*
 
287
 * interactive_getc -- collect one character from stdin
 
288
 *
 
289
 * Even though we are not reading from a "client" process, we still want to
 
290
 * respond to signals, particularly SIGTERM/SIGQUIT.  Hence we must use
 
291
 * prepare_for_client_read and client_read_ended.
 
292
 */
 
293
static int
 
294
interactive_getc(void)
 
295
{
 
296
        int                     c;
 
297
 
 
298
        prepare_for_client_read();
 
299
        c = getc(stdin);
 
300
        client_read_ended();
 
301
        return c;
 
302
}
 
303
 
 
304
/* ----------------
 
305
 *      SocketBackend()         Is called for frontend-backend connections
 
306
 *
 
307
 *      Returns the message type code, and loads message body data into inBuf.
 
308
 *
 
309
 *      EOF is returned if the connection is lost.
 
310
 * ----------------
 
311
 */
 
312
static int
 
313
SocketBackend(StringInfo inBuf)
 
314
{
 
315
        int                     qtype;
 
316
 
 
317
        /*
 
318
         * Get message type code from the frontend.
 
319
         */
 
320
        qtype = pq_getbyte();
 
321
 
 
322
        if (qtype == EOF)                       /* frontend disconnected */
 
323
        {
 
324
                ereport(COMMERROR,
 
325
                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
326
                                 errmsg("unexpected EOF on client connection")));
 
327
                return qtype;
 
328
        }
 
329
 
 
330
        /*
 
331
         * Validate message type code before trying to read body; if we have lost
 
332
         * sync, better to say "command unknown" than to run out of memory because
 
333
         * we used garbage as a length word.
 
334
         *
 
335
         * This also gives us a place to set the doing_extended_query_message flag
 
336
         * as soon as possible.
 
337
         */
 
338
        switch (qtype)
 
339
        {
 
340
                case 'Q':                               /* simple query */
 
341
                        doing_extended_query_message = false;
 
342
                        if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
 
343
                        {
 
344
                                /* old style without length word; convert */
 
345
                                if (pq_getstring(inBuf))
 
346
                                {
 
347
                                        ereport(COMMERROR,
 
348
                                                        (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
349
                                                         errmsg("unexpected EOF on client connection")));
 
350
                                        return EOF;
 
351
                                }
 
352
                        }
 
353
                        break;
 
354
 
 
355
                case 'F':                               /* fastpath function call */
 
356
                        /* we let fastpath.c cope with old-style input of this */
 
357
                        doing_extended_query_message = false;
 
358
                        break;
 
359
 
 
360
                case 'X':                               /* terminate */
 
361
                        doing_extended_query_message = false;
 
362
                        ignore_till_sync = false;
 
363
                        break;
 
364
 
 
365
                case 'B':                               /* bind */
 
366
                case 'C':                               /* close */
 
367
                case 'D':                               /* describe */
 
368
                case 'E':                               /* execute */
 
369
                case 'H':                               /* flush */
 
370
                case 'P':                               /* parse */
 
371
                        doing_extended_query_message = true;
 
372
                        /* these are only legal in protocol 3 */
 
373
                        if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
 
374
                                ereport(FATAL,
 
375
                                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
376
                                                 errmsg("invalid frontend message type %d", qtype)));
 
377
                        break;
 
378
 
 
379
                case 'S':                               /* sync */
 
380
                        /* stop any active skip-till-Sync */
 
381
                        ignore_till_sync = false;
 
382
                        /* mark not-extended, so that a new error doesn't begin skip */
 
383
                        doing_extended_query_message = false;
 
384
                        /* only legal in protocol 3 */
 
385
                        if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
 
386
                                ereport(FATAL,
 
387
                                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
388
                                                 errmsg("invalid frontend message type %d", qtype)));
 
389
                        break;
 
390
 
 
391
                case 'd':                               /* copy data */
 
392
                case 'c':                               /* copy done */
 
393
                case 'f':                               /* copy fail */
 
394
                        doing_extended_query_message = false;
 
395
                        /* these are only legal in protocol 3 */
 
396
                        if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
 
397
                                ereport(FATAL,
 
398
                                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
399
                                                 errmsg("invalid frontend message type %d", qtype)));
 
400
                        break;
 
401
 
 
402
                default:
 
403
 
 
404
                        /*
 
405
                         * Otherwise we got garbage from the frontend.  We treat this as
 
406
                         * fatal because we have probably lost message boundary sync, and
 
407
                         * there's no good way to recover.
 
408
                         */
 
409
                        ereport(FATAL,
 
410
                                        (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
411
                                         errmsg("invalid frontend message type %d", qtype)));
 
412
                        break;
 
413
        }
 
414
 
 
415
        /*
 
416
         * In protocol version 3, all frontend messages have a length word next
 
417
         * after the type code; we can read the message contents independently of
 
418
         * the type.
 
419
         */
 
420
        if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
 
421
        {
 
422
                if (pq_getmessage(inBuf, 0))
 
423
                        return EOF;                     /* suitable message already logged */
 
424
        }
 
425
 
 
426
        return qtype;
 
427
}
 
428
 
 
429
/* ----------------
 
430
 *              ReadCommand reads a command from either the frontend or
 
431
 *              standard input, places it in inBuf, and returns the
 
432
 *              message type code (first byte of the message).
 
433
 *              EOF is returned if end of file.
 
434
 * ----------------
 
435
 */
 
436
static int
 
437
ReadCommand(StringInfo inBuf)
 
438
{
 
439
        int                     result;
 
440
 
 
441
        if (whereToSendOutput == DestRemote)
 
442
                result = SocketBackend(inBuf);
 
443
        else
 
444
                result = InteractiveBackend(inBuf);
 
445
        return result;
 
446
}
 
447
 
 
448
/*
 
449
 * prepare_for_client_read -- set up to possibly block on client input
 
450
 *
 
451
 * This must be called immediately before any low-level read from the
 
452
 * client connection.  It is necessary to do it at a sufficiently low level
 
453
 * that there won't be any other operations except the read kernel call
 
454
 * itself between this call and the subsequent client_read_ended() call.
 
455
 * In particular there mustn't be use of malloc() or other potentially
 
456
 * non-reentrant libc functions.  This restriction makes it safe for us
 
457
 * to allow interrupt service routines to execute nontrivial code while
 
458
 * we are waiting for input.
 
459
 */
 
460
void
 
461
prepare_for_client_read(void)
 
462
{
 
463
        if (DoingCommandRead)
 
464
        {
 
465
                /* Enable immediate processing of asynchronous signals */
 
466
                EnableNotifyInterrupt();
 
467
                EnableCatchupInterrupt();
 
468
 
 
469
                /* Allow "die" interrupt to be processed while waiting */
 
470
                ImmediateInterruptOK = true;
 
471
 
 
472
                /* And don't forget to detect one that already arrived */
 
473
                QueryCancelPending = false;
 
474
                CHECK_FOR_INTERRUPTS();
 
475
        }
 
476
}
 
477
 
 
478
/*
 
479
 * client_read_ended -- get out of the client-input state
 
480
 */
 
481
void
 
482
client_read_ended(void)
 
483
{
 
484
        if (DoingCommandRead)
 
485
        {
 
486
                ImmediateInterruptOK = false;
 
487
                QueryCancelPending = false;             /* forget any CANCEL signal */
 
488
 
 
489
                DisableNotifyInterrupt();
 
490
                DisableCatchupInterrupt();
 
491
        }
 
492
}
 
493
 
 
494
 
 
495
/*
 
496
 * Parse a query string and pass it through the rewriter.
 
497
 *
 
498
 * A list of Query nodes is returned, since the string might contain
 
499
 * multiple queries and/or the rewriter might expand one query to several.
 
500
 *
 
501
 * NOTE: this routine is no longer used for processing interactive queries,
 
502
 * but it is still needed for parsing of SQL function bodies.
 
503
 */
 
504
List *
 
505
pg_parse_and_rewrite(const char *query_string,  /* string to execute */
 
506
                                         Oid *paramTypes,       /* parameter types */
 
507
                                         int numParams)         /* number of parameters */
 
508
{
 
509
        List       *raw_parsetree_list;
 
510
        List       *querytree_list;
 
511
        ListCell   *list_item;
 
512
 
 
513
        /*
 
514
         * (1) parse the request string into a list of raw parse trees.
 
515
         */
 
516
        raw_parsetree_list = pg_parse_query(query_string);
 
517
 
 
518
        /*
 
519
         * (2) Do parse analysis and rule rewrite.
 
520
         */
 
521
        querytree_list = NIL;
 
522
        foreach(list_item, raw_parsetree_list)
 
523
        {
 
524
                Node       *parsetree = (Node *) lfirst(list_item);
 
525
 
 
526
                querytree_list = list_concat(querytree_list,
 
527
                                                                         pg_analyze_and_rewrite(parsetree,
 
528
                                                                                                                        query_string,
 
529
                                                                                                                        paramTypes,
 
530
                                                                                                                        numParams));
 
531
        }
 
532
 
 
533
        return querytree_list;
 
534
}
 
535
 
 
536
/*
 
537
 * Do raw parsing (only).
 
538
 *
 
539
 * A list of parsetrees is returned, since there might be multiple
 
540
 * commands in the given string.
 
541
 *
 
542
 * NOTE: for interactive queries, it is important to keep this routine
 
543
 * separate from the analysis & rewrite stages.  Analysis and rewriting
 
544
 * cannot be done in an aborted transaction, since they require access to
 
545
 * database tables.  So, we rely on the raw parser to determine whether
 
546
 * we've seen a COMMIT or ABORT command; when we are in abort state, other
 
547
 * commands are not processed any further than the raw parse stage.
 
548
 */
 
549
List *
 
550
pg_parse_query(const char *query_string)
 
551
{
 
552
        List       *raw_parsetree_list;
 
553
 
 
554
        TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
 
555
 
 
556
        if (log_parser_stats)
 
557
                ResetUsage();
 
558
 
 
559
        raw_parsetree_list = raw_parser(query_string);
 
560
 
 
561
        if (log_parser_stats)
 
562
                ShowUsage("PARSER STATISTICS");
 
563
 
 
564
#ifdef COPY_PARSE_PLAN_TREES
 
565
        /* Optional debugging check: pass raw parsetrees through copyObject() */
 
566
        {
 
567
                List       *new_list = (List *) copyObject(raw_parsetree_list);
 
568
 
 
569
                /* This checks both copyObject() and the equal() routines... */
 
570
                if (!equal(new_list, raw_parsetree_list))
 
571
                        elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
 
572
                else
 
573
                        raw_parsetree_list = new_list;
 
574
        }
 
575
#endif
 
576
 
 
577
        TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
 
578
 
 
579
        return raw_parsetree_list;
 
580
}
 
581
 
 
582
/*
 
583
 * Given a raw parsetree (gram.y output), and optionally information about
 
584
 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
 
585
 *
 
586
 * A list of Query nodes is returned, since either the analyzer or the
 
587
 * rewriter might expand one query to several.
 
588
 *
 
589
 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
 
590
 */
 
591
List *
 
592
pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
 
593
                                           Oid *paramTypes, int numParams)
 
594
{
 
595
        Query      *query;
 
596
        List       *querytree_list;
 
597
 
 
598
        TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
 
599
 
 
600
        /*
 
601
         * (1) Perform parse analysis.
 
602
         */
 
603
        if (log_parser_stats)
 
604
                ResetUsage();
 
605
 
 
606
        query = parse_analyze(parsetree, query_string, paramTypes, numParams);
 
607
 
 
608
        if (log_parser_stats)
 
609
                ShowUsage("PARSE ANALYSIS STATISTICS");
 
610
 
 
611
        /*
 
612
         * (2) Rewrite the queries, as necessary
 
613
         */
 
614
        querytree_list = pg_rewrite_query(query);
 
615
 
 
616
        TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
 
617
 
 
618
        return querytree_list;
 
619
}
 
620
 
 
621
/*
 
622
 * Perform rewriting of a query produced by parse analysis.
 
623
 *
 
624
 * Note: query must just have come from the parser, because we do not do
 
625
 * AcquireRewriteLocks() on it.
 
626
 */
 
627
static List *
 
628
pg_rewrite_query(Query *query)
 
629
{
 
630
        List       *querytree_list;
 
631
 
 
632
        if (Debug_print_parse)
 
633
                elog_node_display(LOG, "parse tree", query,
 
634
                                                  Debug_pretty_print);
 
635
 
 
636
        if (log_parser_stats)
 
637
                ResetUsage();
 
638
 
 
639
        if (query->commandType == CMD_UTILITY)
 
640
        {
 
641
                /* don't rewrite utilities, just dump 'em into result list */
 
642
                querytree_list = list_make1(query);
 
643
        }
 
644
        else
 
645
        {
 
646
                /* rewrite regular queries */
 
647
                querytree_list = QueryRewrite(query);
 
648
        }
 
649
 
 
650
        if (log_parser_stats)
 
651
                ShowUsage("REWRITER STATISTICS");
 
652
 
 
653
#ifdef COPY_PARSE_PLAN_TREES
 
654
        /* Optional debugging check: pass querytree output through copyObject() */
 
655
        {
 
656
                List       *new_list;
 
657
 
 
658
                new_list = (List *) copyObject(querytree_list);
 
659
                /* This checks both copyObject() and the equal() routines... */
 
660
                if (!equal(new_list, querytree_list))
 
661
                        elog(WARNING, "copyObject() failed to produce equal parse tree");
 
662
                else
 
663
                        querytree_list = new_list;
 
664
        }
 
665
#endif
 
666
 
 
667
        if (Debug_print_rewritten)
 
668
                elog_node_display(LOG, "rewritten parse tree", querytree_list,
 
669
                                                  Debug_pretty_print);
 
670
 
 
671
        return querytree_list;
 
672
}
 
673
 
 
674
 
 
675
/*
 
676
 * Generate a plan for a single already-rewritten query.
 
677
 * This is a thin wrapper around planner() and takes the same parameters.
 
678
 */
 
679
PlannedStmt *
 
680
pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
 
681
{
 
682
        PlannedStmt *plan;
 
683
 
 
684
        /* Utility commands have no plans. */
 
685
        if (querytree->commandType == CMD_UTILITY)
 
686
                return NULL;
 
687
 
 
688
        /* Planner must have a snapshot in case it calls user-defined functions. */
 
689
        Assert(ActiveSnapshotSet());
 
690
 
 
691
        TRACE_POSTGRESQL_QUERY_PLAN_START();
 
692
 
 
693
        if (log_planner_stats)
 
694
                ResetUsage();
 
695
 
 
696
        /* call the optimizer */
 
697
        plan = planner(querytree, cursorOptions, boundParams);
 
698
 
 
699
        if (log_planner_stats)
 
700
                ShowUsage("PLANNER STATISTICS");
 
701
 
 
702
#ifdef COPY_PARSE_PLAN_TREES
 
703
        /* Optional debugging check: pass plan output through copyObject() */
 
704
        {
 
705
                PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
 
706
 
 
707
                /*
 
708
                 * equal() currently does not have routines to compare Plan nodes, so
 
709
                 * don't try to test equality here.  Perhaps fix someday?
 
710
                 */
 
711
#ifdef NOT_USED
 
712
                /* This checks both copyObject() and the equal() routines... */
 
713
                if (!equal(new_plan, plan))
 
714
                        elog(WARNING, "copyObject() failed to produce an equal plan tree");
 
715
                else
 
716
#endif
 
717
                        plan = new_plan;
 
718
        }
 
719
#endif
 
720
 
 
721
        /*
 
722
         * Print plan if debugging.
 
723
         */
 
724
        if (Debug_print_plan)
 
725
                elog_node_display(LOG, "plan", plan, Debug_pretty_print);
 
726
 
 
727
        TRACE_POSTGRESQL_QUERY_PLAN_DONE();
 
728
 
 
729
        return plan;
 
730
}
 
731
 
 
732
/*
 
733
 * Generate plans for a list of already-rewritten queries.
 
734
 *
 
735
 * Normal optimizable statements generate PlannedStmt entries in the result
 
736
 * list.  Utility statements are simply represented by their statement nodes.
 
737
 */
 
738
List *
 
739
pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
 
740
{
 
741
        List       *stmt_list = NIL;
 
742
        ListCell   *query_list;
 
743
 
 
744
        foreach(query_list, querytrees)
 
745
        {
 
746
                Query      *query = (Query *) lfirst(query_list);
 
747
                Node       *stmt;
 
748
 
 
749
                if (query->commandType == CMD_UTILITY)
 
750
                {
 
751
                        /* Utility commands have no plans. */
 
752
                        stmt = query->utilityStmt;
 
753
                }
 
754
                else
 
755
                {
 
756
                        stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
 
757
                }
 
758
 
 
759
                stmt_list = lappend(stmt_list, stmt);
 
760
        }
 
761
 
 
762
        return stmt_list;
 
763
}
 
764
 
 
765
 
 
766
/*
 
767
 * exec_simple_query
 
768
 *
 
769
 * Execute a "simple Query" protocol message.
 
770
 */
 
771
static void
 
772
exec_simple_query(const char *query_string)
 
773
{
 
774
        CommandDest dest = whereToSendOutput;
 
775
        MemoryContext oldcontext;
 
776
        List       *parsetree_list;
 
777
        ListCell   *parsetree_item;
 
778
        bool            save_log_statement_stats = log_statement_stats;
 
779
        bool            was_logged = false;
 
780
        bool            isTopLevel;
 
781
        char            msec_str[32];
 
782
 
 
783
 
 
784
        /*
 
785
         * Report query to various monitoring facilities.
 
786
         */
 
787
        debug_query_string = query_string;
 
788
 
 
789
        pgstat_report_activity(query_string);
 
790
 
 
791
        TRACE_POSTGRESQL_QUERY_START(query_string);
 
792
 
 
793
        /*
 
794
         * We use save_log_statement_stats so ShowUsage doesn't report incorrect
 
795
         * results because ResetUsage wasn't called.
 
796
         */
 
797
        if (save_log_statement_stats)
 
798
                ResetUsage();
 
799
 
 
800
        /*
 
801
         * Start up a transaction command.      All queries generated by the
 
802
         * query_string will be in this same command block, *unless* we find a
 
803
         * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
 
804
         * one of those, else bad things will happen in xact.c. (Note that this
 
805
         * will normally change current memory context.)
 
806
         */
 
807
        start_xact_command();
 
808
 
 
809
        /*
 
810
         * Zap any pre-existing unnamed statement.      (While not strictly necessary,
 
811
         * it seems best to define simple-Query mode as if it used the unnamed
 
812
         * statement and portal; this ensures we recover any storage used by prior
 
813
         * unnamed operations.)
 
814
         */
 
815
        drop_unnamed_stmt();
 
816
 
 
817
        /*
 
818
         * Switch to appropriate context for constructing parsetrees.
 
819
         */
 
820
        oldcontext = MemoryContextSwitchTo(MessageContext);
 
821
 
 
822
        /*
 
823
         * Do basic parsing of the query or queries (this should be safe even if
 
824
         * we are in aborted transaction state!)
 
825
         */
 
826
        parsetree_list = pg_parse_query(query_string);
 
827
 
 
828
        /* Log immediately if dictated by log_statement */
 
829
        if (check_log_statement(parsetree_list))
 
830
        {
 
831
                ereport(LOG,
 
832
                                (errmsg("statement: %s", query_string),
 
833
                                 errhidestmt(true),
 
834
                                 errdetail_execute(parsetree_list)));
 
835
                was_logged = true;
 
836
        }
 
837
 
 
838
        /*
 
839
         * Switch back to transaction context to enter the loop.
 
840
         */
 
841
        MemoryContextSwitchTo(oldcontext);
 
842
 
 
843
        /*
 
844
         * We'll tell PortalRun it's a top-level command iff there's exactly one
 
845
         * raw parsetree.  If more than one, it's effectively a transaction block
 
846
         * and we want PreventTransactionChain to reject unsafe commands. (Note:
 
847
         * we're assuming that query rewrite cannot add commands that are
 
848
         * significant to PreventTransactionChain.)
 
849
         */
 
850
        isTopLevel = (list_length(parsetree_list) == 1);
 
851
 
 
852
        /*
 
853
         * Run through the raw parsetree(s) and process each one.
 
854
         */
 
855
        foreach(parsetree_item, parsetree_list)
 
856
        {
 
857
                Node       *parsetree = (Node *) lfirst(parsetree_item);
 
858
                bool            snapshot_set = false;
 
859
                const char *commandTag;
 
860
                char            completionTag[COMPLETION_TAG_BUFSIZE];
 
861
                List       *querytree_list,
 
862
                                   *plantree_list;
 
863
                Portal          portal;
 
864
                DestReceiver *receiver;
 
865
                int16           format;
 
866
 
 
867
                /*
 
868
                 * Get the command name for use in status display (it also becomes the
 
869
                 * default completion tag, down inside PortalRun).      Set ps_status and
 
870
                 * do any special start-of-SQL-command processing needed by the
 
871
                 * destination.
 
872
                 */
 
873
                commandTag = CreateCommandTag(parsetree);
 
874
 
 
875
                set_ps_display(commandTag, false);
 
876
 
 
877
                BeginCommand(commandTag, dest);
 
878
 
 
879
                /*
 
880
                 * If we are in an aborted transaction, reject all commands except
 
881
                 * COMMIT/ABORT.  It is important that this test occur before we try
 
882
                 * to do parse analysis, rewrite, or planning, since all those phases
 
883
                 * try to do database accesses, which may fail in abort state. (It
 
884
                 * might be safe to allow some additional utility commands in this
 
885
                 * state, but not many...)
 
886
                 */
 
887
                if (IsAbortedTransactionBlockState() &&
 
888
                        !IsTransactionExitStmt(parsetree))
 
889
                        ereport(ERROR,
 
890
                                        (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
891
                                         errmsg("current transaction is aborted, "
 
892
                                                "commands ignored until end of transaction block")));
 
893
 
 
894
                /* Make sure we are in a transaction command */
 
895
                start_xact_command();
 
896
 
 
897
                /* If we got a cancel signal in parsing or prior command, quit */
 
898
                CHECK_FOR_INTERRUPTS();
 
899
 
 
900
                /*
 
901
                 * Set up a snapshot if parse analysis/planning will need one.
 
902
                 */
 
903
                if (analyze_requires_snapshot(parsetree))
 
904
                {
 
905
                        PushActiveSnapshot(GetTransactionSnapshot());
 
906
                        snapshot_set = true;
 
907
                }
 
908
 
 
909
                /*
 
910
                 * OK to analyze, rewrite, and plan this query.
 
911
                 *
 
912
                 * Switch to appropriate context for constructing querytrees (again,
 
913
                 * these must outlive the execution context).
 
914
                 */
 
915
                oldcontext = MemoryContextSwitchTo(MessageContext);
 
916
 
 
917
                querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
 
918
                                                                                                NULL, 0);
 
919
 
 
920
                plantree_list = pg_plan_queries(querytree_list, 0, NULL);
 
921
 
 
922
                /* Done with the snapshot used for parsing/planning */
 
923
                if (snapshot_set)
 
924
                        PopActiveSnapshot();
 
925
 
 
926
                /* If we got a cancel signal in analysis or planning, quit */
 
927
                CHECK_FOR_INTERRUPTS();
 
928
 
 
929
                /*
 
930
                 * Create unnamed portal to run the query or queries in. If there
 
931
                 * already is one, silently drop it.
 
932
                 */
 
933
                portal = CreatePortal("", true, true);
 
934
                /* Don't display the portal in pg_cursors */
 
935
                portal->visible = false;
 
936
 
 
937
                /*
 
938
                 * We don't have to copy anything into the portal, because everything
 
939
                 * we are passing here is in MessageContext, which will outlive the
 
940
                 * portal anyway.
 
941
                 */
 
942
                PortalDefineQuery(portal,
 
943
                                                  NULL,
 
944
                                                  query_string,
 
945
                                                  commandTag,
 
946
                                                  plantree_list,
 
947
                                                  NULL);
 
948
 
 
949
                /*
 
950
                 * Start the portal.  No parameters here.
 
951
                 */
 
952
                PortalStart(portal, NULL, InvalidSnapshot);
 
953
 
 
954
                /*
 
955
                 * Select the appropriate output format: text unless we are doing a
 
956
                 * FETCH from a binary cursor.  (Pretty grotty to have to do this here
 
957
                 * --- but it avoids grottiness in other places.  Ah, the joys of
 
958
                 * backward compatibility...)
 
959
                 */
 
960
                format = 0;                             /* TEXT is default */
 
961
                if (IsA(parsetree, FetchStmt))
 
962
                {
 
963
                        FetchStmt  *stmt = (FetchStmt *) parsetree;
 
964
 
 
965
                        if (!stmt->ismove)
 
966
                        {
 
967
                                Portal          fportal = GetPortalByName(stmt->portalname);
 
968
 
 
969
                                if (PortalIsValid(fportal) &&
 
970
                                        (fportal->cursorOptions & CURSOR_OPT_BINARY))
 
971
                                        format = 1; /* BINARY */
 
972
                        }
 
973
                }
 
974
                PortalSetResultFormat(portal, 1, &format);
 
975
 
 
976
                /*
 
977
                 * Now we can create the destination receiver object.
 
978
                 */
 
979
                receiver = CreateDestReceiver(dest);
 
980
                if (dest == DestRemote)
 
981
                        SetRemoteDestReceiverParams(receiver, portal);
 
982
 
 
983
                /*
 
984
                 * Switch back to transaction context for execution.
 
985
                 */
 
986
                MemoryContextSwitchTo(oldcontext);
 
987
 
 
988
                /*
 
989
                 * Run the portal to completion, and then drop it (and the receiver).
 
990
                 */
 
991
                (void) PortalRun(portal,
 
992
                                                 FETCH_ALL,
 
993
                                                 isTopLevel,
 
994
                                                 receiver,
 
995
                                                 receiver,
 
996
                                                 completionTag);
 
997
 
 
998
                (*receiver->rDestroy) (receiver);
 
999
 
 
1000
                PortalDrop(portal, false);
 
1001
 
 
1002
                if (IsA(parsetree, TransactionStmt))
 
1003
                {
 
1004
                        /*
 
1005
                         * If this was a transaction control statement, commit it. We will
 
1006
                         * start a new xact command for the next command (if any).
 
1007
                         */
 
1008
                        finish_xact_command();
 
1009
                }
 
1010
                else if (lnext(parsetree_item) == NULL)
 
1011
                {
 
1012
                        /*
 
1013
                         * If this is the last parsetree of the query string, close down
 
1014
                         * transaction statement before reporting command-complete.  This
 
1015
                         * is so that any end-of-transaction errors are reported before
 
1016
                         * the command-complete message is issued, to avoid confusing
 
1017
                         * clients who will expect either a command-complete message or an
 
1018
                         * error, not one and then the other.  But for compatibility with
 
1019
                         * historical Postgres behavior, we do not force a transaction
 
1020
                         * boundary between queries appearing in a single query string.
 
1021
                         */
 
1022
                        finish_xact_command();
 
1023
                }
 
1024
                else
 
1025
                {
 
1026
                        /*
 
1027
                         * We need a CommandCounterIncrement after every query, except
 
1028
                         * those that start or end a transaction block.
 
1029
                         */
 
1030
                        CommandCounterIncrement();
 
1031
                }
 
1032
 
 
1033
                /*
 
1034
                 * Tell client that we're done with this query.  Note we emit exactly
 
1035
                 * one EndCommand report for each raw parsetree, thus one for each SQL
 
1036
                 * command the client sent, regardless of rewriting. (But a command
 
1037
                 * aborted by error will not send an EndCommand report at all.)
 
1038
                 */
 
1039
                EndCommand(completionTag, dest);
 
1040
        }                                                       /* end loop over parsetrees */
 
1041
 
 
1042
        /*
 
1043
         * Close down transaction statement, if one is open.
 
1044
         */
 
1045
        finish_xact_command();
 
1046
 
 
1047
        /*
 
1048
         * If there were no parsetrees, return EmptyQueryResponse message.
 
1049
         */
 
1050
        if (!parsetree_list)
 
1051
                NullCommand(dest);
 
1052
 
 
1053
        /*
 
1054
         * Emit duration logging if appropriate.
 
1055
         */
 
1056
        switch (check_log_duration(msec_str, was_logged))
 
1057
        {
 
1058
                case 1:
 
1059
                        ereport(LOG,
 
1060
                                        (errmsg("duration: %s ms", msec_str),
 
1061
                                         errhidestmt(true)));
 
1062
                        break;
 
1063
                case 2:
 
1064
                        ereport(LOG,
 
1065
                                        (errmsg("duration: %s ms  statement: %s",
 
1066
                                                        msec_str, query_string),
 
1067
                                         errhidestmt(true),
 
1068
                                         errdetail_execute(parsetree_list)));
 
1069
                        break;
 
1070
        }
 
1071
 
 
1072
        if (save_log_statement_stats)
 
1073
                ShowUsage("QUERY STATISTICS");
 
1074
 
 
1075
        TRACE_POSTGRESQL_QUERY_DONE(query_string);
 
1076
 
 
1077
        debug_query_string = NULL;
 
1078
}
 
1079
 
 
1080
/*
 
1081
 * exec_parse_message
 
1082
 *
 
1083
 * Execute a "Parse" protocol message.
 
1084
 */
 
1085
static void
 
1086
exec_parse_message(const char *query_string,    /* string to execute */
 
1087
                                   const char *stmt_name,               /* name for prepared stmt */
 
1088
                                   Oid *paramTypes,             /* parameter types */
 
1089
                                   int numParams)               /* number of parameters */
 
1090
{
 
1091
        MemoryContext oldcontext;
 
1092
        List       *parsetree_list;
 
1093
        Node       *raw_parse_tree;
 
1094
        const char *commandTag;
 
1095
        List       *querytree_list,
 
1096
                           *stmt_list;
 
1097
        bool            is_named;
 
1098
        bool            fully_planned;
 
1099
        bool            save_log_statement_stats = log_statement_stats;
 
1100
        char            msec_str[32];
 
1101
 
 
1102
        /*
 
1103
         * Report query to various monitoring facilities.
 
1104
         */
 
1105
        debug_query_string = query_string;
 
1106
 
 
1107
        pgstat_report_activity(query_string);
 
1108
 
 
1109
        set_ps_display("PARSE", false);
 
1110
 
 
1111
        if (save_log_statement_stats)
 
1112
                ResetUsage();
 
1113
 
 
1114
        ereport(DEBUG2,
 
1115
                        (errmsg("parse %s: %s",
 
1116
                                        *stmt_name ? stmt_name : "<unnamed>",
 
1117
                                        query_string)));
 
1118
 
 
1119
        /*
 
1120
         * Start up a transaction command so we can run parse analysis etc. (Note
 
1121
         * that this will normally change current memory context.) Nothing happens
 
1122
         * if we are already in one.
 
1123
         */
 
1124
        start_xact_command();
 
1125
 
 
1126
        /*
 
1127
         * Switch to appropriate context for constructing parsetrees.
 
1128
         *
 
1129
         * We have two strategies depending on whether the prepared statement is
 
1130
         * named or not.  For a named prepared statement, we do parsing in
 
1131
         * MessageContext and copy the finished trees into the prepared
 
1132
         * statement's plancache entry; then the reset of MessageContext releases
 
1133
         * temporary space used by parsing and planning.  For an unnamed prepared
 
1134
         * statement, we assume the statement isn't going to hang around long, so
 
1135
         * getting rid of temp space quickly is probably not worth the costs of
 
1136
         * copying parse/plan trees.  So in this case, we create the plancache
 
1137
         * entry's context here, and do all the parsing work therein.
 
1138
         */
 
1139
        is_named = (stmt_name[0] != '\0');
 
1140
        if (is_named)
 
1141
        {
 
1142
                /* Named prepared statement --- parse in MessageContext */
 
1143
                oldcontext = MemoryContextSwitchTo(MessageContext);
 
1144
        }
 
1145
        else
 
1146
        {
 
1147
                /* Unnamed prepared statement --- release any prior unnamed stmt */
 
1148
                drop_unnamed_stmt();
 
1149
                /* Create context for parsing/planning */
 
1150
                unnamed_stmt_context =
 
1151
                        AllocSetContextCreate(CacheMemoryContext,
 
1152
                                                                  "unnamed prepared statement",
 
1153
                                                                  ALLOCSET_DEFAULT_MINSIZE,
 
1154
                                                                  ALLOCSET_DEFAULT_INITSIZE,
 
1155
                                                                  ALLOCSET_DEFAULT_MAXSIZE);
 
1156
                oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
 
1157
        }
 
1158
 
 
1159
        /*
 
1160
         * Do basic parsing of the query or queries (this should be safe even if
 
1161
         * we are in aborted transaction state!)
 
1162
         */
 
1163
        parsetree_list = pg_parse_query(query_string);
 
1164
 
 
1165
        /*
 
1166
         * We only allow a single user statement in a prepared statement. This is
 
1167
         * mainly to keep the protocol simple --- otherwise we'd need to worry
 
1168
         * about multiple result tupdescs and things like that.
 
1169
         */
 
1170
        if (list_length(parsetree_list) > 1)
 
1171
                ereport(ERROR,
 
1172
                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1173
                errmsg("cannot insert multiple commands into a prepared statement")));
 
1174
 
 
1175
        if (parsetree_list != NIL)
 
1176
        {
 
1177
                Query      *query;
 
1178
                bool            snapshot_set = false;
 
1179
                int                     i;
 
1180
 
 
1181
                raw_parse_tree = (Node *) linitial(parsetree_list);
 
1182
 
 
1183
                /*
 
1184
                 * Get the command name for possible use in status display.
 
1185
                 */
 
1186
                commandTag = CreateCommandTag(raw_parse_tree);
 
1187
 
 
1188
                /*
 
1189
                 * If we are in an aborted transaction, reject all commands except
 
1190
                 * COMMIT/ROLLBACK.  It is important that this test occur before we
 
1191
                 * try to do parse analysis, rewrite, or planning, since all those
 
1192
                 * phases try to do database accesses, which may fail in abort state.
 
1193
                 * (It might be safe to allow some additional utility commands in this
 
1194
                 * state, but not many...)
 
1195
                 */
 
1196
                if (IsAbortedTransactionBlockState() &&
 
1197
                        !IsTransactionExitStmt(raw_parse_tree))
 
1198
                        ereport(ERROR,
 
1199
                                        (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
1200
                                         errmsg("current transaction is aborted, "
 
1201
                                                "commands ignored until end of transaction block")));
 
1202
 
 
1203
                /*
 
1204
                 * Set up a snapshot if parse analysis/planning will need one.
 
1205
                 */
 
1206
                if (analyze_requires_snapshot(raw_parse_tree))
 
1207
                {
 
1208
                        PushActiveSnapshot(GetTransactionSnapshot());
 
1209
                        snapshot_set = true;
 
1210
                }
 
1211
 
 
1212
                /*
 
1213
                 * OK to analyze, rewrite, and plan this query.  Note that the
 
1214
                 * originally specified parameter set is not required to be complete,
 
1215
                 * so we have to use parse_analyze_varparams().
 
1216
                 *
 
1217
                 * XXX must use copyObject here since parse analysis scribbles on its
 
1218
                 * input, and we need the unmodified raw parse tree for possible
 
1219
                 * replanning later.
 
1220
                 */
 
1221
                if (log_parser_stats)
 
1222
                        ResetUsage();
 
1223
 
 
1224
                query = parse_analyze_varparams(copyObject(raw_parse_tree),
 
1225
                                                                                query_string,
 
1226
                                                                                &paramTypes,
 
1227
                                                                                &numParams);
 
1228
 
 
1229
                /*
 
1230
                 * Check all parameter types got determined.
 
1231
                 */
 
1232
                for (i = 0; i < numParams; i++)
 
1233
                {
 
1234
                        Oid                     ptype = paramTypes[i];
 
1235
 
 
1236
                        if (ptype == InvalidOid || ptype == UNKNOWNOID)
 
1237
                                ereport(ERROR,
 
1238
                                                (errcode(ERRCODE_INDETERMINATE_DATATYPE),
 
1239
                                         errmsg("could not determine data type of parameter $%d",
 
1240
                                                        i + 1)));
 
1241
                }
 
1242
 
 
1243
                if (log_parser_stats)
 
1244
                        ShowUsage("PARSE ANALYSIS STATISTICS");
 
1245
 
 
1246
                querytree_list = pg_rewrite_query(query);
 
1247
 
 
1248
                /*
 
1249
                 * If this is the unnamed statement and it has parameters, defer query
 
1250
                 * planning until Bind.  Otherwise do it now.
 
1251
                 */
 
1252
                if (!is_named && numParams > 0)
 
1253
                {
 
1254
                        stmt_list = querytree_list;
 
1255
                        fully_planned = false;
 
1256
                }
 
1257
                else
 
1258
                {
 
1259
                        stmt_list = pg_plan_queries(querytree_list, 0, NULL);
 
1260
                        fully_planned = true;
 
1261
                }
 
1262
 
 
1263
                /* Done with the snapshot used for parsing/planning */
 
1264
                if (snapshot_set)
 
1265
                        PopActiveSnapshot();
 
1266
        }
 
1267
        else
 
1268
        {
 
1269
                /* Empty input string.  This is legal. */
 
1270
                raw_parse_tree = NULL;
 
1271
                commandTag = NULL;
 
1272
                stmt_list = NIL;
 
1273
                fully_planned = true;
 
1274
        }
 
1275
 
 
1276
        /* If we got a cancel signal in analysis or planning, quit */
 
1277
        CHECK_FOR_INTERRUPTS();
 
1278
 
 
1279
        /*
 
1280
         * Store the query as a prepared statement.  See above comments.
 
1281
         */
 
1282
        if (is_named)
 
1283
        {
 
1284
                StorePreparedStatement(stmt_name,
 
1285
                                                           raw_parse_tree,
 
1286
                                                           query_string,
 
1287
                                                           commandTag,
 
1288
                                                           paramTypes,
 
1289
                                                           numParams,
 
1290
                                                           0,           /* default cursor options */
 
1291
                                                           stmt_list,
 
1292
                                                           false);
 
1293
        }
 
1294
        else
 
1295
        {
 
1296
                /*
 
1297
                 * paramTypes and query_string need to be copied into
 
1298
                 * unnamed_stmt_context.  The rest is there already
 
1299
                 */
 
1300
                Oid                *newParamTypes;
 
1301
 
 
1302
                if (numParams > 0)
 
1303
                {
 
1304
                        newParamTypes = (Oid *) palloc(numParams * sizeof(Oid));
 
1305
                        memcpy(newParamTypes, paramTypes, numParams * sizeof(Oid));
 
1306
                }
 
1307
                else
 
1308
                        newParamTypes = NULL;
 
1309
 
 
1310
                unnamed_stmt_psrc = FastCreateCachedPlan(raw_parse_tree,
 
1311
                                                                                                 pstrdup(query_string),
 
1312
                                                                                                 commandTag,
 
1313
                                                                                                 newParamTypes,
 
1314
                                                                                                 numParams,
 
1315
                                                                                                 0,             /* cursor options */
 
1316
                                                                                                 stmt_list,
 
1317
                                                                                                 fully_planned,
 
1318
                                                                                                 true,
 
1319
                                                                                                 unnamed_stmt_context);
 
1320
                /* context now belongs to the plancache entry */
 
1321
                unnamed_stmt_context = NULL;
 
1322
        }
 
1323
 
 
1324
        MemoryContextSwitchTo(oldcontext);
 
1325
 
 
1326
        /*
 
1327
         * We do NOT close the open transaction command here; that only happens
 
1328
         * when the client sends Sync.  Instead, do CommandCounterIncrement just
 
1329
         * in case something happened during parse/plan.
 
1330
         */
 
1331
        CommandCounterIncrement();
 
1332
 
 
1333
        /*
 
1334
         * Send ParseComplete.
 
1335
         */
 
1336
        if (whereToSendOutput == DestRemote)
 
1337
                pq_putemptymessage('1');
 
1338
 
 
1339
        /*
 
1340
         * Emit duration logging if appropriate.
 
1341
         */
 
1342
        switch (check_log_duration(msec_str, false))
 
1343
        {
 
1344
                case 1:
 
1345
                        ereport(LOG,
 
1346
                                        (errmsg("duration: %s ms", msec_str),
 
1347
                                         errhidestmt(true)));
 
1348
                        break;
 
1349
                case 2:
 
1350
                        ereport(LOG,
 
1351
                                        (errmsg("duration: %s ms  parse %s: %s",
 
1352
                                                        msec_str,
 
1353
                                                        *stmt_name ? stmt_name : "<unnamed>",
 
1354
                                                        query_string),
 
1355
                                         errhidestmt(true)));
 
1356
                        break;
 
1357
        }
 
1358
 
 
1359
        if (save_log_statement_stats)
 
1360
                ShowUsage("PARSE MESSAGE STATISTICS");
 
1361
 
 
1362
        debug_query_string = NULL;
 
1363
}
 
1364
 
 
1365
/*
 
1366
 * exec_bind_message
 
1367
 *
 
1368
 * Process a "Bind" message to create a portal from a prepared statement
 
1369
 */
 
1370
static void
 
1371
exec_bind_message(StringInfo input_message)
 
1372
{
 
1373
        const char *portal_name;
 
1374
        const char *stmt_name;
 
1375
        int                     numPFormats;
 
1376
        int16      *pformats = NULL;
 
1377
        int                     numParams;
 
1378
        int                     numRFormats;
 
1379
        int16      *rformats = NULL;
 
1380
        CachedPlanSource *psrc;
 
1381
        CachedPlan *cplan;
 
1382
        Portal          portal;
 
1383
        char       *query_string;
 
1384
        char       *saved_stmt_name;
 
1385
        ParamListInfo params;
 
1386
        List       *plan_list;
 
1387
        MemoryContext oldContext;
 
1388
        bool            save_log_statement_stats = log_statement_stats;
 
1389
        bool            snapshot_set = false;
 
1390
        char            msec_str[32];
 
1391
 
 
1392
        /* Get the fixed part of the message */
 
1393
        portal_name = pq_getmsgstring(input_message);
 
1394
        stmt_name = pq_getmsgstring(input_message);
 
1395
 
 
1396
        ereport(DEBUG2,
 
1397
                        (errmsg("bind %s to %s",
 
1398
                                        *portal_name ? portal_name : "<unnamed>",
 
1399
                                        *stmt_name ? stmt_name : "<unnamed>")));
 
1400
 
 
1401
        /* Find prepared statement */
 
1402
        if (stmt_name[0] != '\0')
 
1403
        {
 
1404
                PreparedStatement *pstmt;
 
1405
 
 
1406
                pstmt = FetchPreparedStatement(stmt_name, true);
 
1407
                psrc = pstmt->plansource;
 
1408
        }
 
1409
        else
 
1410
        {
 
1411
                /* special-case the unnamed statement */
 
1412
                psrc = unnamed_stmt_psrc;
 
1413
                if (!psrc)
 
1414
                        ereport(ERROR,
 
1415
                                        (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
 
1416
                                         errmsg("unnamed prepared statement does not exist")));
 
1417
        }
 
1418
 
 
1419
        /*
 
1420
         * Report query to various monitoring facilities.
 
1421
         */
 
1422
        debug_query_string = psrc->query_string;
 
1423
 
 
1424
        pgstat_report_activity(psrc->query_string);
 
1425
 
 
1426
        set_ps_display("BIND", false);
 
1427
 
 
1428
        if (save_log_statement_stats)
 
1429
                ResetUsage();
 
1430
 
 
1431
        /*
 
1432
         * Start up a transaction command so we can call functions etc. (Note that
 
1433
         * this will normally change current memory context.) Nothing happens if
 
1434
         * we are already in one.
 
1435
         */
 
1436
        start_xact_command();
 
1437
 
 
1438
        /* Switch back to message context */
 
1439
        MemoryContextSwitchTo(MessageContext);
 
1440
 
 
1441
        /* Get the parameter format codes */
 
1442
        numPFormats = pq_getmsgint(input_message, 2);
 
1443
        if (numPFormats > 0)
 
1444
        {
 
1445
                int                     i;
 
1446
 
 
1447
                pformats = (int16 *) palloc(numPFormats * sizeof(int16));
 
1448
                for (i = 0; i < numPFormats; i++)
 
1449
                        pformats[i] = pq_getmsgint(input_message, 2);
 
1450
        }
 
1451
 
 
1452
        /* Get the parameter value count */
 
1453
        numParams = pq_getmsgint(input_message, 2);
 
1454
 
 
1455
        if (numPFormats > 1 && numPFormats != numParams)
 
1456
                ereport(ERROR,
 
1457
                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
1458
                        errmsg("bind message has %d parameter formats but %d parameters",
 
1459
                                   numPFormats, numParams)));
 
1460
 
 
1461
        if (numParams != psrc->num_params)
 
1462
                ereport(ERROR,
 
1463
                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
1464
                                 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
 
1465
                                                numParams, stmt_name, psrc->num_params)));
 
1466
 
 
1467
        /*
 
1468
         * If we are in aborted transaction state, the only portals we can
 
1469
         * actually run are those containing COMMIT or ROLLBACK commands. We
 
1470
         * disallow binding anything else to avoid problems with infrastructure
 
1471
         * that expects to run inside a valid transaction.      We also disallow
 
1472
         * binding any parameters, since we can't risk calling user-defined I/O
 
1473
         * functions.
 
1474
         */
 
1475
        if (IsAbortedTransactionBlockState() &&
 
1476
                (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
 
1477
                 numParams != 0))
 
1478
                ereport(ERROR,
 
1479
                                (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
1480
                                 errmsg("current transaction is aborted, "
 
1481
                                                "commands ignored until end of transaction block")));
 
1482
 
 
1483
        /*
 
1484
         * Create the portal.  Allow silent replacement of an existing portal only
 
1485
         * if the unnamed portal is specified.
 
1486
         */
 
1487
        if (portal_name[0] == '\0')
 
1488
                portal = CreatePortal(portal_name, true, true);
 
1489
        else
 
1490
                portal = CreatePortal(portal_name, false, false);
 
1491
 
 
1492
        /*
 
1493
         * Prepare to copy stuff into the portal's memory context.  We do all this
 
1494
         * copying first, because it could possibly fail (out-of-memory) and we
 
1495
         * don't want a failure to occur between RevalidateCachedPlan and
 
1496
         * PortalDefineQuery; that would result in leaking our plancache refcount.
 
1497
         */
 
1498
        oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
 
1499
 
 
1500
        /* Copy the plan's query string into the portal */
 
1501
        query_string = pstrdup(psrc->query_string);
 
1502
 
 
1503
        /* Likewise make a copy of the statement name, unless it's unnamed */
 
1504
        if (stmt_name[0])
 
1505
                saved_stmt_name = pstrdup(stmt_name);
 
1506
        else
 
1507
                saved_stmt_name = NULL;
 
1508
 
 
1509
        /*
 
1510
         * Set a snapshot if we have parameters to fetch (since the input
 
1511
         * functions might need it) or the query isn't a utility command (and
 
1512
         * hence could require redoing parse analysis and planning).
 
1513
         */
 
1514
        if (numParams > 0 || analyze_requires_snapshot(psrc->raw_parse_tree))
 
1515
        {
 
1516
                PushActiveSnapshot(GetTransactionSnapshot());
 
1517
                snapshot_set = true;
 
1518
        }
 
1519
 
 
1520
        /*
 
1521
         * Fetch parameters, if any, and store in the portal's memory context.
 
1522
         */
 
1523
        if (numParams > 0)
 
1524
        {
 
1525
                int                     paramno;
 
1526
 
 
1527
                /* sizeof(ParamListInfoData) includes the first array element */
 
1528
                params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
 
1529
                                                                   (numParams - 1) *sizeof(ParamExternData));
 
1530
                params->numParams = numParams;
 
1531
 
 
1532
                for (paramno = 0; paramno < numParams; paramno++)
 
1533
                {
 
1534
                        Oid                     ptype = psrc->param_types[paramno];
 
1535
                        int32           plength;
 
1536
                        Datum           pval;
 
1537
                        bool            isNull;
 
1538
                        StringInfoData pbuf;
 
1539
                        char            csave;
 
1540
                        int16           pformat;
 
1541
 
 
1542
                        plength = pq_getmsgint(input_message, 4);
 
1543
                        isNull = (plength == -1);
 
1544
 
 
1545
                        if (!isNull)
 
1546
                        {
 
1547
                                const char *pvalue = pq_getmsgbytes(input_message, plength);
 
1548
 
 
1549
                                /*
 
1550
                                 * Rather than copying data around, we just set up a phony
 
1551
                                 * StringInfo pointing to the correct portion of the message
 
1552
                                 * buffer.      We assume we can scribble on the message buffer so
 
1553
                                 * as to maintain the convention that StringInfos have a
 
1554
                                 * trailing null.  This is grotty but is a big win when
 
1555
                                 * dealing with very large parameter strings.
 
1556
                                 */
 
1557
                                pbuf.data = (char *) pvalue;
 
1558
                                pbuf.maxlen = plength + 1;
 
1559
                                pbuf.len = plength;
 
1560
                                pbuf.cursor = 0;
 
1561
 
 
1562
                                csave = pbuf.data[plength];
 
1563
                                pbuf.data[plength] = '\0';
 
1564
                        }
 
1565
                        else
 
1566
                        {
 
1567
                                pbuf.data = NULL;               /* keep compiler quiet */
 
1568
                                csave = 0;
 
1569
                        }
 
1570
 
 
1571
                        if (numPFormats > 1)
 
1572
                                pformat = pformats[paramno];
 
1573
                        else if (numPFormats > 0)
 
1574
                                pformat = pformats[0];
 
1575
                        else
 
1576
                                pformat = 0;    /* default = text */
 
1577
 
 
1578
                        if (pformat == 0)       /* text mode */
 
1579
                        {
 
1580
                                Oid                     typinput;
 
1581
                                Oid                     typioparam;
 
1582
                                char       *pstring;
 
1583
 
 
1584
                                getTypeInputInfo(ptype, &typinput, &typioparam);
 
1585
 
 
1586
                                /*
 
1587
                                 * We have to do encoding conversion before calling the
 
1588
                                 * typinput routine.
 
1589
                                 */
 
1590
                                if (isNull)
 
1591
                                        pstring = NULL;
 
1592
                                else
 
1593
                                        pstring = pg_client_to_server(pbuf.data, plength);
 
1594
 
 
1595
                                pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
 
1596
 
 
1597
                                /* Free result of encoding conversion, if any */
 
1598
                                if (pstring && pstring != pbuf.data)
 
1599
                                        pfree(pstring);
 
1600
                        }
 
1601
                        else if (pformat == 1)          /* binary mode */
 
1602
                        {
 
1603
                                Oid                     typreceive;
 
1604
                                Oid                     typioparam;
 
1605
                                StringInfo      bufptr;
 
1606
 
 
1607
                                /*
 
1608
                                 * Call the parameter type's binary input converter
 
1609
                                 */
 
1610
                                getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
 
1611
 
 
1612
                                if (isNull)
 
1613
                                        bufptr = NULL;
 
1614
                                else
 
1615
                                        bufptr = &pbuf;
 
1616
 
 
1617
                                pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
 
1618
 
 
1619
                                /* Trouble if it didn't eat the whole buffer */
 
1620
                                if (!isNull && pbuf.cursor != pbuf.len)
 
1621
                                        ereport(ERROR,
 
1622
                                                        (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
 
1623
                                                         errmsg("incorrect binary data format in bind parameter %d",
 
1624
                                                                        paramno + 1)));
 
1625
                        }
 
1626
                        else
 
1627
                        {
 
1628
                                ereport(ERROR,
 
1629
                                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1630
                                                 errmsg("unsupported format code: %d",
 
1631
                                                                pformat)));
 
1632
                                pval = 0;               /* keep compiler quiet */
 
1633
                        }
 
1634
 
 
1635
                        /* Restore message buffer contents */
 
1636
                        if (!isNull)
 
1637
                                pbuf.data[plength] = csave;
 
1638
 
 
1639
                        params->params[paramno].value = pval;
 
1640
                        params->params[paramno].isnull = isNull;
 
1641
 
 
1642
                        /*
 
1643
                         * We mark the params as CONST.  This has no effect if we already
 
1644
                         * did planning, but if we didn't, it licenses the planner to
 
1645
                         * substitute the parameters directly into the one-shot plan we
 
1646
                         * will generate below.
 
1647
                         */
 
1648
                        params->params[paramno].pflags = PARAM_FLAG_CONST;
 
1649
                        params->params[paramno].ptype = ptype;
 
1650
                }
 
1651
        }
 
1652
        else
 
1653
                params = NULL;
 
1654
 
 
1655
        /* Done storing stuff in portal's context */
 
1656
        MemoryContextSwitchTo(oldContext);
 
1657
 
 
1658
        /* Get the result format codes */
 
1659
        numRFormats = pq_getmsgint(input_message, 2);
 
1660
        if (numRFormats > 0)
 
1661
        {
 
1662
                int                     i;
 
1663
 
 
1664
                rformats = (int16 *) palloc(numRFormats * sizeof(int16));
 
1665
                for (i = 0; i < numRFormats; i++)
 
1666
                        rformats[i] = pq_getmsgint(input_message, 2);
 
1667
        }
 
1668
 
 
1669
        pq_getmsgend(input_message);
 
1670
 
 
1671
        if (psrc->fully_planned)
 
1672
        {
 
1673
                /*
 
1674
                 * Revalidate the cached plan; this may result in replanning.  Any
 
1675
                 * cruft will be generated in MessageContext.  The plan refcount will
 
1676
                 * be assigned to the Portal, so it will be released at portal
 
1677
                 * destruction.
 
1678
                 */
 
1679
                cplan = RevalidateCachedPlan(psrc, false);
 
1680
                plan_list = cplan->stmt_list;
 
1681
        }
 
1682
        else
 
1683
        {
 
1684
                List       *query_list;
 
1685
 
 
1686
                /*
 
1687
                 * Revalidate the cached plan; this may result in redoing parse
 
1688
                 * analysis and rewriting (but not planning).  Any cruft will be
 
1689
                 * generated in MessageContext.  The plan refcount is assigned to
 
1690
                 * CurrentResourceOwner.
 
1691
                 */
 
1692
                cplan = RevalidateCachedPlan(psrc, true);
 
1693
 
 
1694
                /*
 
1695
                 * We didn't plan the query before, so do it now.  This allows the
 
1696
                 * planner to make use of the concrete parameter values we now have.
 
1697
                 * Because we use PARAM_FLAG_CONST, the plan is good only for this set
 
1698
                 * of param values, and so we generate the plan in the portal's own
 
1699
                 * memory context where it will be thrown away after use. As in
 
1700
                 * exec_parse_message, we make no attempt to recover planner temporary
 
1701
                 * memory until the end of the operation.
 
1702
                 *
 
1703
                 * XXX because the planner has a bad habit of scribbling on its input,
 
1704
                 * we have to make a copy of the parse trees.  FIXME someday.
 
1705
                 */
 
1706
                oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
 
1707
                query_list = copyObject(cplan->stmt_list);
 
1708
                plan_list = pg_plan_queries(query_list, 0, params);
 
1709
                MemoryContextSwitchTo(oldContext);
 
1710
 
 
1711
                /* We no longer need the cached plan refcount ... */
 
1712
                ReleaseCachedPlan(cplan, true);
 
1713
                /* ... and we don't want the portal to depend on it, either */
 
1714
                cplan = NULL;
 
1715
        }
 
1716
 
 
1717
        /*
 
1718
         * Now we can define the portal.
 
1719
         *
 
1720
         * DO NOT put any code that could possibly throw an error between the
 
1721
         * above "RevalidateCachedPlan(psrc, false)" call and here.
 
1722
         */
 
1723
        PortalDefineQuery(portal,
 
1724
                                          saved_stmt_name,
 
1725
                                          query_string,
 
1726
                                          psrc->commandTag,
 
1727
                                          plan_list,
 
1728
                                          cplan);
 
1729
 
 
1730
        /* Done with the snapshot used for parameter I/O and parsing/planning */
 
1731
        if (snapshot_set)
 
1732
                PopActiveSnapshot();
 
1733
 
 
1734
        /*
 
1735
         * And we're ready to start portal execution.
 
1736
         */
 
1737
        PortalStart(portal, params, InvalidSnapshot);
 
1738
 
 
1739
        /*
 
1740
         * Apply the result format requests to the portal.
 
1741
         */
 
1742
        PortalSetResultFormat(portal, numRFormats, rformats);
 
1743
 
 
1744
        /*
 
1745
         * Send BindComplete.
 
1746
         */
 
1747
        if (whereToSendOutput == DestRemote)
 
1748
                pq_putemptymessage('2');
 
1749
 
 
1750
        /*
 
1751
         * Emit duration logging if appropriate.
 
1752
         */
 
1753
        switch (check_log_duration(msec_str, false))
 
1754
        {
 
1755
                case 1:
 
1756
                        ereport(LOG,
 
1757
                                        (errmsg("duration: %s ms", msec_str),
 
1758
                                         errhidestmt(true)));
 
1759
                        break;
 
1760
                case 2:
 
1761
                        ereport(LOG,
 
1762
                                        (errmsg("duration: %s ms  bind %s%s%s: %s",
 
1763
                                                        msec_str,
 
1764
                                                        *stmt_name ? stmt_name : "<unnamed>",
 
1765
                                                        *portal_name ? "/" : "",
 
1766
                                                        *portal_name ? portal_name : "",
 
1767
                                                        psrc->query_string),
 
1768
                                         errhidestmt(true),
 
1769
                                         errdetail_params(params)));
 
1770
                        break;
 
1771
        }
 
1772
 
 
1773
        if (save_log_statement_stats)
 
1774
                ShowUsage("BIND MESSAGE STATISTICS");
 
1775
 
 
1776
        debug_query_string = NULL;
 
1777
}
 
1778
 
 
1779
/*
 
1780
 * exec_execute_message
 
1781
 *
 
1782
 * Process an "Execute" message for a portal
 
1783
 */
 
1784
static void
 
1785
exec_execute_message(const char *portal_name, long max_rows)
 
1786
{
 
1787
        CommandDest dest;
 
1788
        DestReceiver *receiver;
 
1789
        Portal          portal;
 
1790
        bool            completed;
 
1791
        char            completionTag[COMPLETION_TAG_BUFSIZE];
 
1792
        const char *sourceText;
 
1793
        const char *prepStmtName;
 
1794
        ParamListInfo portalParams;
 
1795
        bool            save_log_statement_stats = log_statement_stats;
 
1796
        bool            is_xact_command;
 
1797
        bool            execute_is_fetch;
 
1798
        bool            was_logged = false;
 
1799
        char            msec_str[32];
 
1800
 
 
1801
        /* Adjust destination to tell printtup.c what to do */
 
1802
        dest = whereToSendOutput;
 
1803
        if (dest == DestRemote)
 
1804
                dest = DestRemoteExecute;
 
1805
 
 
1806
        portal = GetPortalByName(portal_name);
 
1807
        if (!PortalIsValid(portal))
 
1808
                ereport(ERROR,
 
1809
                                (errcode(ERRCODE_UNDEFINED_CURSOR),
 
1810
                                 errmsg("portal \"%s\" does not exist", portal_name)));
 
1811
 
 
1812
        /*
 
1813
         * If the original query was a null string, just return
 
1814
         * EmptyQueryResponse.
 
1815
         */
 
1816
        if (portal->commandTag == NULL)
 
1817
        {
 
1818
                Assert(portal->stmts == NIL);
 
1819
                NullCommand(dest);
 
1820
                return;
 
1821
        }
 
1822
 
 
1823
        /* Does the portal contain a transaction command? */
 
1824
        is_xact_command = IsTransactionStmtList(portal->stmts);
 
1825
 
 
1826
        /*
 
1827
         * We must copy the sourceText and prepStmtName into MessageContext in
 
1828
         * case the portal is destroyed during finish_xact_command. Can avoid the
 
1829
         * copy if it's not an xact command, though.
 
1830
         */
 
1831
        if (is_xact_command)
 
1832
        {
 
1833
                sourceText = pstrdup(portal->sourceText);
 
1834
                if (portal->prepStmtName)
 
1835
                        prepStmtName = pstrdup(portal->prepStmtName);
 
1836
                else
 
1837
                        prepStmtName = "<unnamed>";
 
1838
 
 
1839
                /*
 
1840
                 * An xact command shouldn't have any parameters, which is a good
 
1841
                 * thing because they wouldn't be around after finish_xact_command.
 
1842
                 */
 
1843
                portalParams = NULL;
 
1844
        }
 
1845
        else
 
1846
        {
 
1847
                sourceText = portal->sourceText;
 
1848
                if (portal->prepStmtName)
 
1849
                        prepStmtName = portal->prepStmtName;
 
1850
                else
 
1851
                        prepStmtName = "<unnamed>";
 
1852
                portalParams = portal->portalParams;
 
1853
        }
 
1854
 
 
1855
        /*
 
1856
         * Report query to various monitoring facilities.
 
1857
         */
 
1858
        debug_query_string = sourceText;
 
1859
 
 
1860
        pgstat_report_activity(sourceText);
 
1861
 
 
1862
        set_ps_display(portal->commandTag, false);
 
1863
 
 
1864
        if (save_log_statement_stats)
 
1865
                ResetUsage();
 
1866
 
 
1867
        BeginCommand(portal->commandTag, dest);
 
1868
 
 
1869
        /*
 
1870
         * Create dest receiver in MessageContext (we don't want it in transaction
 
1871
         * context, because that may get deleted if portal contains VACUUM).
 
1872
         */
 
1873
        receiver = CreateDestReceiver(dest);
 
1874
        if (dest == DestRemoteExecute)
 
1875
                SetRemoteDestReceiverParams(receiver, portal);
 
1876
 
 
1877
        /*
 
1878
         * Ensure we are in a transaction command (this should normally be the
 
1879
         * case already due to prior BIND).
 
1880
         */
 
1881
        start_xact_command();
 
1882
 
 
1883
        /*
 
1884
         * If we re-issue an Execute protocol request against an existing portal,
 
1885
         * then we are only fetching more rows rather than completely re-executing
 
1886
         * the query from the start. atStart is never reset for a v3 portal, so we
 
1887
         * are safe to use this check.
 
1888
         */
 
1889
        execute_is_fetch = !portal->atStart;
 
1890
 
 
1891
        /* Log immediately if dictated by log_statement */
 
1892
        if (check_log_statement(portal->stmts))
 
1893
        {
 
1894
                ereport(LOG,
 
1895
                                (errmsg("%s %s%s%s: %s",
 
1896
                                                execute_is_fetch ?
 
1897
                                                _("execute fetch from") :
 
1898
                                                _("execute"),
 
1899
                                                prepStmtName,
 
1900
                                                *portal_name ? "/" : "",
 
1901
                                                *portal_name ? portal_name : "",
 
1902
                                                sourceText),
 
1903
                                 errhidestmt(true),
 
1904
                                 errdetail_params(portalParams)));
 
1905
                was_logged = true;
 
1906
        }
 
1907
 
 
1908
        /*
 
1909
         * If we are in aborted transaction state, the only portals we can
 
1910
         * actually run are those containing COMMIT or ROLLBACK commands.
 
1911
         */
 
1912
        if (IsAbortedTransactionBlockState() &&
 
1913
                !IsTransactionExitStmtList(portal->stmts))
 
1914
                ereport(ERROR,
 
1915
                                (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
1916
                                 errmsg("current transaction is aborted, "
 
1917
                                                "commands ignored until end of transaction block")));
 
1918
 
 
1919
        /* Check for cancel signal before we start execution */
 
1920
        CHECK_FOR_INTERRUPTS();
 
1921
 
 
1922
        /*
 
1923
         * Okay to run the portal.
 
1924
         */
 
1925
        if (max_rows <= 0)
 
1926
                max_rows = FETCH_ALL;
 
1927
 
 
1928
        completed = PortalRun(portal,
 
1929
                                                  max_rows,
 
1930
                                                  true, /* always top level */
 
1931
                                                  receiver,
 
1932
                                                  receiver,
 
1933
                                                  completionTag);
 
1934
 
 
1935
        (*receiver->rDestroy) (receiver);
 
1936
 
 
1937
        if (completed)
 
1938
        {
 
1939
                if (is_xact_command)
 
1940
                {
 
1941
                        /*
 
1942
                         * If this was a transaction control statement, commit it.      We
 
1943
                         * will start a new xact command for the next command (if any).
 
1944
                         */
 
1945
                        finish_xact_command();
 
1946
                }
 
1947
                else
 
1948
                {
 
1949
                        /*
 
1950
                         * We need a CommandCounterIncrement after every query, except
 
1951
                         * those that start or end a transaction block.
 
1952
                         */
 
1953
                        CommandCounterIncrement();
 
1954
                }
 
1955
 
 
1956
                /* Send appropriate CommandComplete to client */
 
1957
                EndCommand(completionTag, dest);
 
1958
        }
 
1959
        else
 
1960
        {
 
1961
                /* Portal run not complete, so send PortalSuspended */
 
1962
                if (whereToSendOutput == DestRemote)
 
1963
                        pq_putemptymessage('s');
 
1964
        }
 
1965
 
 
1966
        /*
 
1967
         * Emit duration logging if appropriate.
 
1968
         */
 
1969
        switch (check_log_duration(msec_str, was_logged))
 
1970
        {
 
1971
                case 1:
 
1972
                        ereport(LOG,
 
1973
                                        (errmsg("duration: %s ms", msec_str),
 
1974
                                         errhidestmt(true)));
 
1975
                        break;
 
1976
                case 2:
 
1977
                        ereport(LOG,
 
1978
                                        (errmsg("duration: %s ms  %s %s%s%s: %s",
 
1979
                                                        msec_str,
 
1980
                                                        execute_is_fetch ?
 
1981
                                                        _("execute fetch from") :
 
1982
                                                        _("execute"),
 
1983
                                                        prepStmtName,
 
1984
                                                        *portal_name ? "/" : "",
 
1985
                                                        *portal_name ? portal_name : "",
 
1986
                                                        sourceText),
 
1987
                                         errhidestmt(true),
 
1988
                                         errdetail_params(portalParams)));
 
1989
                        break;
 
1990
        }
 
1991
 
 
1992
        if (save_log_statement_stats)
 
1993
                ShowUsage("EXECUTE MESSAGE STATISTICS");
 
1994
 
 
1995
        debug_query_string = NULL;
 
1996
}
 
1997
 
 
1998
/*
 
1999
 * check_log_statement
 
2000
 *              Determine whether command should be logged because of log_statement
 
2001
 *
 
2002
 * parsetree_list can be either raw grammar output or a list of planned
 
2003
 * statements
 
2004
 */
 
2005
static bool
 
2006
check_log_statement(List *stmt_list)
 
2007
{
 
2008
        ListCell   *stmt_item;
 
2009
 
 
2010
        if (log_statement == LOGSTMT_NONE)
 
2011
                return false;
 
2012
        if (log_statement == LOGSTMT_ALL)
 
2013
                return true;
 
2014
 
 
2015
        /* Else we have to inspect the statement(s) to see whether to log */
 
2016
        foreach(stmt_item, stmt_list)
 
2017
        {
 
2018
                Node       *stmt = (Node *) lfirst(stmt_item);
 
2019
 
 
2020
                if (GetCommandLogLevel(stmt) <= log_statement)
 
2021
                        return true;
 
2022
        }
 
2023
 
 
2024
        return false;
 
2025
}
 
2026
 
 
2027
/*
 
2028
 * check_log_duration
 
2029
 *              Determine whether current command's duration should be logged
 
2030
 *
 
2031
 * Returns:
 
2032
 *              0 if no logging is needed
 
2033
 *              1 if just the duration should be logged
 
2034
 *              2 if duration and query details should be logged
 
2035
 *
 
2036
 * If logging is needed, the duration in msec is formatted into msec_str[],
 
2037
 * which must be a 32-byte buffer.
 
2038
 *
 
2039
 * was_logged should be TRUE if caller already logged query details (this
 
2040
 * essentially prevents 2 from being returned).
 
2041
 */
 
2042
int
 
2043
check_log_duration(char *msec_str, bool was_logged)
 
2044
{
 
2045
        if (log_duration || log_min_duration_statement >= 0)
 
2046
        {
 
2047
                long            secs;
 
2048
                int                     usecs;
 
2049
                int                     msecs;
 
2050
                bool            exceeded;
 
2051
 
 
2052
                TimestampDifference(GetCurrentStatementStartTimestamp(),
 
2053
                                                        GetCurrentTimestamp(),
 
2054
                                                        &secs, &usecs);
 
2055
                msecs = usecs / 1000;
 
2056
 
 
2057
                /*
 
2058
                 * This odd-looking test for log_min_duration_statement being exceeded
 
2059
                 * is designed to avoid integer overflow with very long durations:
 
2060
                 * don't compute secs * 1000 until we've verified it will fit in int.
 
2061
                 */
 
2062
                exceeded = (log_min_duration_statement == 0 ||
 
2063
                                        (log_min_duration_statement > 0 &&
 
2064
                                         (secs > log_min_duration_statement / 1000 ||
 
2065
                                          secs * 1000 + msecs >= log_min_duration_statement)));
 
2066
 
 
2067
                if (exceeded || log_duration)
 
2068
                {
 
2069
                        snprintf(msec_str, 32, "%ld.%03d",
 
2070
                                         secs * 1000 + msecs, usecs % 1000);
 
2071
                        if (exceeded && !was_logged)
 
2072
                                return 2;
 
2073
                        else
 
2074
                                return 1;
 
2075
                }
 
2076
        }
 
2077
 
 
2078
        return 0;
 
2079
}
 
2080
 
 
2081
/*
 
2082
 * errdetail_execute
 
2083
 *
 
2084
 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
 
2085
 * The argument is the raw parsetree list.
 
2086
 */
 
2087
static int
 
2088
errdetail_execute(List *raw_parsetree_list)
 
2089
{
 
2090
        ListCell   *parsetree_item;
 
2091
 
 
2092
        foreach(parsetree_item, raw_parsetree_list)
 
2093
        {
 
2094
                Node       *parsetree = (Node *) lfirst(parsetree_item);
 
2095
 
 
2096
                if (IsA(parsetree, ExecuteStmt))
 
2097
                {
 
2098
                        ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
 
2099
                        PreparedStatement *pstmt;
 
2100
 
 
2101
                        pstmt = FetchPreparedStatement(stmt->name, false);
 
2102
                        if (pstmt)
 
2103
                        {
 
2104
                                errdetail("prepare: %s", pstmt->plansource->query_string);
 
2105
                                return 0;
 
2106
                        }
 
2107
                }
 
2108
        }
 
2109
 
 
2110
        return 0;
 
2111
}
 
2112
 
 
2113
/*
 
2114
 * errdetail_params
 
2115
 *
 
2116
 * Add an errdetail() line showing bind-parameter data, if available.
 
2117
 */
 
2118
static int
 
2119
errdetail_params(ParamListInfo params)
 
2120
{
 
2121
        /* We mustn't call user-defined I/O functions when in an aborted xact */
 
2122
        if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
 
2123
        {
 
2124
                StringInfoData param_str;
 
2125
                MemoryContext oldcontext;
 
2126
                int                     paramno;
 
2127
 
 
2128
                /* Make sure any trash is generated in MessageContext */
 
2129
                oldcontext = MemoryContextSwitchTo(MessageContext);
 
2130
 
 
2131
                initStringInfo(&param_str);
 
2132
 
 
2133
                for (paramno = 0; paramno < params->numParams; paramno++)
 
2134
                {
 
2135
                        ParamExternData *prm = &params->params[paramno];
 
2136
                        Oid                     typoutput;
 
2137
                        bool            typisvarlena;
 
2138
                        char       *pstring;
 
2139
                        char       *p;
 
2140
 
 
2141
                        appendStringInfo(&param_str, "%s$%d = ",
 
2142
                                                         paramno > 0 ? ", " : "",
 
2143
                                                         paramno + 1);
 
2144
 
 
2145
                        if (prm->isnull || !OidIsValid(prm->ptype))
 
2146
                        {
 
2147
                                appendStringInfoString(&param_str, "NULL");
 
2148
                                continue;
 
2149
                        }
 
2150
 
 
2151
                        getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
 
2152
 
 
2153
                        pstring = OidOutputFunctionCall(typoutput, prm->value);
 
2154
 
 
2155
                        appendStringInfoCharMacro(&param_str, '\'');
 
2156
                        for (p = pstring; *p; p++)
 
2157
                        {
 
2158
                                if (*p == '\'') /* double single quotes */
 
2159
                                        appendStringInfoCharMacro(&param_str, *p);
 
2160
                                appendStringInfoCharMacro(&param_str, *p);
 
2161
                        }
 
2162
                        appendStringInfoCharMacro(&param_str, '\'');
 
2163
 
 
2164
                        pfree(pstring);
 
2165
                }
 
2166
 
 
2167
                errdetail("parameters: %s", param_str.data);
 
2168
 
 
2169
                pfree(param_str.data);
 
2170
 
 
2171
                MemoryContextSwitchTo(oldcontext);
 
2172
        }
 
2173
 
 
2174
        return 0;
 
2175
}
 
2176
 
 
2177
/*
 
2178
 * exec_describe_statement_message
 
2179
 *
 
2180
 * Process a "Describe" message for a prepared statement
 
2181
 */
 
2182
static void
 
2183
exec_describe_statement_message(const char *stmt_name)
 
2184
{
 
2185
        CachedPlanSource *psrc;
 
2186
        StringInfoData buf;
 
2187
        int                     i;
 
2188
 
 
2189
        /*
 
2190
         * Start up a transaction command. (Note that this will normally change
 
2191
         * current memory context.) Nothing happens if we are already in one.
 
2192
         */
 
2193
        start_xact_command();
 
2194
 
 
2195
        /* Switch back to message context */
 
2196
        MemoryContextSwitchTo(MessageContext);
 
2197
 
 
2198
        /* Find prepared statement */
 
2199
        if (stmt_name[0] != '\0')
 
2200
        {
 
2201
                PreparedStatement *pstmt;
 
2202
 
 
2203
                pstmt = FetchPreparedStatement(stmt_name, true);
 
2204
                psrc = pstmt->plansource;
 
2205
        }
 
2206
        else
 
2207
        {
 
2208
                /* special-case the unnamed statement */
 
2209
                psrc = unnamed_stmt_psrc;
 
2210
                if (!psrc)
 
2211
                        ereport(ERROR,
 
2212
                                        (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
 
2213
                                         errmsg("unnamed prepared statement does not exist")));
 
2214
        }
 
2215
 
 
2216
        /* Prepared statements shouldn't have changeable result descs */
 
2217
        Assert(psrc->fixed_result);
 
2218
 
 
2219
        /*
 
2220
         * If we are in aborted transaction state, we can't run
 
2221
         * SendRowDescriptionMessage(), because that needs catalog accesses. (We
 
2222
         * can't do RevalidateCachedPlan, either, but that's a lesser problem.)
 
2223
         * Hence, refuse to Describe statements that return data.  (We shouldn't
 
2224
         * just refuse all Describes, since that might break the ability of some
 
2225
         * clients to issue COMMIT or ROLLBACK commands, if they use code that
 
2226
         * blindly Describes whatever it does.)  We can Describe parameters
 
2227
         * without doing anything dangerous, so we don't restrict that.
 
2228
         */
 
2229
        if (IsAbortedTransactionBlockState() &&
 
2230
                psrc->resultDesc)
 
2231
                ereport(ERROR,
 
2232
                                (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
2233
                                 errmsg("current transaction is aborted, "
 
2234
                                                "commands ignored until end of transaction block")));
 
2235
 
 
2236
        if (whereToSendOutput != DestRemote)
 
2237
                return;                                 /* can't actually do anything... */
 
2238
 
 
2239
        /*
 
2240
         * First describe the parameters...
 
2241
         */
 
2242
        pq_beginmessage(&buf, 't'); /* parameter description message type */
 
2243
        pq_sendint(&buf, psrc->num_params, 2);
 
2244
 
 
2245
        for (i = 0; i < psrc->num_params; i++)
 
2246
        {
 
2247
                Oid                     ptype = psrc->param_types[i];
 
2248
 
 
2249
                pq_sendint(&buf, (int) ptype, 4);
 
2250
        }
 
2251
        pq_endmessage(&buf);
 
2252
 
 
2253
        /*
 
2254
         * Next send RowDescription or NoData to describe the result...
 
2255
         */
 
2256
        if (psrc->resultDesc)
 
2257
        {
 
2258
                CachedPlan *cplan;
 
2259
                List       *tlist;
 
2260
 
 
2261
                /* Make sure the plan is up to date */
 
2262
                cplan = RevalidateCachedPlan(psrc, true);
 
2263
 
 
2264
                /* Get the primary statement and find out what it returns */
 
2265
                tlist = FetchStatementTargetList(PortalListGetPrimaryStmt(cplan->stmt_list));
 
2266
 
 
2267
                SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
 
2268
 
 
2269
                ReleaseCachedPlan(cplan, true);
 
2270
        }
 
2271
        else
 
2272
                pq_putemptymessage('n');        /* NoData */
 
2273
 
 
2274
}
 
2275
 
 
2276
/*
 
2277
 * exec_describe_portal_message
 
2278
 *
 
2279
 * Process a "Describe" message for a portal
 
2280
 */
 
2281
static void
 
2282
exec_describe_portal_message(const char *portal_name)
 
2283
{
 
2284
        Portal          portal;
 
2285
 
 
2286
        /*
 
2287
         * Start up a transaction command. (Note that this will normally change
 
2288
         * current memory context.) Nothing happens if we are already in one.
 
2289
         */
 
2290
        start_xact_command();
 
2291
 
 
2292
        /* Switch back to message context */
 
2293
        MemoryContextSwitchTo(MessageContext);
 
2294
 
 
2295
        portal = GetPortalByName(portal_name);
 
2296
        if (!PortalIsValid(portal))
 
2297
                ereport(ERROR,
 
2298
                                (errcode(ERRCODE_UNDEFINED_CURSOR),
 
2299
                                 errmsg("portal \"%s\" does not exist", portal_name)));
 
2300
 
 
2301
        /*
 
2302
         * If we are in aborted transaction state, we can't run
 
2303
         * SendRowDescriptionMessage(), because that needs catalog accesses.
 
2304
         * Hence, refuse to Describe portals that return data.  (We shouldn't just
 
2305
         * refuse all Describes, since that might break the ability of some
 
2306
         * clients to issue COMMIT or ROLLBACK commands, if they use code that
 
2307
         * blindly Describes whatever it does.)
 
2308
         */
 
2309
        if (IsAbortedTransactionBlockState() &&
 
2310
                portal->tupDesc)
 
2311
                ereport(ERROR,
 
2312
                                (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
 
2313
                                 errmsg("current transaction is aborted, "
 
2314
                                                "commands ignored until end of transaction block")));
 
2315
 
 
2316
        if (whereToSendOutput != DestRemote)
 
2317
                return;                                 /* can't actually do anything... */
 
2318
 
 
2319
        if (portal->tupDesc)
 
2320
                SendRowDescriptionMessage(portal->tupDesc,
 
2321
                                                                  FetchPortalTargetList(portal),
 
2322
                                                                  portal->formats);
 
2323
        else
 
2324
                pq_putemptymessage('n');        /* NoData */
 
2325
}
 
2326
 
 
2327
 
 
2328
/*
 
2329
 * Convenience routines for starting/committing a single command.
 
2330
 */
 
2331
static void
 
2332
start_xact_command(void)
 
2333
{
 
2334
        if (!xact_started)
 
2335
        {
 
2336
                ereport(DEBUG3,
 
2337
                                (errmsg_internal("StartTransactionCommand")));
 
2338
                StartTransactionCommand();
 
2339
 
 
2340
                /* Set statement timeout running, if any */
 
2341
                /* NB: this mustn't be enabled until we are within an xact */
 
2342
                if (StatementTimeout > 0)
 
2343
                        enable_sig_alarm(StatementTimeout, true);
 
2344
                else
 
2345
                        cancel_from_timeout = false;
 
2346
 
 
2347
                xact_started = true;
 
2348
        }
 
2349
}
 
2350
 
 
2351
static void
 
2352
finish_xact_command(void)
 
2353
{
 
2354
        if (xact_started)
 
2355
        {
 
2356
                /* Cancel any active statement timeout before committing */
 
2357
                disable_sig_alarm(true);
 
2358
 
 
2359
                /* Now commit the command */
 
2360
                ereport(DEBUG3,
 
2361
                                (errmsg_internal("CommitTransactionCommand")));
 
2362
 
 
2363
                CommitTransactionCommand();
 
2364
 
 
2365
#ifdef MEMORY_CONTEXT_CHECKING
 
2366
                /* Check all memory contexts that weren't freed during commit */
 
2367
                /* (those that were, were checked before being deleted) */
 
2368
                MemoryContextCheck(TopMemoryContext);
 
2369
#endif
 
2370
 
 
2371
#ifdef SHOW_MEMORY_STATS
 
2372
                /* Print mem stats after each commit for leak tracking */
 
2373
                MemoryContextStats(TopMemoryContext);
 
2374
#endif
 
2375
 
 
2376
                xact_started = false;
 
2377
        }
 
2378
}
 
2379
 
 
2380
 
 
2381
/*
 
2382
 * Convenience routines for checking whether a statement is one of the
 
2383
 * ones that we allow in transaction-aborted state.
 
2384
 */
 
2385
 
 
2386
/* Test a bare parsetree */
 
2387
static bool
 
2388
IsTransactionExitStmt(Node *parsetree)
 
2389
{
 
2390
        if (parsetree && IsA(parsetree, TransactionStmt))
 
2391
        {
 
2392
                TransactionStmt *stmt = (TransactionStmt *) parsetree;
 
2393
 
 
2394
                if (stmt->kind == TRANS_STMT_COMMIT ||
 
2395
                        stmt->kind == TRANS_STMT_PREPARE ||
 
2396
                        stmt->kind == TRANS_STMT_ROLLBACK ||
 
2397
                        stmt->kind == TRANS_STMT_ROLLBACK_TO)
 
2398
                        return true;
 
2399
        }
 
2400
        return false;
 
2401
}
 
2402
 
 
2403
/* Test a list that might contain Query nodes or bare parsetrees */
 
2404
static bool
 
2405
IsTransactionExitStmtList(List *parseTrees)
 
2406
{
 
2407
        if (list_length(parseTrees) == 1)
 
2408
        {
 
2409
                Node       *stmt = (Node *) linitial(parseTrees);
 
2410
 
 
2411
                if (IsA(stmt, Query))
 
2412
                {
 
2413
                        Query      *query = (Query *) stmt;
 
2414
 
 
2415
                        if (query->commandType == CMD_UTILITY &&
 
2416
                                IsTransactionExitStmt(query->utilityStmt))
 
2417
                                return true;
 
2418
                }
 
2419
                else if (IsTransactionExitStmt(stmt))
 
2420
                        return true;
 
2421
        }
 
2422
        return false;
 
2423
}
 
2424
 
 
2425
/* Test a list that might contain Query nodes or bare parsetrees */
 
2426
static bool
 
2427
IsTransactionStmtList(List *parseTrees)
 
2428
{
 
2429
        if (list_length(parseTrees) == 1)
 
2430
        {
 
2431
                Node       *stmt = (Node *) linitial(parseTrees);
 
2432
 
 
2433
                if (IsA(stmt, Query))
 
2434
                {
 
2435
                        Query      *query = (Query *) stmt;
 
2436
 
 
2437
                        if (query->commandType == CMD_UTILITY &&
 
2438
                                IsA(query->utilityStmt, TransactionStmt))
 
2439
                                return true;
 
2440
                }
 
2441
                else if (IsA(stmt, TransactionStmt))
 
2442
                        return true;
 
2443
        }
 
2444
        return false;
 
2445
}
 
2446
 
 
2447
/* Release any existing unnamed prepared statement */
 
2448
static void
 
2449
drop_unnamed_stmt(void)
 
2450
{
 
2451
        /* Release any completed unnamed statement */
 
2452
        if (unnamed_stmt_psrc)
 
2453
                DropCachedPlan(unnamed_stmt_psrc);
 
2454
        unnamed_stmt_psrc = NULL;
 
2455
 
 
2456
        /*
 
2457
         * If we failed while trying to build a prior unnamed statement, we may
 
2458
         * have a memory context that wasn't assigned to a completed plancache
 
2459
         * entry.  If so, drop it to avoid a permanent memory leak.
 
2460
         */
 
2461
        if (unnamed_stmt_context)
 
2462
                MemoryContextDelete(unnamed_stmt_context);
 
2463
        unnamed_stmt_context = NULL;
 
2464
}
 
2465
 
 
2466
 
 
2467
/* --------------------------------
 
2468
 *              signal handler routines used in PostgresMain()
 
2469
 * --------------------------------
 
2470
 */
 
2471
 
 
2472
/*
 
2473
 * quickdie() occurs when signalled SIGQUIT by the postmaster.
 
2474
 *
 
2475
 * Some backend has bought the farm,
 
2476
 * so we need to stop what we're doing and exit.
 
2477
 */
 
2478
void
 
2479
quickdie(SIGNAL_ARGS)
 
2480
{
 
2481
        PG_SETMASK(&BlockSig);
 
2482
 
 
2483
        /*
 
2484
         * Ideally this should be ereport(FATAL), but then we'd not get control
 
2485
         * back...
 
2486
         */
 
2487
        ereport(WARNING,
 
2488
                        (errcode(ERRCODE_CRASH_SHUTDOWN),
 
2489
                         errmsg("terminating connection because of crash of another server process"),
 
2490
        errdetail("The postmaster has commanded this server process to roll back"
 
2491
                          " the current transaction and exit, because another"
 
2492
                          " server process exited abnormally and possibly corrupted"
 
2493
                          " shared memory."),
 
2494
                         errhint("In a moment you should be able to reconnect to the"
 
2495
                                         " database and repeat your command.")));
 
2496
 
 
2497
        /*
 
2498
         * DO NOT proc_exit() -- we're here because shared memory may be
 
2499
         * corrupted, so we don't want to try to clean up our transaction. Just
 
2500
         * nail the windows shut and get out of town.
 
2501
         *
 
2502
         * Note we do exit(2) not exit(0).      This is to force the postmaster into a
 
2503
         * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
 
2504
         * backend.  This is necessary precisely because we don't clean up our
 
2505
         * shared memory state.
 
2506
         */
 
2507
        exit(2);
 
2508
}
 
2509
 
 
2510
/*
 
2511
 * Shutdown signal from postmaster: abort transaction and exit
 
2512
 * at soonest convenient time
 
2513
 */
 
2514
void
 
2515
die(SIGNAL_ARGS)
 
2516
{
 
2517
        int                     save_errno = errno;
 
2518
 
 
2519
        /* Don't joggle the elbow of proc_exit */
 
2520
        if (!proc_exit_inprogress)
 
2521
        {
 
2522
                InterruptPending = true;
 
2523
                ProcDiePending = true;
 
2524
 
 
2525
                /*
 
2526
                 * If it's safe to interrupt, and we're waiting for input or a lock,
 
2527
                 * service the interrupt immediately
 
2528
                 */
 
2529
                if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
 
2530
                        CritSectionCount == 0)
 
2531
                {
 
2532
                        /* bump holdoff count to make ProcessInterrupts() a no-op */
 
2533
                        /* until we are done getting ready for it */
 
2534
                        InterruptHoldoffCount++;
 
2535
                        LockWaitCancel();       /* prevent CheckDeadLock from running */
 
2536
                        DisableNotifyInterrupt();
 
2537
                        DisableCatchupInterrupt();
 
2538
                        InterruptHoldoffCount--;
 
2539
                        ProcessInterrupts();
 
2540
                }
 
2541
        }
 
2542
 
 
2543
        errno = save_errno;
 
2544
}
 
2545
 
 
2546
/*
 
2547
 * Timeout or shutdown signal from postmaster during client authentication.
 
2548
 * Simply exit(1).
 
2549
 *
 
2550
 * XXX: possible future improvement: try to send a message indicating
 
2551
 * why we are disconnecting.  Problem is to be sure we don't block while
 
2552
 * doing so, nor mess up the authentication message exchange.
 
2553
 */
 
2554
void
 
2555
authdie(SIGNAL_ARGS)
 
2556
{
 
2557
        exit(1);
 
2558
}
 
2559
 
 
2560
/*
 
2561
 * Query-cancel signal from postmaster: abort current transaction
 
2562
 * at soonest convenient time
 
2563
 */
 
2564
void
 
2565
StatementCancelHandler(SIGNAL_ARGS)
 
2566
{
 
2567
        int                     save_errno = errno;
 
2568
 
 
2569
        /*
 
2570
         * Don't joggle the elbow of proc_exit
 
2571
         */
 
2572
        if (!proc_exit_inprogress)
 
2573
        {
 
2574
                InterruptPending = true;
 
2575
                QueryCancelPending = true;
 
2576
 
 
2577
                /*
 
2578
                 * If it's safe to interrupt, and we're waiting for a lock, service
 
2579
                 * the interrupt immediately.  No point in interrupting if we're
 
2580
                 * waiting for input, however.
 
2581
                 */
 
2582
                if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
 
2583
                        CritSectionCount == 0 && !DoingCommandRead)
 
2584
                {
 
2585
                        /* bump holdoff count to make ProcessInterrupts() a no-op */
 
2586
                        /* until we are done getting ready for it */
 
2587
                        InterruptHoldoffCount++;
 
2588
                        LockWaitCancel();       /* prevent CheckDeadLock from running */
 
2589
                        DisableNotifyInterrupt();
 
2590
                        DisableCatchupInterrupt();
 
2591
                        InterruptHoldoffCount--;
 
2592
                        ProcessInterrupts();
 
2593
                }
 
2594
        }
 
2595
 
 
2596
        errno = save_errno;
 
2597
}
 
2598
 
 
2599
/* signal handler for floating point exception */
 
2600
void
 
2601
FloatExceptionHandler(SIGNAL_ARGS)
 
2602
{
 
2603
        ereport(ERROR,
 
2604
                        (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
 
2605
                         errmsg("floating-point exception"),
 
2606
                         errdetail("An invalid floating-point operation was signaled. "
 
2607
                                           "This probably means an out-of-range result or an "
 
2608
                                           "invalid operation, such as division by zero.")));
 
2609
}
 
2610
 
 
2611
/* SIGHUP: set flag to re-read config file at next convenient time */
 
2612
static void
 
2613
SigHupHandler(SIGNAL_ARGS)
 
2614
{
 
2615
        got_SIGHUP = true;
 
2616
}
 
2617
 
 
2618
 
 
2619
/*
 
2620
 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
 
2621
 *
 
2622
 * If an interrupt condition is pending, and it's safe to service it,
 
2623
 * then clear the flag and accept the interrupt.  Called only when
 
2624
 * InterruptPending is true.
 
2625
 */
 
2626
void
 
2627
ProcessInterrupts(void)
 
2628
{
 
2629
        /* OK to accept interrupt now? */
 
2630
        if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
 
2631
                return;
 
2632
        InterruptPending = false;
 
2633
        if (ProcDiePending)
 
2634
        {
 
2635
                ProcDiePending = false;
 
2636
                QueryCancelPending = false;             /* ProcDie trumps QueryCancel */
 
2637
                ImmediateInterruptOK = false;   /* not idle anymore */
 
2638
                DisableNotifyInterrupt();
 
2639
                DisableCatchupInterrupt();
 
2640
                if (IsAutoVacuumWorkerProcess())
 
2641
                        ereport(FATAL,
 
2642
                                        (errcode(ERRCODE_ADMIN_SHUTDOWN),
 
2643
                                         errmsg("terminating autovacuum process due to administrator command")));
 
2644
                else
 
2645
                        ereport(FATAL,
 
2646
                                        (errcode(ERRCODE_ADMIN_SHUTDOWN),
 
2647
                         errmsg("terminating connection due to administrator command")));
 
2648
        }
 
2649
        if (QueryCancelPending)
 
2650
        {
 
2651
                QueryCancelPending = false;
 
2652
                ImmediateInterruptOK = false;   /* not idle anymore */
 
2653
                DisableNotifyInterrupt();
 
2654
                DisableCatchupInterrupt();
 
2655
                if (cancel_from_timeout)
 
2656
                        ereport(ERROR,
 
2657
                                        (errcode(ERRCODE_QUERY_CANCELED),
 
2658
                                         errmsg("canceling statement due to statement timeout")));
 
2659
                else if (IsAutoVacuumWorkerProcess())
 
2660
                        ereport(ERROR,
 
2661
                                        (errcode(ERRCODE_QUERY_CANCELED),
 
2662
                                         errmsg("canceling autovacuum task")));
 
2663
                else
 
2664
                        ereport(ERROR,
 
2665
                                        (errcode(ERRCODE_QUERY_CANCELED),
 
2666
                                         errmsg("canceling statement due to user request")));
 
2667
        }
 
2668
        /* If we get here, do nothing (probably, QueryCancelPending was reset) */
 
2669
}
 
2670
 
 
2671
 
 
2672
/*
 
2673
 * check_stack_depth: check for excessively deep recursion
 
2674
 *
 
2675
 * This should be called someplace in any recursive routine that might possibly
 
2676
 * recurse deep enough to overflow the stack.  Most Unixen treat stack
 
2677
 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
 
2678
 * before hitting the hardware limit.
 
2679
 */
 
2680
void
 
2681
check_stack_depth(void)
 
2682
{
 
2683
        char            stack_top_loc;
 
2684
        long            stack_depth;
 
2685
 
 
2686
        /*
 
2687
         * Compute distance from PostgresMain's local variables to my own
 
2688
         */
 
2689
        stack_depth = (long) (stack_base_ptr - &stack_top_loc);
 
2690
 
 
2691
        /*
 
2692
         * Take abs value, since stacks grow up on some machines, down on others
 
2693
         */
 
2694
        if (stack_depth < 0)
 
2695
                stack_depth = -stack_depth;
 
2696
 
 
2697
        /*
 
2698
         * Trouble?
 
2699
         *
 
2700
         * The test on stack_base_ptr prevents us from erroring out if called
 
2701
         * during process setup or in a non-backend process.  Logically it should
 
2702
         * be done first, but putting it here avoids wasting cycles during normal
 
2703
         * cases.
 
2704
         */
 
2705
        if (stack_depth > max_stack_depth_bytes &&
 
2706
                stack_base_ptr != NULL)
 
2707
        {
 
2708
                ereport(ERROR,
 
2709
                                (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
 
2710
                                 errmsg("stack depth limit exceeded"),
 
2711
                 errhint("Increase the configuration parameter \"max_stack_depth\", "
 
2712
                   "after ensuring the platform's stack depth limit is adequate.")));
 
2713
        }
 
2714
}
 
2715
 
 
2716
/* GUC assign hook for max_stack_depth */
 
2717
bool
 
2718
assign_max_stack_depth(int newval, bool doit, GucSource source)
 
2719
{
 
2720
        long            newval_bytes = newval * 1024L;
 
2721
        long            stack_rlimit = get_stack_depth_rlimit();
 
2722
 
 
2723
        if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
 
2724
        {
 
2725
                ereport(GUC_complaint_elevel(source),
 
2726
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
2727
                                 errmsg("\"max_stack_depth\" must not exceed %ldkB",
 
2728
                                                (stack_rlimit - STACK_DEPTH_SLOP) / 1024L),
 
2729
                                 errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.")));
 
2730
                return false;
 
2731
        }
 
2732
        if (doit)
 
2733
                max_stack_depth_bytes = newval_bytes;
 
2734
        return true;
 
2735
}
 
2736
 
 
2737
 
 
2738
/*
 
2739
 * set_debug_options --- apply "-d N" command line option
 
2740
 *
 
2741
 * -d is not quite the same as setting log_min_messages because it enables
 
2742
 * other output options.
 
2743
 */
 
2744
void
 
2745
set_debug_options(int debug_flag, GucContext context, GucSource source)
 
2746
{
 
2747
        if (debug_flag > 0)
 
2748
        {
 
2749
                char            debugstr[64];
 
2750
 
 
2751
                sprintf(debugstr, "debug%d", debug_flag);
 
2752
                SetConfigOption("log_min_messages", debugstr, context, source);
 
2753
        }
 
2754
        else
 
2755
                SetConfigOption("log_min_messages", "notice", context, source);
 
2756
 
 
2757
        if (debug_flag >= 1 && context == PGC_POSTMASTER)
 
2758
        {
 
2759
                SetConfigOption("log_connections", "true", context, source);
 
2760
                SetConfigOption("log_disconnections", "true", context, source);
 
2761
        }
 
2762
        if (debug_flag >= 2)
 
2763
                SetConfigOption("log_statement", "all", context, source);
 
2764
        if (debug_flag >= 3)
 
2765
                SetConfigOption("debug_print_parse", "true", context, source);
 
2766
        if (debug_flag >= 4)
 
2767
                SetConfigOption("debug_print_plan", "true", context, source);
 
2768
        if (debug_flag >= 5)
 
2769
                SetConfigOption("debug_print_rewritten", "true", context, source);
 
2770
}
 
2771
 
 
2772
 
 
2773
bool
 
2774
set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
 
2775
{
 
2776
        char       *tmp = NULL;
 
2777
 
 
2778
        switch (arg[0])
 
2779
        {
 
2780
                case 's':                               /* seqscan */
 
2781
                        tmp = "enable_seqscan";
 
2782
                        break;
 
2783
                case 'i':                               /* indexscan */
 
2784
                        tmp = "enable_indexscan";
 
2785
                        break;
 
2786
                case 'b':                               /* bitmapscan */
 
2787
                        tmp = "enable_bitmapscan";
 
2788
                        break;
 
2789
                case 't':                               /* tidscan */
 
2790
                        tmp = "enable_tidscan";
 
2791
                        break;
 
2792
                case 'n':                               /* nestloop */
 
2793
                        tmp = "enable_nestloop";
 
2794
                        break;
 
2795
                case 'm':                               /* mergejoin */
 
2796
                        tmp = "enable_mergejoin";
 
2797
                        break;
 
2798
                case 'h':                               /* hashjoin */
 
2799
                        tmp = "enable_hashjoin";
 
2800
                        break;
 
2801
        }
 
2802
        if (tmp)
 
2803
        {
 
2804
                SetConfigOption(tmp, "false", context, source);
 
2805
                return true;
 
2806
        }
 
2807
        else
 
2808
                return false;
 
2809
}
 
2810
 
 
2811
 
 
2812
const char *
 
2813
get_stats_option_name(const char *arg)
 
2814
{
 
2815
        switch (arg[0])
 
2816
        {
 
2817
                case 'p':
 
2818
                        if (optarg[1] == 'a')           /* "parser" */
 
2819
                                return "log_parser_stats";
 
2820
                        else if (optarg[1] == 'l')      /* "planner" */
 
2821
                                return "log_planner_stats";
 
2822
                        break;
 
2823
 
 
2824
                case 'e':                               /* "executor" */
 
2825
                        return "log_executor_stats";
 
2826
                        break;
 
2827
        }
 
2828
 
 
2829
        return NULL;
 
2830
}
 
2831
 
 
2832
 
 
2833
/* ----------------------------------------------------------------
 
2834
 * PostgresMain
 
2835
 *         postgres main loop -- all backends, interactive or otherwise start here
 
2836
 *
 
2837
 * argc/argv are the command line arguments to be used.  (When being forked
 
2838
 * by the postmaster, these are not the original argv array of the process.)
 
2839
 * username is the (possibly authenticated) PostgreSQL user name to be used
 
2840
 * for the session.
 
2841
 * ----------------------------------------------------------------
 
2842
 */
 
2843
int
 
2844
PostgresMain(int argc, char *argv[], const char *username)
 
2845
{
 
2846
        int                     flag;
 
2847
        const char *dbname = NULL;
 
2848
        char       *userDoption = NULL;
 
2849
        bool            secure;
 
2850
        int                     errs = 0;
 
2851
        int                     debug_flag = -1;        /* -1 means not given */
 
2852
        List       *guc_names = NIL;    /* for SUSET options */
 
2853
        List       *guc_values = NIL;
 
2854
        GucContext      ctx;
 
2855
        GucSource       gucsource;
 
2856
        bool            am_superuser;
 
2857
        int                     firstchar;
 
2858
        char            stack_base;
 
2859
        StringInfoData input_message;
 
2860
        sigjmp_buf      local_sigjmp_buf;
 
2861
        volatile bool send_ready_for_query = true;
 
2862
 
 
2863
#define PendingConfigOption(name,val) \
 
2864
        (guc_names = lappend(guc_names, pstrdup(name)), \
 
2865
         guc_values = lappend(guc_values, pstrdup(val)))
 
2866
 
 
2867
        /*
 
2868
         * initialize globals (already done if under postmaster, but not if
 
2869
         * standalone; cheap enough to do over)
 
2870
         */
 
2871
        MyProcPid = getpid();
 
2872
 
 
2873
        MyStartTime = time(NULL);
 
2874
 
 
2875
        /*
 
2876
         * Fire up essential subsystems: error and memory management
 
2877
         *
 
2878
         * If we are running under the postmaster, this is done already.
 
2879
         */
 
2880
        if (!IsUnderPostmaster)
 
2881
                MemoryContextInit();
 
2882
 
 
2883
        set_ps_display("startup", false);
 
2884
 
 
2885
        SetProcessingMode(InitProcessing);
 
2886
 
 
2887
        /* Set up reference point for stack depth checking */
 
2888
        stack_base_ptr = &stack_base;
 
2889
 
 
2890
        /* Compute paths, if we didn't inherit them from postmaster */
 
2891
        if (my_exec_path[0] == '\0')
 
2892
        {
 
2893
                if (find_my_exec(argv[0], my_exec_path) < 0)
 
2894
                        elog(FATAL, "%s: could not locate my own executable path",
 
2895
                                 argv[0]);
 
2896
        }
 
2897
 
 
2898
        if (pkglib_path[0] == '\0')
 
2899
                get_pkglib_path(my_exec_path, pkglib_path);
 
2900
 
 
2901
        /*
 
2902
         * Set default values for command-line options.
 
2903
         */
 
2904
        EchoQuery = false;
 
2905
 
 
2906
        if (!IsUnderPostmaster)
 
2907
                InitializeGUCOptions();
 
2908
 
 
2909
        /* ----------------
 
2910
         *      parse command line arguments
 
2911
         *
 
2912
         *      There are now two styles of command line layout for the backend:
 
2913
         *
 
2914
         *      For interactive use (not started from postmaster) the format is
 
2915
         *              postgres [switches] [databasename]
 
2916
         *      If the databasename is omitted it is taken to be the user name.
 
2917
         *
 
2918
         *      When started from the postmaster, the format is
 
2919
         *              postgres [secure switches] -p databasename [insecure switches]
 
2920
         *      Switches appearing after -p came from the client (via "options"
 
2921
         *      field of connection request).  For security reasons we restrict
 
2922
         *      what these switches can do.
 
2923
         * ----------------
 
2924
         */
 
2925
 
 
2926
        /* Ignore the initial --single argument, if present */
 
2927
        if (argc > 1 && strcmp(argv[1], "--single") == 0)
 
2928
        {
 
2929
                argv++;
 
2930
                argc--;
 
2931
        }
 
2932
 
 
2933
        /* all options are allowed until '-p' */
 
2934
        secure = true;
 
2935
        ctx = PGC_POSTMASTER;
 
2936
        gucsource = PGC_S_ARGV;         /* initial switches came from command line */
 
2937
 
 
2938
        /*
 
2939
         * Parse command-line options.  CAUTION: keep this in sync with
 
2940
         * postmaster/postmaster.c (the option sets should not conflict) and with
 
2941
         * the common help() function in main/main.c.
 
2942
         */
 
2943
        while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
 
2944
        {
 
2945
                switch (flag)
 
2946
                {
 
2947
                        case 'A':
 
2948
                                SetConfigOption("debug_assertions", optarg, ctx, gucsource);
 
2949
                                break;
 
2950
 
 
2951
                        case 'B':
 
2952
                                SetConfigOption("shared_buffers", optarg, ctx, gucsource);
 
2953
                                break;
 
2954
 
 
2955
                        case 'D':
 
2956
                                if (secure)
 
2957
                                        userDoption = optarg;
 
2958
                                break;
 
2959
 
 
2960
                        case 'd':
 
2961
                                debug_flag = atoi(optarg);
 
2962
                                break;
 
2963
 
 
2964
                        case 'E':
 
2965
                                EchoQuery = true;
 
2966
                                break;
 
2967
 
 
2968
                        case 'e':
 
2969
                                SetConfigOption("datestyle", "euro", ctx, gucsource);
 
2970
                                break;
 
2971
 
 
2972
                        case 'F':
 
2973
                                SetConfigOption("fsync", "false", ctx, gucsource);
 
2974
                                break;
 
2975
 
 
2976
                        case 'f':
 
2977
                                if (!set_plan_disabling_options(optarg, ctx, gucsource))
 
2978
                                        errs++;
 
2979
                                break;
 
2980
 
 
2981
                        case 'h':
 
2982
                                SetConfigOption("listen_addresses", optarg, ctx, gucsource);
 
2983
                                break;
 
2984
 
 
2985
                        case 'i':
 
2986
                                SetConfigOption("listen_addresses", "*", ctx, gucsource);
 
2987
                                break;
 
2988
 
 
2989
                        case 'j':
 
2990
                                UseNewLine = 0;
 
2991
                                break;
 
2992
 
 
2993
                        case 'k':
 
2994
                                SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
 
2995
                                break;
 
2996
 
 
2997
                        case 'l':
 
2998
                                SetConfigOption("ssl", "true", ctx, gucsource);
 
2999
                                break;
 
3000
 
 
3001
                        case 'N':
 
3002
                                SetConfigOption("max_connections", optarg, ctx, gucsource);
 
3003
                                break;
 
3004
 
 
3005
                        case 'n':
 
3006
                                /* ignored for consistency with postmaster */
 
3007
                                break;
 
3008
 
 
3009
                        case 'O':
 
3010
                                SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
 
3011
                                break;
 
3012
 
 
3013
                        case 'o':
 
3014
                                errs++;
 
3015
                                break;
 
3016
 
 
3017
                        case 'P':
 
3018
                                SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
 
3019
                                break;
 
3020
 
 
3021
                        case 'p':
 
3022
                                SetConfigOption("port", optarg, ctx, gucsource);
 
3023
                                break;
 
3024
 
 
3025
                        case 'r':
 
3026
                                /* send output (stdout and stderr) to the given file */
 
3027
                                if (secure)
 
3028
                                        strlcpy(OutputFileName, optarg, MAXPGPATH);
 
3029
                                break;
 
3030
 
 
3031
                        case 'S':
 
3032
                                SetConfigOption("work_mem", optarg, ctx, gucsource);
 
3033
                                break;
 
3034
 
 
3035
                        case 's':
 
3036
 
 
3037
                                /*
 
3038
                                 * Since log options are SUSET, we need to postpone unless
 
3039
                                 * still in secure context
 
3040
                                 */
 
3041
                                if (ctx == PGC_BACKEND)
 
3042
                                        PendingConfigOption("log_statement_stats", "true");
 
3043
                                else
 
3044
                                        SetConfigOption("log_statement_stats", "true",
 
3045
                                                                        ctx, gucsource);
 
3046
                                break;
 
3047
 
 
3048
                        case 'T':
 
3049
                                /* ignored for consistency with postmaster */
 
3050
                                break;
 
3051
 
 
3052
                        case 't':
 
3053
                                {
 
3054
                                        const char *tmp = get_stats_option_name(optarg);
 
3055
 
 
3056
                                        if (tmp)
 
3057
                                        {
 
3058
                                                if (ctx == PGC_BACKEND)
 
3059
                                                        PendingConfigOption(tmp, "true");
 
3060
                                                else
 
3061
                                                        SetConfigOption(tmp, "true", ctx, gucsource);
 
3062
                                        }
 
3063
                                        else
 
3064
                                                errs++;
 
3065
                                        break;
 
3066
                                }
 
3067
 
 
3068
                        case 'v':
 
3069
                                if (secure)
 
3070
                                        FrontendProtocol = (ProtocolVersion) atoi(optarg);
 
3071
                                break;
 
3072
 
 
3073
                        case 'W':
 
3074
                                SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
 
3075
                                break;
 
3076
 
 
3077
 
 
3078
                        case 'y':
 
3079
 
 
3080
                                /*
 
3081
                                 * y - special flag passed if backend was forked by a
 
3082
                                 * postmaster.
 
3083
                                 */
 
3084
                                if (secure)
 
3085
                                {
 
3086
                                        dbname = strdup(optarg);
 
3087
 
 
3088
                                        secure = false;         /* subsequent switches are NOT secure */
 
3089
                                        ctx = PGC_BACKEND;
 
3090
                                        gucsource = PGC_S_CLIENT;
 
3091
                                }
 
3092
                                break;
 
3093
 
 
3094
                        case 'c':
 
3095
                        case '-':
 
3096
                                {
 
3097
                                        char       *name,
 
3098
                                                           *value;
 
3099
 
 
3100
                                        ParseLongOption(optarg, &name, &value);
 
3101
                                        if (!value)
 
3102
                                        {
 
3103
                                                if (flag == '-')
 
3104
                                                        ereport(ERROR,
 
3105
                                                                        (errcode(ERRCODE_SYNTAX_ERROR),
 
3106
                                                                         errmsg("--%s requires a value",
 
3107
                                                                                        optarg)));
 
3108
                                                else
 
3109
                                                        ereport(ERROR,
 
3110
                                                                        (errcode(ERRCODE_SYNTAX_ERROR),
 
3111
                                                                         errmsg("-c %s requires a value",
 
3112
                                                                                        optarg)));
 
3113
                                        }
 
3114
 
 
3115
                                        /*
 
3116
                                         * If a SUSET option, must postpone evaluation, unless we
 
3117
                                         * are still reading secure switches.
 
3118
                                         */
 
3119
                                        if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
 
3120
                                                PendingConfigOption(name, value);
 
3121
                                        else
 
3122
                                                SetConfigOption(name, value, ctx, gucsource);
 
3123
                                        free(name);
 
3124
                                        if (value)
 
3125
                                                free(value);
 
3126
                                        break;
 
3127
                                }
 
3128
 
 
3129
                        default:
 
3130
                                errs++;
 
3131
                                break;
 
3132
                }
 
3133
        }
 
3134
 
 
3135
        /*
 
3136
         * Process any additional GUC variable settings passed in startup packet.
 
3137
         * These are handled exactly like command-line variables.
 
3138
         */
 
3139
        if (MyProcPort != NULL)
 
3140
        {
 
3141
                ListCell   *gucopts = list_head(MyProcPort->guc_options);
 
3142
 
 
3143
                while (gucopts)
 
3144
                {
 
3145
                        char       *name;
 
3146
                        char       *value;
 
3147
 
 
3148
                        name = lfirst(gucopts);
 
3149
                        gucopts = lnext(gucopts);
 
3150
 
 
3151
                        value = lfirst(gucopts);
 
3152
                        gucopts = lnext(gucopts);
 
3153
 
 
3154
                        if (IsSuperuserConfigOption(name))
 
3155
                                PendingConfigOption(name, value);
 
3156
                        else
 
3157
                                SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
 
3158
                }
 
3159
        }
 
3160
 
 
3161
        /* Acquire configuration parameters, unless inherited from postmaster */
 
3162
        if (!IsUnderPostmaster)
 
3163
        {
 
3164
                if (!SelectConfigFiles(userDoption, argv[0]))
 
3165
                        proc_exit(1);
 
3166
                /* If timezone is not set, determine what the OS uses */
 
3167
                pg_timezone_initialize();
 
3168
                /* If timezone_abbreviations is not set, select default */
 
3169
                pg_timezone_abbrev_initialize();
 
3170
        }
 
3171
 
 
3172
        if (PostAuthDelay)
 
3173
                pg_usleep(PostAuthDelay * 1000000L);
 
3174
 
 
3175
        /*
 
3176
         * You might expect to see a setsid() call here, but it's not needed,
 
3177
         * because if we are under a postmaster then BackendInitialize() did it.
 
3178
         */
 
3179
 
 
3180
        /*
 
3181
         * Set up signal handlers and masks.
 
3182
         *
 
3183
         * Note that postmaster blocked all signals before forking child process,
 
3184
         * so there is no race condition whereby we might receive a signal before
 
3185
         * we have set up the handler.
 
3186
         *
 
3187
         * Also note: it's best not to use any signals that are SIG_IGNored in the
 
3188
         * postmaster.  If such a signal arrives before we are able to change the
 
3189
         * handler to non-SIG_IGN, it'll get dropped.  Instead, make a dummy
 
3190
         * handler in the postmaster to reserve the signal. (Of course, this isn't
 
3191
         * an issue for signals that are locally generated, such as SIGALRM and
 
3192
         * SIGPIPE.)
 
3193
         */
 
3194
        pqsignal(SIGHUP, SigHupHandler);        /* set flag to read config file */
 
3195
        pqsignal(SIGINT, StatementCancelHandler);       /* cancel current query */
 
3196
        pqsignal(SIGTERM, die);         /* cancel current query and exit */
 
3197
 
 
3198
        /*
 
3199
         * In a standalone backend, SIGQUIT can be generated from the keyboard
 
3200
         * easily, while SIGTERM cannot, so we make both signals do die() rather
 
3201
         * than quickdie().
 
3202
         */
 
3203
        if (IsUnderPostmaster)
 
3204
                pqsignal(SIGQUIT, quickdie);    /* hard crash time */
 
3205
        else
 
3206
                pqsignal(SIGQUIT, die); /* cancel current query and exit */
 
3207
        pqsignal(SIGALRM, handle_sig_alarm);            /* timeout conditions */
 
3208
 
 
3209
        /*
 
3210
         * Ignore failure to write to frontend. Note: if frontend closes
 
3211
         * connection, we will notice it and exit cleanly when control next
 
3212
         * returns to outer loop.  This seems safer than forcing exit in the midst
 
3213
         * of output during who-knows-what operation...
 
3214
         */
 
3215
        pqsignal(SIGPIPE, SIG_IGN);
 
3216
        pqsignal(SIGUSR1, CatchupInterruptHandler);
 
3217
        pqsignal(SIGUSR2, NotifyInterruptHandler);
 
3218
        pqsignal(SIGFPE, FloatExceptionHandler);
 
3219
 
 
3220
        /*
 
3221
         * Reset some signals that are accepted by postmaster but not by backend
 
3222
         */
 
3223
        pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
 
3224
 
 
3225
        pqinitmask();
 
3226
 
 
3227
        if (IsUnderPostmaster)
 
3228
        {
 
3229
                /* We allow SIGQUIT (quickdie) at all times */
 
3230
#ifdef HAVE_SIGPROCMASK
 
3231
                sigdelset(&BlockSig, SIGQUIT);
 
3232
#else
 
3233
                BlockSig &= ~(sigmask(SIGQUIT));
 
3234
#endif
 
3235
        }
 
3236
 
 
3237
        PG_SETMASK(&BlockSig);          /* block everything except SIGQUIT */
 
3238
 
 
3239
        if (IsUnderPostmaster)
 
3240
        {
 
3241
                /* noninteractive case: nothing should be left after switches */
 
3242
                if (errs || argc != optind || dbname == NULL)
 
3243
                {
 
3244
                        ereport(FATAL,
 
3245
                                        (errcode(ERRCODE_SYNTAX_ERROR),
 
3246
                                 errmsg("invalid command-line arguments for server process"),
 
3247
                           errhint("Try \"%s --help\" for more information.", argv[0])));
 
3248
                }
 
3249
 
 
3250
                BaseInit();
 
3251
        }
 
3252
        else
 
3253
        {
 
3254
                /* interactive case: database name can be last arg on command line */
 
3255
                if (errs || argc - optind > 1)
 
3256
                {
 
3257
                        ereport(FATAL,
 
3258
                                        (errcode(ERRCODE_SYNTAX_ERROR),
 
3259
                                         errmsg("%s: invalid command-line arguments",
 
3260
                                                        argv[0]),
 
3261
                           errhint("Try \"%s --help\" for more information.", argv[0])));
 
3262
                }
 
3263
                else if (argc - optind == 1)
 
3264
                        dbname = argv[optind];
 
3265
                else if ((dbname = username) == NULL)
 
3266
                {
 
3267
                        ereport(FATAL,
 
3268
                                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
3269
                                         errmsg("%s: no database nor user name specified",
 
3270
                                                        argv[0])));
 
3271
                }
 
3272
 
 
3273
                /*
 
3274
                 * Validate we have been given a reasonable-looking DataDir (if under
 
3275
                 * postmaster, assume postmaster did this already).
 
3276
                 */
 
3277
                Assert(DataDir);
 
3278
                ValidatePgVersion(DataDir);
 
3279
 
 
3280
                /* Change into DataDir (if under postmaster, was done already) */
 
3281
                ChangeToDataDir();
 
3282
 
 
3283
                /*
 
3284
                 * Create lockfile for data directory.
 
3285
                 */
 
3286
                CreateDataDirLockFile(false);
 
3287
 
 
3288
                BaseInit();
 
3289
 
 
3290
                /*
 
3291
                 * Start up xlog for standalone backend, and register to have it
 
3292
                 * closed down at exit.
 
3293
                 */
 
3294
                StartupXLOG();
 
3295
                on_shmem_exit(ShutdownXLOG, 0);
 
3296
 
 
3297
                /*
 
3298
                 * We have to build the flat file for pg_database, but not for the
 
3299
                 * user and group tables, since we won't try to do authentication.
 
3300
                 */
 
3301
                BuildFlatFiles(true);
 
3302
        }
 
3303
 
 
3304
        /*
 
3305
         * Create a per-backend PGPROC struct in shared memory, except in the
 
3306
         * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
 
3307
         * this before we can use LWLocks (and in the EXEC_BACKEND case we already
 
3308
         * had to do some stuff with LWLocks).
 
3309
         */
 
3310
#ifdef EXEC_BACKEND
 
3311
        if (!IsUnderPostmaster)
 
3312
                InitProcess();
 
3313
#else
 
3314
        InitProcess();
 
3315
#endif
 
3316
 
 
3317
        /*
 
3318
         * General initialization.
 
3319
         *
 
3320
         * NOTE: if you are tempted to add code in this vicinity, consider putting
 
3321
         * it inside InitPostgres() instead.  In particular, anything that
 
3322
         * involves database access should be there, not here.
 
3323
         */
 
3324
        ereport(DEBUG3,
 
3325
                        (errmsg_internal("InitPostgres")));
 
3326
        am_superuser = InitPostgres(dbname, InvalidOid, username, NULL);
 
3327
 
 
3328
        SetProcessingMode(NormalProcessing);
 
3329
 
 
3330
        /*
 
3331
         * Now that we know if client is a superuser, we can try to apply SUSET
 
3332
         * GUC options that came from the client.
 
3333
         */
 
3334
        ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
 
3335
 
 
3336
        if (debug_flag >= 0)
 
3337
                set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
 
3338
 
 
3339
        if (guc_names != NIL)
 
3340
        {
 
3341
                ListCell   *namcell,
 
3342
                                   *valcell;
 
3343
 
 
3344
                forboth(namcell, guc_names, valcell, guc_values)
 
3345
                {
 
3346
                        char       *name = (char *) lfirst(namcell);
 
3347
                        char       *value = (char *) lfirst(valcell);
 
3348
 
 
3349
                        SetConfigOption(name, value, ctx, PGC_S_CLIENT);
 
3350
                        pfree(name);
 
3351
                        pfree(value);
 
3352
                }
 
3353
        }
 
3354
 
 
3355
        /*
 
3356
         * Now all GUC states are fully set up.  Report them to client if
 
3357
         * appropriate.
 
3358
         */
 
3359
        BeginReportingGUCOptions();
 
3360
 
 
3361
        /*
 
3362
         * Also set up handler to log session end; we have to wait till now to be
 
3363
         * sure Log_disconnections has its final value.
 
3364
         */
 
3365
        if (IsUnderPostmaster && Log_disconnections)
 
3366
                on_proc_exit(log_disconnections, 0);
 
3367
 
 
3368
        /*
 
3369
         * process any libraries that should be preloaded at backend start (this
 
3370
         * likewise can't be done until GUC settings are complete)
 
3371
         */
 
3372
        process_local_preload_libraries();
 
3373
 
 
3374
        /*
 
3375
         * Send this backend's cancellation info to the frontend.
 
3376
         */
 
3377
        if (whereToSendOutput == DestRemote &&
 
3378
                PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
 
3379
        {
 
3380
                StringInfoData buf;
 
3381
 
 
3382
                pq_beginmessage(&buf, 'K');
 
3383
                pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
 
3384
                pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
 
3385
                pq_endmessage(&buf);
 
3386
                /* Need not flush since ReadyForQuery will do it. */
 
3387
        }
 
3388
 
 
3389
        /* Welcome banner for standalone case */
 
3390
        if (whereToSendOutput == DestDebug)
 
3391
                printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
 
3392
 
 
3393
        /*
 
3394
         * Create the memory context we will use in the main loop.
 
3395
         *
 
3396
         * MessageContext is reset once per iteration of the main loop, ie, upon
 
3397
         * completion of processing of each command message from the client.
 
3398
         */
 
3399
        MessageContext = AllocSetContextCreate(TopMemoryContext,
 
3400
                                                                                   "MessageContext",
 
3401
                                                                                   ALLOCSET_DEFAULT_MINSIZE,
 
3402
                                                                                   ALLOCSET_DEFAULT_INITSIZE,
 
3403
                                                                                   ALLOCSET_DEFAULT_MAXSIZE);
 
3404
 
 
3405
        /*
 
3406
         * Remember stand-alone backend startup time
 
3407
         */
 
3408
        if (!IsUnderPostmaster)
 
3409
                PgStartTime = GetCurrentTimestamp();
 
3410
 
 
3411
        /*
 
3412
         * POSTGRES main processing loop begins here
 
3413
         *
 
3414
         * If an exception is encountered, processing resumes here so we abort the
 
3415
         * current transaction and start a new one.
 
3416
         *
 
3417
         * You might wonder why this isn't coded as an infinite loop around a
 
3418
         * PG_TRY construct.  The reason is that this is the bottom of the
 
3419
         * exception stack, and so with PG_TRY there would be no exception handler
 
3420
         * in force at all during the CATCH part.  By leaving the outermost setjmp
 
3421
         * always active, we have at least some chance of recovering from an error
 
3422
         * during error recovery.  (If we get into an infinite loop thereby, it
 
3423
         * will soon be stopped by overflow of elog.c's internal state stack.)
 
3424
         */
 
3425
 
 
3426
        if (sigsetjmp(local_sigjmp_buf, 1) != 0)
 
3427
        {
 
3428
                /*
 
3429
                 * NOTE: if you are tempted to add more code in this if-block,
 
3430
                 * consider the high probability that it should be in
 
3431
                 * AbortTransaction() instead.  The only stuff done directly here
 
3432
                 * should be stuff that is guaranteed to apply *only* for outer-level
 
3433
                 * error recovery, such as adjusting the FE/BE protocol status.
 
3434
                 */
 
3435
 
 
3436
                /* Since not using PG_TRY, must reset error stack by hand */
 
3437
                error_context_stack = NULL;
 
3438
 
 
3439
                /* Prevent interrupts while cleaning up */
 
3440
                HOLD_INTERRUPTS();
 
3441
 
 
3442
                /*
 
3443
                 * Forget any pending QueryCancel request, since we're returning to
 
3444
                 * the idle loop anyway, and cancel the statement timer if running.
 
3445
                 */
 
3446
                QueryCancelPending = false;
 
3447
                disable_sig_alarm(true);
 
3448
                QueryCancelPending = false;             /* again in case timeout occurred */
 
3449
 
 
3450
                /*
 
3451
                 * Turn off these interrupts too.  This is only needed here and not in
 
3452
                 * other exception-catching places since these interrupts are only
 
3453
                 * enabled while we wait for client input.
 
3454
                 */
 
3455
                DoingCommandRead = false;
 
3456
                DisableNotifyInterrupt();
 
3457
                DisableCatchupInterrupt();
 
3458
 
 
3459
                /* Make sure libpq is in a good state */
 
3460
                pq_comm_reset();
 
3461
 
 
3462
                /* Report the error to the client and/or server log */
 
3463
                EmitErrorReport();
 
3464
 
 
3465
                /*
 
3466
                 * Make sure debug_query_string gets reset before we possibly clobber
 
3467
                 * the storage it points at.
 
3468
                 */
 
3469
                debug_query_string = NULL;
 
3470
 
 
3471
                /*
 
3472
                 * Abort the current transaction in order to recover.
 
3473
                 */
 
3474
                AbortCurrentTransaction();
 
3475
 
 
3476
                /*
 
3477
                 * Now return to normal top-level context and clear ErrorContext for
 
3478
                 * next time.
 
3479
                 */
 
3480
                MemoryContextSwitchTo(TopMemoryContext);
 
3481
                FlushErrorState();
 
3482
 
 
3483
                /*
 
3484
                 * If we were handling an extended-query-protocol message, initiate
 
3485
                 * skip till next Sync.  This also causes us not to issue
 
3486
                 * ReadyForQuery (until we get Sync).
 
3487
                 */
 
3488
                if (doing_extended_query_message)
 
3489
                        ignore_till_sync = true;
 
3490
 
 
3491
                /* We don't have a transaction command open anymore */
 
3492
                xact_started = false;
 
3493
 
 
3494
                /* Now we can allow interrupts again */
 
3495
                RESUME_INTERRUPTS();
 
3496
        }
 
3497
 
 
3498
        /* We can now handle ereport(ERROR) */
 
3499
        PG_exception_stack = &local_sigjmp_buf;
 
3500
 
 
3501
        PG_SETMASK(&UnBlockSig);
 
3502
 
 
3503
        if (!ignore_till_sync)
 
3504
                send_ready_for_query = true;    /* initially, or after error */
 
3505
 
 
3506
        /*
 
3507
         * Non-error queries loop here.
 
3508
         */
 
3509
 
 
3510
        for (;;)
 
3511
        {
 
3512
                /*
 
3513
                 * At top of loop, reset extended-query-message flag, so that any
 
3514
                 * errors encountered in "idle" state don't provoke skip.
 
3515
                 */
 
3516
                doing_extended_query_message = false;
 
3517
 
 
3518
                /*
 
3519
                 * Release storage left over from prior query cycle, and create a new
 
3520
                 * query input buffer in the cleared MessageContext.
 
3521
                 */
 
3522
                MemoryContextSwitchTo(MessageContext);
 
3523
                MemoryContextResetAndDeleteChildren(MessageContext);
 
3524
 
 
3525
                initStringInfo(&input_message);
 
3526
 
 
3527
                /*
 
3528
                 * (1) If we've reached idle state, tell the frontend we're ready for
 
3529
                 * a new query.
 
3530
                 *
 
3531
                 * Note: this includes fflush()'ing the last of the prior output.
 
3532
                 *
 
3533
                 * This is also a good time to send collected statistics to the
 
3534
                 * collector, and to update the PS stats display.  We avoid doing
 
3535
                 * those every time through the message loop because it'd slow down
 
3536
                 * processing of batched messages, and because we don't want to report
 
3537
                 * uncommitted updates (that confuses autovacuum).
 
3538
                 */
 
3539
                if (send_ready_for_query)
 
3540
                {
 
3541
                        if (IsTransactionOrTransactionBlock())
 
3542
                        {
 
3543
                                set_ps_display("idle in transaction", false);
 
3544
                                pgstat_report_activity("<IDLE> in transaction");
 
3545
                        }
 
3546
                        else
 
3547
                        {
 
3548
                                pgstat_report_stat(false);
 
3549
 
 
3550
                                set_ps_display("idle", false);
 
3551
                                pgstat_report_activity("<IDLE>");
 
3552
                        }
 
3553
 
 
3554
                        ReadyForQuery(whereToSendOutput);
 
3555
                        send_ready_for_query = false;
 
3556
                }
 
3557
 
 
3558
                /*
 
3559
                 * (2) Allow asynchronous signals to be executed immediately if they
 
3560
                 * come in while we are waiting for client input. (This must be
 
3561
                 * conditional since we don't want, say, reads on behalf of COPY FROM
 
3562
                 * STDIN doing the same thing.)
 
3563
                 */
 
3564
                QueryCancelPending = false;             /* forget any earlier CANCEL signal */
 
3565
                DoingCommandRead = true;
 
3566
 
 
3567
                /*
 
3568
                 * (3) read a command (loop blocks here)
 
3569
                 */
 
3570
                firstchar = ReadCommand(&input_message);
 
3571
 
 
3572
                /*
 
3573
                 * (4) disable async signal conditions again.
 
3574
                 */
 
3575
                DoingCommandRead = false;
 
3576
 
 
3577
                /*
 
3578
                 * (5) check for any other interesting events that happened while we
 
3579
                 * slept.
 
3580
                 */
 
3581
                if (got_SIGHUP)
 
3582
                {
 
3583
                        got_SIGHUP = false;
 
3584
                        ProcessConfigFile(PGC_SIGHUP);
 
3585
                }
 
3586
 
 
3587
                /*
 
3588
                 * (6) process the command.  But ignore it if we're skipping till
 
3589
                 * Sync.
 
3590
                 */
 
3591
                if (ignore_till_sync && firstchar != EOF)
 
3592
                        continue;
 
3593
 
 
3594
                switch (firstchar)
 
3595
                {
 
3596
                        case 'Q':                       /* simple query */
 
3597
                                {
 
3598
                                        const char *query_string;
 
3599
 
 
3600
                                        /* Set statement_timestamp() */
 
3601
                                        SetCurrentStatementStartTimestamp();
 
3602
 
 
3603
                                        query_string = pq_getmsgstring(&input_message);
 
3604
                                        pq_getmsgend(&input_message);
 
3605
 
 
3606
                                        exec_simple_query(query_string);
 
3607
 
 
3608
                                        send_ready_for_query = true;
 
3609
                                }
 
3610
                                break;
 
3611
 
 
3612
                        case 'P':                       /* parse */
 
3613
                                {
 
3614
                                        const char *stmt_name;
 
3615
                                        const char *query_string;
 
3616
                                        int                     numParams;
 
3617
                                        Oid                *paramTypes = NULL;
 
3618
 
 
3619
                                        /* Set statement_timestamp() */
 
3620
                                        SetCurrentStatementStartTimestamp();
 
3621
 
 
3622
                                        stmt_name = pq_getmsgstring(&input_message);
 
3623
                                        query_string = pq_getmsgstring(&input_message);
 
3624
                                        numParams = pq_getmsgint(&input_message, 2);
 
3625
                                        if (numParams > 0)
 
3626
                                        {
 
3627
                                                int                     i;
 
3628
 
 
3629
                                                paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
 
3630
                                                for (i = 0; i < numParams; i++)
 
3631
                                                        paramTypes[i] = pq_getmsgint(&input_message, 4);
 
3632
                                        }
 
3633
                                        pq_getmsgend(&input_message);
 
3634
 
 
3635
                                        exec_parse_message(query_string, stmt_name,
 
3636
                                                                           paramTypes, numParams);
 
3637
                                }
 
3638
                                break;
 
3639
 
 
3640
                        case 'B':                       /* bind */
 
3641
                                /* Set statement_timestamp() */
 
3642
                                SetCurrentStatementStartTimestamp();
 
3643
 
 
3644
                                /*
 
3645
                                 * this message is complex enough that it seems best to put
 
3646
                                 * the field extraction out-of-line
 
3647
                                 */
 
3648
                                exec_bind_message(&input_message);
 
3649
                                break;
 
3650
 
 
3651
                        case 'E':                       /* execute */
 
3652
                                {
 
3653
                                        const char *portal_name;
 
3654
                                        int                     max_rows;
 
3655
 
 
3656
                                        /* Set statement_timestamp() */
 
3657
                                        SetCurrentStatementStartTimestamp();
 
3658
 
 
3659
                                        portal_name = pq_getmsgstring(&input_message);
 
3660
                                        max_rows = pq_getmsgint(&input_message, 4);
 
3661
                                        pq_getmsgend(&input_message);
 
3662
 
 
3663
                                        exec_execute_message(portal_name, max_rows);
 
3664
                                }
 
3665
                                break;
 
3666
 
 
3667
                        case 'F':                       /* fastpath function call */
 
3668
                                /* Set statement_timestamp() */
 
3669
                                SetCurrentStatementStartTimestamp();
 
3670
 
 
3671
                                /* Tell the collector what we're doing */
 
3672
                                pgstat_report_activity("<FASTPATH> function call");
 
3673
 
 
3674
                                /* start an xact for this function invocation */
 
3675
                                start_xact_command();
 
3676
 
 
3677
                                /*
 
3678
                                 * Note: we may at this point be inside an aborted
 
3679
                                 * transaction.  We can't throw error for that until we've
 
3680
                                 * finished reading the function-call message, so
 
3681
                                 * HandleFunctionRequest() must check for it after doing so.
 
3682
                                 * Be careful not to do anything that assumes we're inside a
 
3683
                                 * valid transaction here.
 
3684
                                 */
 
3685
 
 
3686
                                /* switch back to message context */
 
3687
                                MemoryContextSwitchTo(MessageContext);
 
3688
 
 
3689
                                if (HandleFunctionRequest(&input_message) == EOF)
 
3690
                                {
 
3691
                                        /* lost frontend connection during F message input */
 
3692
 
 
3693
                                        /*
 
3694
                                         * Reset whereToSendOutput to prevent ereport from
 
3695
                                         * attempting to send any more messages to client.
 
3696
                                         */
 
3697
                                        if (whereToSendOutput == DestRemote)
 
3698
                                                whereToSendOutput = DestNone;
 
3699
 
 
3700
                                        proc_exit(0);
 
3701
                                }
 
3702
 
 
3703
                                /* commit the function-invocation transaction */
 
3704
                                finish_xact_command();
 
3705
 
 
3706
                                send_ready_for_query = true;
 
3707
                                break;
 
3708
 
 
3709
                        case 'C':                       /* close */
 
3710
                                {
 
3711
                                        int                     close_type;
 
3712
                                        const char *close_target;
 
3713
 
 
3714
                                        close_type = pq_getmsgbyte(&input_message);
 
3715
                                        close_target = pq_getmsgstring(&input_message);
 
3716
                                        pq_getmsgend(&input_message);
 
3717
 
 
3718
                                        switch (close_type)
 
3719
                                        {
 
3720
                                                case 'S':
 
3721
                                                        if (close_target[0] != '\0')
 
3722
                                                                DropPreparedStatement(close_target, false);
 
3723
                                                        else
 
3724
                                                        {
 
3725
                                                                /* special-case the unnamed statement */
 
3726
                                                                drop_unnamed_stmt();
 
3727
                                                        }
 
3728
                                                        break;
 
3729
                                                case 'P':
 
3730
                                                        {
 
3731
                                                                Portal          portal;
 
3732
 
 
3733
                                                                portal = GetPortalByName(close_target);
 
3734
                                                                if (PortalIsValid(portal))
 
3735
                                                                        PortalDrop(portal, false);
 
3736
                                                        }
 
3737
                                                        break;
 
3738
                                                default:
 
3739
                                                        ereport(ERROR,
 
3740
                                                                        (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
3741
                                                                   errmsg("invalid CLOSE message subtype %d",
 
3742
                                                                                  close_type)));
 
3743
                                                        break;
 
3744
                                        }
 
3745
 
 
3746
                                        if (whereToSendOutput == DestRemote)
 
3747
                                                pq_putemptymessage('3');                /* CloseComplete */
 
3748
                                }
 
3749
                                break;
 
3750
 
 
3751
                        case 'D':                       /* describe */
 
3752
                                {
 
3753
                                        int                     describe_type;
 
3754
                                        const char *describe_target;
 
3755
 
 
3756
                                        /* Set statement_timestamp() (needed for xact) */
 
3757
                                        SetCurrentStatementStartTimestamp();
 
3758
 
 
3759
                                        describe_type = pq_getmsgbyte(&input_message);
 
3760
                                        describe_target = pq_getmsgstring(&input_message);
 
3761
                                        pq_getmsgend(&input_message);
 
3762
 
 
3763
                                        switch (describe_type)
 
3764
                                        {
 
3765
                                                case 'S':
 
3766
                                                        exec_describe_statement_message(describe_target);
 
3767
                                                        break;
 
3768
                                                case 'P':
 
3769
                                                        exec_describe_portal_message(describe_target);
 
3770
                                                        break;
 
3771
                                                default:
 
3772
                                                        ereport(ERROR,
 
3773
                                                                        (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
3774
                                                                errmsg("invalid DESCRIBE message subtype %d",
 
3775
                                                                           describe_type)));
 
3776
                                                        break;
 
3777
                                        }
 
3778
                                }
 
3779
                                break;
 
3780
 
 
3781
                        case 'H':                       /* flush */
 
3782
                                pq_getmsgend(&input_message);
 
3783
                                if (whereToSendOutput == DestRemote)
 
3784
                                        pq_flush();
 
3785
                                break;
 
3786
 
 
3787
                        case 'S':                       /* sync */
 
3788
                                pq_getmsgend(&input_message);
 
3789
                                finish_xact_command();
 
3790
                                send_ready_for_query = true;
 
3791
                                break;
 
3792
 
 
3793
                                /*
 
3794
                                 * 'X' means that the frontend is closing down the socket. EOF
 
3795
                                 * means unexpected loss of frontend connection. Either way,
 
3796
                                 * perform normal shutdown.
 
3797
                                 */
 
3798
                        case 'X':
 
3799
                        case EOF:
 
3800
 
 
3801
                                /*
 
3802
                                 * Reset whereToSendOutput to prevent ereport from attempting
 
3803
                                 * to send any more messages to client.
 
3804
                                 */
 
3805
                                if (whereToSendOutput == DestRemote)
 
3806
                                        whereToSendOutput = DestNone;
 
3807
 
 
3808
                                /*
 
3809
                                 * NOTE: if you are tempted to add more code here, DON'T!
 
3810
                                 * Whatever you had in mind to do should be set up as an
 
3811
                                 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
 
3812
                                 * it will fail to be called during other backend-shutdown
 
3813
                                 * scenarios.
 
3814
                                 */
 
3815
                                proc_exit(0);
 
3816
 
 
3817
                        case 'd':                       /* copy data */
 
3818
                        case 'c':                       /* copy done */
 
3819
                        case 'f':                       /* copy fail */
 
3820
 
 
3821
                                /*
 
3822
                                 * Accept but ignore these messages, per protocol spec; we
 
3823
                                 * probably got here because a COPY failed, and the frontend
 
3824
                                 * is still sending data.
 
3825
                                 */
 
3826
                                break;
 
3827
 
 
3828
                        default:
 
3829
                                ereport(FATAL,
 
3830
                                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
 
3831
                                                 errmsg("invalid frontend message type %d",
 
3832
                                                                firstchar)));
 
3833
                }
 
3834
        }                                                       /* end of input-reading loop */
 
3835
 
 
3836
        /* can't get here because the above loop never exits */
 
3837
        Assert(false);
 
3838
 
 
3839
        return 1;                                       /* keep compiler quiet */
 
3840
}
 
3841
 
 
3842
 
 
3843
/*
 
3844
 * Obtain platform stack depth limit (in bytes)
 
3845
 *
 
3846
 * Return -1 if unlimited or not known
 
3847
 */
 
3848
long
 
3849
get_stack_depth_rlimit(void)
 
3850
{
 
3851
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
 
3852
        static long val = 0;
 
3853
 
 
3854
        /* This won't change after process launch, so check just once */
 
3855
        if (val == 0)
 
3856
        {
 
3857
                struct rlimit rlim;
 
3858
 
 
3859
                if (getrlimit(RLIMIT_STACK, &rlim) < 0)
 
3860
                        val = -1;
 
3861
                else if (rlim.rlim_cur == RLIM_INFINITY)
 
3862
                        val = -1;
 
3863
                else
 
3864
                        val = rlim.rlim_cur;
 
3865
        }
 
3866
        return val;
 
3867
#else                                                   /* no getrlimit */
 
3868
#if defined(WIN32) || defined(__CYGWIN__)
 
3869
        /* On Windows we set the backend stack size in src/backend/Makefile */
 
3870
        return WIN32_STACK_RLIMIT;
 
3871
#else                                                   /* not windows ... give up */
 
3872
        return -1;
 
3873
#endif
 
3874
#endif
 
3875
}
 
3876
 
 
3877
 
 
3878
static struct rusage Save_r;
 
3879
static struct timeval Save_t;
 
3880
 
 
3881
void
 
3882
ResetUsage(void)
 
3883
{
 
3884
        getrusage(RUSAGE_SELF, &Save_r);
 
3885
        gettimeofday(&Save_t, NULL);
 
3886
        ResetBufferUsage();
 
3887
        /* ResetTupleCount(); */
 
3888
}
 
3889
 
 
3890
void
 
3891
ShowUsage(const char *title)
 
3892
{
 
3893
        StringInfoData str;
 
3894
        struct timeval user,
 
3895
                                sys;
 
3896
        struct timeval elapse_t;
 
3897
        struct rusage r;
 
3898
        char       *bufusage;
 
3899
 
 
3900
        getrusage(RUSAGE_SELF, &r);
 
3901
        gettimeofday(&elapse_t, NULL);
 
3902
        memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
 
3903
        memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
 
3904
        if (elapse_t.tv_usec < Save_t.tv_usec)
 
3905
        {
 
3906
                elapse_t.tv_sec--;
 
3907
                elapse_t.tv_usec += 1000000;
 
3908
        }
 
3909
        if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
 
3910
        {
 
3911
                r.ru_utime.tv_sec--;
 
3912
                r.ru_utime.tv_usec += 1000000;
 
3913
        }
 
3914
        if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
 
3915
        {
 
3916
                r.ru_stime.tv_sec--;
 
3917
                r.ru_stime.tv_usec += 1000000;
 
3918
        }
 
3919
 
 
3920
        /*
 
3921
         * the only stats we don't show here are for memory usage -- i can't
 
3922
         * figure out how to interpret the relevant fields in the rusage struct,
 
3923
         * and they change names across o/s platforms, anyway. if you can figure
 
3924
         * out what the entries mean, you can somehow extract resident set size,
 
3925
         * shared text size, and unshared data and stack sizes.
 
3926
         */
 
3927
        initStringInfo(&str);
 
3928
 
 
3929
        appendStringInfo(&str, "! system usage stats:\n");
 
3930
        appendStringInfo(&str,
 
3931
                                "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
 
3932
                                         (long) (elapse_t.tv_sec - Save_t.tv_sec),
 
3933
                                         (long) (elapse_t.tv_usec - Save_t.tv_usec),
 
3934
                                         (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
 
3935
                                         (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
 
3936
                                         (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
 
3937
                                         (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
 
3938
        appendStringInfo(&str,
 
3939
                                         "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
 
3940
                                         (long) user.tv_sec,
 
3941
                                         (long) user.tv_usec,
 
3942
                                         (long) sys.tv_sec,
 
3943
                                         (long) sys.tv_usec);
 
3944
#if defined(HAVE_GETRUSAGE)
 
3945
        appendStringInfo(&str,
 
3946
                                         "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
 
3947
                                         r.ru_inblock - Save_r.ru_inblock,
 
3948
        /* they only drink coffee at dec */
 
3949
                                         r.ru_oublock - Save_r.ru_oublock,
 
3950
                                         r.ru_inblock, r.ru_oublock);
 
3951
        appendStringInfo(&str,
 
3952
                          "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
 
3953
                                         r.ru_majflt - Save_r.ru_majflt,
 
3954
                                         r.ru_minflt - Save_r.ru_minflt,
 
3955
                                         r.ru_majflt, r.ru_minflt,
 
3956
                                         r.ru_nswap - Save_r.ru_nswap,
 
3957
                                         r.ru_nswap);
 
3958
        appendStringInfo(&str,
 
3959
                 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
 
3960
                                         r.ru_nsignals - Save_r.ru_nsignals,
 
3961
                                         r.ru_nsignals,
 
3962
                                         r.ru_msgrcv - Save_r.ru_msgrcv,
 
3963
                                         r.ru_msgsnd - Save_r.ru_msgsnd,
 
3964
                                         r.ru_msgrcv, r.ru_msgsnd);
 
3965
        appendStringInfo(&str,
 
3966
                         "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
 
3967
                                         r.ru_nvcsw - Save_r.ru_nvcsw,
 
3968
                                         r.ru_nivcsw - Save_r.ru_nivcsw,
 
3969
                                         r.ru_nvcsw, r.ru_nivcsw);
 
3970
#endif   /* HAVE_GETRUSAGE */
 
3971
 
 
3972
        bufusage = ShowBufferUsage();
 
3973
        appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
 
3974
        pfree(bufusage);
 
3975
 
 
3976
        /* remove trailing newline */
 
3977
        if (str.data[str.len - 1] == '\n')
 
3978
                str.data[--str.len] = '\0';
 
3979
 
 
3980
        ereport(LOG,
 
3981
                        (errmsg_internal("%s", title),
 
3982
                         errdetail("%s", str.data)));
 
3983
 
 
3984
        pfree(str.data);
 
3985
}
 
3986
 
 
3987
/*
 
3988
 * on_proc_exit handler to log end of session
 
3989
 */
 
3990
static void
 
3991
log_disconnections(int code, Datum arg)
 
3992
{
 
3993
        Port       *port = MyProcPort;
 
3994
        long            secs;
 
3995
        int                     usecs;
 
3996
        int                     msecs;
 
3997
        int                     hours,
 
3998
                                minutes,
 
3999
                                seconds;
 
4000
 
 
4001
        TimestampDifference(port->SessionStartTime,
 
4002
                                                GetCurrentTimestamp(),
 
4003
                                                &secs, &usecs);
 
4004
        msecs = usecs / 1000;
 
4005
 
 
4006
        hours = secs / SECS_PER_HOUR;
 
4007
        secs %= SECS_PER_HOUR;
 
4008
        minutes = secs / SECS_PER_MINUTE;
 
4009
        seconds = secs % SECS_PER_MINUTE;
 
4010
 
 
4011
        ereport(LOG,
 
4012
                        (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
 
4013
                                        "user=%s database=%s host=%s%s%s",
 
4014
                                        hours, minutes, seconds, msecs,
 
4015
                                        port->user_name, port->database_name, port->remote_host,
 
4016
                                  port->remote_port[0] ? " port=" : "", port->remote_port)));
 
4017
}