1
/*-------------------------------------------------------------------------
4
* POSTGRES C Backend Interface
6
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7
* Portions Copyright (c) 1994, Regents of the University of California
14
* this is the "main" module of the postgres backend and
15
* hence the main module of the "traffic cop".
17
*-------------------------------------------------------------------------
26
#include <sys/socket.h>
27
#ifdef HAVE_SYS_SELECT_H
28
#include <sys/select.h>
30
#ifdef HAVE_SYS_RESOURCE_H
32
#include <sys/resource.h>
38
#ifndef HAVE_GETRUSAGE
39
#include "rusagestub.h"
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"
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"
82
const char *debug_query_string; /* client-supplied query string */
84
/* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
85
CommandDest whereToSendOutput = DestDebug;
87
/* flag for logging end of session */
88
bool Log_disconnections = false;
90
int log_statement = LOGSTMT_NONE;
92
/* GUC variable for maximum stack depth (measured in kilobytes) */
93
int max_stack_depth = 100;
95
/* wait N seconds to allow attach from a debugger */
96
int PostAuthDelay = 0;
105
/* max_stack_depth converted to bytes for speed of checking */
106
static long max_stack_depth_bytes = 100 * 1024L;
109
* Stack base pointer -- initialized by PostgresMain. This is not static
110
* so that PL/Java can modify it.
112
char *stack_base_ptr = NULL;
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?)
120
static volatile sig_atomic_t got_SIGHUP = false;
123
* Flag to keep track of whether we have started a transaction.
124
* For extended query protocol this has to be remembered across messages.
126
static bool xact_started = false;
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.
133
static bool DoingCommandRead = false;
136
* Flags to implement skip-till-Sync-after-error behavior for messages of
137
* the extended query protocol.
139
static bool doing_extended_query_message = false;
140
static bool ignore_till_sync = false;
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.
147
static CachedPlanSource *unnamed_stmt_psrc = NULL;
149
/* workspace for building a new unnamed statement in */
150
static MemoryContext unnamed_stmt_context = NULL;
153
static bool EchoQuery = false; /* default don't echo */
156
* people who want to use EOF should #define DONTUSENEWLINE in
159
#ifndef TCOP_DONTUSENEWLINE
160
static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
162
static int UseNewLine = 0; /* Use EOF as query delimiters */
163
#endif /* TCOP_DONTUSENEWLINE */
166
/* ----------------------------------------------------------------
167
* decls for routines only used in this file
168
* ----------------------------------------------------------------
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);
188
/* ----------------------------------------------------------------
189
* routines to obtain user input
190
* ----------------------------------------------------------------
194
* InteractiveBackend() is called for user interactive connections
196
* the string entered by the user is placed in its parameter inBuf,
197
* and we act like a Q message was received.
199
* EOF is returned if end-of-file input is seen; time to shut down.
204
InteractiveBackend(StringInfo inBuf)
206
int c; /* character read from getc() */
207
bool end = false; /* end-of-input flag */
208
bool backslashSeen = false; /* have we seen a \ ? */
211
* display a prompt and obtain input from the user
216
resetStringInfo(inBuf);
221
* if we are using \n as a delimiter, then read characters until the
224
while ((c = interactive_getc()) != EOF)
230
/* discard backslash from inBuf */
231
inBuf->data[--inBuf->len] = '\0';
232
backslashSeen = false;
237
/* keep the newline character */
238
appendStringInfoChar(inBuf, '\n');
243
backslashSeen = true;
245
backslashSeen = false;
247
appendStringInfoChar(inBuf, (char) c);
256
* otherwise read characters until EOF.
258
while ((c = interactive_getc()) != EOF)
259
appendStringInfoChar(inBuf, (char) c);
261
/* No input before EOF signal means time to quit. */
270
* otherwise we have a user query so process it.
273
/* Add '\0' to make it look the same as message case. */
274
appendStringInfoChar(inBuf, (char) '\0');
277
* if the query echo flag was given, print the query..
280
printf("statement: %s\n", inBuf->data);
287
* interactive_getc -- collect one character from stdin
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.
294
interactive_getc(void)
298
prepare_for_client_read();
305
* SocketBackend() Is called for frontend-backend connections
307
* Returns the message type code, and loads message body data into inBuf.
309
* EOF is returned if the connection is lost.
313
SocketBackend(StringInfo inBuf)
318
* Get message type code from the frontend.
320
qtype = pq_getbyte();
322
if (qtype == EOF) /* frontend disconnected */
325
(errcode(ERRCODE_PROTOCOL_VIOLATION),
326
errmsg("unexpected EOF on client connection")));
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.
335
* This also gives us a place to set the doing_extended_query_message flag
336
* as soon as possible.
340
case 'Q': /* simple query */
341
doing_extended_query_message = false;
342
if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
344
/* old style without length word; convert */
345
if (pq_getstring(inBuf))
348
(errcode(ERRCODE_PROTOCOL_VIOLATION),
349
errmsg("unexpected EOF on client connection")));
355
case 'F': /* fastpath function call */
356
/* we let fastpath.c cope with old-style input of this */
357
doing_extended_query_message = false;
360
case 'X': /* terminate */
361
doing_extended_query_message = false;
362
ignore_till_sync = false;
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)
375
(errcode(ERRCODE_PROTOCOL_VIOLATION),
376
errmsg("invalid frontend message type %d", qtype)));
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)
387
(errcode(ERRCODE_PROTOCOL_VIOLATION),
388
errmsg("invalid frontend message type %d", qtype)));
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)
398
(errcode(ERRCODE_PROTOCOL_VIOLATION),
399
errmsg("invalid frontend message type %d", qtype)));
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.
410
(errcode(ERRCODE_PROTOCOL_VIOLATION),
411
errmsg("invalid frontend message type %d", qtype)));
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
420
if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
422
if (pq_getmessage(inBuf, 0))
423
return EOF; /* suitable message already logged */
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.
437
ReadCommand(StringInfo inBuf)
441
if (whereToSendOutput == DestRemote)
442
result = SocketBackend(inBuf);
444
result = InteractiveBackend(inBuf);
449
* prepare_for_client_read -- set up to possibly block on client input
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.
461
prepare_for_client_read(void)
463
if (DoingCommandRead)
465
/* Enable immediate processing of asynchronous signals */
466
EnableNotifyInterrupt();
467
EnableCatchupInterrupt();
469
/* Allow "die" interrupt to be processed while waiting */
470
ImmediateInterruptOK = true;
472
/* And don't forget to detect one that already arrived */
473
QueryCancelPending = false;
474
CHECK_FOR_INTERRUPTS();
479
* client_read_ended -- get out of the client-input state
482
client_read_ended(void)
484
if (DoingCommandRead)
486
ImmediateInterruptOK = false;
487
QueryCancelPending = false; /* forget any CANCEL signal */
489
DisableNotifyInterrupt();
490
DisableCatchupInterrupt();
496
* Parse a query string and pass it through the rewriter.
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.
501
* NOTE: this routine is no longer used for processing interactive queries,
502
* but it is still needed for parsing of SQL function bodies.
505
pg_parse_and_rewrite(const char *query_string, /* string to execute */
506
Oid *paramTypes, /* parameter types */
507
int numParams) /* number of parameters */
509
List *raw_parsetree_list;
510
List *querytree_list;
514
* (1) parse the request string into a list of raw parse trees.
516
raw_parsetree_list = pg_parse_query(query_string);
519
* (2) Do parse analysis and rule rewrite.
521
querytree_list = NIL;
522
foreach(list_item, raw_parsetree_list)
524
Node *parsetree = (Node *) lfirst(list_item);
526
querytree_list = list_concat(querytree_list,
527
pg_analyze_and_rewrite(parsetree,
533
return querytree_list;
537
* Do raw parsing (only).
539
* A list of parsetrees is returned, since there might be multiple
540
* commands in the given string.
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.
550
pg_parse_query(const char *query_string)
552
List *raw_parsetree_list;
554
TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
556
if (log_parser_stats)
559
raw_parsetree_list = raw_parser(query_string);
561
if (log_parser_stats)
562
ShowUsage("PARSER STATISTICS");
564
#ifdef COPY_PARSE_PLAN_TREES
565
/* Optional debugging check: pass raw parsetrees through copyObject() */
567
List *new_list = (List *) copyObject(raw_parsetree_list);
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");
573
raw_parsetree_list = new_list;
577
TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
579
return raw_parsetree_list;
583
* Given a raw parsetree (gram.y output), and optionally information about
584
* types of parameter symbols ($n), perform parse analysis and rule rewriting.
586
* A list of Query nodes is returned, since either the analyzer or the
587
* rewriter might expand one query to several.
589
* NOTE: for reasons mentioned above, this must be separate from raw parsing.
592
pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
593
Oid *paramTypes, int numParams)
596
List *querytree_list;
598
TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
601
* (1) Perform parse analysis.
603
if (log_parser_stats)
606
query = parse_analyze(parsetree, query_string, paramTypes, numParams);
608
if (log_parser_stats)
609
ShowUsage("PARSE ANALYSIS STATISTICS");
612
* (2) Rewrite the queries, as necessary
614
querytree_list = pg_rewrite_query(query);
616
TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
618
return querytree_list;
622
* Perform rewriting of a query produced by parse analysis.
624
* Note: query must just have come from the parser, because we do not do
625
* AcquireRewriteLocks() on it.
628
pg_rewrite_query(Query *query)
630
List *querytree_list;
632
if (Debug_print_parse)
633
elog_node_display(LOG, "parse tree", query,
636
if (log_parser_stats)
639
if (query->commandType == CMD_UTILITY)
641
/* don't rewrite utilities, just dump 'em into result list */
642
querytree_list = list_make1(query);
646
/* rewrite regular queries */
647
querytree_list = QueryRewrite(query);
650
if (log_parser_stats)
651
ShowUsage("REWRITER STATISTICS");
653
#ifdef COPY_PARSE_PLAN_TREES
654
/* Optional debugging check: pass querytree output through copyObject() */
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");
663
querytree_list = new_list;
667
if (Debug_print_rewritten)
668
elog_node_display(LOG, "rewritten parse tree", querytree_list,
671
return querytree_list;
676
* Generate a plan for a single already-rewritten query.
677
* This is a thin wrapper around planner() and takes the same parameters.
680
pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
684
/* Utility commands have no plans. */
685
if (querytree->commandType == CMD_UTILITY)
688
/* Planner must have a snapshot in case it calls user-defined functions. */
689
Assert(ActiveSnapshotSet());
691
TRACE_POSTGRESQL_QUERY_PLAN_START();
693
if (log_planner_stats)
696
/* call the optimizer */
697
plan = planner(querytree, cursorOptions, boundParams);
699
if (log_planner_stats)
700
ShowUsage("PLANNER STATISTICS");
702
#ifdef COPY_PARSE_PLAN_TREES
703
/* Optional debugging check: pass plan output through copyObject() */
705
PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
708
* equal() currently does not have routines to compare Plan nodes, so
709
* don't try to test equality here. Perhaps fix someday?
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");
722
* Print plan if debugging.
724
if (Debug_print_plan)
725
elog_node_display(LOG, "plan", plan, Debug_pretty_print);
727
TRACE_POSTGRESQL_QUERY_PLAN_DONE();
733
* Generate plans for a list of already-rewritten queries.
735
* Normal optimizable statements generate PlannedStmt entries in the result
736
* list. Utility statements are simply represented by their statement nodes.
739
pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
741
List *stmt_list = NIL;
742
ListCell *query_list;
744
foreach(query_list, querytrees)
746
Query *query = (Query *) lfirst(query_list);
749
if (query->commandType == CMD_UTILITY)
751
/* Utility commands have no plans. */
752
stmt = query->utilityStmt;
756
stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
759
stmt_list = lappend(stmt_list, stmt);
769
* Execute a "simple Query" protocol message.
772
exec_simple_query(const char *query_string)
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;
785
* Report query to various monitoring facilities.
787
debug_query_string = query_string;
789
pgstat_report_activity(query_string);
791
TRACE_POSTGRESQL_QUERY_START(query_string);
794
* We use save_log_statement_stats so ShowUsage doesn't report incorrect
795
* results because ResetUsage wasn't called.
797
if (save_log_statement_stats)
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.)
807
start_xact_command();
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.)
818
* Switch to appropriate context for constructing parsetrees.
820
oldcontext = MemoryContextSwitchTo(MessageContext);
823
* Do basic parsing of the query or queries (this should be safe even if
824
* we are in aborted transaction state!)
826
parsetree_list = pg_parse_query(query_string);
828
/* Log immediately if dictated by log_statement */
829
if (check_log_statement(parsetree_list))
832
(errmsg("statement: %s", query_string),
834
errdetail_execute(parsetree_list)));
839
* Switch back to transaction context to enter the loop.
841
MemoryContextSwitchTo(oldcontext);
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.)
850
isTopLevel = (list_length(parsetree_list) == 1);
853
* Run through the raw parsetree(s) and process each one.
855
foreach(parsetree_item, parsetree_list)
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,
864
DestReceiver *receiver;
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
873
commandTag = CreateCommandTag(parsetree);
875
set_ps_display(commandTag, false);
877
BeginCommand(commandTag, dest);
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...)
887
if (IsAbortedTransactionBlockState() &&
888
!IsTransactionExitStmt(parsetree))
890
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
891
errmsg("current transaction is aborted, "
892
"commands ignored until end of transaction block")));
894
/* Make sure we are in a transaction command */
895
start_xact_command();
897
/* If we got a cancel signal in parsing or prior command, quit */
898
CHECK_FOR_INTERRUPTS();
901
* Set up a snapshot if parse analysis/planning will need one.
903
if (analyze_requires_snapshot(parsetree))
905
PushActiveSnapshot(GetTransactionSnapshot());
910
* OK to analyze, rewrite, and plan this query.
912
* Switch to appropriate context for constructing querytrees (again,
913
* these must outlive the execution context).
915
oldcontext = MemoryContextSwitchTo(MessageContext);
917
querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
920
plantree_list = pg_plan_queries(querytree_list, 0, NULL);
922
/* Done with the snapshot used for parsing/planning */
926
/* If we got a cancel signal in analysis or planning, quit */
927
CHECK_FOR_INTERRUPTS();
930
* Create unnamed portal to run the query or queries in. If there
931
* already is one, silently drop it.
933
portal = CreatePortal("", true, true);
934
/* Don't display the portal in pg_cursors */
935
portal->visible = false;
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
942
PortalDefineQuery(portal,
950
* Start the portal. No parameters here.
952
PortalStart(portal, NULL, InvalidSnapshot);
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...)
960
format = 0; /* TEXT is default */
961
if (IsA(parsetree, FetchStmt))
963
FetchStmt *stmt = (FetchStmt *) parsetree;
967
Portal fportal = GetPortalByName(stmt->portalname);
969
if (PortalIsValid(fportal) &&
970
(fportal->cursorOptions & CURSOR_OPT_BINARY))
971
format = 1; /* BINARY */
974
PortalSetResultFormat(portal, 1, &format);
977
* Now we can create the destination receiver object.
979
receiver = CreateDestReceiver(dest);
980
if (dest == DestRemote)
981
SetRemoteDestReceiverParams(receiver, portal);
984
* Switch back to transaction context for execution.
986
MemoryContextSwitchTo(oldcontext);
989
* Run the portal to completion, and then drop it (and the receiver).
991
(void) PortalRun(portal,
998
(*receiver->rDestroy) (receiver);
1000
PortalDrop(portal, false);
1002
if (IsA(parsetree, TransactionStmt))
1005
* If this was a transaction control statement, commit it. We will
1006
* start a new xact command for the next command (if any).
1008
finish_xact_command();
1010
else if (lnext(parsetree_item) == NULL)
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.
1022
finish_xact_command();
1027
* We need a CommandCounterIncrement after every query, except
1028
* those that start or end a transaction block.
1030
CommandCounterIncrement();
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.)
1039
EndCommand(completionTag, dest);
1040
} /* end loop over parsetrees */
1043
* Close down transaction statement, if one is open.
1045
finish_xact_command();
1048
* If there were no parsetrees, return EmptyQueryResponse message.
1050
if (!parsetree_list)
1054
* Emit duration logging if appropriate.
1056
switch (check_log_duration(msec_str, was_logged))
1060
(errmsg("duration: %s ms", msec_str),
1061
errhidestmt(true)));
1065
(errmsg("duration: %s ms statement: %s",
1066
msec_str, query_string),
1068
errdetail_execute(parsetree_list)));
1072
if (save_log_statement_stats)
1073
ShowUsage("QUERY STATISTICS");
1075
TRACE_POSTGRESQL_QUERY_DONE(query_string);
1077
debug_query_string = NULL;
1081
* exec_parse_message
1083
* Execute a "Parse" protocol message.
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 */
1091
MemoryContext oldcontext;
1092
List *parsetree_list;
1093
Node *raw_parse_tree;
1094
const char *commandTag;
1095
List *querytree_list,
1099
bool save_log_statement_stats = log_statement_stats;
1103
* Report query to various monitoring facilities.
1105
debug_query_string = query_string;
1107
pgstat_report_activity(query_string);
1109
set_ps_display("PARSE", false);
1111
if (save_log_statement_stats)
1115
(errmsg("parse %s: %s",
1116
*stmt_name ? stmt_name : "<unnamed>",
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.
1124
start_xact_command();
1127
* Switch to appropriate context for constructing parsetrees.
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.
1139
is_named = (stmt_name[0] != '\0');
1142
/* Named prepared statement --- parse in MessageContext */
1143
oldcontext = MemoryContextSwitchTo(MessageContext);
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);
1160
* Do basic parsing of the query or queries (this should be safe even if
1161
* we are in aborted transaction state!)
1163
parsetree_list = pg_parse_query(query_string);
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.
1170
if (list_length(parsetree_list) > 1)
1172
(errcode(ERRCODE_SYNTAX_ERROR),
1173
errmsg("cannot insert multiple commands into a prepared statement")));
1175
if (parsetree_list != NIL)
1178
bool snapshot_set = false;
1181
raw_parse_tree = (Node *) linitial(parsetree_list);
1184
* Get the command name for possible use in status display.
1186
commandTag = CreateCommandTag(raw_parse_tree);
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...)
1196
if (IsAbortedTransactionBlockState() &&
1197
!IsTransactionExitStmt(raw_parse_tree))
1199
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1200
errmsg("current transaction is aborted, "
1201
"commands ignored until end of transaction block")));
1204
* Set up a snapshot if parse analysis/planning will need one.
1206
if (analyze_requires_snapshot(raw_parse_tree))
1208
PushActiveSnapshot(GetTransactionSnapshot());
1209
snapshot_set = true;
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().
1217
* XXX must use copyObject here since parse analysis scribbles on its
1218
* input, and we need the unmodified raw parse tree for possible
1221
if (log_parser_stats)
1224
query = parse_analyze_varparams(copyObject(raw_parse_tree),
1230
* Check all parameter types got determined.
1232
for (i = 0; i < numParams; i++)
1234
Oid ptype = paramTypes[i];
1236
if (ptype == InvalidOid || ptype == UNKNOWNOID)
1238
(errcode(ERRCODE_INDETERMINATE_DATATYPE),
1239
errmsg("could not determine data type of parameter $%d",
1243
if (log_parser_stats)
1244
ShowUsage("PARSE ANALYSIS STATISTICS");
1246
querytree_list = pg_rewrite_query(query);
1249
* If this is the unnamed statement and it has parameters, defer query
1250
* planning until Bind. Otherwise do it now.
1252
if (!is_named && numParams > 0)
1254
stmt_list = querytree_list;
1255
fully_planned = false;
1259
stmt_list = pg_plan_queries(querytree_list, 0, NULL);
1260
fully_planned = true;
1263
/* Done with the snapshot used for parsing/planning */
1265
PopActiveSnapshot();
1269
/* Empty input string. This is legal. */
1270
raw_parse_tree = NULL;
1273
fully_planned = true;
1276
/* If we got a cancel signal in analysis or planning, quit */
1277
CHECK_FOR_INTERRUPTS();
1280
* Store the query as a prepared statement. See above comments.
1284
StorePreparedStatement(stmt_name,
1290
0, /* default cursor options */
1297
* paramTypes and query_string need to be copied into
1298
* unnamed_stmt_context. The rest is there already
1304
newParamTypes = (Oid *) palloc(numParams * sizeof(Oid));
1305
memcpy(newParamTypes, paramTypes, numParams * sizeof(Oid));
1308
newParamTypes = NULL;
1310
unnamed_stmt_psrc = FastCreateCachedPlan(raw_parse_tree,
1311
pstrdup(query_string),
1315
0, /* cursor options */
1319
unnamed_stmt_context);
1320
/* context now belongs to the plancache entry */
1321
unnamed_stmt_context = NULL;
1324
MemoryContextSwitchTo(oldcontext);
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.
1331
CommandCounterIncrement();
1334
* Send ParseComplete.
1336
if (whereToSendOutput == DestRemote)
1337
pq_putemptymessage('1');
1340
* Emit duration logging if appropriate.
1342
switch (check_log_duration(msec_str, false))
1346
(errmsg("duration: %s ms", msec_str),
1347
errhidestmt(true)));
1351
(errmsg("duration: %s ms parse %s: %s",
1353
*stmt_name ? stmt_name : "<unnamed>",
1355
errhidestmt(true)));
1359
if (save_log_statement_stats)
1360
ShowUsage("PARSE MESSAGE STATISTICS");
1362
debug_query_string = NULL;
1368
* Process a "Bind" message to create a portal from a prepared statement
1371
exec_bind_message(StringInfo input_message)
1373
const char *portal_name;
1374
const char *stmt_name;
1376
int16 *pformats = NULL;
1379
int16 *rformats = NULL;
1380
CachedPlanSource *psrc;
1384
char *saved_stmt_name;
1385
ParamListInfo params;
1387
MemoryContext oldContext;
1388
bool save_log_statement_stats = log_statement_stats;
1389
bool snapshot_set = false;
1392
/* Get the fixed part of the message */
1393
portal_name = pq_getmsgstring(input_message);
1394
stmt_name = pq_getmsgstring(input_message);
1397
(errmsg("bind %s to %s",
1398
*portal_name ? portal_name : "<unnamed>",
1399
*stmt_name ? stmt_name : "<unnamed>")));
1401
/* Find prepared statement */
1402
if (stmt_name[0] != '\0')
1404
PreparedStatement *pstmt;
1406
pstmt = FetchPreparedStatement(stmt_name, true);
1407
psrc = pstmt->plansource;
1411
/* special-case the unnamed statement */
1412
psrc = unnamed_stmt_psrc;
1415
(errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1416
errmsg("unnamed prepared statement does not exist")));
1420
* Report query to various monitoring facilities.
1422
debug_query_string = psrc->query_string;
1424
pgstat_report_activity(psrc->query_string);
1426
set_ps_display("BIND", false);
1428
if (save_log_statement_stats)
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.
1436
start_xact_command();
1438
/* Switch back to message context */
1439
MemoryContextSwitchTo(MessageContext);
1441
/* Get the parameter format codes */
1442
numPFormats = pq_getmsgint(input_message, 2);
1443
if (numPFormats > 0)
1447
pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1448
for (i = 0; i < numPFormats; i++)
1449
pformats[i] = pq_getmsgint(input_message, 2);
1452
/* Get the parameter value count */
1453
numParams = pq_getmsgint(input_message, 2);
1455
if (numPFormats > 1 && numPFormats != numParams)
1457
(errcode(ERRCODE_PROTOCOL_VIOLATION),
1458
errmsg("bind message has %d parameter formats but %d parameters",
1459
numPFormats, numParams)));
1461
if (numParams != psrc->num_params)
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)));
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
1475
if (IsAbortedTransactionBlockState() &&
1476
(!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1479
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1480
errmsg("current transaction is aborted, "
1481
"commands ignored until end of transaction block")));
1484
* Create the portal. Allow silent replacement of an existing portal only
1485
* if the unnamed portal is specified.
1487
if (portal_name[0] == '\0')
1488
portal = CreatePortal(portal_name, true, true);
1490
portal = CreatePortal(portal_name, false, false);
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.
1498
oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1500
/* Copy the plan's query string into the portal */
1501
query_string = pstrdup(psrc->query_string);
1503
/* Likewise make a copy of the statement name, unless it's unnamed */
1505
saved_stmt_name = pstrdup(stmt_name);
1507
saved_stmt_name = NULL;
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).
1514
if (numParams > 0 || analyze_requires_snapshot(psrc->raw_parse_tree))
1516
PushActiveSnapshot(GetTransactionSnapshot());
1517
snapshot_set = true;
1521
* Fetch parameters, if any, and store in the portal's memory context.
1527
/* sizeof(ParamListInfoData) includes the first array element */
1528
params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1529
(numParams - 1) *sizeof(ParamExternData));
1530
params->numParams = numParams;
1532
for (paramno = 0; paramno < numParams; paramno++)
1534
Oid ptype = psrc->param_types[paramno];
1538
StringInfoData pbuf;
1542
plength = pq_getmsgint(input_message, 4);
1543
isNull = (plength == -1);
1547
const char *pvalue = pq_getmsgbytes(input_message, plength);
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.
1557
pbuf.data = (char *) pvalue;
1558
pbuf.maxlen = plength + 1;
1562
csave = pbuf.data[plength];
1563
pbuf.data[plength] = '\0';
1567
pbuf.data = NULL; /* keep compiler quiet */
1571
if (numPFormats > 1)
1572
pformat = pformats[paramno];
1573
else if (numPFormats > 0)
1574
pformat = pformats[0];
1576
pformat = 0; /* default = text */
1578
if (pformat == 0) /* text mode */
1584
getTypeInputInfo(ptype, &typinput, &typioparam);
1587
* We have to do encoding conversion before calling the
1593
pstring = pg_client_to_server(pbuf.data, plength);
1595
pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1597
/* Free result of encoding conversion, if any */
1598
if (pstring && pstring != pbuf.data)
1601
else if (pformat == 1) /* binary mode */
1608
* Call the parameter type's binary input converter
1610
getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1617
pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1619
/* Trouble if it didn't eat the whole buffer */
1620
if (!isNull && pbuf.cursor != pbuf.len)
1622
(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1623
errmsg("incorrect binary data format in bind parameter %d",
1629
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1630
errmsg("unsupported format code: %d",
1632
pval = 0; /* keep compiler quiet */
1635
/* Restore message buffer contents */
1637
pbuf.data[plength] = csave;
1639
params->params[paramno].value = pval;
1640
params->params[paramno].isnull = isNull;
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.
1648
params->params[paramno].pflags = PARAM_FLAG_CONST;
1649
params->params[paramno].ptype = ptype;
1655
/* Done storing stuff in portal's context */
1656
MemoryContextSwitchTo(oldContext);
1658
/* Get the result format codes */
1659
numRFormats = pq_getmsgint(input_message, 2);
1660
if (numRFormats > 0)
1664
rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1665
for (i = 0; i < numRFormats; i++)
1666
rformats[i] = pq_getmsgint(input_message, 2);
1669
pq_getmsgend(input_message);
1671
if (psrc->fully_planned)
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
1679
cplan = RevalidateCachedPlan(psrc, false);
1680
plan_list = cplan->stmt_list;
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.
1692
cplan = RevalidateCachedPlan(psrc, true);
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.
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.
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);
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 */
1718
* Now we can define the portal.
1720
* DO NOT put any code that could possibly throw an error between the
1721
* above "RevalidateCachedPlan(psrc, false)" call and here.
1723
PortalDefineQuery(portal,
1730
/* Done with the snapshot used for parameter I/O and parsing/planning */
1732
PopActiveSnapshot();
1735
* And we're ready to start portal execution.
1737
PortalStart(portal, params, InvalidSnapshot);
1740
* Apply the result format requests to the portal.
1742
PortalSetResultFormat(portal, numRFormats, rformats);
1745
* Send BindComplete.
1747
if (whereToSendOutput == DestRemote)
1748
pq_putemptymessage('2');
1751
* Emit duration logging if appropriate.
1753
switch (check_log_duration(msec_str, false))
1757
(errmsg("duration: %s ms", msec_str),
1758
errhidestmt(true)));
1762
(errmsg("duration: %s ms bind %s%s%s: %s",
1764
*stmt_name ? stmt_name : "<unnamed>",
1765
*portal_name ? "/" : "",
1766
*portal_name ? portal_name : "",
1767
psrc->query_string),
1769
errdetail_params(params)));
1773
if (save_log_statement_stats)
1774
ShowUsage("BIND MESSAGE STATISTICS");
1776
debug_query_string = NULL;
1780
* exec_execute_message
1782
* Process an "Execute" message for a portal
1785
exec_execute_message(const char *portal_name, long max_rows)
1788
DestReceiver *receiver;
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;
1801
/* Adjust destination to tell printtup.c what to do */
1802
dest = whereToSendOutput;
1803
if (dest == DestRemote)
1804
dest = DestRemoteExecute;
1806
portal = GetPortalByName(portal_name);
1807
if (!PortalIsValid(portal))
1809
(errcode(ERRCODE_UNDEFINED_CURSOR),
1810
errmsg("portal \"%s\" does not exist", portal_name)));
1813
* If the original query was a null string, just return
1814
* EmptyQueryResponse.
1816
if (portal->commandTag == NULL)
1818
Assert(portal->stmts == NIL);
1823
/* Does the portal contain a transaction command? */
1824
is_xact_command = IsTransactionStmtList(portal->stmts);
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.
1831
if (is_xact_command)
1833
sourceText = pstrdup(portal->sourceText);
1834
if (portal->prepStmtName)
1835
prepStmtName = pstrdup(portal->prepStmtName);
1837
prepStmtName = "<unnamed>";
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.
1843
portalParams = NULL;
1847
sourceText = portal->sourceText;
1848
if (portal->prepStmtName)
1849
prepStmtName = portal->prepStmtName;
1851
prepStmtName = "<unnamed>";
1852
portalParams = portal->portalParams;
1856
* Report query to various monitoring facilities.
1858
debug_query_string = sourceText;
1860
pgstat_report_activity(sourceText);
1862
set_ps_display(portal->commandTag, false);
1864
if (save_log_statement_stats)
1867
BeginCommand(portal->commandTag, dest);
1870
* Create dest receiver in MessageContext (we don't want it in transaction
1871
* context, because that may get deleted if portal contains VACUUM).
1873
receiver = CreateDestReceiver(dest);
1874
if (dest == DestRemoteExecute)
1875
SetRemoteDestReceiverParams(receiver, portal);
1878
* Ensure we are in a transaction command (this should normally be the
1879
* case already due to prior BIND).
1881
start_xact_command();
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.
1889
execute_is_fetch = !portal->atStart;
1891
/* Log immediately if dictated by log_statement */
1892
if (check_log_statement(portal->stmts))
1895
(errmsg("%s %s%s%s: %s",
1897
_("execute fetch from") :
1900
*portal_name ? "/" : "",
1901
*portal_name ? portal_name : "",
1904
errdetail_params(portalParams)));
1909
* If we are in aborted transaction state, the only portals we can
1910
* actually run are those containing COMMIT or ROLLBACK commands.
1912
if (IsAbortedTransactionBlockState() &&
1913
!IsTransactionExitStmtList(portal->stmts))
1915
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1916
errmsg("current transaction is aborted, "
1917
"commands ignored until end of transaction block")));
1919
/* Check for cancel signal before we start execution */
1920
CHECK_FOR_INTERRUPTS();
1923
* Okay to run the portal.
1926
max_rows = FETCH_ALL;
1928
completed = PortalRun(portal,
1930
true, /* always top level */
1935
(*receiver->rDestroy) (receiver);
1939
if (is_xact_command)
1942
* If this was a transaction control statement, commit it. We
1943
* will start a new xact command for the next command (if any).
1945
finish_xact_command();
1950
* We need a CommandCounterIncrement after every query, except
1951
* those that start or end a transaction block.
1953
CommandCounterIncrement();
1956
/* Send appropriate CommandComplete to client */
1957
EndCommand(completionTag, dest);
1961
/* Portal run not complete, so send PortalSuspended */
1962
if (whereToSendOutput == DestRemote)
1963
pq_putemptymessage('s');
1967
* Emit duration logging if appropriate.
1969
switch (check_log_duration(msec_str, was_logged))
1973
(errmsg("duration: %s ms", msec_str),
1974
errhidestmt(true)));
1978
(errmsg("duration: %s ms %s %s%s%s: %s",
1981
_("execute fetch from") :
1984
*portal_name ? "/" : "",
1985
*portal_name ? portal_name : "",
1988
errdetail_params(portalParams)));
1992
if (save_log_statement_stats)
1993
ShowUsage("EXECUTE MESSAGE STATISTICS");
1995
debug_query_string = NULL;
1999
* check_log_statement
2000
* Determine whether command should be logged because of log_statement
2002
* parsetree_list can be either raw grammar output or a list of planned
2006
check_log_statement(List *stmt_list)
2008
ListCell *stmt_item;
2010
if (log_statement == LOGSTMT_NONE)
2012
if (log_statement == LOGSTMT_ALL)
2015
/* Else we have to inspect the statement(s) to see whether to log */
2016
foreach(stmt_item, stmt_list)
2018
Node *stmt = (Node *) lfirst(stmt_item);
2020
if (GetCommandLogLevel(stmt) <= log_statement)
2028
* check_log_duration
2029
* Determine whether current command's duration should be logged
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
2036
* If logging is needed, the duration in msec is formatted into msec_str[],
2037
* which must be a 32-byte buffer.
2039
* was_logged should be TRUE if caller already logged query details (this
2040
* essentially prevents 2 from being returned).
2043
check_log_duration(char *msec_str, bool was_logged)
2045
if (log_duration || log_min_duration_statement >= 0)
2052
TimestampDifference(GetCurrentStatementStartTimestamp(),
2053
GetCurrentTimestamp(),
2055
msecs = usecs / 1000;
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.
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)));
2067
if (exceeded || log_duration)
2069
snprintf(msec_str, 32, "%ld.%03d",
2070
secs * 1000 + msecs, usecs % 1000);
2071
if (exceeded && !was_logged)
2084
* Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2085
* The argument is the raw parsetree list.
2088
errdetail_execute(List *raw_parsetree_list)
2090
ListCell *parsetree_item;
2092
foreach(parsetree_item, raw_parsetree_list)
2094
Node *parsetree = (Node *) lfirst(parsetree_item);
2096
if (IsA(parsetree, ExecuteStmt))
2098
ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2099
PreparedStatement *pstmt;
2101
pstmt = FetchPreparedStatement(stmt->name, false);
2104
errdetail("prepare: %s", pstmt->plansource->query_string);
2116
* Add an errdetail() line showing bind-parameter data, if available.
2119
errdetail_params(ParamListInfo params)
2121
/* We mustn't call user-defined I/O functions when in an aborted xact */
2122
if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2124
StringInfoData param_str;
2125
MemoryContext oldcontext;
2128
/* Make sure any trash is generated in MessageContext */
2129
oldcontext = MemoryContextSwitchTo(MessageContext);
2131
initStringInfo(¶m_str);
2133
for (paramno = 0; paramno < params->numParams; paramno++)
2135
ParamExternData *prm = ¶ms->params[paramno];
2141
appendStringInfo(¶m_str, "%s$%d = ",
2142
paramno > 0 ? ", " : "",
2145
if (prm->isnull || !OidIsValid(prm->ptype))
2147
appendStringInfoString(¶m_str, "NULL");
2151
getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2153
pstring = OidOutputFunctionCall(typoutput, prm->value);
2155
appendStringInfoCharMacro(¶m_str, '\'');
2156
for (p = pstring; *p; p++)
2158
if (*p == '\'') /* double single quotes */
2159
appendStringInfoCharMacro(¶m_str, *p);
2160
appendStringInfoCharMacro(¶m_str, *p);
2162
appendStringInfoCharMacro(¶m_str, '\'');
2167
errdetail("parameters: %s", param_str.data);
2169
pfree(param_str.data);
2171
MemoryContextSwitchTo(oldcontext);
2178
* exec_describe_statement_message
2180
* Process a "Describe" message for a prepared statement
2183
exec_describe_statement_message(const char *stmt_name)
2185
CachedPlanSource *psrc;
2190
* Start up a transaction command. (Note that this will normally change
2191
* current memory context.) Nothing happens if we are already in one.
2193
start_xact_command();
2195
/* Switch back to message context */
2196
MemoryContextSwitchTo(MessageContext);
2198
/* Find prepared statement */
2199
if (stmt_name[0] != '\0')
2201
PreparedStatement *pstmt;
2203
pstmt = FetchPreparedStatement(stmt_name, true);
2204
psrc = pstmt->plansource;
2208
/* special-case the unnamed statement */
2209
psrc = unnamed_stmt_psrc;
2212
(errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2213
errmsg("unnamed prepared statement does not exist")));
2216
/* Prepared statements shouldn't have changeable result descs */
2217
Assert(psrc->fixed_result);
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.
2229
if (IsAbortedTransactionBlockState() &&
2232
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2233
errmsg("current transaction is aborted, "
2234
"commands ignored until end of transaction block")));
2236
if (whereToSendOutput != DestRemote)
2237
return; /* can't actually do anything... */
2240
* First describe the parameters...
2242
pq_beginmessage(&buf, 't'); /* parameter description message type */
2243
pq_sendint(&buf, psrc->num_params, 2);
2245
for (i = 0; i < psrc->num_params; i++)
2247
Oid ptype = psrc->param_types[i];
2249
pq_sendint(&buf, (int) ptype, 4);
2251
pq_endmessage(&buf);
2254
* Next send RowDescription or NoData to describe the result...
2256
if (psrc->resultDesc)
2261
/* Make sure the plan is up to date */
2262
cplan = RevalidateCachedPlan(psrc, true);
2264
/* Get the primary statement and find out what it returns */
2265
tlist = FetchStatementTargetList(PortalListGetPrimaryStmt(cplan->stmt_list));
2267
SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2269
ReleaseCachedPlan(cplan, true);
2272
pq_putemptymessage('n'); /* NoData */
2277
* exec_describe_portal_message
2279
* Process a "Describe" message for a portal
2282
exec_describe_portal_message(const char *portal_name)
2287
* Start up a transaction command. (Note that this will normally change
2288
* current memory context.) Nothing happens if we are already in one.
2290
start_xact_command();
2292
/* Switch back to message context */
2293
MemoryContextSwitchTo(MessageContext);
2295
portal = GetPortalByName(portal_name);
2296
if (!PortalIsValid(portal))
2298
(errcode(ERRCODE_UNDEFINED_CURSOR),
2299
errmsg("portal \"%s\" does not exist", portal_name)));
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.)
2309
if (IsAbortedTransactionBlockState() &&
2312
(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2313
errmsg("current transaction is aborted, "
2314
"commands ignored until end of transaction block")));
2316
if (whereToSendOutput != DestRemote)
2317
return; /* can't actually do anything... */
2319
if (portal->tupDesc)
2320
SendRowDescriptionMessage(portal->tupDesc,
2321
FetchPortalTargetList(portal),
2324
pq_putemptymessage('n'); /* NoData */
2329
* Convenience routines for starting/committing a single command.
2332
start_xact_command(void)
2337
(errmsg_internal("StartTransactionCommand")));
2338
StartTransactionCommand();
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);
2345
cancel_from_timeout = false;
2347
xact_started = true;
2352
finish_xact_command(void)
2356
/* Cancel any active statement timeout before committing */
2357
disable_sig_alarm(true);
2359
/* Now commit the command */
2361
(errmsg_internal("CommitTransactionCommand")));
2363
CommitTransactionCommand();
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);
2371
#ifdef SHOW_MEMORY_STATS
2372
/* Print mem stats after each commit for leak tracking */
2373
MemoryContextStats(TopMemoryContext);
2376
xact_started = false;
2382
* Convenience routines for checking whether a statement is one of the
2383
* ones that we allow in transaction-aborted state.
2386
/* Test a bare parsetree */
2388
IsTransactionExitStmt(Node *parsetree)
2390
if (parsetree && IsA(parsetree, TransactionStmt))
2392
TransactionStmt *stmt = (TransactionStmt *) parsetree;
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)
2403
/* Test a list that might contain Query nodes or bare parsetrees */
2405
IsTransactionExitStmtList(List *parseTrees)
2407
if (list_length(parseTrees) == 1)
2409
Node *stmt = (Node *) linitial(parseTrees);
2411
if (IsA(stmt, Query))
2413
Query *query = (Query *) stmt;
2415
if (query->commandType == CMD_UTILITY &&
2416
IsTransactionExitStmt(query->utilityStmt))
2419
else if (IsTransactionExitStmt(stmt))
2425
/* Test a list that might contain Query nodes or bare parsetrees */
2427
IsTransactionStmtList(List *parseTrees)
2429
if (list_length(parseTrees) == 1)
2431
Node *stmt = (Node *) linitial(parseTrees);
2433
if (IsA(stmt, Query))
2435
Query *query = (Query *) stmt;
2437
if (query->commandType == CMD_UTILITY &&
2438
IsA(query->utilityStmt, TransactionStmt))
2441
else if (IsA(stmt, TransactionStmt))
2447
/* Release any existing unnamed prepared statement */
2449
drop_unnamed_stmt(void)
2451
/* Release any completed unnamed statement */
2452
if (unnamed_stmt_psrc)
2453
DropCachedPlan(unnamed_stmt_psrc);
2454
unnamed_stmt_psrc = NULL;
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.
2461
if (unnamed_stmt_context)
2462
MemoryContextDelete(unnamed_stmt_context);
2463
unnamed_stmt_context = NULL;
2467
/* --------------------------------
2468
* signal handler routines used in PostgresMain()
2469
* --------------------------------
2473
* quickdie() occurs when signalled SIGQUIT by the postmaster.
2475
* Some backend has bought the farm,
2476
* so we need to stop what we're doing and exit.
2479
quickdie(SIGNAL_ARGS)
2481
PG_SETMASK(&BlockSig);
2484
* Ideally this should be ereport(FATAL), but then we'd not get control
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"
2494
errhint("In a moment you should be able to reconnect to the"
2495
" database and repeat your command.")));
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.
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.
2511
* Shutdown signal from postmaster: abort transaction and exit
2512
* at soonest convenient time
2517
int save_errno = errno;
2519
/* Don't joggle the elbow of proc_exit */
2520
if (!proc_exit_inprogress)
2522
InterruptPending = true;
2523
ProcDiePending = true;
2526
* If it's safe to interrupt, and we're waiting for input or a lock,
2527
* service the interrupt immediately
2529
if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2530
CritSectionCount == 0)
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();
2547
* Timeout or shutdown signal from postmaster during client authentication.
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.
2555
authdie(SIGNAL_ARGS)
2561
* Query-cancel signal from postmaster: abort current transaction
2562
* at soonest convenient time
2565
StatementCancelHandler(SIGNAL_ARGS)
2567
int save_errno = errno;
2570
* Don't joggle the elbow of proc_exit
2572
if (!proc_exit_inprogress)
2574
InterruptPending = true;
2575
QueryCancelPending = true;
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.
2582
if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2583
CritSectionCount == 0 && !DoingCommandRead)
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();
2599
/* signal handler for floating point exception */
2601
FloatExceptionHandler(SIGNAL_ARGS)
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.")));
2611
/* SIGHUP: set flag to re-read config file at next convenient time */
2613
SigHupHandler(SIGNAL_ARGS)
2620
* ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
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.
2627
ProcessInterrupts(void)
2629
/* OK to accept interrupt now? */
2630
if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2632
InterruptPending = false;
2635
ProcDiePending = false;
2636
QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2637
ImmediateInterruptOK = false; /* not idle anymore */
2638
DisableNotifyInterrupt();
2639
DisableCatchupInterrupt();
2640
if (IsAutoVacuumWorkerProcess())
2642
(errcode(ERRCODE_ADMIN_SHUTDOWN),
2643
errmsg("terminating autovacuum process due to administrator command")));
2646
(errcode(ERRCODE_ADMIN_SHUTDOWN),
2647
errmsg("terminating connection due to administrator command")));
2649
if (QueryCancelPending)
2651
QueryCancelPending = false;
2652
ImmediateInterruptOK = false; /* not idle anymore */
2653
DisableNotifyInterrupt();
2654
DisableCatchupInterrupt();
2655
if (cancel_from_timeout)
2657
(errcode(ERRCODE_QUERY_CANCELED),
2658
errmsg("canceling statement due to statement timeout")));
2659
else if (IsAutoVacuumWorkerProcess())
2661
(errcode(ERRCODE_QUERY_CANCELED),
2662
errmsg("canceling autovacuum task")));
2665
(errcode(ERRCODE_QUERY_CANCELED),
2666
errmsg("canceling statement due to user request")));
2668
/* If we get here, do nothing (probably, QueryCancelPending was reset) */
2673
* check_stack_depth: check for excessively deep recursion
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.
2681
check_stack_depth(void)
2687
* Compute distance from PostgresMain's local variables to my own
2689
stack_depth = (long) (stack_base_ptr - &stack_top_loc);
2692
* Take abs value, since stacks grow up on some machines, down on others
2694
if (stack_depth < 0)
2695
stack_depth = -stack_depth;
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
2705
if (stack_depth > max_stack_depth_bytes &&
2706
stack_base_ptr != NULL)
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.")));
2716
/* GUC assign hook for max_stack_depth */
2718
assign_max_stack_depth(int newval, bool doit, GucSource source)
2720
long newval_bytes = newval * 1024L;
2721
long stack_rlimit = get_stack_depth_rlimit();
2723
if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
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.")));
2733
max_stack_depth_bytes = newval_bytes;
2739
* set_debug_options --- apply "-d N" command line option
2741
* -d is not quite the same as setting log_min_messages because it enables
2742
* other output options.
2745
set_debug_options(int debug_flag, GucContext context, GucSource source)
2751
sprintf(debugstr, "debug%d", debug_flag);
2752
SetConfigOption("log_min_messages", debugstr, context, source);
2755
SetConfigOption("log_min_messages", "notice", context, source);
2757
if (debug_flag >= 1 && context == PGC_POSTMASTER)
2759
SetConfigOption("log_connections", "true", context, source);
2760
SetConfigOption("log_disconnections", "true", context, source);
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);
2774
set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
2780
case 's': /* seqscan */
2781
tmp = "enable_seqscan";
2783
case 'i': /* indexscan */
2784
tmp = "enable_indexscan";
2786
case 'b': /* bitmapscan */
2787
tmp = "enable_bitmapscan";
2789
case 't': /* tidscan */
2790
tmp = "enable_tidscan";
2792
case 'n': /* nestloop */
2793
tmp = "enable_nestloop";
2795
case 'm': /* mergejoin */
2796
tmp = "enable_mergejoin";
2798
case 'h': /* hashjoin */
2799
tmp = "enable_hashjoin";
2804
SetConfigOption(tmp, "false", context, source);
2813
get_stats_option_name(const char *arg)
2818
if (optarg[1] == 'a') /* "parser" */
2819
return "log_parser_stats";
2820
else if (optarg[1] == 'l') /* "planner" */
2821
return "log_planner_stats";
2824
case 'e': /* "executor" */
2825
return "log_executor_stats";
2833
/* ----------------------------------------------------------------
2835
* postgres main loop -- all backends, interactive or otherwise start here
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
2841
* ----------------------------------------------------------------
2844
PostgresMain(int argc, char *argv[], const char *username)
2847
const char *dbname = NULL;
2848
char *userDoption = NULL;
2851
int debug_flag = -1; /* -1 means not given */
2852
List *guc_names = NIL; /* for SUSET options */
2853
List *guc_values = NIL;
2855
GucSource gucsource;
2859
StringInfoData input_message;
2860
sigjmp_buf local_sigjmp_buf;
2861
volatile bool send_ready_for_query = true;
2863
#define PendingConfigOption(name,val) \
2864
(guc_names = lappend(guc_names, pstrdup(name)), \
2865
guc_values = lappend(guc_values, pstrdup(val)))
2868
* initialize globals (already done if under postmaster, but not if
2869
* standalone; cheap enough to do over)
2871
MyProcPid = getpid();
2873
MyStartTime = time(NULL);
2876
* Fire up essential subsystems: error and memory management
2878
* If we are running under the postmaster, this is done already.
2880
if (!IsUnderPostmaster)
2881
MemoryContextInit();
2883
set_ps_display("startup", false);
2885
SetProcessingMode(InitProcessing);
2887
/* Set up reference point for stack depth checking */
2888
stack_base_ptr = &stack_base;
2890
/* Compute paths, if we didn't inherit them from postmaster */
2891
if (my_exec_path[0] == '\0')
2893
if (find_my_exec(argv[0], my_exec_path) < 0)
2894
elog(FATAL, "%s: could not locate my own executable path",
2898
if (pkglib_path[0] == '\0')
2899
get_pkglib_path(my_exec_path, pkglib_path);
2902
* Set default values for command-line options.
2906
if (!IsUnderPostmaster)
2907
InitializeGUCOptions();
2910
* parse command line arguments
2912
* There are now two styles of command line layout for the backend:
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.
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.
2926
/* Ignore the initial --single argument, if present */
2927
if (argc > 1 && strcmp(argv[1], "--single") == 0)
2933
/* all options are allowed until '-p' */
2935
ctx = PGC_POSTMASTER;
2936
gucsource = PGC_S_ARGV; /* initial switches came from command line */
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.
2943
while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
2948
SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2952
SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2957
userDoption = optarg;
2961
debug_flag = atoi(optarg);
2969
SetConfigOption("datestyle", "euro", ctx, gucsource);
2973
SetConfigOption("fsync", "false", ctx, gucsource);
2977
if (!set_plan_disabling_options(optarg, ctx, gucsource))
2982
SetConfigOption("listen_addresses", optarg, ctx, gucsource);
2986
SetConfigOption("listen_addresses", "*", ctx, gucsource);
2994
SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
2998
SetConfigOption("ssl", "true", ctx, gucsource);
3002
SetConfigOption("max_connections", optarg, ctx, gucsource);
3006
/* ignored for consistency with postmaster */
3010
SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3018
SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3022
SetConfigOption("port", optarg, ctx, gucsource);
3026
/* send output (stdout and stderr) to the given file */
3028
strlcpy(OutputFileName, optarg, MAXPGPATH);
3032
SetConfigOption("work_mem", optarg, ctx, gucsource);
3038
* Since log options are SUSET, we need to postpone unless
3039
* still in secure context
3041
if (ctx == PGC_BACKEND)
3042
PendingConfigOption("log_statement_stats", "true");
3044
SetConfigOption("log_statement_stats", "true",
3049
/* ignored for consistency with postmaster */
3054
const char *tmp = get_stats_option_name(optarg);
3058
if (ctx == PGC_BACKEND)
3059
PendingConfigOption(tmp, "true");
3061
SetConfigOption(tmp, "true", ctx, gucsource);
3070
FrontendProtocol = (ProtocolVersion) atoi(optarg);
3074
SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3081
* y - special flag passed if backend was forked by a
3086
dbname = strdup(optarg);
3088
secure = false; /* subsequent switches are NOT secure */
3090
gucsource = PGC_S_CLIENT;
3100
ParseLongOption(optarg, &name, &value);
3105
(errcode(ERRCODE_SYNTAX_ERROR),
3106
errmsg("--%s requires a value",
3110
(errcode(ERRCODE_SYNTAX_ERROR),
3111
errmsg("-c %s requires a value",
3116
* If a SUSET option, must postpone evaluation, unless we
3117
* are still reading secure switches.
3119
if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
3120
PendingConfigOption(name, value);
3122
SetConfigOption(name, value, ctx, gucsource);
3136
* Process any additional GUC variable settings passed in startup packet.
3137
* These are handled exactly like command-line variables.
3139
if (MyProcPort != NULL)
3141
ListCell *gucopts = list_head(MyProcPort->guc_options);
3148
name = lfirst(gucopts);
3149
gucopts = lnext(gucopts);
3151
value = lfirst(gucopts);
3152
gucopts = lnext(gucopts);
3154
if (IsSuperuserConfigOption(name))
3155
PendingConfigOption(name, value);
3157
SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
3161
/* Acquire configuration parameters, unless inherited from postmaster */
3162
if (!IsUnderPostmaster)
3164
if (!SelectConfigFiles(userDoption, argv[0]))
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();
3173
pg_usleep(PostAuthDelay * 1000000L);
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.
3181
* Set up signal handlers and masks.
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.
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
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 */
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
3203
if (IsUnderPostmaster)
3204
pqsignal(SIGQUIT, quickdie); /* hard crash time */
3206
pqsignal(SIGQUIT, die); /* cancel current query and exit */
3207
pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
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...
3215
pqsignal(SIGPIPE, SIG_IGN);
3216
pqsignal(SIGUSR1, CatchupInterruptHandler);
3217
pqsignal(SIGUSR2, NotifyInterruptHandler);
3218
pqsignal(SIGFPE, FloatExceptionHandler);
3221
* Reset some signals that are accepted by postmaster but not by backend
3223
pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
3227
if (IsUnderPostmaster)
3229
/* We allow SIGQUIT (quickdie) at all times */
3230
#ifdef HAVE_SIGPROCMASK
3231
sigdelset(&BlockSig, SIGQUIT);
3233
BlockSig &= ~(sigmask(SIGQUIT));
3237
PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3239
if (IsUnderPostmaster)
3241
/* noninteractive case: nothing should be left after switches */
3242
if (errs || argc != optind || dbname == NULL)
3245
(errcode(ERRCODE_SYNTAX_ERROR),
3246
errmsg("invalid command-line arguments for server process"),
3247
errhint("Try \"%s --help\" for more information.", argv[0])));
3254
/* interactive case: database name can be last arg on command line */
3255
if (errs || argc - optind > 1)
3258
(errcode(ERRCODE_SYNTAX_ERROR),
3259
errmsg("%s: invalid command-line arguments",
3261
errhint("Try \"%s --help\" for more information.", argv[0])));
3263
else if (argc - optind == 1)
3264
dbname = argv[optind];
3265
else if ((dbname = username) == NULL)
3268
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3269
errmsg("%s: no database nor user name specified",
3274
* Validate we have been given a reasonable-looking DataDir (if under
3275
* postmaster, assume postmaster did this already).
3278
ValidatePgVersion(DataDir);
3280
/* Change into DataDir (if under postmaster, was done already) */
3284
* Create lockfile for data directory.
3286
CreateDataDirLockFile(false);
3291
* Start up xlog for standalone backend, and register to have it
3292
* closed down at exit.
3295
on_shmem_exit(ShutdownXLOG, 0);
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.
3301
BuildFlatFiles(true);
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).
3311
if (!IsUnderPostmaster)
3318
* General initialization.
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.
3325
(errmsg_internal("InitPostgres")));
3326
am_superuser = InitPostgres(dbname, InvalidOid, username, NULL);
3328
SetProcessingMode(NormalProcessing);
3331
* Now that we know if client is a superuser, we can try to apply SUSET
3332
* GUC options that came from the client.
3334
ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
3336
if (debug_flag >= 0)
3337
set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
3339
if (guc_names != NIL)
3344
forboth(namcell, guc_names, valcell, guc_values)
3346
char *name = (char *) lfirst(namcell);
3347
char *value = (char *) lfirst(valcell);
3349
SetConfigOption(name, value, ctx, PGC_S_CLIENT);
3356
* Now all GUC states are fully set up. Report them to client if
3359
BeginReportingGUCOptions();
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.
3365
if (IsUnderPostmaster && Log_disconnections)
3366
on_proc_exit(log_disconnections, 0);
3369
* process any libraries that should be preloaded at backend start (this
3370
* likewise can't be done until GUC settings are complete)
3372
process_local_preload_libraries();
3375
* Send this backend's cancellation info to the frontend.
3377
if (whereToSendOutput == DestRemote &&
3378
PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
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. */
3389
/* Welcome banner for standalone case */
3390
if (whereToSendOutput == DestDebug)
3391
printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3394
* Create the memory context we will use in the main loop.
3396
* MessageContext is reset once per iteration of the main loop, ie, upon
3397
* completion of processing of each command message from the client.
3399
MessageContext = AllocSetContextCreate(TopMemoryContext,
3401
ALLOCSET_DEFAULT_MINSIZE,
3402
ALLOCSET_DEFAULT_INITSIZE,
3403
ALLOCSET_DEFAULT_MAXSIZE);
3406
* Remember stand-alone backend startup time
3408
if (!IsUnderPostmaster)
3409
PgStartTime = GetCurrentTimestamp();
3412
* POSTGRES main processing loop begins here
3414
* If an exception is encountered, processing resumes here so we abort the
3415
* current transaction and start a new one.
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.)
3426
if (sigsetjmp(local_sigjmp_buf, 1) != 0)
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.
3436
/* Since not using PG_TRY, must reset error stack by hand */
3437
error_context_stack = NULL;
3439
/* Prevent interrupts while cleaning up */
3443
* Forget any pending QueryCancel request, since we're returning to
3444
* the idle loop anyway, and cancel the statement timer if running.
3446
QueryCancelPending = false;
3447
disable_sig_alarm(true);
3448
QueryCancelPending = false; /* again in case timeout occurred */
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.
3455
DoingCommandRead = false;
3456
DisableNotifyInterrupt();
3457
DisableCatchupInterrupt();
3459
/* Make sure libpq is in a good state */
3462
/* Report the error to the client and/or server log */
3466
* Make sure debug_query_string gets reset before we possibly clobber
3467
* the storage it points at.
3469
debug_query_string = NULL;
3472
* Abort the current transaction in order to recover.
3474
AbortCurrentTransaction();
3477
* Now return to normal top-level context and clear ErrorContext for
3480
MemoryContextSwitchTo(TopMemoryContext);
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).
3488
if (doing_extended_query_message)
3489
ignore_till_sync = true;
3491
/* We don't have a transaction command open anymore */
3492
xact_started = false;
3494
/* Now we can allow interrupts again */
3495
RESUME_INTERRUPTS();
3498
/* We can now handle ereport(ERROR) */
3499
PG_exception_stack = &local_sigjmp_buf;
3501
PG_SETMASK(&UnBlockSig);
3503
if (!ignore_till_sync)
3504
send_ready_for_query = true; /* initially, or after error */
3507
* Non-error queries loop here.
3513
* At top of loop, reset extended-query-message flag, so that any
3514
* errors encountered in "idle" state don't provoke skip.
3516
doing_extended_query_message = false;
3519
* Release storage left over from prior query cycle, and create a new
3520
* query input buffer in the cleared MessageContext.
3522
MemoryContextSwitchTo(MessageContext);
3523
MemoryContextResetAndDeleteChildren(MessageContext);
3525
initStringInfo(&input_message);
3528
* (1) If we've reached idle state, tell the frontend we're ready for
3531
* Note: this includes fflush()'ing the last of the prior output.
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).
3539
if (send_ready_for_query)
3541
if (IsTransactionOrTransactionBlock())
3543
set_ps_display("idle in transaction", false);
3544
pgstat_report_activity("<IDLE> in transaction");
3548
pgstat_report_stat(false);
3550
set_ps_display("idle", false);
3551
pgstat_report_activity("<IDLE>");
3554
ReadyForQuery(whereToSendOutput);
3555
send_ready_for_query = false;
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.)
3564
QueryCancelPending = false; /* forget any earlier CANCEL signal */
3565
DoingCommandRead = true;
3568
* (3) read a command (loop blocks here)
3570
firstchar = ReadCommand(&input_message);
3573
* (4) disable async signal conditions again.
3575
DoingCommandRead = false;
3578
* (5) check for any other interesting events that happened while we
3584
ProcessConfigFile(PGC_SIGHUP);
3588
* (6) process the command. But ignore it if we're skipping till
3591
if (ignore_till_sync && firstchar != EOF)
3596
case 'Q': /* simple query */
3598
const char *query_string;
3600
/* Set statement_timestamp() */
3601
SetCurrentStatementStartTimestamp();
3603
query_string = pq_getmsgstring(&input_message);
3604
pq_getmsgend(&input_message);
3606
exec_simple_query(query_string);
3608
send_ready_for_query = true;
3612
case 'P': /* parse */
3614
const char *stmt_name;
3615
const char *query_string;
3617
Oid *paramTypes = NULL;
3619
/* Set statement_timestamp() */
3620
SetCurrentStatementStartTimestamp();
3622
stmt_name = pq_getmsgstring(&input_message);
3623
query_string = pq_getmsgstring(&input_message);
3624
numParams = pq_getmsgint(&input_message, 2);
3629
paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3630
for (i = 0; i < numParams; i++)
3631
paramTypes[i] = pq_getmsgint(&input_message, 4);
3633
pq_getmsgend(&input_message);
3635
exec_parse_message(query_string, stmt_name,
3636
paramTypes, numParams);
3640
case 'B': /* bind */
3641
/* Set statement_timestamp() */
3642
SetCurrentStatementStartTimestamp();
3645
* this message is complex enough that it seems best to put
3646
* the field extraction out-of-line
3648
exec_bind_message(&input_message);
3651
case 'E': /* execute */
3653
const char *portal_name;
3656
/* Set statement_timestamp() */
3657
SetCurrentStatementStartTimestamp();
3659
portal_name = pq_getmsgstring(&input_message);
3660
max_rows = pq_getmsgint(&input_message, 4);
3661
pq_getmsgend(&input_message);
3663
exec_execute_message(portal_name, max_rows);
3667
case 'F': /* fastpath function call */
3668
/* Set statement_timestamp() */
3669
SetCurrentStatementStartTimestamp();
3671
/* Tell the collector what we're doing */
3672
pgstat_report_activity("<FASTPATH> function call");
3674
/* start an xact for this function invocation */
3675
start_xact_command();
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.
3686
/* switch back to message context */
3687
MemoryContextSwitchTo(MessageContext);
3689
if (HandleFunctionRequest(&input_message) == EOF)
3691
/* lost frontend connection during F message input */
3694
* Reset whereToSendOutput to prevent ereport from
3695
* attempting to send any more messages to client.
3697
if (whereToSendOutput == DestRemote)
3698
whereToSendOutput = DestNone;
3703
/* commit the function-invocation transaction */
3704
finish_xact_command();
3706
send_ready_for_query = true;
3709
case 'C': /* close */
3712
const char *close_target;
3714
close_type = pq_getmsgbyte(&input_message);
3715
close_target = pq_getmsgstring(&input_message);
3716
pq_getmsgend(&input_message);
3721
if (close_target[0] != '\0')
3722
DropPreparedStatement(close_target, false);
3725
/* special-case the unnamed statement */
3726
drop_unnamed_stmt();
3733
portal = GetPortalByName(close_target);
3734
if (PortalIsValid(portal))
3735
PortalDrop(portal, false);
3740
(errcode(ERRCODE_PROTOCOL_VIOLATION),
3741
errmsg("invalid CLOSE message subtype %d",
3746
if (whereToSendOutput == DestRemote)
3747
pq_putemptymessage('3'); /* CloseComplete */
3751
case 'D': /* describe */
3754
const char *describe_target;
3756
/* Set statement_timestamp() (needed for xact) */
3757
SetCurrentStatementStartTimestamp();
3759
describe_type = pq_getmsgbyte(&input_message);
3760
describe_target = pq_getmsgstring(&input_message);
3761
pq_getmsgend(&input_message);
3763
switch (describe_type)
3766
exec_describe_statement_message(describe_target);
3769
exec_describe_portal_message(describe_target);
3773
(errcode(ERRCODE_PROTOCOL_VIOLATION),
3774
errmsg("invalid DESCRIBE message subtype %d",
3781
case 'H': /* flush */
3782
pq_getmsgend(&input_message);
3783
if (whereToSendOutput == DestRemote)
3787
case 'S': /* sync */
3788
pq_getmsgend(&input_message);
3789
finish_xact_command();
3790
send_ready_for_query = true;
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.
3802
* Reset whereToSendOutput to prevent ereport from attempting
3803
* to send any more messages to client.
3805
if (whereToSendOutput == DestRemote)
3806
whereToSendOutput = DestNone;
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
3817
case 'd': /* copy data */
3818
case 'c': /* copy done */
3819
case 'f': /* copy fail */
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.
3830
(errcode(ERRCODE_PROTOCOL_VIOLATION),
3831
errmsg("invalid frontend message type %d",
3834
} /* end of input-reading loop */
3836
/* can't get here because the above loop never exits */
3839
return 1; /* keep compiler quiet */
3844
* Obtain platform stack depth limit (in bytes)
3846
* Return -1 if unlimited or not known
3849
get_stack_depth_rlimit(void)
3851
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
3852
static long val = 0;
3854
/* This won't change after process launch, so check just once */
3859
if (getrlimit(RLIMIT_STACK, &rlim) < 0)
3861
else if (rlim.rlim_cur == RLIM_INFINITY)
3864
val = rlim.rlim_cur;
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 */
3878
static struct rusage Save_r;
3879
static struct timeval Save_t;
3884
getrusage(RUSAGE_SELF, &Save_r);
3885
gettimeofday(&Save_t, NULL);
3887
/* ResetTupleCount(); */
3891
ShowUsage(const char *title)
3894
struct timeval user,
3896
struct timeval elapse_t;
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)
3907
elapse_t.tv_usec += 1000000;
3909
if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3911
r.ru_utime.tv_sec--;
3912
r.ru_utime.tv_usec += 1000000;
3914
if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3916
r.ru_stime.tv_sec--;
3917
r.ru_stime.tv_usec += 1000000;
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.
3927
initStringInfo(&str);
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",
3941
(long) user.tv_usec,
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,
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,
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 */
3972
bufusage = ShowBufferUsage();
3973
appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3976
/* remove trailing newline */
3977
if (str.data[str.len - 1] == '\n')
3978
str.data[--str.len] = '\0';
3981
(errmsg_internal("%s", title),
3982
errdetail("%s", str.data)));
3988
* on_proc_exit handler to log end of session
3991
log_disconnections(int code, Datum arg)
3993
Port *port = MyProcPort;
4001
TimestampDifference(port->SessionStartTime,
4002
GetCurrentTimestamp(),
4004
msecs = usecs / 1000;
4006
hours = secs / SECS_PER_HOUR;
4007
secs %= SECS_PER_HOUR;
4008
minutes = secs / SECS_PER_MINUTE;
4009
seconds = secs % SECS_PER_MINUTE;
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)));