PostgreSQL Source Code git master
postgres.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/time.h>
#include "access/parallel.h"
#include "access/printtup.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/async.h"
#include "commands/event_trigger.h"
#include "commands/prepare.h"
#include "common/pg_prng.h"
#include "jit/jit.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "mb/stringinfo_mb.h"
#include "miscadmin.h"
#include "nodes/print.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parser.h"
#include "pg_getopt.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/sinval.h"
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/guc_hooks.h"
#include "utils/injection_point.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/snapmgr.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postgres.c:

Go to the source code of this file.

Data Structures

struct  BindParamCbData
 

Macros

#define valgrind_report_error_query(query)   ((void) 0)
 

Typedefs

typedef struct BindParamCbData BindParamCbData
 

Functions

static int InteractiveBackend (StringInfo inBuf)
 
static int interactive_getc (void)
 
static int SocketBackend (StringInfo inBuf)
 
static int ReadCommand (StringInfo inBuf)
 
static void forbidden_in_wal_sender (char firstchar)
 
static bool check_log_statement (List *stmt_list)
 
static int errdetail_execute (List *raw_parsetree_list)
 
static int errdetail_params (ParamListInfo params)
 
static int errdetail_abort (void)
 
static void bind_param_error_callback (void *arg)
 
static void start_xact_command (void)
 
static void finish_xact_command (void)
 
static bool IsTransactionExitStmt (Node *parsetree)
 
static bool IsTransactionExitStmtList (List *pstmts)
 
static bool IsTransactionStmtList (List *pstmts)
 
static void drop_unnamed_stmt (void)
 
static void log_disconnections (int code, Datum arg)
 
static void enable_statement_timeout (void)
 
static void disable_statement_timeout (void)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
Listpg_parse_query (const char *query_string)
 
Listpg_analyze_and_rewrite_fixedparams (RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_varparams (RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_withcb (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
Listpg_rewrite_query (Query *query)
 
PlannedStmtpg_plan_query (Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
static void exec_simple_query (const char *query_string)
 
static void exec_parse_message (const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
 
static void exec_bind_message (StringInfo input_message)
 
static void exec_execute_message (const char *portal_name, long max_rows)
 
int check_log_duration (char *msec_str, bool was_logged)
 
static int errdetail_recovery_conflict (ProcSignalReason reason)
 
static void exec_describe_statement_message (const char *stmt_name)
 
static void exec_describe_portal_message (const char *portal_name)
 
void quickdie (SIGNAL_ARGS)
 
void die (SIGNAL_ARGS)
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS)
 
void HandleRecoveryConflictInterrupt (ProcSignalReason reason)
 
static void ProcessRecoveryConflictInterrupt (ProcSignalReason reason)
 
static void ProcessRecoveryConflictInterrupts (void)
 
void ProcessInterrupts (void)
 
bool check_client_connection_check_interval (int *newval, void **extra, GucSource source)
 
bool check_stage_log_stats (bool *newval, void **extra, GucSource source)
 
bool check_log_stats (bool *newval, void **extra, GucSource source)
 
void assign_transaction_timeout (int newval, void *extra)
 
bool check_restrict_nonsystem_relation_kind (char **newval, void **extra, GucSource source)
 
void assign_restrict_nonsystem_relation_kind (const char *newval, void *extra)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresSingleUserMain (int argc, char *argv[], const char *username)
 
void PostgresMain (const char *dbname, const char *username)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 

Variables

const char * debug_query_string
 
CommandDest whereToSendOutput = DestDebug
 
bool Log_disconnections = false
 
int log_statement = LOGSTMT_NONE
 
int PostAuthDelay = 0
 
int client_connection_check_interval = 0
 
int restrict_nonsystem_relation_kind
 
static bool xact_started = false
 
static bool DoingCommandRead = false
 
static bool doing_extended_query_message = false
 
static bool ignore_till_sync = false
 
static CachedPlanSourceunnamed_stmt_psrc = NULL
 
static const char * userDoption = NULL
 
static bool EchoQuery = false
 
static bool UseSemiNewlineNewline = false
 
static volatile sig_atomic_t RecoveryConflictPending = false
 
static volatile sig_atomic_t RecoveryConflictPendingReasons [NUM_PROCSIGNALS]
 
static MemoryContext row_description_context = NULL
 
static StringInfoData row_description_buf
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Macro Definition Documentation

◆ valgrind_report_error_query

#define valgrind_report_error_query (   query)    ((void) 0)

Definition at line 215 of file postgres.c.

Typedef Documentation

◆ BindParamCbData

Function Documentation

◆ assign_restrict_nonsystem_relation_kind()

void assign_restrict_nonsystem_relation_kind ( const char *  newval,
void *  extra 
)

Definition at line 3627 of file postgres.c.

3628{
3629 int *flags = (int *) extra;
3630
3632}
int restrict_nonsystem_relation_kind
Definition: postgres.c:104

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3558 of file postgres.c.

3559{
3560 if (IsTransactionState())
3561 {
3562 /*
3563 * If transaction_timeout GUC has changed within the transaction block
3564 * enable or disable the timer correspondingly.
3565 */
3570 }
3571}
#define newval
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:780
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
bool IsTransactionState(void)
Definition: xact.c:386

References disable_timeout(), enable_timeout_after(), get_timeout_active(), IsTransactionState(), newval, and TRANSACTION_TIMEOUT.

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2567 of file postgres.c.

2568{
2571 char *quotedval;
2572
2573 if (data->paramno < 0)
2574 return;
2575
2576 /* If we have a textual value, quote it, and trim if necessary */
2577 if (data->paramval)
2578 {
2582 quotedval = buf.data;
2583 }
2584 else
2585 quotedval = NULL;
2586
2587 if (data->portalName && data->portalName[0] != '\0')
2588 {
2589 if (quotedval)
2590 errcontext("portal \"%s\" parameter $%d = %s",
2591 data->portalName, data->paramno + 1, quotedval);
2592 else
2593 errcontext("portal \"%s\" parameter $%d",
2594 data->portalName, data->paramno + 1);
2595 }
2596 else
2597 {
2598 if (quotedval)
2599 errcontext("unnamed portal parameter $%d = %s",
2600 data->paramno + 1, quotedval);
2601 else
2602 errcontext("unnamed portal parameter $%d",
2603 data->paramno + 1);
2604 }
2605
2606 if (quotedval)
2607 pfree(quotedval);
2608}
#define errcontext
Definition: elog.h:196
int log_parameter_max_length_on_error
Definition: guc_tables.c:527
void pfree(void *pointer)
Definition: mcxt.c:1521
void * arg
const void * data
static char * buf
Definition: pg_test_fsync.c:72
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)
Definition: stringinfo_mb.c:34

References appendStringInfoStringQuoted(), arg, buf, data, errcontext, initStringInfo(), log_parameter_max_length_on_error, and pfree().

Referenced by exec_bind_message().

◆ check_client_connection_check_interval()

bool check_client_connection_check_interval ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3508 of file postgres.c.

3509{
3510 if (!WaitEventSetCanReportClosed() && *newval != 0)
3511 {
3512 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3513 return false;
3514 }
3515 return true;
3516}
#define GUC_check_errdetail
Definition: guc.h:476
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2248

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2398 of file postgres.c.

2399{
2402 {
2403 long secs;
2404 int usecs;
2405 int msecs;
2406 bool exceeded_duration;
2407 bool exceeded_sample_duration;
2408 bool in_sample = false;
2409
2412 &secs, &usecs);
2413 msecs = usecs / 1000;
2414
2415 /*
2416 * This odd-looking test for log_min_duration_* being exceeded is
2417 * designed to avoid integer overflow with very long durations: don't
2418 * compute secs * 1000 until we've verified it will fit in int.
2419 */
2420 exceeded_duration = (log_min_duration_statement == 0 ||
2422 (secs > log_min_duration_statement / 1000 ||
2423 secs * 1000 + msecs >= log_min_duration_statement)));
2424
2425 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2427 (secs > log_min_duration_sample / 1000 ||
2428 secs * 1000 + msecs >= log_min_duration_sample)));
2429
2430 /*
2431 * Do not log if log_statement_sample_rate = 0. Log a sample if
2432 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2433 * log_statement_sample_rate = 1.
2434 */
2435 if (exceeded_sample_duration)
2436 in_sample = log_statement_sample_rate != 0 &&
2439
2440 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2441 {
2442 snprintf(msec_str, 32, "%ld.%03d",
2443 secs * 1000 + msecs, usecs % 1000);
2444 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2445 return 2;
2446 else
2447 return 1;
2448 }
2449 }
2450
2451 return 0;
2452}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1720
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
int log_min_duration_statement
Definition: guc_tables.c:525
int log_min_duration_sample
Definition: guc_tables.c:524
double log_statement_sample_rate
Definition: guc_tables.c:529
bool log_duration
Definition: guc_tables.c:490
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:878
bool xact_is_sampled
Definition: xact.c:295

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, pg_global_prng_state, pg_prng_double(), snprintf, TimestampDifference(), and xact_is_sampled.

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2359 of file postgres.c.

2360{
2361 ListCell *stmt_item;
2362
2364 return false;
2366 return true;
2367
2368 /* Else we have to inspect the statement(s) to see whether to log */
2369 foreach(stmt_item, stmt_list)
2370 {
2371 Node *stmt = (Node *) lfirst(stmt_item);
2372
2374 return true;
2375 }
2376
2377 return false;
2378}
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:95
Definition: nodes.h:129
@ LOGSTMT_NONE
Definition: tcopprot.h:33
@ LOGSTMT_ALL
Definition: tcopprot.h:36
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3249

References GetCommandLogLevel(), lfirst, log_statement, LOGSTMT_ALL, LOGSTMT_NONE, and stmt.

Referenced by exec_execute_message(), and exec_simple_query().

◆ check_log_stats()

bool check_log_stats ( bool *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3543 of file postgres.c.

3544{
3545 if (*newval &&
3547 {
3548 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3549 "\"log_parser_stats\", \"log_planner_stats\", "
3550 "or \"log_executor_stats\" is true.");
3551 return false;
3552 }
3553 return true;
3554}
bool log_parser_stats
Definition: guc_tables.c:502
bool log_planner_stats
Definition: guc_tables.c:503
bool log_executor_stats
Definition: guc_tables.c:504

References GUC_check_errdetail, log_executor_stats, log_parser_stats, log_planner_stats, and newval.

◆ check_restrict_nonsystem_relation_kind()

bool check_restrict_nonsystem_relation_kind ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 3577 of file postgres.c.

3578{
3579 char *rawstring;
3580 List *elemlist;
3581 ListCell *l;
3582 int flags = 0;
3583
3584 /* Need a modifiable copy of string */
3585 rawstring = pstrdup(*newval);
3586
3587 if (!SplitIdentifierString(rawstring, ',', &elemlist))
3588 {
3589 /* syntax error in list */
3590 GUC_check_errdetail("List syntax is invalid.");
3591 pfree(rawstring);
3592 list_free(elemlist);
3593 return false;
3594 }
3595
3596 foreach(l, elemlist)
3597 {
3598 char *tok = (char *) lfirst(l);
3599
3600 if (pg_strcasecmp(tok, "view") == 0)
3601 flags |= RESTRICT_RELKIND_VIEW;
3602 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3604 else
3605 {
3606 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3607 pfree(rawstring);
3608 list_free(elemlist);
3609 return false;
3610 }
3611 }
3612
3613 pfree(rawstring);
3614 list_free(elemlist);
3615
3616 /* Save the flags in *extra, for use by the assign function */
3617 *extra = guc_malloc(ERROR, sizeof(int));
3618 *((int *) *extra) = flags;
3619
3620 return true;
3621}
#define ERROR
Definition: elog.h:39
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:638
void list_free(List *list)
Definition: list.c:1546
char * pstrdup(const char *in)
Definition: mcxt.c:1696
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
Definition: pg_list.h:54
#define RESTRICT_RELKIND_FOREIGN_TABLE
Definition: tcopprot.h:44
#define RESTRICT_RELKIND_VIEW
Definition: tcopprot.h:43
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3432

References ERROR, GUC_check_errdetail, guc_malloc(), lfirst, list_free(), newval, pfree(), pg_strcasecmp(), pstrdup(), RESTRICT_RELKIND_FOREIGN_TABLE, RESTRICT_RELKIND_VIEW, and SplitIdentifierString().

◆ check_stage_log_stats()

bool check_stage_log_stats ( bool *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3529 of file postgres.c.

3530{
3532 {
3533 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3534 return false;
3535 }
3536 return true;
3537}
bool log_statement_stats
Definition: guc_tables.c:505

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3001 of file postgres.c.

3002{
3003 /* Don't joggle the elbow of proc_exit */
3005 {
3006 InterruptPending = true;
3007 ProcDiePending = true;
3008 }
3009
3010 /* for the cumulative stats system */
3012
3013 /* If we're still here, waken anything waiting on the process latch */
3015
3016 /*
3017 * If we're in single user mode, we want to quit immediately - we can't
3018 * rely on latches as they wouldn't work when stdin/stdout is a file.
3019 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3020 * effort just for the benefit of single user mode.
3021 */
3024}
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:62
volatile sig_atomic_t ProcDiePending
Definition: globals.c:33
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:632
@ DISCONNECT_KILLED
Definition: pgstat.h:59
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool DoingCommandRead
Definition: postgres.c:135
void ProcessInterrupts(void)
Definition: postgres.c:3273

References DestRemote, DISCONNECT_KILLED, DoingCommandRead, InterruptPending, MyLatch, pgStatSessionEndCause, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by PostgresMain().

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2879 of file postgres.c.

2880{
2881 /* paranoia to avoid a dangling pointer in case of error */
2883 {
2885
2886 unnamed_stmt_psrc = NULL;
2887 DropCachedPlan(psrc);
2888 }
2889}
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:526
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:149

References DropCachedPlan(), and unnamed_stmt_psrc.

Referenced by exec_parse_message(), exec_simple_query(), and PostgresMain().

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

Definition at line 5129 of file postgres.c.

5130{
5131 /* must be within an xact */
5133
5134 if (StatementTimeout > 0
5136 {
5139 }
5140 else
5141 {
5144 }
5145}
#define Assert(condition)
Definition: c.h:815
static bool xact_started
Definition: postgres.c:128
int StatementTimeout
Definition: proc.c:58
int TransactionTimeout
Definition: proc.c:61

References Assert, disable_timeout(), enable_timeout_after(), get_timeout_active(), STATEMENT_TIMEOUT, StatementTimeout, TransactionTimeout, and xact_started.

Referenced by start_xact_command().

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2514 of file postgres.c.

2515{
2517 errdetail("Abort reason: recovery conflict");
2518
2519 return 0;
2520}
int errdetail(const char *fmt,...)
Definition: elog.c:1203
PGPROC * MyProc
Definition: proc.c:66
bool recoveryConflictPending
Definition: proc.h:220

References errdetail(), MyProc, and PGPROC::recoveryConflictPending.

Referenced by exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), and exec_simple_query().

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2461 of file postgres.c.

2462{
2463 ListCell *parsetree_item;
2464
2465 foreach(parsetree_item, raw_parsetree_list)
2466 {
2467 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2468
2469 if (IsA(parsetree->stmt, ExecuteStmt))
2470 {
2471 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2472 PreparedStatement *pstmt;
2473
2474 pstmt = FetchPreparedStatement(stmt->name, false);
2475 if (pstmt)
2476 {
2477 errdetail("prepare: %s", pstmt->plansource->query_string);
2478 return 0;
2479 }
2480 }
2481 }
2482
2483 return 0;
2484}
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:431
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define lfirst_node(type, lc)
Definition: pg_list.h:176
Node * stmt
Definition: parsenodes.h:2066

References errdetail(), FetchPreparedStatement(), IsA, lfirst_node, RawStmt::stmt, and stmt.

Referenced by exec_simple_query().

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2494 of file postgres.c.

2495{
2496 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2497 {
2498 char *str;
2499
2501 if (str && str[0] != '\0')
2502 errdetail("Parameters: %s", str);
2503 }
2504
2505 return 0;
2506}
int log_parameter_max_length
Definition: guc_tables.c:526
const char * str
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

References BuildParamLogString(), errdetail(), log_parameter_max_length, ParamListInfoData::numParams, and str.

Referenced by exec_bind_message(), and exec_execute_message().

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( ProcSignalReason  reason)
static

Definition at line 2528 of file postgres.c.

2529{
2530 switch (reason)
2531 {
2533 errdetail("User was holding shared buffer pin for too long.");
2534 break;
2536 errdetail("User was holding a relation lock for too long.");
2537 break;
2539 errdetail("User was or might have been using tablespace that must be dropped.");
2540 break;
2542 errdetail("User query might have needed to see row versions that must be removed.");
2543 break;
2545 errdetail("User was using a logical replication slot that must be invalidated.");
2546 break;
2548 errdetail("User transaction caused buffer deadlock with recovery.");
2549 break;
2551 errdetail("User was connected to a database that must be dropped.");
2552 break;
2553 default:
2554 break;
2555 /* no errdetail */
2556 }
2557
2558 return 0;
2559}
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:47
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
Definition: procsignal.h:46
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:42
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:45
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:48

References errdetail(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, and PROCSIG_RECOVERY_CONFLICT_TABLESPACE.

Referenced by ProcessRecoveryConflictInterrupt().

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1622 of file postgres.c.

1623{
1624 const char *portal_name;
1625 const char *stmt_name;
1626 int numPFormats;
1627 int16 *pformats = NULL;
1628 int numParams;
1629 int numRFormats;
1630 int16 *rformats = NULL;
1631 CachedPlanSource *psrc;
1632 CachedPlan *cplan;
1633 Portal portal;
1634 char *query_string;
1635 char *saved_stmt_name;
1636 ParamListInfo params;
1637 MemoryContext oldContext;
1638 bool save_log_statement_stats = log_statement_stats;
1639 bool snapshot_set = false;
1640 char msec_str[32];
1641 ParamsErrorCbData params_data;
1642 ErrorContextCallback params_errcxt;
1643 ListCell *lc;
1644
1645 /* Get the fixed part of the message */
1646 portal_name = pq_getmsgstring(input_message);
1647 stmt_name = pq_getmsgstring(input_message);
1648
1650 (errmsg_internal("bind %s to %s",
1651 *portal_name ? portal_name : "<unnamed>",
1652 *stmt_name ? stmt_name : "<unnamed>")));
1653
1654 /* Find prepared statement */
1655 if (stmt_name[0] != '\0')
1656 {
1657 PreparedStatement *pstmt;
1658
1659 pstmt = FetchPreparedStatement(stmt_name, true);
1660 psrc = pstmt->plansource;
1661 }
1662 else
1663 {
1664 /* special-case the unnamed statement */
1665 psrc = unnamed_stmt_psrc;
1666 if (!psrc)
1667 ereport(ERROR,
1668 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1669 errmsg("unnamed prepared statement does not exist")));
1670 }
1671
1672 /*
1673 * Report query to various monitoring facilities.
1674 */
1676
1678
1679 foreach(lc, psrc->query_list)
1680 {
1681 Query *query = lfirst_node(Query, lc);
1682
1683 if (query->queryId != UINT64CONST(0))
1684 {
1685 pgstat_report_query_id(query->queryId, false);
1686 break;
1687 }
1688 }
1689
1690 set_ps_display("BIND");
1691
1692 if (save_log_statement_stats)
1693 ResetUsage();
1694
1695 /*
1696 * Start up a transaction command so we can call functions etc. (Note that
1697 * this will normally change current memory context.) Nothing happens if
1698 * we are already in one. This also arms the statement timeout if
1699 * necessary.
1700 */
1702
1703 /* Switch back to message context */
1705
1706 /* Get the parameter format codes */
1707 numPFormats = pq_getmsgint(input_message, 2);
1708 if (numPFormats > 0)
1709 {
1710 pformats = palloc_array(int16, numPFormats);
1711 for (int i = 0; i < numPFormats; i++)
1712 pformats[i] = pq_getmsgint(input_message, 2);
1713 }
1714
1715 /* Get the parameter value count */
1716 numParams = pq_getmsgint(input_message, 2);
1717
1718 if (numPFormats > 1 && numPFormats != numParams)
1719 ereport(ERROR,
1720 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1721 errmsg("bind message has %d parameter formats but %d parameters",
1722 numPFormats, numParams)));
1723
1724 if (numParams != psrc->num_params)
1725 ereport(ERROR,
1726 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1727 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1728 numParams, stmt_name, psrc->num_params)));
1729
1730 /*
1731 * If we are in aborted transaction state, the only portals we can
1732 * actually run are those containing COMMIT or ROLLBACK commands. We
1733 * disallow binding anything else to avoid problems with infrastructure
1734 * that expects to run inside a valid transaction. We also disallow
1735 * binding any parameters, since we can't risk calling user-defined I/O
1736 * functions.
1737 */
1739 (!(psrc->raw_parse_tree &&
1741 numParams != 0))
1742 ereport(ERROR,
1743 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1744 errmsg("current transaction is aborted, "
1745 "commands ignored until end of transaction block"),
1746 errdetail_abort()));
1747
1748 /*
1749 * Create the portal. Allow silent replacement of an existing portal only
1750 * if the unnamed portal is specified.
1751 */
1752 if (portal_name[0] == '\0')
1753 portal = CreatePortal(portal_name, true, true);
1754 else
1755 portal = CreatePortal(portal_name, false, false);
1756
1757 /*
1758 * Prepare to copy stuff into the portal's memory context. We do all this
1759 * copying first, because it could possibly fail (out-of-memory) and we
1760 * don't want a failure to occur between GetCachedPlan and
1761 * PortalDefineQuery; that would result in leaking our plancache refcount.
1762 */
1763 oldContext = MemoryContextSwitchTo(portal->portalContext);
1764
1765 /* Copy the plan's query string into the portal */
1766 query_string = pstrdup(psrc->query_string);
1767
1768 /* Likewise make a copy of the statement name, unless it's unnamed */
1769 if (stmt_name[0])
1770 saved_stmt_name = pstrdup(stmt_name);
1771 else
1772 saved_stmt_name = NULL;
1773
1774 /*
1775 * Set a snapshot if we have parameters to fetch (since the input
1776 * functions might need it) or the query isn't a utility command (and
1777 * hence could require redoing parse analysis and planning). We keep the
1778 * snapshot active till we're done, so that plancache.c doesn't have to
1779 * take new ones.
1780 */
1781 if (numParams > 0 ||
1782 (psrc->raw_parse_tree &&
1784 {
1786 snapshot_set = true;
1787 }
1788
1789 /*
1790 * Fetch parameters, if any, and store in the portal's memory context.
1791 */
1792 if (numParams > 0)
1793 {
1794 char **knownTextValues = NULL; /* allocate on first use */
1795 BindParamCbData one_param_data;
1796
1797 /*
1798 * Set up an error callback so that if there's an error in this phase,
1799 * we can report the specific parameter causing the problem.
1800 */
1801 one_param_data.portalName = portal->name;
1802 one_param_data.paramno = -1;
1803 one_param_data.paramval = NULL;
1804 params_errcxt.previous = error_context_stack;
1805 params_errcxt.callback = bind_param_error_callback;
1806 params_errcxt.arg = &one_param_data;
1807 error_context_stack = &params_errcxt;
1808
1809 params = makeParamList(numParams);
1810
1811 for (int paramno = 0; paramno < numParams; paramno++)
1812 {
1813 Oid ptype = psrc->param_types[paramno];
1814 int32 plength;
1815 Datum pval;
1816 bool isNull;
1817 StringInfoData pbuf;
1818 char csave;
1819 int16 pformat;
1820
1821 one_param_data.paramno = paramno;
1822 one_param_data.paramval = NULL;
1823
1824 plength = pq_getmsgint(input_message, 4);
1825 isNull = (plength == -1);
1826
1827 if (!isNull)
1828 {
1829 char *pvalue;
1830
1831 /*
1832 * Rather than copying data around, we just initialize a
1833 * StringInfo pointing to the correct portion of the message
1834 * buffer. We assume we can scribble on the message buffer to
1835 * add a trailing NUL which is required for the input function
1836 * call.
1837 */
1838 pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1839 csave = pvalue[plength];
1840 pvalue[plength] = '\0';
1841 initReadOnlyStringInfo(&pbuf, pvalue, plength);
1842 }
1843 else
1844 {
1845 pbuf.data = NULL; /* keep compiler quiet */
1846 csave = 0;
1847 }
1848
1849 if (numPFormats > 1)
1850 pformat = pformats[paramno];
1851 else if (numPFormats > 0)
1852 pformat = pformats[0];
1853 else
1854 pformat = 0; /* default = text */
1855
1856 if (pformat == 0) /* text mode */
1857 {
1858 Oid typinput;
1859 Oid typioparam;
1860 char *pstring;
1861
1862 getTypeInputInfo(ptype, &typinput, &typioparam);
1863
1864 /*
1865 * We have to do encoding conversion before calling the
1866 * typinput routine.
1867 */
1868 if (isNull)
1869 pstring = NULL;
1870 else
1871 pstring = pg_client_to_server(pbuf.data, plength);
1872
1873 /* Now we can log the input string in case of error */
1874 one_param_data.paramval = pstring;
1875
1876 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1877
1878 one_param_data.paramval = NULL;
1879
1880 /*
1881 * If we might need to log parameters later, save a copy of
1882 * the converted string in MessageContext; then free the
1883 * result of encoding conversion, if any was done.
1884 */
1885 if (pstring)
1886 {
1888 {
1889 MemoryContext oldcxt;
1890
1892
1893 if (knownTextValues == NULL)
1894 knownTextValues = palloc0_array(char *, numParams);
1895
1897 knownTextValues[paramno] = pstrdup(pstring);
1898 else
1899 {
1900 /*
1901 * We can trim the saved string, knowing that we
1902 * won't print all of it. But we must copy at
1903 * least two more full characters than
1904 * BuildParamLogString wants to use; otherwise it
1905 * might fail to include the trailing ellipsis.
1906 */
1907 knownTextValues[paramno] =
1908 pnstrdup(pstring,
1911 }
1912
1913 MemoryContextSwitchTo(oldcxt);
1914 }
1915 if (pstring != pbuf.data)
1916 pfree(pstring);
1917 }
1918 }
1919 else if (pformat == 1) /* binary mode */
1920 {
1921 Oid typreceive;
1922 Oid typioparam;
1923 StringInfo bufptr;
1924
1925 /*
1926 * Call the parameter type's binary input converter
1927 */
1928 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1929
1930 if (isNull)
1931 bufptr = NULL;
1932 else
1933 bufptr = &pbuf;
1934
1935 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1936
1937 /* Trouble if it didn't eat the whole buffer */
1938 if (!isNull && pbuf.cursor != pbuf.len)
1939 ereport(ERROR,
1940 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1941 errmsg("incorrect binary data format in bind parameter %d",
1942 paramno + 1)));
1943 }
1944 else
1945 {
1946 ereport(ERROR,
1947 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1948 errmsg("unsupported format code: %d",
1949 pformat)));
1950 pval = 0; /* keep compiler quiet */
1951 }
1952
1953 /* Restore message buffer contents */
1954 if (!isNull)
1955 pbuf.data[plength] = csave;
1956
1957 params->params[paramno].value = pval;
1958 params->params[paramno].isnull = isNull;
1959
1960 /*
1961 * We mark the params as CONST. This ensures that any custom plan
1962 * makes full use of the parameter values.
1963 */
1964 params->params[paramno].pflags = PARAM_FLAG_CONST;
1965 params->params[paramno].ptype = ptype;
1966 }
1967
1968 /* Pop the per-parameter error callback */
1970
1971 /*
1972 * Once all parameters have been received, prepare for printing them
1973 * in future errors, if configured to do so. (This is saved in the
1974 * portal, so that they'll appear when the query is executed later.)
1975 */
1977 params->paramValuesStr =
1978 BuildParamLogString(params,
1979 knownTextValues,
1981 }
1982 else
1983 params = NULL;
1984
1985 /* Done storing stuff in portal's context */
1986 MemoryContextSwitchTo(oldContext);
1987
1988 /*
1989 * Set up another error callback so that all the parameters are logged if
1990 * we get an error during the rest of the BIND processing.
1991 */
1992 params_data.portalName = portal->name;
1993 params_data.params = params;
1994 params_errcxt.previous = error_context_stack;
1995 params_errcxt.callback = ParamsErrorCallback;
1996 params_errcxt.arg = &params_data;
1997 error_context_stack = &params_errcxt;
1998
1999 /* Get the result format codes */
2000 numRFormats = pq_getmsgint(input_message, 2);
2001 if (numRFormats > 0)
2002 {
2003 rformats = palloc_array(int16, numRFormats);
2004 for (int i = 0; i < numRFormats; i++)
2005 rformats[i] = pq_getmsgint(input_message, 2);
2006 }
2007
2008 pq_getmsgend(input_message);
2009
2010 /*
2011 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2012 * will be generated in MessageContext. The plan refcount will be
2013 * assigned to the Portal, so it will be released at portal destruction.
2014 */
2015 cplan = GetCachedPlan(psrc, params, NULL, NULL);
2016
2017 /*
2018 * Now we can define the portal.
2019 *
2020 * DO NOT put any code that could possibly throw an error between the
2021 * above GetCachedPlan call and here.
2022 */
2023 PortalDefineQuery(portal,
2024 saved_stmt_name,
2025 query_string,
2026 psrc->commandTag,
2027 cplan->stmt_list,
2028 cplan);
2029
2030 /* Done with the snapshot used for parameter I/O and parsing/planning */
2031 if (snapshot_set)
2033
2034 /*
2035 * And we're ready to start portal execution.
2036 */
2037 PortalStart(portal, params, 0, InvalidSnapshot);
2038
2039 /*
2040 * Apply the result format requests to the portal.
2041 */
2042 PortalSetResultFormat(portal, numRFormats, rformats);
2043
2044 /*
2045 * Done binding; remove the parameters error callback. Entries emitted
2046 * later determine independently whether to log the parameters or not.
2047 */
2049
2050 /*
2051 * Send BindComplete.
2052 */
2055
2056 /*
2057 * Emit duration logging if appropriate.
2058 */
2059 switch (check_log_duration(msec_str, false))
2060 {
2061 case 1:
2062 ereport(LOG,
2063 (errmsg("duration: %s ms", msec_str),
2064 errhidestmt(true)));
2065 break;
2066 case 2:
2067 ereport(LOG,
2068 (errmsg("duration: %s ms bind %s%s%s: %s",
2069 msec_str,
2070 *stmt_name ? stmt_name : "<unnamed>",
2071 *portal_name ? "/" : "",
2072 *portal_name ? portal_name : "",
2073 psrc->query_string),
2074 errhidestmt(true),
2075 errdetail_params(params)));
2076 break;
2077 }
2078
2079 if (save_log_statement_stats)
2080 ShowUsage("BIND MESSAGE STATISTICS");
2081
2083
2084 debug_query_string = NULL;
2085}
void pgstat_report_query_id(uint64 query_id, bool force)
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
#define unconstify(underlying_type, expr)
Definition: c.h:1202
int16_t int16
Definition: c.h:483
int32_t int32
Definition: c.h:484
#define UINT64CONST(x)
Definition: c.h:503
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errhidestmt(bool hide_stmt)
Definition: elog.c:1411
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:149
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1772
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1754
int i
Definition: isn.c:72
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2874
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2940
char * pg_client_to_server(const char *s, int len)
Definition: mbutils.c:660
MemoryContext MessageContext
Definition: mcxt.c:153
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1707
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
void ParamsErrorCallback(void *arg)
Definition: params.c:407
#define PARAM_FLAG_CONST
Definition: params.h:88
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:576
#define MAX_MULTIBYTE_CHAR_LEN
Definition: pg_wchar.h:33
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, ResourceOwner owner, QueryEnvironment *queryEnv)
Definition: plancache.c:1168
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:282
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
static int errdetail_abort(void)
Definition: postgres.c:2514
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2398
const char * debug_query_string
Definition: postgres.c:87
void ShowUsage(const char *title)
Definition: postgres.c:4984
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2494
static void bind_param_error_callback(void *arg)
Definition: postgres.c:2567
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2832
void ResetUsage(void)
Definition: postgres.c:4977
static void start_xact_command(void)
Definition: postgres.c:2761
#define valgrind_report_error_query(query)
Definition: postgres.c:215
uintptr_t Datum
Definition: postgres.h:69
unsigned int Oid
Definition: postgres_ext.h:32
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:415
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:635
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:579
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:388
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:508
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:623
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:433
#define PqMsg_BindComplete
Definition: protocol.h:39
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:212
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:610
void PopActiveSnapshot(void)
Definition: snapmgr.c:703
#define InvalidSnapshot
Definition: snapshot.h:119
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition: stringinfo.h:157
const char * portalName
Definition: postgres.c:114
const char * paramval
Definition: postgres.c:116
CommandTag commandTag
Definition: plancache.h:101
const char * query_string
Definition: plancache.h:100
struct RawStmt * raw_parse_tree
Definition: plancache.h:99
List * query_list
Definition: plancache.h:111
List * stmt_list
Definition: plancache.h:150
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
bool isnull
Definition: params.h:93
uint16 pflags
Definition: params.h:94
Datum value
Definition: params.h:92
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
char * paramValuesStr
Definition: params.h:118
ParamListInfo params
Definition: params.h:157
const char * portalName
Definition: params.h:156
MemoryContext portalContext
Definition: portal.h:120
const char * name
Definition: portal.h:118
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:406

References analyze_requires_snapshot(), ErrorContextCallback::arg, bind_param_error_callback(), BuildParamLogString(), ErrorContextCallback::callback, check_log_duration(), CachedPlanSource::commandTag, CreatePortal(), StringInfoData::cursor, StringInfoData::data, DEBUG2, debug_query_string, DestRemote, ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), errmsg_internal(), ERROR, error_context_stack, FetchPreparedStatement(), GetCachedPlan(), GetTransactionSnapshot(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, initReadOnlyStringInfo(), InvalidSnapshot, IsAbortedTransactionBlockState(), ParamExternData::isnull, IsTransactionExitStmt(), StringInfoData::len, lfirst_node, LOG, log_parameter_max_length_on_error, log_statement_stats, makeParamList(), MAX_MULTIBYTE_CHAR_LEN, MemoryContextSwitchTo(), MessageContext, PortalData::name, CachedPlanSource::num_params, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc0_array, palloc_array, PARAM_FLAG_CONST, CachedPlanSource::param_types, BindParamCbData::paramno, ParamListInfoData::params, ParamsErrorCbData::params, ParamsErrorCallback(), BindParamCbData::paramval, ParamListInfoData::paramValuesStr, ParamExternData::pflags, pfree(), pg_client_to_server(), pgstat_report_activity(), pgstat_report_query_id(), PreparedStatement::plansource, pnstrdup(), PopActiveSnapshot(), PortalData::portalContext, PortalDefineQuery(), BindParamCbData::portalName, ParamsErrorCbData::portalName, PortalSetResultFormat(), PortalStart(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_putemptymessage(), PqMsg_BindComplete, ErrorContextCallback::previous, pstrdup(), ParamExternData::ptype, PushActiveSnapshot(), CachedPlanSource::query_list, CachedPlanSource::query_string, CachedPlanSource::raw_parse_tree, ResetUsage(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, CachedPlan::stmt_list, UINT64CONST, unconstify, unnamed_stmt_psrc, valgrind_report_error_query, ParamExternData::value, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2709 of file postgres.c.

2710{
2711 Portal portal;
2712
2713 /*
2714 * Start up a transaction command. (Note that this will normally change
2715 * current memory context.) Nothing happens if we are already in one.
2716 */
2718
2719 /* Switch back to message context */
2721
2722 portal = GetPortalByName(portal_name);
2723 if (!PortalIsValid(portal))
2724 ereport(ERROR,
2725 (errcode(ERRCODE_UNDEFINED_CURSOR),
2726 errmsg("portal \"%s\" does not exist", portal_name)));
2727
2728 /*
2729 * If we are in aborted transaction state, we can't run
2730 * SendRowDescriptionMessage(), because that needs catalog accesses.
2731 * Hence, refuse to Describe portals that return data. (We shouldn't just
2732 * refuse all Describes, since that might break the ability of some
2733 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2734 * blindly Describes whatever it does.)
2735 */
2737 portal->tupDesc)
2738 ereport(ERROR,
2739 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2740 errmsg("current transaction is aborted, "
2741 "commands ignored until end of transaction block"),
2742 errdetail_abort()));
2743
2745 return; /* can't actually do anything... */
2746
2747 if (portal->tupDesc)
2749 portal->tupDesc,
2750 FetchPortalTargetList(portal),
2751 portal->formats);
2752 else
2754}
#define PortalIsValid(p)
Definition: portal.h:211
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
static StringInfoData row_description_buf
Definition: postgres.c:162
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:326
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:166
#define PqMsg_NoData
Definition: protocol.h:56
int16 * formats
Definition: portal.h:161
TupleDesc tupDesc
Definition: portal.h:159

References DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPortalTargetList(), PortalData::formats, GetPortalByName(), IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, PortalIsValid, pq_putemptymessage(), PqMsg_NoData, row_description_buf, SendRowDescriptionMessage(), start_xact_command(), PortalData::tupDesc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2616 of file postgres.c.

2617{
2618 CachedPlanSource *psrc;
2619
2620 /*
2621 * Start up a transaction command. (Note that this will normally change
2622 * current memory context.) Nothing happens if we are already in one.
2623 */
2625
2626 /* Switch back to message context */
2628
2629 /* Find prepared statement */
2630 if (stmt_name[0] != '\0')
2631 {
2632 PreparedStatement *pstmt;
2633
2634 pstmt = FetchPreparedStatement(stmt_name, true);
2635 psrc = pstmt->plansource;
2636 }
2637 else
2638 {
2639 /* special-case the unnamed statement */
2640 psrc = unnamed_stmt_psrc;
2641 if (!psrc)
2642 ereport(ERROR,
2643 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2644 errmsg("unnamed prepared statement does not exist")));
2645 }
2646
2647 /* Prepared statements shouldn't have changeable result descs */
2648 Assert(psrc->fixed_result);
2649
2650 /*
2651 * If we are in aborted transaction state, we can't run
2652 * SendRowDescriptionMessage(), because that needs catalog accesses.
2653 * Hence, refuse to Describe statements that return data. (We shouldn't
2654 * just refuse all Describes, since that might break the ability of some
2655 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2656 * blindly Describes whatever it does.) We can Describe parameters
2657 * without doing anything dangerous, so we don't restrict that.
2658 */
2660 psrc->resultDesc)
2661 ereport(ERROR,
2662 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2663 errmsg("current transaction is aborted, "
2664 "commands ignored until end of transaction block"),
2665 errdetail_abort()));
2666
2668 return; /* can't actually do anything... */
2669
2670 /*
2671 * First describe the parameters...
2672 */
2675
2676 for (int i = 0; i < psrc->num_params; i++)
2677 {
2678 Oid ptype = psrc->param_types[i];
2679
2680 pq_sendint32(&row_description_buf, (int) ptype);
2681 }
2683
2684 /*
2685 * Next send RowDescription or NoData to describe the result...
2686 */
2687 if (psrc->resultDesc)
2688 {
2689 List *tlist;
2690
2691 /* Get the plan's primary targetlist */
2692 tlist = CachedPlanGetTargetList(psrc, NULL);
2693
2695 psrc->resultDesc,
2696 tlist,
2697 NULL);
2698 }
2699 else
2701}
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1640
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition: pqformat.c:109
void pq_endmessage_reuse(StringInfo buf)
Definition: pqformat.c:314
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:136
#define PqMsg_ParameterDescription
Definition: protocol.h:58
TupleDesc resultDesc
Definition: plancache.h:108

References Assert, CachedPlanGetTargetList(), DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPreparedStatement(), CachedPlanSource::fixed_result, i, IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, CachedPlanSource::num_params, CachedPlanSource::param_types, PreparedStatement::plansource, pq_beginmessage_reuse(), pq_endmessage_reuse(), pq_putemptymessage(), pq_sendint16(), pq_sendint32(), PqMsg_NoData, PqMsg_ParameterDescription, CachedPlanSource::resultDesc, row_description_buf, SendRowDescriptionMessage(), start_xact_command(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_execute_message()

static void exec_execute_message ( const char *  portal_name,
long  max_rows 
)
static

Definition at line 2093 of file postgres.c.

2094{
2096 DestReceiver *receiver;
2097 Portal portal;
2098 bool completed;
2099 QueryCompletion qc;
2100 const char *sourceText;
2101 const char *prepStmtName;
2102 ParamListInfo portalParams;
2103 bool save_log_statement_stats = log_statement_stats;
2104 bool is_xact_command;
2105 bool execute_is_fetch;
2106 bool was_logged = false;
2107 char msec_str[32];
2108 ParamsErrorCbData params_data;
2109 ErrorContextCallback params_errcxt;
2110 const char *cmdtagname;
2111 size_t cmdtaglen;
2112 ListCell *lc;
2113
2114 /* Adjust destination to tell printtup.c what to do */
2116 if (dest == DestRemote)
2118
2119 portal = GetPortalByName(portal_name);
2120 if (!PortalIsValid(portal))
2121 ereport(ERROR,
2122 (errcode(ERRCODE_UNDEFINED_CURSOR),
2123 errmsg("portal \"%s\" does not exist", portal_name)));
2124
2125 /*
2126 * If the original query was a null string, just return
2127 * EmptyQueryResponse.
2128 */
2129 if (portal->commandTag == CMDTAG_UNKNOWN)
2130 {
2131 Assert(portal->stmts == NIL);
2133 return;
2134 }
2135
2136 /* Does the portal contain a transaction command? */
2137 is_xact_command = IsTransactionStmtList(portal->stmts);
2138
2139 /*
2140 * We must copy the sourceText and prepStmtName into MessageContext in
2141 * case the portal is destroyed during finish_xact_command. We do not
2142 * make a copy of the portalParams though, preferring to just not print
2143 * them in that case.
2144 */
2145 sourceText = pstrdup(portal->sourceText);
2146 if (portal->prepStmtName)
2147 prepStmtName = pstrdup(portal->prepStmtName);
2148 else
2149 prepStmtName = "<unnamed>";
2150 portalParams = portal->portalParams;
2151
2152 /*
2153 * Report query to various monitoring facilities.
2154 */
2155 debug_query_string = sourceText;
2156
2158
2159 foreach(lc, portal->stmts)
2160 {
2162
2163 if (stmt->queryId != UINT64CONST(0))
2164 {
2165 pgstat_report_query_id(stmt->queryId, false);
2166 break;
2167 }
2168 }
2169
2170 cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
2171
2172 set_ps_display_with_len(cmdtagname, cmdtaglen);
2173
2174 if (save_log_statement_stats)
2175 ResetUsage();
2176
2177 BeginCommand(portal->commandTag, dest);
2178
2179 /*
2180 * Create dest receiver in MessageContext (we don't want it in transaction
2181 * context, because that may get deleted if portal contains VACUUM).
2182 */
2183 receiver = CreateDestReceiver(dest);
2184 if (dest == DestRemoteExecute)
2185 SetRemoteDestReceiverParams(receiver, portal);
2186
2187 /*
2188 * Ensure we are in a transaction command (this should normally be the
2189 * case already due to prior BIND).
2190 */
2192
2193 /*
2194 * If we re-issue an Execute protocol request against an existing portal,
2195 * then we are only fetching more rows rather than completely re-executing
2196 * the query from the start. atStart is never reset for a v3 portal, so we
2197 * are safe to use this check.
2198 */
2199 execute_is_fetch = !portal->atStart;
2200
2201 /* Log immediately if dictated by log_statement */
2202 if (check_log_statement(portal->stmts))
2203 {
2204 ereport(LOG,
2205 (errmsg("%s %s%s%s: %s",
2206 execute_is_fetch ?
2207 _("execute fetch from") :
2208 _("execute"),
2209 prepStmtName,
2210 *portal_name ? "/" : "",
2211 *portal_name ? portal_name : "",
2212 sourceText),
2213 errhidestmt(true),
2214 errdetail_params(portalParams)));
2215 was_logged = true;
2216 }
2217
2218 /*
2219 * If we are in aborted transaction state, the only portals we can
2220 * actually run are those containing COMMIT or ROLLBACK commands.
2221 */
2224 ereport(ERROR,
2225 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2226 errmsg("current transaction is aborted, "
2227 "commands ignored until end of transaction block"),
2228 errdetail_abort()));
2229
2230 /* Check for cancel signal before we start execution */
2232
2233 /*
2234 * Okay to run the portal. Set the error callback so that parameters are
2235 * logged. The parameters must have been saved during the bind phase.
2236 */
2237 params_data.portalName = portal->name;
2238 params_data.params = portalParams;
2239 params_errcxt.previous = error_context_stack;
2240 params_errcxt.callback = ParamsErrorCallback;
2241 params_errcxt.arg = &params_data;
2242 error_context_stack = &params_errcxt;
2243
2244 if (max_rows <= 0)
2245 max_rows = FETCH_ALL;
2246
2247 completed = PortalRun(portal,
2248 max_rows,
2249 true, /* always top level */
2250 receiver,
2251 receiver,
2252 &qc);
2253
2254 receiver->rDestroy(receiver);
2255
2256 /* Done executing; remove the params error callback */
2258
2259 if (completed)
2260 {
2261 if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
2262 {
2263 /*
2264 * If this was a transaction control statement, commit it. We
2265 * will start a new xact command for the next command (if any).
2266 * Likewise if the statement required immediate commit. Without
2267 * this provision, we wouldn't force commit until Sync is
2268 * received, which creates a hazard if the client tries to
2269 * pipeline immediate-commit statements.
2270 */
2272
2273 /*
2274 * These commands typically don't have any parameters, and even if
2275 * one did we couldn't print them now because the storage went
2276 * away during finish_xact_command. So pretend there were none.
2277 */
2278 portalParams = NULL;
2279 }
2280 else
2281 {
2282 /*
2283 * We need a CommandCounterIncrement after every query, except
2284 * those that start or end a transaction block.
2285 */
2287
2288 /*
2289 * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2290 * message without immediately committing the transaction.
2291 */
2293
2294 /*
2295 * Disable statement timeout whenever we complete an Execute
2296 * message. The next protocol message will start a fresh timeout.
2297 */
2299 }
2300
2301 /* Send appropriate CommandComplete to client */
2302 EndCommand(&qc, dest, false);
2303 }
2304 else
2305 {
2306 /* Portal run not complete, so send PortalSuspended */
2309
2310 /*
2311 * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2312 * too.
2313 */
2315 }
2316
2317 /*
2318 * Emit duration logging if appropriate.
2319 */
2320 switch (check_log_duration(msec_str, was_logged))
2321 {
2322 case 1:
2323 ereport(LOG,
2324 (errmsg("duration: %s ms", msec_str),
2325 errhidestmt(true)));
2326 break;
2327 case 2:
2328 ereport(LOG,
2329 (errmsg("duration: %s ms %s %s%s%s: %s",
2330 msec_str,
2331 execute_is_fetch ?
2332 _("execute fetch from") :
2333 _("execute"),
2334 prepStmtName,
2335 *portal_name ? "/" : "",
2336 *portal_name ? portal_name : "",
2337 sourceText),
2338 errhidestmt(true),
2339 errdetail_params(portalParams)));
2340 break;
2341 }
2342
2343 if (save_log_statement_stats)
2344 ShowUsage("EXECUTE MESSAGE STATISTICS");
2345
2347
2348 debug_query_string = NULL;
2349}
const char * GetCommandTagNameAndLen(CommandTag commandTag, Size *len)
Definition: cmdtag.c:53
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:169
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
void NullCommand(CommandDest dest)
Definition: dest.c:218
CommandDest
Definition: dest.h:86
@ DestRemoteExecute
Definition: dest.h:90
#define _(x)
Definition: elog.c:90
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define FETCH_ALL
Definition: parsenodes.h:3399
#define NIL
Definition: pg_list.h:68
static void disable_statement_timeout(void)
Definition: postgres.c:5151
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2864
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2359
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2849
static void finish_xact_command(void)
Definition: postgres.c:2800
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:684
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:100
#define PqMsg_PortalSuspended
Definition: protocol.h:57
void set_ps_display_with_len(const char *activity, size_t len)
Definition: ps_status.c:453
CommandTag commandTag
Definition: portal.h:137
const char * sourceText
Definition: portal.h:136
bool atStart
Definition: portal.h:198
List * stmts
Definition: portal.h:139
ParamListInfo portalParams
Definition: portal.h:142
const char * prepStmtName
Definition: portal.h:119
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
void CommandCounterIncrement(void)
Definition: xact.c:1099
int MyXactFlags
Definition: xact.c:135
#define XACT_FLAGS_PIPELINING
Definition: xact.h:121
#define XACT_FLAGS_NEEDIMMEDIATECOMMIT
Definition: xact.h:114

References _, ErrorContextCallback::arg, Assert, PortalData::atStart, BeginCommand(), ErrorContextCallback::callback, CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), PortalData::commandTag, CreateDestReceiver(), debug_query_string, generate_unaccent_rules::dest, DestRemote, DestRemoteExecute, disable_statement_timeout(), EndCommand(), ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, error_context_stack, FETCH_ALL, finish_xact_command(), GetCommandTagNameAndLen(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), lfirst_node, LOG, log_statement_stats, MyXactFlags, PortalData::name, NIL, NullCommand(), ParamsErrorCbData::params, ParamsErrorCallback(), pgstat_report_activity(), pgstat_report_query_id(), PortalIsValid, ParamsErrorCbData::portalName, PortalData::portalParams, PortalRun(), pq_putemptymessage(), PqMsg_PortalSuspended, PortalData::prepStmtName, ErrorContextCallback::previous, pstrdup(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display_with_len(), SetRemoteDestReceiverParams(), ShowUsage(), PortalData::sourceText, start_xact_command(), STATE_RUNNING, stmt, PortalData::stmts, UINT64CONST, valgrind_report_error_query, whereToSendOutput, XACT_FLAGS_NEEDIMMEDIATECOMMIT, and XACT_FLAGS_PIPELINING.

Referenced by PostgresMain().

◆ exec_parse_message()

static void exec_parse_message ( const char *  query_string,
const char *  stmt_name,
Oid paramTypes,
int  numParams 
)
static

Definition at line 1387 of file postgres.c.

1391{
1392 MemoryContext unnamed_stmt_context = NULL;
1393 MemoryContext oldcontext;
1394 List *parsetree_list;
1395 RawStmt *raw_parse_tree;
1396 List *querytree_list;
1397 CachedPlanSource *psrc;
1398 bool is_named;
1399 bool save_log_statement_stats = log_statement_stats;
1400 char msec_str[32];
1401
1402 /*
1403 * Report query to various monitoring facilities.
1404 */
1405 debug_query_string = query_string;
1406
1408
1409 set_ps_display("PARSE");
1410
1411 if (save_log_statement_stats)
1412 ResetUsage();
1413
1415 (errmsg_internal("parse %s: %s",
1416 *stmt_name ? stmt_name : "<unnamed>",
1417 query_string)));
1418
1419 /*
1420 * Start up a transaction command so we can run parse analysis etc. (Note
1421 * that this will normally change current memory context.) Nothing happens
1422 * if we are already in one. This also arms the statement timeout if
1423 * necessary.
1424 */
1426
1427 /*
1428 * Switch to appropriate context for constructing parsetrees.
1429 *
1430 * We have two strategies depending on whether the prepared statement is
1431 * named or not. For a named prepared statement, we do parsing in
1432 * MessageContext and copy the finished trees into the prepared
1433 * statement's plancache entry; then the reset of MessageContext releases
1434 * temporary space used by parsing and rewriting. For an unnamed prepared
1435 * statement, we assume the statement isn't going to hang around long, so
1436 * getting rid of temp space quickly is probably not worth the costs of
1437 * copying parse trees. So in this case, we create the plancache entry's
1438 * query_context here, and do all the parsing work therein.
1439 */
1440 is_named = (stmt_name[0] != '\0');
1441 if (is_named)
1442 {
1443 /* Named prepared statement --- parse in MessageContext */
1445 }
1446 else
1447 {
1448 /* Unnamed prepared statement --- release any prior unnamed stmt */
1450 /* Create context for parsing */
1451 unnamed_stmt_context =
1453 "unnamed prepared statement",
1455 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1456 }
1457
1458 /*
1459 * Do basic parsing of the query or queries (this should be safe even if
1460 * we are in aborted transaction state!)
1461 */
1462 parsetree_list = pg_parse_query(query_string);
1463
1464 /*
1465 * We only allow a single user statement in a prepared statement. This is
1466 * mainly to keep the protocol simple --- otherwise we'd need to worry
1467 * about multiple result tupdescs and things like that.
1468 */
1469 if (list_length(parsetree_list) > 1)
1470 ereport(ERROR,
1471 (errcode(ERRCODE_SYNTAX_ERROR),
1472 errmsg("cannot insert multiple commands into a prepared statement")));
1473
1474 if (parsetree_list != NIL)
1475 {
1476 bool snapshot_set = false;
1477
1478 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1479
1480 /*
1481 * If we are in an aborted transaction, reject all commands except
1482 * COMMIT/ROLLBACK. It is important that this test occur before we
1483 * try to do parse analysis, rewrite, or planning, since all those
1484 * phases try to do database accesses, which may fail in abort state.
1485 * (It might be safe to allow some additional utility commands in this
1486 * state, but not many...)
1487 */
1489 !IsTransactionExitStmt(raw_parse_tree->stmt))
1490 ereport(ERROR,
1491 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1492 errmsg("current transaction is aborted, "
1493 "commands ignored until end of transaction block"),
1494 errdetail_abort()));
1495
1496 /*
1497 * Create the CachedPlanSource before we do parse analysis, since it
1498 * needs to see the unmodified raw parse tree.
1499 */
1500 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1501 CreateCommandTag(raw_parse_tree->stmt));
1502
1503 /*
1504 * Set up a snapshot if parse analysis will need one.
1505 */
1506 if (analyze_requires_snapshot(raw_parse_tree))
1507 {
1509 snapshot_set = true;
1510 }
1511
1512 /*
1513 * Analyze and rewrite the query. Note that the originally specified
1514 * parameter set is not required to be complete, so we have to use
1515 * pg_analyze_and_rewrite_varparams().
1516 */
1517 querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
1518 query_string,
1519 &paramTypes,
1520 &numParams,
1521 NULL);
1522
1523 /* Done with the snapshot used for parsing */
1524 if (snapshot_set)
1526 }
1527 else
1528 {
1529 /* Empty input string. This is legal. */
1530 raw_parse_tree = NULL;
1531 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1532 CMDTAG_UNKNOWN);
1533 querytree_list = NIL;
1534 }
1535
1536 /*
1537 * CachedPlanSource must be a direct child of MessageContext before we
1538 * reparent unnamed_stmt_context under it, else we have a disconnected
1539 * circular subgraph. Klugy, but less so than flipping contexts even more
1540 * above.
1541 */
1542 if (unnamed_stmt_context)
1544
1545 /* Finish filling in the CachedPlanSource */
1546 CompleteCachedPlan(psrc,
1547 querytree_list,
1548 unnamed_stmt_context,
1549 paramTypes,
1550 numParams,
1551 NULL,
1552 NULL,
1553 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1554 true); /* fixed result */
1555
1556 /* If we got a cancel signal during analysis, quit */
1558
1559 if (is_named)
1560 {
1561 /*
1562 * Store the query as a prepared statement.
1563 */
1564 StorePreparedStatement(stmt_name, psrc, false);
1565 }
1566 else
1567 {
1568 /*
1569 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1570 */
1571 SaveCachedPlan(psrc);
1572 unnamed_stmt_psrc = psrc;
1573 }
1574
1575 MemoryContextSwitchTo(oldcontext);
1576
1577 /*
1578 * We do NOT close the open transaction command here; that only happens
1579 * when the client sends Sync. Instead, do CommandCounterIncrement just
1580 * in case something happened during parse/plan.
1581 */
1583
1584 /*
1585 * Send ParseComplete.
1586 */
1589
1590 /*
1591 * Emit duration logging if appropriate.
1592 */
1593 switch (check_log_duration(msec_str, false))
1594 {
1595 case 1:
1596 ereport(LOG,
1597 (errmsg("duration: %s ms", msec_str),
1598 errhidestmt(true)));
1599 break;
1600 case 2:
1601 ereport(LOG,
1602 (errmsg("duration: %s ms parse %s: %s",
1603 msec_str,
1604 *stmt_name ? stmt_name : "<unnamed>",
1605 query_string),
1606 errhidestmt(true)));
1607 break;
1608 }
1609
1610 if (save_log_statement_stats)
1611 ShowUsage("PARSE MESSAGE STATISTICS");
1612
1613 debug_query_string = NULL;
1614}
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:389
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:637
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3364
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:482
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:366
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:192
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
List * pg_analyze_and_rewrite_varparams(RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:703
static void drop_unnamed_stmt(void)
Definition: postgres.c:2879
#define PqMsg_ParseComplete
Definition: protocol.h:38
MemoryContext context
Definition: plancache.h:109
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2362

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_requires_snapshot(), CHECK_FOR_INTERRUPTS, check_log_duration(), CommandCounterIncrement(), CompleteCachedPlan(), CachedPlanSource::context, CreateCachedPlan(), CreateCommandTag(), CURSOR_OPT_PARALLEL_OK, DEBUG2, debug_query_string, DestRemote, drop_unnamed_stmt(), ereport, errcode(), errdetail_abort(), errhidestmt(), errmsg(), errmsg_internal(), ERROR, GetTransactionSnapshot(), IsAbortedTransactionBlockState(), IsTransactionExitStmt(), linitial_node, list_length(), LOG, log_statement_stats, MemoryContextSetParent(), MemoryContextSwitchTo(), MessageContext, NIL, pg_analyze_and_rewrite_varparams(), pg_parse_query(), pgstat_report_activity(), PopActiveSnapshot(), pq_putemptymessage(), PqMsg_ParseComplete, PushActiveSnapshot(), ResetUsage(), SaveCachedPlan(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, StorePreparedStatement(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 1010 of file postgres.c.

1011{
1013 MemoryContext oldcontext;
1014 List *parsetree_list;
1015 ListCell *parsetree_item;
1016 bool save_log_statement_stats = log_statement_stats;
1017 bool was_logged = false;
1018 bool use_implicit_block;
1019 char msec_str[32];
1020
1021 /*
1022 * Report query to various monitoring facilities.
1023 */
1024 debug_query_string = query_string;
1025
1027
1028 TRACE_POSTGRESQL_QUERY_START(query_string);
1029
1030 /*
1031 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1032 * results because ResetUsage wasn't called.
1033 */
1034 if (save_log_statement_stats)
1035 ResetUsage();
1036
1037 /*
1038 * Start up a transaction command. All queries generated by the
1039 * query_string will be in this same command block, *unless* we find a
1040 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1041 * one of those, else bad things will happen in xact.c. (Note that this
1042 * will normally change current memory context.)
1043 */
1045
1046 /*
1047 * Zap any pre-existing unnamed statement. (While not strictly necessary,
1048 * it seems best to define simple-Query mode as if it used the unnamed
1049 * statement and portal; this ensures we recover any storage used by prior
1050 * unnamed operations.)
1051 */
1053
1054 /*
1055 * Switch to appropriate context for constructing parsetrees.
1056 */
1058
1059 /*
1060 * Do basic parsing of the query or queries (this should be safe even if
1061 * we are in aborted transaction state!)
1062 */
1063 parsetree_list = pg_parse_query(query_string);
1064
1065 /* Log immediately if dictated by log_statement */
1066 if (check_log_statement(parsetree_list))
1067 {
1068 ereport(LOG,
1069 (errmsg("statement: %s", query_string),
1070 errhidestmt(true),
1071 errdetail_execute(parsetree_list)));
1072 was_logged = true;
1073 }
1074
1075 /*
1076 * Switch back to transaction context to enter the loop.
1077 */
1078 MemoryContextSwitchTo(oldcontext);
1079
1080 /*
1081 * For historical reasons, if multiple SQL statements are given in a
1082 * single "simple Query" message, we execute them as a single transaction,
1083 * unless explicit transaction control commands are included to make
1084 * portions of the list be separate transactions. To represent this
1085 * behavior properly in the transaction machinery, we use an "implicit"
1086 * transaction block.
1087 */
1088 use_implicit_block = (list_length(parsetree_list) > 1);
1089
1090 /*
1091 * Run through the raw parsetree(s) and process each one.
1092 */
1093 foreach(parsetree_item, parsetree_list)
1094 {
1095 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1096 bool snapshot_set = false;
1097 CommandTag commandTag;
1098 QueryCompletion qc;
1099 MemoryContext per_parsetree_context = NULL;
1100 List *querytree_list,
1101 *plantree_list;
1102 Portal portal;
1103 DestReceiver *receiver;
1104 int16 format;
1105 const char *cmdtagname;
1106 size_t cmdtaglen;
1107
1108 pgstat_report_query_id(0, true);
1109
1110 /*
1111 * Get the command name for use in status display (it also becomes the
1112 * default completion tag, down inside PortalRun). Set ps_status and
1113 * do any special start-of-SQL-command processing needed by the
1114 * destination.
1115 */
1116 commandTag = CreateCommandTag(parsetree->stmt);
1117 cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
1118
1119 set_ps_display_with_len(cmdtagname, cmdtaglen);
1120
1121 BeginCommand(commandTag, dest);
1122
1123 /*
1124 * If we are in an aborted transaction, reject all commands except
1125 * COMMIT/ABORT. It is important that this test occur before we try
1126 * to do parse analysis, rewrite, or planning, since all those phases
1127 * try to do database accesses, which may fail in abort state. (It
1128 * might be safe to allow some additional utility commands in this
1129 * state, but not many...)
1130 */
1132 !IsTransactionExitStmt(parsetree->stmt))
1133 ereport(ERROR,
1134 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1135 errmsg("current transaction is aborted, "
1136 "commands ignored until end of transaction block"),
1137 errdetail_abort()));
1138
1139 /* Make sure we are in a transaction command */
1141
1142 /*
1143 * If using an implicit transaction block, and we're not already in a
1144 * transaction block, start an implicit block to force this statement
1145 * to be grouped together with any following ones. (We must do this
1146 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1147 * list would cause later statements to not be grouped.)
1148 */
1149 if (use_implicit_block)
1151
1152 /* If we got a cancel signal in parsing or prior command, quit */
1154
1155 /*
1156 * Set up a snapshot if parse analysis/planning will need one.
1157 */
1158 if (analyze_requires_snapshot(parsetree))
1159 {
1161 snapshot_set = true;
1162 }
1163
1164 /*
1165 * OK to analyze, rewrite, and plan this query.
1166 *
1167 * Switch to appropriate context for constructing query and plan trees
1168 * (these can't be in the transaction context, as that will get reset
1169 * when the command is COMMIT/ROLLBACK). If we have multiple
1170 * parsetrees, we use a separate context for each one, so that we can
1171 * free that memory before moving on to the next one. But for the
1172 * last (or only) parsetree, just use MessageContext, which will be
1173 * reset shortly after completion anyway. In event of an error, the
1174 * per_parsetree_context will be deleted when MessageContext is reset.
1175 */
1176 if (lnext(parsetree_list, parsetree_item) != NULL)
1177 {
1178 per_parsetree_context =
1180 "per-parsetree message context",
1182 oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1183 }
1184 else
1186
1187 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1188 NULL, 0, NULL);
1189
1190 plantree_list = pg_plan_queries(querytree_list, query_string,
1192
1193 /*
1194 * Done with the snapshot used for parsing/planning.
1195 *
1196 * While it looks promising to reuse the same snapshot for query
1197 * execution (at least for simple protocol), unfortunately it causes
1198 * execution to use a snapshot that has been acquired before locking
1199 * any of the tables mentioned in the query. This creates user-
1200 * visible anomalies, so refrain. Refer to
1201 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1202 */
1203 if (snapshot_set)
1205
1206 /* If we got a cancel signal in analysis or planning, quit */
1208
1209 /*
1210 * Create unnamed portal to run the query or queries in. If there
1211 * already is one, silently drop it.
1212 */
1213 portal = CreatePortal("", true, true);
1214 /* Don't display the portal in pg_cursors */
1215 portal->visible = false;
1216
1217 /*
1218 * We don't have to copy anything into the portal, because everything
1219 * we are passing here is in MessageContext or the
1220 * per_parsetree_context, and so will outlive the portal anyway.
1221 */
1222 PortalDefineQuery(portal,
1223 NULL,
1224 query_string,
1225 commandTag,
1226 plantree_list,
1227 NULL);
1228
1229 /*
1230 * Start the portal. No parameters here.
1231 */
1232 PortalStart(portal, NULL, 0, InvalidSnapshot);
1233
1234 /*
1235 * Select the appropriate output format: text unless we are doing a
1236 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1237 * --- but it avoids grottiness in other places. Ah, the joys of
1238 * backward compatibility...)
1239 */
1240 format = 0; /* TEXT is default */
1241 if (IsA(parsetree->stmt, FetchStmt))
1242 {
1243 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1244
1245 if (!stmt->ismove)
1246 {
1247 Portal fportal = GetPortalByName(stmt->portalname);
1248
1249 if (PortalIsValid(fportal) &&
1250 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1251 format = 1; /* BINARY */
1252 }
1253 }
1254 PortalSetResultFormat(portal, 1, &format);
1255
1256 /*
1257 * Now we can create the destination receiver object.
1258 */
1259 receiver = CreateDestReceiver(dest);
1260 if (dest == DestRemote)
1261 SetRemoteDestReceiverParams(receiver, portal);
1262
1263 /*
1264 * Switch back to transaction context for execution.
1265 */
1266 MemoryContextSwitchTo(oldcontext);
1267
1268 /*
1269 * Run the portal to completion, and then drop it (and the receiver).
1270 */
1271 (void) PortalRun(portal,
1272 FETCH_ALL,
1273 true, /* always top level */
1274 receiver,
1275 receiver,
1276 &qc);
1277
1278 receiver->rDestroy(receiver);
1279
1280 PortalDrop(portal, false);
1281
1282 if (lnext(parsetree_list, parsetree_item) == NULL)
1283 {
1284 /*
1285 * If this is the last parsetree of the query string, close down
1286 * transaction statement before reporting command-complete. This
1287 * is so that any end-of-transaction errors are reported before
1288 * the command-complete message is issued, to avoid confusing
1289 * clients who will expect either a command-complete message or an
1290 * error, not one and then the other. Also, if we're using an
1291 * implicit transaction block, we must close that out first.
1292 */
1293 if (use_implicit_block)
1296 }
1297 else if (IsA(parsetree->stmt, TransactionStmt))
1298 {
1299 /*
1300 * If this was a transaction control statement, commit it. We will
1301 * start a new xact command for the next command.
1302 */
1304 }
1305 else
1306 {
1307 /*
1308 * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1309 * we're not calling finish_xact_command(). (The implicit
1310 * transaction block should have prevented it from getting set.)
1311 */
1313
1314 /*
1315 * We need a CommandCounterIncrement after every query, except
1316 * those that start or end a transaction block.
1317 */
1319
1320 /*
1321 * Disable statement timeout between queries of a multi-query
1322 * string, so that the timeout applies separately to each query.
1323 * (Our next loop iteration will start a fresh timeout.)
1324 */
1326 }
1327
1328 /*
1329 * Tell client that we're done with this query. Note we emit exactly
1330 * one EndCommand report for each raw parsetree, thus one for each SQL
1331 * command the client sent, regardless of rewriting. (But a command
1332 * aborted by error will not send an EndCommand report at all.)
1333 */
1334 EndCommand(&qc, dest, false);
1335
1336 /* Now we may drop the per-parsetree context, if one was created. */
1337 if (per_parsetree_context)
1338 MemoryContextDelete(per_parsetree_context);
1339 } /* end loop over parsetrees */
1340
1341 /*
1342 * Close down transaction statement, if one is open. (This will only do
1343 * something if the parsetree list was empty; otherwise the last loop
1344 * iteration already did it.)
1345 */
1347
1348 /*
1349 * If there were no parsetrees, return EmptyQueryResponse message.
1350 */
1351 if (!parsetree_list)
1353
1354 /*
1355 * Emit duration logging if appropriate.
1356 */
1357 switch (check_log_duration(msec_str, was_logged))
1358 {
1359 case 1:
1360 ereport(LOG,
1361 (errmsg("duration: %s ms", msec_str),
1362 errhidestmt(true)));
1363 break;
1364 case 2:
1365 ereport(LOG,
1366 (errmsg("duration: %s ms statement: %s",
1367 msec_str, query_string),
1368 errhidestmt(true),
1369 errdetail_execute(parsetree_list)));
1370 break;
1371 }
1372
1373 if (save_log_statement_stats)
1374 ShowUsage("QUERY STATISTICS");
1375
1376 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1377
1378 debug_query_string = NULL;
1379}
CommandTag
Definition: cmdtag.h:23
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:3354
static char format
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:468
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:969
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:664
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2461
bool visible
Definition: portal.h:204
int cursorOptions
Definition: portal.h:147
void BeginImplicitTransactionBlock(void)
Definition: xact.c:4318
void EndImplicitTransactionBlock(void)
Definition: xact.c:4343

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_requires_snapshot(), Assert, BeginCommand(), BeginImplicitTransactionBlock(), CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), CreateCommandTag(), CreateDestReceiver(), CreatePortal(), CURSOR_OPT_BINARY, CURSOR_OPT_PARALLEL_OK, PortalData::cursorOptions, debug_query_string, generate_unaccent_rules::dest, DestRemote, disable_statement_timeout(), drop_unnamed_stmt(), EndCommand(), EndImplicitTransactionBlock(), ereport, errcode(), errdetail_abort(), errdetail_execute(), errhidestmt(), errmsg(), ERROR, FETCH_ALL, finish_xact_command(), format, GetCommandTagNameAndLen(), GetPortalByName(), GetTransactionSnapshot(), if(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), IsTransactionExitStmt(), lfirst_node, list_length(), lnext(), LOG, log_statement_stats, MemoryContextDelete(), MemoryContextSwitchTo(), MessageContext, MyXactFlags, NullCommand(), pg_analyze_and_rewrite_fixedparams(), pg_parse_query(), pg_plan_queries(), pgstat_report_activity(), pgstat_report_query_id(), PopActiveSnapshot(), PortalDefineQuery(), PortalDrop(), PortalIsValid, PortalRun(), PortalSetResultFormat(), PortalStart(), PushActiveSnapshot(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display_with_len(), SetRemoteDestReceiverParams(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, stmt, PortalData::visible, whereToSendOutput, and XACT_FLAGS_NEEDIMMEDIATECOMMIT.

Referenced by PostgresMain().

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2800 of file postgres.c.

2801{
2802 /* cancel active statement timeout after each command */
2804
2805 if (xact_started)
2806 {
2808
2809#ifdef MEMORY_CONTEXT_CHECKING
2810 /* Check all memory contexts that weren't freed during commit */
2811 /* (those that were, were checked before being deleted) */
2812 MemoryContextCheck(TopMemoryContext);
2813#endif
2814
2815#ifdef SHOW_MEMORY_STATS
2816 /* Print mem stats after each commit for leak tracking */
2818#endif
2819
2820 xact_started = false;
2821 }
2822}
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:814
void CommitTransactionCommand(void)
Definition: xact.c:3149

References CommitTransactionCommand(), disable_statement_timeout(), MemoryContextStats(), TopMemoryContext, and xact_started.

Referenced by exec_execute_message(), exec_simple_query(), and PostgresMain().

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 3048 of file postgres.c.

3049{
3050 /* We're not returning, so no need to save errno */
3051 ereport(ERROR,
3052 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3053 errmsg("floating-point exception"),
3054 errdetail("An invalid floating-point operation was signaled. "
3055 "This probably means an out-of-range result or an "
3056 "invalid operation, such as division by zero.")));
3057}

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), plperl_init_interp(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4957 of file postgres.c.

4958{
4959 if (am_walsender)
4960 {
4961 if (firstchar == PqMsg_FunctionCall)
4962 ereport(ERROR,
4963 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4964 errmsg("fastpath function calls not supported in a replication connection")));
4965 else
4966 ereport(ERROR,
4967 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4968 errmsg("extended query protocol not supported in a replication connection")));
4969 }
4970}
#define PqMsg_FunctionCall
Definition: protocol.h:23
bool am_walsender
Definition: walsender.c:115

References am_walsender, ereport, errcode(), errmsg(), ERROR, and PqMsg_FunctionCall.

Referenced by PostgresMain().

◆ get_stats_option_name()

const char * get_stats_option_name ( const char *  arg)

Definition at line 3712 of file postgres.c.

3713{
3714 switch (arg[0])
3715 {
3716 case 'p':
3717 if (optarg[1] == 'a') /* "parser" */
3718 return "log_parser_stats";
3719 else if (optarg[1] == 'l') /* "planner" */
3720 return "log_planner_stats";
3721 break;
3722
3723 case 'e': /* "executor" */
3724 return "log_executor_stats";
3725 break;
3726 }
3727
3728 return NULL;
3729}
PGDLLIMPORT char * optarg
Definition: getopt.c:53

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3064 of file postgres.c.

3065{
3066 RecoveryConflictPendingReasons[reason] = true;
3068 InterruptPending = true;
3069 /* latch will be set by procsignal_sigusr1_handler */
3070}
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:158
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:157

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 323 of file postgres.c.

324{
325 int c;
326
327 /*
328 * This will not process catchup interrupts or notifications while
329 * reading. But those can't really be relevant for a standalone backend
330 * anyway. To properly handle SIGTERM there's a hack in die() that
331 * directly processes interrupts at this stage...
332 */
334
335 c = getc(stdin);
336
338
339 return c;
340}
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:500
char * c

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 235 of file postgres.c.

236{
237 int c; /* character read from getc() */
238
239 /*
240 * display a prompt and obtain input from the user
241 */
242 printf("backend> ");
243 fflush(stdout);
244
245 resetStringInfo(inBuf);
246
247 /*
248 * Read characters until EOF or the appropriate delimiter is seen.
249 */
250 while ((c = interactive_getc()) != EOF)
251 {
252 if (c == '\n')
253 {
255 {
256 /*
257 * In -j mode, semicolon followed by two newlines ends the
258 * command; otherwise treat newline as regular character.
259 */
260 if (inBuf->len > 1 &&
261 inBuf->data[inBuf->len - 1] == '\n' &&
262 inBuf->data[inBuf->len - 2] == ';')
263 {
264 /* might as well drop the second newline */
265 break;
266 }
267 }
268 else
269 {
270 /*
271 * In plain mode, newline ends the command unless preceded by
272 * backslash.
273 */
274 if (inBuf->len > 0 &&
275 inBuf->data[inBuf->len - 1] == '\\')
276 {
277 /* discard backslash from inBuf */
278 inBuf->data[--inBuf->len] = '\0';
279 /* discard newline too */
280 continue;
281 }
282 else
283 {
284 /* keep the newline character, but end the command */
285 appendStringInfoChar(inBuf, '\n');
286 break;
287 }
288 }
289 }
290
291 /* Not newline, or newline treated as regular character */
292 appendStringInfoChar(inBuf, (char) c);
293 }
294
295 /* No input before EOF signal means time to quit. */
296 if (c == EOF && inBuf->len == 0)
297 return EOF;
298
299 /*
300 * otherwise we have a user query so process it.
301 */
302
303 /* Add '\0' to make it look the same as message case. */
304 appendStringInfoChar(inBuf, (char) '\0');
305
306 /*
307 * if the query echo flag was given, print the query..
308 */
309 if (EchoQuery)
310 printf("statement: %s\n", inBuf->data);
311 fflush(stdout);
312
313 return PqMsg_Query;
314}
static void const char fflush(stdout)
#define printf(...)
Definition: port.h:244
static bool UseSemiNewlineNewline
Definition: postgres.c:154
static bool EchoQuery
Definition: postgres.c:153
static int interactive_getc(void)
Definition: postgres.c:323
#define PqMsg_Query
Definition: protocol.h:26
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:126
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242

References appendStringInfoChar(), StringInfoData::data, EchoQuery, fflush(), interactive_getc(), StringInfoData::len, PqMsg_Query, printf, resetStringInfo(), generate_unaccent_rules::stdout, and UseSemiNewlineNewline.

Referenced by ReadCommand().

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2832 of file postgres.c.

2833{
2834 if (parsetree && IsA(parsetree, TransactionStmt))
2835 {
2836 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2837
2838 if (stmt->kind == TRANS_STMT_COMMIT ||
2839 stmt->kind == TRANS_STMT_PREPARE ||
2840 stmt->kind == TRANS_STMT_ROLLBACK ||
2842 return true;
2843 }
2844 return false;
2845}
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3736
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3733
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3732
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3737

References IsA, stmt, TRANS_STMT_COMMIT, TRANS_STMT_PREPARE, TRANS_STMT_ROLLBACK, and TRANS_STMT_ROLLBACK_TO.

Referenced by exec_bind_message(), exec_parse_message(), exec_simple_query(), and IsTransactionExitStmtList().

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2849 of file postgres.c.

2850{
2851 if (list_length(pstmts) == 1)
2852 {
2853 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2854
2855 if (pstmt->commandType == CMD_UTILITY &&
2857 return true;
2858 }
2859 return false;
2860}
@ CMD_UTILITY
Definition: nodes.h:270
CmdType commandType
Definition: plannodes.h:52
Node * utilityStmt
Definition: plannodes.h:95

References CMD_UTILITY, PlannedStmt::commandType, IsTransactionExitStmt(), linitial_node, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2864 of file postgres.c.

2865{
2866 if (list_length(pstmts) == 1)
2867 {
2868 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2869
2870 if (pstmt->commandType == CMD_UTILITY &&
2872 return true;
2873 }
2874 return false;
2875}

References CMD_UTILITY, PlannedStmt::commandType, IsA, linitial_node, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 5093 of file postgres.c.

5094{
5095 Port *port = MyProcPort;
5096 long secs;
5097 int usecs;
5098 int msecs;
5099 int hours,
5100 minutes,
5101 seconds;
5102
5105 &secs, &usecs);
5106 msecs = usecs / 1000;
5107
5108 hours = secs / SECS_PER_HOUR;
5109 secs %= SECS_PER_HOUR;
5110 minutes = secs / SECS_PER_MINUTE;
5111 seconds = secs % SECS_PER_MINUTE;
5112
5113 ereport(LOG,
5114 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5115 "user=%s database=%s host=%s%s%s",
5116 hours, minutes, seconds, msecs,
5117 port->user_name, port->database_name, port->remote_host,
5118 port->remote_port[0] ? " port=" : "", port->remote_port)));
5119}
#define SECS_PER_HOUR
Definition: timestamp.h:127
#define SECS_PER_MINUTE
Definition: timestamp.h:128
TimestampTz MyStartTimestamp
Definition: globals.c:48
struct Port * MyProcPort
Definition: globals.c:50
static int port
Definition: pg_regress.c:115
Definition: libpq-be.h:135

References ereport, errmsg(), GetCurrentTimestamp(), LOG, MyProcPort, MyStartTimestamp, port, SECS_PER_HOUR, SECS_PER_MINUTE, and TimestampDifference().

Referenced by PostgresMain().

◆ pg_analyze_and_rewrite_fixedparams()

List * pg_analyze_and_rewrite_fixedparams ( RawStmt parsetree,
const char *  query_string,
const Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 664 of file postgres.c.

669{
670 Query *query;
671 List *querytree_list;
672
673 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
674
675 /*
676 * (1) Perform parse analysis.
677 */
679 ResetUsage();
680
681 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
682 queryEnv);
683
685 ShowUsage("PARSE ANALYSIS STATISTICS");
686
687 /*
688 * (2) Rewrite the queries, as necessary
689 */
690 querytree_list = pg_rewrite_query(query);
691
692 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
693
694 return querytree_list;
695}
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:105
List * pg_rewrite_query(Query *query)
Definition: postgres.c:797

References log_parser_stats, parse_analyze_fixedparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopyTo(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

◆ pg_analyze_and_rewrite_varparams()

List * pg_analyze_and_rewrite_varparams ( RawStmt parsetree,
const char *  query_string,
Oid **  paramTypes,
int *  numParams,
QueryEnvironment queryEnv 
)

Definition at line 703 of file postgres.c.

708{
709 Query *query;
710 List *querytree_list;
711
712 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
713
714 /*
715 * (1) Perform parse analysis.
716 */
718 ResetUsage();
719
720 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
721 queryEnv);
722
723 /*
724 * Check all parameter types got determined.
725 */
726 for (int i = 0; i < *numParams; i++)
727 {
728 Oid ptype = (*paramTypes)[i];
729
730 if (ptype == InvalidOid || ptype == UNKNOWNOID)
732 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
733 errmsg("could not determine data type of parameter $%d",
734 i + 1)));
735 }
736
738 ShowUsage("PARSE ANALYSIS STATISTICS");
739
740 /*
741 * (2) Rewrite the queries, as necessary
742 */
743 querytree_list = pg_rewrite_query(query);
744
745 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
746
747 return querytree_list;
748}
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:145
#define InvalidOid
Definition: postgres_ext.h:37

References ereport, errcode(), errmsg(), ERROR, i, InvalidOid, log_parser_stats, parse_analyze_varparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

List * pg_analyze_and_rewrite_withcb ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 757 of file postgres.c.

762{
763 Query *query;
764 List *querytree_list;
765
766 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
767
768 /*
769 * (1) Perform parse analysis.
770 */
772 ResetUsage();
773
774 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
775 queryEnv);
776
778 ShowUsage("PARSE ANALYSIS STATISTICS");
779
780 /*
781 * (2) Rewrite the queries, as necessary
782 */
783 querytree_list = pg_rewrite_query(query);
784
785 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
786
787 return querytree_list;
788}
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:186

References log_parser_stats, parse_analyze_withcb(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

◆ pg_parse_query()

List * pg_parse_query ( const char *  query_string)

Definition at line 602 of file postgres.c.

603{
604 List *raw_parsetree_list;
605
606 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
607
609 ResetUsage();
610
611 raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
612
614 ShowUsage("PARSER STATISTICS");
615
616#ifdef DEBUG_NODE_TESTS_ENABLED
617
618 /* Optional debugging check: pass raw parsetrees through copyObject() */
619 if (Debug_copy_parse_plan_trees)
620 {
621 List *new_list = copyObject(raw_parsetree_list);
622
623 /* This checks both copyObject() and the equal() routines... */
624 if (!equal(new_list, raw_parsetree_list))
625 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
626 else
627 raw_parsetree_list = new_list;
628 }
629
630 /*
631 * Optional debugging check: pass raw parsetrees through
632 * outfuncs/readfuncs
633 */
634 if (Debug_write_read_parse_plan_trees)
635 {
636 char *str = nodeToStringWithLocations(raw_parsetree_list);
637 List *new_list = stringToNodeWithLocations(str);
638
639 pfree(str);
640 /* This checks both outfuncs/readfuncs and the equal() routines... */
641 if (!equal(new_list, raw_parsetree_list))
642 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
643 else
644 raw_parsetree_list = new_list;
645 }
646
647#endif /* DEBUG_NODE_TESTS_ENABLED */
648
649 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
650
651 return raw_parsetree_list;
652}
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:225
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static List * new_list(NodeTag type, int min_size)
Definition: list.c:91
#define copyObject(obj)
Definition: nodes.h:224
char * nodeToStringWithLocations(const void *obj)
Definition: outfuncs.c:800
@ RAW_PARSE_DEFAULT
Definition: parser.h:39

References copyObject, elog, equal(), log_parser_stats, new_list(), nodeToStringWithLocations(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

◆ pg_plan_queries()

List * pg_plan_queries ( List querytrees,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 969 of file postgres.c.

971{
972 List *stmt_list = NIL;
973 ListCell *query_list;
974
975 foreach(query_list, querytrees)
976 {
977 Query *query = lfirst_node(Query, query_list);
979
980 if (query->commandType == CMD_UTILITY)
981 {
982 /* Utility commands require no planning. */
984 stmt->commandType = CMD_UTILITY;
985 stmt->canSetTag = query->canSetTag;
986 stmt->utilityStmt = query->utilityStmt;
987 stmt->stmt_location = query->stmt_location;
988 stmt->stmt_len = query->stmt_len;
989 stmt->queryId = query->queryId;
990 }
991 else
992 {
993 stmt = pg_plan_query(query, query_string, cursorOptions,
994 boundParams);
995 }
996
997 stmt_list = lappend(stmt_list, stmt);
998 }
999
1000 return stmt_list;
1001}
List * lappend(List *list, void *datum)
Definition: list.c:339
#define makeNode(_type_)
Definition: nodes.h:155
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:881
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
ParseLoc stmt_location
Definition: parsenodes.h:249

References CMD_UTILITY, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), stmt, Query::stmt_location, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

◆ pg_plan_query()

PlannedStmt * pg_plan_query ( Query querytree,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 881 of file postgres.c.

883{
885
886 /* Utility commands have no plans. */
887 if (querytree->commandType == CMD_UTILITY)
888 return NULL;
889
890 /* Planner must have a snapshot in case it calls user-defined functions. */
892
893 TRACE_POSTGRESQL_QUERY_PLAN_START();
894
896 ResetUsage();
897
898 /* call the optimizer */
899 plan = planner(querytree, query_string, cursorOptions, boundParams);
900
902 ShowUsage("PLANNER STATISTICS");
903
904#ifdef DEBUG_NODE_TESTS_ENABLED
905
906 /* Optional debugging check: pass plan tree through copyObject() */
907 if (Debug_copy_parse_plan_trees)
908 {
909 PlannedStmt *new_plan = copyObject(plan);
910
911 /*
912 * equal() currently does not have routines to compare Plan nodes, so
913 * don't try to test equality here. Perhaps fix someday?
914 */
915#ifdef NOT_USED
916 /* This checks both copyObject() and the equal() routines... */
917 if (!equal(new_plan, plan))
918 elog(WARNING, "copyObject() failed to produce an equal plan tree");
919 else
920#endif
921 plan = new_plan;
922 }
923
924 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
925 if (Debug_write_read_parse_plan_trees)
926 {
927 char *str;
928 PlannedStmt *new_plan;
929
931 new_plan = stringToNodeWithLocations(str);
932 pfree(str);
933
934 /*
935 * equal() currently does not have routines to compare Plan nodes, so
936 * don't try to test equality here. Perhaps fix someday?
937 */
938#ifdef NOT_USED
939 /* This checks both outfuncs/readfuncs and the equal() routines... */
940 if (!equal(new_plan, plan))
941 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
942 else
943#endif
944 plan = new_plan;
945 }
946
947#endif /* DEBUG_NODE_TESTS_ENABLED */
948
949 /*
950 * Print plan if debugging.
951 */
954
955 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
956
957 return plan;
958}
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool Debug_print_plan
Definition: guc_tables.c:491
bool Debug_pretty_print
Definition: guc_tables.c:494
#define plan(x)
Definition: pg_regress.c:161
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:284
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:740

References ActiveSnapshotSet(), Assert, CMD_UTILITY, copyObject, Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, nodeToStringWithLocations(), pfree(), plan, planner(), querytree(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by BeginCopyTo(), ExecCreateTableAs(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), refresh_matview_datafill(), and standard_ExplainOneQuery().

◆ pg_rewrite_query()

List * pg_rewrite_query ( Query query)

Definition at line 797 of file postgres.c.

798{
799 List *querytree_list;
800
802 elog_node_display(LOG, "parse tree", query,
804
806 ResetUsage();
807
808 if (query->commandType == CMD_UTILITY)
809 {
810 /* don't rewrite utilities, just dump 'em into result list */
811 querytree_list = list_make1(query);
812 }
813 else
814 {
815 /* rewrite regular queries */
816 querytree_list = QueryRewrite(query);
817 }
818
820 ShowUsage("REWRITER STATISTICS");
821
822#ifdef DEBUG_NODE_TESTS_ENABLED
823
824 /* Optional debugging check: pass querytree through copyObject() */
825 if (Debug_copy_parse_plan_trees)
826 {
827 List *new_list;
828
829 new_list = copyObject(querytree_list);
830 /* This checks both copyObject() and the equal() routines... */
831 if (!equal(new_list, querytree_list))
832 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
833 else
834 querytree_list = new_list;
835 }
836
837 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
838 if (Debug_write_read_parse_plan_trees)
839 {
840 List *new_list = NIL;
841 ListCell *lc;
842
843 foreach(lc, querytree_list)
844 {
845 Query *curr_query = lfirst_node(Query, lc);
846 char *str = nodeToStringWithLocations(curr_query);
847 Query *new_query = stringToNodeWithLocations(str);
848
849 /*
850 * queryId is not saved in stored rules, but we must preserve it
851 * here to avoid breaking pg_stat_statements.
852 */
853 new_query->queryId = curr_query->queryId;
854
855 new_list = lappend(new_list, new_query);
856 pfree(str);
857 }
858
859 /* This checks both outfuncs/readfuncs and the equal() routines... */
860 if (!equal(new_list, querytree_list))
861 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
862 else
863 querytree_list = new_list;
864 }
865
866#endif /* DEBUG_NODE_TESTS_ENABLED */
867
869 elog_node_display(LOG, "rewritten parse tree", querytree_list,
871
872 return querytree_list;
873}
bool Debug_print_rewritten
Definition: guc_tables.c:493
bool Debug_print_parse
Definition: guc_tables.c:492
#define list_make1(x1)
Definition: pg_list.h:212
List * QueryRewrite(Query *parsetree)

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), lappend(), lfirst_node, list_make1, LOG, log_parser_stats, new_list(), NIL, nodeToStringWithLocations(), pfree(), QueryRewrite(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), and pg_analyze_and_rewrite_withcb().

◆ PostgresMain()

void PostgresMain ( const char *  dbname,
const char *  username 
)

Definition at line 4146 of file postgres.c.

4147{
4148 sigjmp_buf local_sigjmp_buf;
4149
4150 /* these must be volatile to ensure state is preserved across longjmp: */
4151 volatile bool send_ready_for_query = true;
4152 volatile bool idle_in_transaction_timeout_enabled = false;
4153 volatile bool idle_session_timeout_enabled = false;
4154
4155 Assert(dbname != NULL);
4156 Assert(username != NULL);
4157
4159
4160 /*
4161 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4162 * has already set up BlockSig and made that the active signal mask.)
4163 *
4164 * Note that postmaster blocked all signals before forking child process,
4165 * so there is no race condition whereby we might receive a signal before
4166 * we have set up the handler.
4167 *
4168 * Also note: it's best not to use any signals that are SIG_IGNored in the
4169 * postmaster. If such a signal arrives before we are able to change the
4170 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4171 * handler in the postmaster to reserve the signal. (Of course, this isn't
4172 * an issue for signals that are locally generated, such as SIGALRM and
4173 * SIGPIPE.)
4174 */
4175 if (am_walsender)
4176 WalSndSignals();
4177 else
4178 {
4180 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4181 pqsignal(SIGTERM, die); /* cancel current query and exit */
4182
4183 /*
4184 * In a postmaster child backend, replace SignalHandlerForCrashExit
4185 * with quickdie, so we can tell the client we're dying.
4186 *
4187 * In a standalone backend, SIGQUIT can be generated from the keyboard
4188 * easily, while SIGTERM cannot, so we make both signals do die()
4189 * rather than quickdie().
4190 */
4192 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4193 else
4194 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4195 InitializeTimeouts(); /* establishes SIGALRM handler */
4196
4197 /*
4198 * Ignore failure to write to frontend. Note: if frontend closes
4199 * connection, we will notice it and exit cleanly when control next
4200 * returns to outer loop. This seems safer than forcing exit in the
4201 * midst of output during who-knows-what operation...
4202 */
4203 pqsignal(SIGPIPE, SIG_IGN);
4205 pqsignal(SIGUSR2, SIG_IGN);
4207
4208 /*
4209 * Reset some signals that are accepted by postmaster but not by
4210 * backend
4211 */
4212 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4213 * platforms */
4214 }
4215
4216 /* Early initialization */
4217 BaseInit();
4218
4219 /* We need to allow SIGINT, etc during the initial transaction */
4220 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4221
4222 /*
4223 * Generate a random cancel key, if this is a backend serving a
4224 * connection. InitPostgres() will advertise it in shared memory.
4225 */
4228 {
4229 if (!pg_strong_random(&MyCancelKey, sizeof(int32)))
4230 {
4231 ereport(ERROR,
4232 (errcode(ERRCODE_INTERNAL_ERROR),
4233 errmsg("could not generate random cancel key")));
4234 }
4235 MyCancelKeyValid = true;
4236 }
4237
4238 /*
4239 * General initialization.
4240 *
4241 * NOTE: if you are tempted to add code in this vicinity, consider putting
4242 * it inside InitPostgres() instead. In particular, anything that
4243 * involves database access should be there, not here.
4244 *
4245 * Honor session_preload_libraries if not dealing with a WAL sender.
4246 */
4247 InitPostgres(dbname, InvalidOid, /* database to connect to */
4248 username, InvalidOid, /* role to connect as */
4250 NULL); /* no out_dbname */
4251
4252 /*
4253 * If the PostmasterContext is still around, recycle the space; we don't
4254 * need it anymore after InitPostgres completes.
4255 */
4257 {
4259 PostmasterContext = NULL;
4260 }
4261
4263
4264 /*
4265 * Now all GUC states are fully set up. Report them to client if
4266 * appropriate.
4267 */
4269
4270 /*
4271 * Also set up handler to log session end; we have to wait till now to be
4272 * sure Log_disconnections has its final value.
4273 */
4276
4278
4279 /* Perform initialization specific to a WAL sender process. */
4280 if (am_walsender)
4281 InitWalSender();
4282
4283 /*
4284 * Send this backend's cancellation info to the frontend.
4285 */
4287 {
4289
4295 /* Need not flush since ReadyForQuery will do it. */
4296 }
4297
4298 /* Welcome banner for standalone case */
4300 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4301
4302 /*
4303 * Create the memory context we will use in the main loop.
4304 *
4305 * MessageContext is reset once per iteration of the main loop, ie, upon
4306 * completion of processing of each command message from the client.
4307 */
4309 "MessageContext",
4311
4312 /*
4313 * Create memory context and buffer used for RowDescription messages. As
4314 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4315 * frequently executed for ever single statement, we don't want to
4316 * allocate a separate buffer every time.
4317 */
4319 "RowDescriptionContext",
4324
4325 /* Fire any defined login event triggers, if appropriate */
4327
4328 /*
4329 * POSTGRES main processing loop begins here
4330 *
4331 * If an exception is encountered, processing resumes here so we abort the
4332 * current transaction and start a new one.
4333 *
4334 * You might wonder why this isn't coded as an infinite loop around a
4335 * PG_TRY construct. The reason is that this is the bottom of the
4336 * exception stack, and so with PG_TRY there would be no exception handler
4337 * in force at all during the CATCH part. By leaving the outermost setjmp
4338 * always active, we have at least some chance of recovering from an error
4339 * during error recovery. (If we get into an infinite loop thereby, it
4340 * will soon be stopped by overflow of elog.c's internal state stack.)
4341 *
4342 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4343 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4344 * is essential in case we longjmp'd out of a signal handler on a platform
4345 * where that leaves the signal blocked. It's not redundant with the
4346 * unblock in AbortTransaction() because the latter is only called if we
4347 * were inside a transaction.
4348 */
4349
4350 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4351 {
4352 /*
4353 * NOTE: if you are tempted to add more code in this if-block,
4354 * consider the high probability that it should be in
4355 * AbortTransaction() instead. The only stuff done directly here
4356 * should be stuff that is guaranteed to apply *only* for outer-level
4357 * error recovery, such as adjusting the FE/BE protocol status.
4358 */
4359
4360 /* Since not using PG_TRY, must reset error stack by hand */
4361 error_context_stack = NULL;
4362
4363 /* Prevent interrupts while cleaning up */
4365
4366 /*
4367 * Forget any pending QueryCancel request, since we're returning to
4368 * the idle loop anyway, and cancel any active timeout requests. (In
4369 * future we might want to allow some timeout requests to survive, but
4370 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4371 * we got here because of a query cancel interrupting the SIGALRM
4372 * interrupt handler.) Note in particular that we must clear the
4373 * statement and lock timeout indicators, to prevent any future plain
4374 * query cancels from being misreported as timeouts in case we're
4375 * forgetting a timeout cancel.
4376 */
4377 disable_all_timeouts(false); /* do first to avoid race condition */
4378 QueryCancelPending = false;
4379 idle_in_transaction_timeout_enabled = false;
4380 idle_session_timeout_enabled = false;
4381
4382 /* Not reading from the client anymore. */
4383 DoingCommandRead = false;
4384
4385 /* Make sure libpq is in a good state */
4386 pq_comm_reset();
4387
4388 /* Report the error to the client and/or server log */
4390
4391 /*
4392 * If Valgrind noticed something during the erroneous query, print the
4393 * query string, assuming we have one.
4394 */
4396
4397 /*
4398 * Make sure debug_query_string gets reset before we possibly clobber
4399 * the storage it points at.
4400 */
4401 debug_query_string = NULL;
4402
4403 /*
4404 * Abort the current transaction in order to recover.
4405 */
4407
4408 if (am_walsender)
4410
4412
4413 /*
4414 * We can't release replication slots inside AbortTransaction() as we
4415 * need to be able to start and abort transactions while having a slot
4416 * acquired. But we never need to hold them across top level errors,
4417 * so releasing here is fine. There also is a before_shmem_exit()
4418 * callback ensuring correct cleanup on FATAL errors.
4419 */
4420 if (MyReplicationSlot != NULL)
4422
4423 /* We also want to cleanup temporary slots on error. */
4425
4427
4428 /*
4429 * Now return to normal top-level context and clear ErrorContext for
4430 * next time.
4431 */
4434
4435 /*
4436 * If we were handling an extended-query-protocol message, initiate
4437 * skip till next Sync. This also causes us not to issue
4438 * ReadyForQuery (until we get Sync).
4439 */
4441 ignore_till_sync = true;
4442
4443 /* We don't have a transaction command open anymore */
4444 xact_started = false;
4445
4446 /*
4447 * If an error occurred while we were reading a message from the
4448 * client, we have potentially lost track of where the previous
4449 * message ends and the next one begins. Even though we have
4450 * otherwise recovered from the error, we cannot safely read any more
4451 * messages from the client, so there isn't much we can do with the
4452 * connection anymore.
4453 */
4454 if (pq_is_reading_msg())
4455 ereport(FATAL,
4456 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4457 errmsg("terminating connection because protocol synchronization was lost")));
4458
4459 /* Now we can allow interrupts again */
4461 }
4462
4463 /* We can now handle ereport(ERROR) */
4464 PG_exception_stack = &local_sigjmp_buf;
4465
4466 if (!ignore_till_sync)
4467 send_ready_for_query = true; /* initially, or after error */
4468
4469 /*
4470 * Non-error queries loop here.
4471 */
4472
4473 for (;;)
4474 {
4475 int firstchar;
4476 StringInfoData input_message;
4477
4478 /*
4479 * At top of loop, reset extended-query-message flag, so that any
4480 * errors encountered in "idle" state don't provoke skip.
4481 */
4483
4484 /*
4485 * For valgrind reporting purposes, the "current query" begins here.
4486 */
4487#ifdef USE_VALGRIND
4488 old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4489#endif
4490
4491 /*
4492 * Release storage left over from prior query cycle, and create a new
4493 * query input buffer in the cleared MessageContext.
4494 */
4497
4498 initStringInfo(&input_message);
4499
4500 /*
4501 * Also consider releasing our catalog snapshot if any, so that it's
4502 * not preventing advance of global xmin while we wait for the client.
4503 */
4505
4506 /*
4507 * (1) If we've reached idle state, tell the frontend we're ready for
4508 * a new query.
4509 *
4510 * Note: this includes fflush()'ing the last of the prior output.
4511 *
4512 * This is also a good time to flush out collected statistics to the
4513 * cumulative stats system, and to update the PS stats display. We
4514 * avoid doing those every time through the message loop because it'd
4515 * slow down processing of batched messages, and because we don't want
4516 * to report uncommitted updates (that confuses autovacuum). The
4517 * notification processor wants a call too, if we are not in a
4518 * transaction block.
4519 *
4520 * Also, if an idle timeout is enabled, start the timer for that.
4521 */
4522 if (send_ready_for_query)
4523 {
4525 {
4526 set_ps_display("idle in transaction (aborted)");
4528
4529 /* Start the idle-in-transaction timer */
4532 {
4533 idle_in_transaction_timeout_enabled = true;
4536 }
4537 }
4539 {
4540 set_ps_display("idle in transaction");
4542
4543 /* Start the idle-in-transaction timer */
4546 {
4547 idle_in_transaction_timeout_enabled = true;
4550 }
4551 }
4552 else
4553 {
4554 long stats_timeout;
4555
4556 /*
4557 * Process incoming notifies (including self-notifies), if
4558 * any, and send relevant messages to the client. Doing it
4559 * here helps ensure stable behavior in tests: if any notifies
4560 * were received during the just-finished transaction, they'll
4561 * be seen by the client before ReadyForQuery is.
4562 */
4565
4566 /*
4567 * Check if we need to report stats. If pgstat_report_stat()
4568 * decides it's too soon to flush out pending stats / lock
4569 * contention prevented reporting, it'll tell us when we
4570 * should try to report stats again (so that stats updates
4571 * aren't unduly delayed if the connection goes idle for a
4572 * long time). We only enable the timeout if we don't already
4573 * have a timeout in progress, because we don't disable the
4574 * timeout below. enable_timeout_after() needs to determine
4575 * the current timestamp, which can have a negative
4576 * performance impact. That's OK because pgstat_report_stat()
4577 * won't have us wake up sooner than a prior call.
4578 */
4579 stats_timeout = pgstat_report_stat(false);
4580 if (stats_timeout > 0)
4581 {
4584 stats_timeout);
4585 }
4586 else
4587 {
4588 /* all stats flushed, no need for the timeout */
4591 }
4592
4593 set_ps_display("idle");
4595
4596 /* Start the idle-session timer */
4597 if (IdleSessionTimeout > 0)
4598 {
4599 idle_session_timeout_enabled = true;
4602 }
4603 }
4604
4605 /* Report any recently-changed GUC options */
4607
4609 send_ready_for_query = false;
4610 }
4611
4612 /*
4613 * (2) Allow asynchronous signals to be executed immediately if they
4614 * come in while we are waiting for client input. (This must be
4615 * conditional since we don't want, say, reads on behalf of COPY FROM
4616 * STDIN doing the same thing.)
4617 */
4618 DoingCommandRead = true;
4619
4620 /*
4621 * (3) read a command (loop blocks here)
4622 */
4623 firstchar = ReadCommand(&input_message);
4624
4625 /*
4626 * (4) turn off the idle-in-transaction and idle-session timeouts if
4627 * active. We do this before step (5) so that any last-moment timeout
4628 * is certain to be detected in step (5).
4629 *
4630 * At most one of these timeouts will be active, so there's no need to
4631 * worry about combining the timeout.c calls into one.
4632 */
4633 if (idle_in_transaction_timeout_enabled)
4634 {
4636 idle_in_transaction_timeout_enabled = false;
4637 }
4638 if (idle_session_timeout_enabled)
4639 {
4641 idle_session_timeout_enabled = false;
4642 }
4643
4644 /*
4645 * (5) disable async signal conditions again.
4646 *
4647 * Query cancel is supposed to be a no-op when there is no query in
4648 * progress, so if a query cancel arrived while we were idle, just
4649 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4650 * it's called when DoingCommandRead is set, so check for interrupts
4651 * before resetting DoingCommandRead.
4652 */
4654 DoingCommandRead = false;
4655
4656 /*
4657 * (6) check for any other interesting events that happened while we
4658 * slept.
4659 */
4661 {
4662 ConfigReloadPending = false;
4664 }
4665
4666 /*
4667 * (7) process the command. But ignore it if we're skipping till
4668 * Sync.
4669 */
4670 if (ignore_till_sync && firstchar != EOF)
4671 continue;
4672
4673 switch (firstchar)
4674 {
4675 case PqMsg_Query:
4676 {
4677 const char *query_string;
4678
4679 /* Set statement_timestamp() */
4681
4682 query_string = pq_getmsgstring(&input_message);
4683 pq_getmsgend(&input_message);
4684
4685 if (am_walsender)
4686 {
4687 if (!exec_replication_command(query_string))
4688 exec_simple_query(query_string);
4689 }
4690 else
4691 exec_simple_query(query_string);
4692
4693 valgrind_report_error_query(query_string);
4694
4695 send_ready_for_query = true;
4696 }
4697 break;
4698
4699 case PqMsg_Parse:
4700 {
4701 const char *stmt_name;
4702 const char *query_string;
4703 int numParams;
4704 Oid *paramTypes = NULL;
4705
4706 forbidden_in_wal_sender(firstchar);
4707
4708 /* Set statement_timestamp() */
4710
4711 stmt_name = pq_getmsgstring(&input_message);
4712 query_string = pq_getmsgstring(&input_message);
4713 numParams = pq_getmsgint(&input_message, 2);
4714 if (numParams > 0)
4715 {
4716 paramTypes = palloc_array(Oid, numParams);
4717 for (int i = 0; i < numParams; i++)
4718 paramTypes[i] = pq_getmsgint(&input_message, 4);
4719 }
4720 pq_getmsgend(&input_message);
4721
4722 exec_parse_message(query_string, stmt_name,
4723 paramTypes, numParams);
4724
4725 valgrind_report_error_query(query_string);
4726 }
4727 break;
4728
4729 case PqMsg_Bind:
4730 forbidden_in_wal_sender(firstchar);
4731
4732 /* Set statement_timestamp() */
4734
4735 /*
4736 * this message is complex enough that it seems best to put
4737 * the field extraction out-of-line
4738 */
4739 exec_bind_message(&input_message);
4740
4741 /* exec_bind_message does valgrind_report_error_query */
4742 break;
4743
4744 case PqMsg_Execute:
4745 {
4746 const char *portal_name;
4747 int max_rows;
4748
4749 forbidden_in_wal_sender(firstchar);
4750
4751 /* Set statement_timestamp() */
4753
4754 portal_name = pq_getmsgstring(&input_message);
4755 max_rows = pq_getmsgint(&input_message, 4);
4756 pq_getmsgend(&input_message);
4757
4758 exec_execute_message(portal_name, max_rows);
4759
4760 /* exec_execute_message does valgrind_report_error_query */
4761 }
4762 break;
4763
4764 case PqMsg_FunctionCall:
4765 forbidden_in_wal_sender(firstchar);
4766
4767 /* Set statement_timestamp() */
4769
4770 /* Report query to various monitoring facilities. */
4772 set_ps_display("<FASTPATH>");
4773
4774 /* start an xact for this function invocation */
4776
4777 /*
4778 * Note: we may at this point be inside an aborted
4779 * transaction. We can't throw error for that until we've
4780 * finished reading the function-call message, so
4781 * HandleFunctionRequest() must check for it after doing so.
4782 * Be careful not to do anything that assumes we're inside a
4783 * valid transaction here.
4784 */
4785
4786 /* switch back to message context */
4788
4789 HandleFunctionRequest(&input_message);
4790
4791 /* commit the function-invocation transaction */
4793
4794 valgrind_report_error_query("fastpath function call");
4795
4796 send_ready_for_query = true;
4797 break;
4798
4799 case PqMsg_Close:
4800 {
4801 int close_type;
4802 const char *close_target;
4803
4804 forbidden_in_wal_sender(firstchar);
4805
4806 close_type = pq_getmsgbyte(&input_message);
4807 close_target = pq_getmsgstring(&input_message);
4808 pq_getmsgend(&input_message);
4809
4810 switch (close_type)
4811 {
4812 case 'S':
4813 if (close_target[0] != '\0')
4814 DropPreparedStatement(close_target, false);
4815 else
4816 {
4817 /* special-case the unnamed statement */
4819 }
4820 break;
4821 case 'P':
4822 {
4823 Portal portal;
4824
4825 portal = GetPortalByName(close_target);
4826 if (PortalIsValid(portal))
4827 PortalDrop(portal, false);
4828 }
4829 break;
4830 default:
4831 ereport(ERROR,
4832 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4833 errmsg("invalid CLOSE message subtype %d",
4834 close_type)));
4835 break;
4836 }
4837
4840
4841 valgrind_report_error_query("CLOSE message");
4842 }
4843 break;
4844
4845 case PqMsg_Describe:
4846 {
4847 int describe_type;
4848 const char *describe_target;
4849
4850 forbidden_in_wal_sender(firstchar);
4851
4852 /* Set statement_timestamp() (needed for xact) */
4854
4855 describe_type = pq_getmsgbyte(&input_message);
4856 describe_target = pq_getmsgstring(&input_message);
4857 pq_getmsgend(&input_message);
4858
4859 switch (describe_type)
4860 {
4861 case 'S':
4862 exec_describe_statement_message(describe_target);
4863 break;
4864 case 'P':
4865 exec_describe_portal_message(describe_target);
4866 break;
4867 default:
4868 ereport(ERROR,
4869 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4870 errmsg("invalid DESCRIBE message subtype %d",
4871 describe_type)));
4872 break;
4873 }
4874
4875 valgrind_report_error_query("DESCRIBE message");
4876 }
4877 break;
4878
4879 case PqMsg_Flush:
4880 pq_getmsgend(&input_message);
4882 pq_flush();
4883 break;
4884
4885 case PqMsg_Sync:
4886 pq_getmsgend(&input_message);
4887
4888 /*
4889 * If pipelining was used, we may be in an implicit
4890 * transaction block. Close it before calling
4891 * finish_xact_command.
4892 */
4895 valgrind_report_error_query("SYNC message");
4896 send_ready_for_query = true;
4897 break;
4898
4899 /*
4900 * PqMsg_Terminate means that the frontend is closing down the
4901 * socket. EOF means unexpected loss of frontend connection.
4902 * Either way, perform normal shutdown.
4903 */
4904 case EOF:
4905
4906 /* for the cumulative statistics system */
4908
4909 /* FALLTHROUGH */
4910
4911 case PqMsg_Terminate:
4912
4913 /*
4914 * Reset whereToSendOutput to prevent ereport from attempting
4915 * to send any more messages to client.
4916 */
4919
4920 /*
4921 * NOTE: if you are tempted to add more code here, DON'T!
4922 * Whatever you had in mind to do should be set up as an
4923 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4924 * it will fail to be called during other backend-shutdown
4925 * scenarios.
4926 */
4927 proc_exit(0);
4928
4929 case PqMsg_CopyData:
4930 case PqMsg_CopyDone:
4931 case PqMsg_CopyFail:
4932
4933 /*
4934 * Accept but ignore these messages, per protocol spec; we
4935 * probably got here because a COPY failed, and the frontend
4936 * is still sending data.
4937 */
4938 break;
4939
4940 default:
4941 ereport(FATAL,
4942 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4943 errmsg("invalid frontend message type %d",
4944 firstchar)));
4945 }
4946 } /* end of input-reading loop */
4947}
void ProcessNotifyInterrupt(bool flush)
Definition: async.c:1834
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:413
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:516
sigset_t UnBlockSig
Definition: pqsignal.c:22
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
void ReadyForQuery(CommandDest dest)
Definition: dest.c:256
@ DestDebug
Definition: dest.h:88
@ DestNone
Definition: dest.h:87
void EmitErrorReport(void)
Definition: elog.c:1687
void FlushErrorState(void)
Definition: elog.c:1867
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#define FATAL
Definition: elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:188
int32 MyCancelKey
Definition: globals.c:52
int MyProcPid
Definition: globals.c:46
bool IsUnderPostmaster
Definition: globals.c:119
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
bool MyCancelKeyValid
Definition: globals.c:51
Oid MyDatabaseId
Definition: globals.c:93
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
void BeginReportingGUCOptions(void)
Definition: guc.c:2546
void ReportChangedGUCOptions(void)
Definition: guc.c:2596
@ PGC_SIGHUP
Definition: guc.h:71
static char * username
Definition: initdb.c:153
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void proc_exit(int code)
Definition: ipc.c:104
void jit_reset_after_error(void)
Definition: jit.c:127
#define pq_flush()
Definition: libpq.h:46
#define pq_comm_reset()
Definition: libpq.h:45
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:461
@ InitProcessing
Definition: miscadmin.h:460
#define GetProcessingMode()
Definition: miscadmin.h:470
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:488
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:472
long pgstat_report_stat(bool force)
Definition: pgstat.c:692
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:57
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition: port.h:520
bool pg_strong_random(void *buf, size_t len)
void PortalErrorCleanup(void)
Definition: portalmem.c:917
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2616
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2904
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5093
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4957
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2093
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3048
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3031
static bool ignore_till_sync
Definition: postgres.c:142
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1010
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1387
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1622
void die(SIGNAL_ARGS)
Definition: postgres.c:3001
static MemoryContext row_description_context
Definition: postgres.c:161
static bool doing_extended_query_message
Definition: postgres.c:141
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2709
bool Log_disconnections
Definition: postgres.c:93
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:479
void BaseInit(void)
Definition: postinit.c:606
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:700
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1181
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:399
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:671
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_Describe
Definition: protocol.h:21
#define PqMsg_Parse
Definition: protocol.h:25
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
#define PqMsg_Flush
Definition: protocol.h:24
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_Terminate
Definition: protocol.h:28
#define PqMsg_Execute
Definition: protocol.h:22
#define PqMsg_Close
Definition: protocol.h:20
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotRelease(void)
Definition: slot.c:652
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:745
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:405
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
char * dbname
Definition: streamutil.c:50
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
void WalSndErrorCleanup(void)
Definition: walsender.c:325
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1952
void WalSndSignals(void)
Definition: walsender.c:3563
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:168
#define SIGHUP
Definition: win32_port.h:158
#define SIGPIPE
Definition: win32_port.h:163
#define SIGQUIT
Definition: win32_port.h:159
#define SIGUSR1
Definition: win32_port.h:170
#define SIGUSR2
Definition: win32_port.h:171
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4981
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void AbortCurrentTransaction(void)
Definition: xact.c:3443

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, dbname, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), DISCONNECT_CLIENT_EOF, doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), EndImplicitTransactionBlock(), ereport, errcode(), errmsg(), ERROR, error_context_stack, EventTriggerOnLogin(), exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), get_timeout_active(), GetPortalByName(), GetProcessingMode, HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, ignore_till_sync, INIT_PG_LOAD_SESSION_LIBS, InitializeTimeouts(), InitPostgres(), InitProcessing, initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyCancelKeyValid, MyDatabaseId, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc_array, PG_exception_stack, pg_strong_random(), PGC_SIGHUP, pgstat_report_activity(), pgstat_report_connect(), pgstat_report_stat(), pgStatSessionEndCause, PortalDrop(), PortalErrorCleanup(), PortalIsValid, PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint32(), PqMsg_BackendKeyData, PqMsg_Bind, PqMsg_Close, PqMsg_CloseComplete, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, pqsignal, printf, proc_exit(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, TransactionTimeout, UnBlockSig, username, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

void PostgresSingleUserMain ( int  argc,
char *  argv[],
const char *  username 
)

Definition at line 4017 of file postgres.c.

4019{
4020 const char *dbname = NULL;
4021
4023
4024 /* Initialize startup process environment. */
4025 InitStandaloneProcess(argv[0]);
4026
4027 /*
4028 * Set default values for command-line options.
4029 */
4031
4032 /*
4033 * Parse command-line options.
4034 */
4036
4037 /* Must have gotten a database name, or have a default (the username) */
4038 if (dbname == NULL)
4039 {
4040 dbname = username;
4041 if (dbname == NULL)
4042 ereport(FATAL,
4043 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4044 errmsg("%s: no database nor user name specified",
4045 progname)));
4046 }
4047
4048 /* Acquire configuration parameters */
4050 proc_exit(1);
4051
4052 /*
4053 * Validate we have been given a reasonable-looking DataDir and change
4054 * into it.
4055 */
4056 checkDataDir();
4058
4059 /*
4060 * Create lockfile for data directory.
4061 */
4062 CreateDataDirLockFile(false);
4063
4064 /* read control file (error checking and contains config ) */
4066
4067 /*
4068 * process any libraries that should be preloaded at postmaster start
4069 */
4071
4072 /* Initialize MaxBackends */
4074
4075 /*
4076 * We don't need postmaster child slots in single-user mode, but
4077 * initialize them anyway to avoid having special handling.
4078 */
4080
4081 /* Initialize size of fast-path lock cache. */
4083
4084 /*
4085 * Give preloaded libraries a chance to request additional shared memory.
4086 */
4088
4089 /*
4090 * Now that loadable modules have had their chance to request additional
4091 * shared memory, determine the value of any runtime-computed GUCs that
4092 * depend on the amount of shared memory required.
4093 */
4095
4096 /*
4097 * Now that modules have been loaded, we can process any custom resource
4098 * managers specified in the wal_consistency_checking GUC.
4099 */
4101
4102 /*
4103 * Create shared memory etc. (Nothing's really "shared" in single-user
4104 * mode, but we must have these data structures anyway.)
4105 */
4107
4108 /*
4109 * Estimate number of openable files. This must happen after setting up
4110 * semaphores, because on some platforms semaphores count as open files.
4111 */
4113
4114 /*
4115 * Remember stand-alone backend startup time,roughly at the same point
4116 * during startup that postmaster does so.
4117 */
4119
4120 /*
4121 * Create a per-backend PGPROC struct in shared memory. We must do this
4122 * before we can use LWLocks.
4123 */
4124 InitProcess();
4125
4126 /*
4127 * Now that sufficient infrastructure has been initialized, PostgresMain()
4128 * can do the rest.
4129 */
4131}
TimestampTz PgStartTime
Definition: timestamp.c:53
void set_max_safe_fds(void)
Definition: fd.c:1043
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1784
void InitializeGUCOptions(void)
Definition: guc.c:1530
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:352
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:198
const char * progname
Definition: main.c:44
void ChangeToDataDir(void)
Definition: miscinit.c:457
void process_shmem_requests(void)
Definition: miscinit.c:1927
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void process_shared_preload_libraries(void)
Definition: miscinit.c:1899
void checkDataDir(void)
Definition: miscinit.c:344
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1511
void InitPostmasterChildSlots(void)
Definition: pmchild.c:86
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3752
static const char * userDoption
Definition: postgres.c:152
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4146
void InitializeMaxBackends(void)
Definition: postinit.c:545
void InitializeFastPathLocks(void)
Definition: postinit.c:577
void InitProcess(void)
Definition: proc.c:341
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4784
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4846

References Assert, ChangeToDataDir(), checkDataDir(), CreateDataDirLockFile(), CreateSharedMemoryAndSemaphores(), dbname, ereport, errcode(), errmsg(), FATAL, GetCurrentTimestamp(), InitializeFastPathLocks(), InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterChildSlots(), InitProcess(), InitStandaloneProcess(), IsUnderPostmaster, LocalProcessControlFile(), PGC_POSTMASTER, PgStartTime, PostgresMain(), proc_exit(), process_postgres_switches(), process_shared_preload_libraries(), process_shmem_requests(), progname, SelectConfigFiles(), set_max_safe_fds(), userDoption, and username.

Referenced by main().

◆ process_postgres_switches()

void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3752 of file postgres.c.

3754{
3755 bool secure = (ctx == PGC_POSTMASTER);
3756 int errs = 0;
3757 GucSource gucsource;
3758 int flag;
3759
3760 if (secure)
3761 {
3762 gucsource = PGC_S_ARGV; /* switches came from command line */
3763
3764 /* Ignore the initial --single argument, if present */
3765 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3766 {
3767 argv++;
3768 argc--;
3769 }
3770 }
3771 else
3772 {
3773 gucsource = PGC_S_CLIENT; /* switches came from client */
3774 }
3775
3776#ifdef HAVE_INT_OPTERR
3777
3778 /*
3779 * Turn this off because it's either printed to stderr and not the log
3780 * where we'd want it, or argv[0] is now "--single", which would make for
3781 * a weird error message. We print our own error message below.
3782 */
3783 opterr = 0;
3784#endif
3785
3786 /*
3787 * Parse command-line options. CAUTION: keep this in sync with
3788 * postmaster/postmaster.c (the option sets should not conflict) and with
3789 * the common help() function in main/main.c.
3790 */
3791 while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3792 {
3793 switch (flag)
3794 {
3795 case 'B':
3796 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3797 break;
3798
3799 case 'b':
3800 /* Undocumented flag used for binary upgrades */
3801 if (secure)
3802 IsBinaryUpgrade = true;
3803 break;
3804
3805 case 'C':
3806 /* ignored for consistency with the postmaster */
3807 break;
3808
3809 case '-':
3810
3811 /*
3812 * Error if the user misplaced a special must-be-first option
3813 * for dispatching to a subprogram. parse_dispatch_option()
3814 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3815 * error for anything else.
3816 */
3818 ereport(ERROR,
3819 (errcode(ERRCODE_SYNTAX_ERROR),
3820 errmsg("--%s must be first argument", optarg)));
3821
3822 /* FALLTHROUGH */
3823 case 'c':
3824 {
3825 char *name,
3826 *value;
3827
3829 if (!value)
3830 {
3831 if (flag == '-')
3832 ereport(ERROR,
3833 (errcode(ERRCODE_SYNTAX_ERROR),
3834 errmsg("--%s requires a value",
3835 optarg)));
3836 else
3837 ereport(ERROR,
3838 (errcode(ERRCODE_SYNTAX_ERROR),
3839 errmsg("-c %s requires a value",
3840 optarg)));
3841 }
3842 SetConfigOption(name, value, ctx, gucsource);
3843 pfree(name);
3844 pfree(value);
3845 break;
3846 }
3847
3848 case 'D':
3849 if (secure)
3850 userDoption = strdup(optarg);
3851 break;
3852
3853 case 'd':
3854 set_debug_options(atoi(optarg), ctx, gucsource);
3855 break;
3856
3857 case 'E':
3858 if (secure)
3859 EchoQuery = true;
3860 break;
3861
3862 case 'e':
3863 SetConfigOption("datestyle", "euro", ctx, gucsource);
3864 break;
3865
3866 case 'F':
3867 SetConfigOption("fsync", "false", ctx, gucsource);
3868 break;
3869
3870 case 'f':
3871 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3872 errs++;
3873 break;
3874
3875 case 'h':
3876 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3877 break;
3878
3879 case 'i':
3880 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3881 break;
3882
3883 case 'j':
3884 if (secure)
3885 UseSemiNewlineNewline = true;
3886 break;
3887
3888 case 'k':
3889 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3890 break;
3891
3892 case 'l':
3893 SetConfigOption("ssl", "true", ctx, gucsource);
3894 break;
3895
3896 case 'N':
3897 SetConfigOption("max_connections", optarg, ctx, gucsource);
3898 break;
3899
3900 case 'n':
3901 /* ignored for consistency with postmaster */
3902 break;
3903
3904 case 'O':
3905 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3906 break;
3907
3908 case 'P':
3909 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3910 break;
3911
3912 case 'p':
3913 SetConfigOption("port", optarg, ctx, gucsource);
3914 break;
3915
3916 case 'r':
3917 /* send output (stdout and stderr) to the given file */
3918 if (secure)
3920 break;
3921
3922 case 'S':
3923 SetConfigOption("work_mem", optarg, ctx, gucsource);
3924 break;
3925
3926 case 's':
3927 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3928 break;
3929
3930 case 'T':
3931 /* ignored for consistency with the postmaster */
3932 break;
3933
3934 case 't':
3935 {
3936 const char *tmp = get_stats_option_name(optarg);
3937
3938 if (tmp)
3939 SetConfigOption(tmp, "true", ctx, gucsource);
3940 else
3941 errs++;
3942 break;
3943 }
3944
3945 case 'v':
3946
3947 /*
3948 * -v is no longer used in normal operation, since
3949 * FrontendProtocol is already set before we get here. We keep
3950 * the switch only for possible use in standalone operation,
3951 * in case we ever support using normal FE/BE protocol with a
3952 * standalone backend.
3953 */
3954 if (secure)
3956 break;
3957
3958 case 'W':
3959 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3960 break;
3961
3962 default:
3963 errs++;
3964 break;
3965 }
3966
3967 if (errs)
3968 break;
3969 }
3970
3971 /*
3972 * Optional database name should be there only if *dbname is NULL.
3973 */
3974 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3975 *dbname = strdup(argv[optind++]);
3976
3977 if (errs || argc != optind)
3978 {
3979 if (errs)
3980 optind--; /* complain about the previous argument */
3981
3982 /* spell the error message a bit differently depending on context */
3984 ereport(FATAL,
3985 errcode(ERRCODE_SYNTAX_ERROR),
3986 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3987 errhint("Try \"%s --help\" for more information.", progname));
3988 else
3989 ereport(FATAL,
3990 errcode(ERRCODE_SYNTAX_ERROR),
3991 errmsg("%s: invalid command-line argument: %s",
3992 progname, argv[optind]),
3993 errhint("Try \"%s --help\" for more information.", progname));
3994 }
3995
3996 /*
3997 * Reset getopt(3) library so that it will work correctly in subprocesses
3998 * or when this function is called a second time with another array.
3999 */
4000 optind = 1;
4001#ifdef HAVE_INT_OPTRESET
4002 optreset = 1; /* some systems need this too */
4003#endif
4004}
int errhint(const char *fmt,...)
Definition: elog.c:1317
bool IsBinaryUpgrade
Definition: globals.c:120
ProtocolVersion FrontendProtocol
Definition: globals.c:29
char OutputFileName[MAXPGPATH]
Definition: globals.c:78
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6362
GucSource
Definition: guc.h:108
@ PGC_S_ARGV
Definition: guc.h:113
@ PGC_S_CLIENT
Definition: guc.h:118
static struct @162 value
DispatchOption parse_dispatch_option(const char *name)
Definition: main.c:243
#define MAXPGPATH
PGDLLIMPORT int optind
Definition: getopt.c:51
PGDLLIMPORT int opterr
Definition: getopt.c:50
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3641
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3670
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3712
@ DISPATCH_POSTMASTER
Definition: postmaster.h:152
uint32 ProtocolVersion
Definition: pqcomm.h:100
char * flag(int b)
Definition: test-ctype.c:33
const char * name

References dbname, DISPATCH_POSTMASTER, EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, optarg, opterr, optind, OutputFileName, parse_dispatch_option(), ParseLongOption(), pfree(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 500 of file postgres.c.

501{
502 int save_errno = errno;
503
505 {
506 /* Check for general interrupts that arrived before/while reading */
508
509 /* Process sinval catchup interrupts, if any */
512
513 /* Process notify interrupts, if any */
516 }
517 else if (ProcDiePending)
518 {
519 /*
520 * We're dying. If there is no data available to read, then it's safe
521 * (and sane) to handle that now. If we haven't tried to read yet,
522 * make sure the process latch is set, so that if there is no data
523 * then we'll come back here and die. If we're done reading, also
524 * make sure the process latch is set, as we might've undesirably
525 * cleared it while reading.
526 */
527 if (blocked)
529 else
531 }
532
533 errno = save_errno;
534}
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:39

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, MyLatch, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), ProcessNotifyInterrupt(), and SetLatch().

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 546 of file postgres.c.

547{
548 int save_errno = errno;
549
550 if (ProcDiePending)
551 {
552 /*
553 * We're dying. If it's not possible to write, then we should handle
554 * that immediately, else a stuck client could indefinitely delay our
555 * response to the signal. If we haven't tried to write yet, make
556 * sure the process latch is set, so that if the write would block
557 * then we'll come back here and die. If we're done writing, also
558 * make sure the process latch is set, as we might've undesirably
559 * cleared it while writing.
560 */
561 if (blocked)
562 {
563 /*
564 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
565 * service ProcDiePending.
566 */
568 {
569 /*
570 * We don't want to send the client the error message, as a)
571 * that would possibly block again, and b) it would likely
572 * lead to loss of protocol sync because we may have already
573 * sent a partial protocol message.
574 */
577
579 }
580 }
581 else
583 }
584
585 errno = save_errno;
586}
volatile uint32 InterruptHoldoffCount
Definition: globals.c:42
volatile uint32 CritSectionCount
Definition: globals.c:44

References CHECK_FOR_INTERRUPTS, CritSectionCount, DestNone, DestRemote, InterruptHoldoffCount, MyLatch, ProcDiePending, SetLatch(), and whereToSendOutput.

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3273 of file postgres.c.

3274{
3275 /* OK to accept any interrupts now? */
3276 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3277 return;
3278 InterruptPending = false;
3279
3280 if (ProcDiePending)
3281 {
3282 ProcDiePending = false;
3283 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3285 /* As in quickdie, don't risk sending to client during auth */
3289 ereport(FATAL,
3290 (errcode(ERRCODE_QUERY_CANCELED),
3291 errmsg("canceling authentication due to timeout")));
3292 else if (AmAutoVacuumWorkerProcess())
3293 ereport(FATAL,
3294 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3295 errmsg("terminating autovacuum process due to administrator command")));
3296 else if (IsLogicalWorker())
3297 ereport(FATAL,
3298 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3299 errmsg("terminating logical replication worker due to administrator command")));
3300 else if (IsLogicalLauncher())
3301 {
3303 (errmsg_internal("logical replication launcher shutting down")));
3304
3305 /*
3306 * The logical replication launcher can be stopped at any time.
3307 * Use exit status 1 so the background worker is restarted.
3308 */
3309 proc_exit(1);
3310 }
3311 else if (AmBackgroundWorkerProcess())
3312 ereport(FATAL,
3313 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3314 errmsg("terminating background worker \"%s\" due to administrator command",
3316 else
3317 ereport(FATAL,
3318 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3319 errmsg("terminating connection due to administrator command")));
3320 }
3321
3323 {
3325
3326 /*
3327 * Check for lost connection and re-arm, if still configured, but not
3328 * if we've arrived back at DoingCommandRead state. We don't want to
3329 * wake up idle sessions, and they already know how to detect lost
3330 * connections.
3331 */
3333 {
3334 if (!pq_check_connection())
3335 ClientConnectionLost = true;
3336 else
3339 }
3340 }
3341
3343 {
3344 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3346 /* don't send to client, we already know the connection to be dead. */
3348 ereport(FATAL,
3349 (errcode(ERRCODE_CONNECTION_FAILURE),
3350 errmsg("connection to client lost")));
3351 }
3352
3353 /*
3354 * Don't allow query cancel interrupts while reading input from the
3355 * client, because we might lose sync in the FE/BE protocol. (Die
3356 * interrupts are OK, because we won't read any further messages from the
3357 * client in that case.)
3358 *
3359 * See similar logic in ProcessRecoveryConflictInterrupts().
3360 */
3362 {
3363 /*
3364 * Re-arm InterruptPending so that we process the cancel request as
3365 * soon as we're done reading the message. (XXX this is seriously
3366 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3367 * can't use that macro directly as the initial test in this function,
3368 * meaning that this code also creates opportunities for other bugs to
3369 * appear.)
3370 */
3371 InterruptPending = true;
3372 }
3373 else if (QueryCancelPending)
3374 {
3375 bool lock_timeout_occurred;
3376 bool stmt_timeout_occurred;
3377
3378 QueryCancelPending = false;
3379
3380 /*
3381 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3382 * need to clear both, so always fetch both.
3383 */
3384 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3385 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3386
3387 /*
3388 * If both were set, we want to report whichever timeout completed
3389 * earlier; this ensures consistent behavior if the machine is slow
3390 * enough that the second timeout triggers before we get here. A tie
3391 * is arbitrarily broken in favor of reporting a lock timeout.
3392 */
3393 if (lock_timeout_occurred && stmt_timeout_occurred &&
3395 lock_timeout_occurred = false; /* report stmt timeout */
3396
3397 if (lock_timeout_occurred)
3398 {
3400 ereport(ERROR,
3401 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3402 errmsg("canceling statement due to lock timeout")));
3403 }
3404 if (stmt_timeout_occurred)
3405 {
3407 ereport(ERROR,
3408 (errcode(ERRCODE_QUERY_CANCELED),
3409 errmsg("canceling statement due to statement timeout")));
3410 }
3412 {
3414 ereport(ERROR,
3415 (errcode(ERRCODE_QUERY_CANCELED),
3416 errmsg("canceling autovacuum task")));
3417 }
3418
3419 /*
3420 * If we are reading a command from the client, just ignore the cancel
3421 * request --- sending an extra error message won't accomplish
3422 * anything. Otherwise, go ahead and throw the error.
3423 */
3424 if (!DoingCommandRead)
3425 {
3427 ereport(ERROR,
3428 (errcode(ERRCODE_QUERY_CANCELED),
3429 errmsg("canceling statement due to user request")));
3430 }
3431 }
3432
3435
3437 {
3438 /*
3439 * If the GUC has been reset to zero, ignore the signal. This is
3440 * important because the GUC update itself won't disable any pending
3441 * interrupt. We need to unset the flag before the injection point,
3442 * otherwise we could loop in interrupts checking.
3443 */
3446 {
3447 INJECTION_POINT("idle-in-transaction-session-timeout");
3448 ereport(FATAL,
3449 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3450 errmsg("terminating connection due to idle-in-transaction timeout")));
3451 }
3452 }
3453
3455 {
3456 /* As above, ignore the signal if the GUC has been reset to zero. */
3458 if (TransactionTimeout > 0)
3459 {
3460 INJECTION_POINT("transaction-timeout");
3461 ereport(FATAL,
3462 (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3463 errmsg("terminating connection due to transaction timeout")));
3464 }
3465 }
3466
3468 {
3469 /* As above, ignore the signal if the GUC has been reset to zero. */
3471 if (IdleSessionTimeout > 0)
3472 {
3473 INJECTION_POINT("idle-session-timeout");
3474 ereport(FATAL,
3475 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3476 errmsg("terminating connection due to idle-session timeout")));
3477 }
3478 }
3479
3480 /*
3481 * If there are pending stats updates and we currently are truly idle
3482 * (matching the conditions in PostgresMain(), report stats now.
3483 */
3486 {
3488 pgstat_report_stat(true);
3489 }
3490
3493
3496
3499
3502}
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1044
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:117
bool IsLogicalWorker(void)
Definition: worker.c:4846
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:41
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:40
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:39
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:38
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:43
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:36
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:37
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:35
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:34
#define INJECTION_POINT(name)
bool IsLogicalLauncher(void)
Definition: launcher.c:1240
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1289
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:381
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:382
int client_connection_check_interval
Definition: postgres.c:101
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3234
bool ClientAuthInProgress
Definition: postmaster.c:360
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:196
bool pq_check_connection(void)
Definition: pqcomm.c:2054
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:496
void LockErrorCleanup(void)
Definition: proc.c:764
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:793
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelApplyMessages(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, INJECTION_POINT, InterruptHoldoffCount, InterruptPending, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionOrTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelApplyMessagePending, ParallelMessagePending, pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcessRecoveryConflictInterrupts(), ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, STATEMENT_TIMEOUT, TransactionTimeout, TransactionTimeoutPending, and whereToSendOutput.

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( ProcSignalReason  reason)
static

Definition at line 3076 of file postgres.c.

3077{
3078 switch (reason)
3079 {
3081
3082 /*
3083 * If we aren't waiting for a lock we can never deadlock.
3084 */
3085 if (GetAwaitedLock() == NULL)
3086 return;
3087
3088 /* Intentional fall through to check wait for pin */
3089 /* FALLTHROUGH */
3090
3092
3093 /*
3094 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3095 * aren't blocking the Startup process there is nothing more to
3096 * do.
3097 *
3098 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3099 * if we're waiting for locks and the startup process is not
3100 * waiting for buffer pin (i.e., also waiting for locks), we set
3101 * the flag so that ProcSleep() will check for deadlocks.
3102 */
3104 {
3108 return;
3109 }
3110
3112
3113 /* Intentional fall through to error handling */
3114 /* FALLTHROUGH */
3115
3119
3120 /*
3121 * If we aren't in a transaction any longer then ignore.
3122 */
3124 return;
3125
3126 /* FALLTHROUGH */
3127
3129
3130 /*
3131 * If we're not in a subtransaction then we are OK to throw an
3132 * ERROR to resolve the conflict. Otherwise drop through to the
3133 * FATAL case.
3134 *
3135 * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3136 * always throws an ERROR (ie never promotes to FATAL), though it
3137 * still has to respect QueryCancelHoldoffCount, so it shares this
3138 * code path. Logical decoding slots are only acquired while
3139 * performing logical decoding. During logical decoding no user
3140 * controlled code is run. During [sub]transaction abort, the
3141 * slot is released. Therefore user controlled code cannot
3142 * intercept an error before the replication slot is released.
3143 *
3144 * XXX other times that we can throw just an ERROR *may* be
3145 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3146 * transactions
3147 *
3148 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3149 * parent transactions and the transaction is not
3150 * transaction-snapshot mode
3151 *
3152 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3153 * cursors open in parent transactions
3154 */
3157 {
3158 /*
3159 * If we already aborted then we no longer need to cancel. We
3160 * do this here since we do not wish to ignore aborted
3161 * subtransactions, which must cause FATAL, currently.
3162 */
3164 return;
3165
3166 /*
3167 * If a recovery conflict happens while we are waiting for
3168 * input from the client, the client is presumably just
3169 * sitting idle in a transaction, preventing recovery from
3170 * making progress. We'll drop through to the FATAL case
3171 * below to dislodge it, in that case.
3172 */
3173 if (!DoingCommandRead)
3174 {
3175 /* Avoid losing sync in the FE/BE protocol. */
3176 if (QueryCancelHoldoffCount != 0)
3177 {
3178 /*
3179 * Re-arm and defer this interrupt until later. See
3180 * similar code in ProcessInterrupts().
3181 */
3182 RecoveryConflictPendingReasons[reason] = true;
3184 InterruptPending = true;
3185 return;
3186 }
3187
3188 /*
3189 * We are cleared to throw an ERROR. Either it's the
3190 * logical slot case, or we have a top-level transaction
3191 * that we can abort and a conflict that isn't inherently
3192 * non-retryable.
3193 */
3196 ereport(ERROR,
3198 errmsg("canceling statement due to conflict with recovery"),
3200 break;
3201 }
3202 }
3203
3204 /* Intentional fall through to session cancel */
3205 /* FALLTHROUGH */
3206
3208
3209 /*
3210 * Retrying is not possible because the database is dropped, or we
3211 * decided above that we couldn't resolve the conflict with an
3212 * ERROR and fell through. Terminate the session.
3213 */
3215 ereport(FATAL,
3217 ERRCODE_DATABASE_DROPPED :
3219 errmsg("terminating connection due to conflict with recovery"),
3221 errhint("In a moment you should be able to reconnect to the"
3222 " database and repeat your command.")));
3223 break;
3224
3225 default:
3226 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3227 }
3228}
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:5315
LOCALLOCK * GetAwaitedLock(void)
Definition: lock.c:1847
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
void pgstat_report_recovery_conflict(int reason)
static int errdetail_recovery_conflict(ProcSignalReason reason)
Definition: postgres.c:2528
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:717
void CheckDeadLockAlert(void)
Definition: proc.c:1870
bool IsSubTransaction(void)
Definition: xact.c:5036

References CheckDeadLockAlert(), DoingCommandRead, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, GetAwaitedLock(), GetStartupBufferPinWaitBufId(), HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), LockErrorCleanup(), MyProc, pgstat_report_recovery_conflict(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelHoldoffCount, RecoveryConflictPending, PGPROC::recoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by ProcessRecoveryConflictInterrupts().

◆ ProcessRecoveryConflictInterrupts()

static void ProcessRecoveryConflictInterrupts ( void  )
static

Definition at line 3234 of file postgres.c.

3235{
3236 /*
3237 * We don't need to worry about joggling the elbow of proc_exit, because
3238 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3239 * us.
3240 */
3244
3246
3249 reason++)
3250 {
3252 {
3253 RecoveryConflictPendingReasons[reason] = false;
3255 }
3256 }
3257}
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3076
ProcSignalReason
Definition: procsignal.h:31
@ PROCSIG_RECOVERY_CONFLICT_LAST
Definition: procsignal.h:49
@ PROCSIG_RECOVERY_CONFLICT_FIRST
Definition: procsignal.h:41

References Assert, InterruptHoldoffCount, proc_exit_inprogress, ProcessRecoveryConflictInterrupt(), PROCSIG_RECOVERY_CONFLICT_FIRST, PROCSIG_RECOVERY_CONFLICT_LAST, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by ProcessInterrupts().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2904 of file postgres.c.

2905{
2906 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2907 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2908
2909 /*
2910 * Prevent interrupts while exiting; though we just blocked signals that
2911 * would queue new interrupts, one may have been pending. We don't want a
2912 * quickdie() downgraded to a mere query cancel.
2913 */
2915
2916 /*
2917 * If we're aborting out of client auth, don't risk trying to send
2918 * anything to the client; we will likely violate the protocol, not to
2919 * mention that we may have interrupted the guts of OpenSSL or some
2920 * authentication library.
2921 */
2924
2925 /*
2926 * Notify the client before exiting, to give a clue on what happened.
2927 *
2928 * It's dubious to call ereport() from a signal handler. It is certainly
2929 * not async-signal safe. But it seems better to try, than to disconnect
2930 * abruptly and leave the client wondering what happened. It's remotely
2931 * possible that we crash or hang while trying to send the message, but
2932 * receiving a SIGQUIT is a sign that something has already gone badly
2933 * wrong, so there's not much to lose. Assuming the postmaster is still
2934 * running, it will SIGKILL us soon if we get stuck for some reason.
2935 *
2936 * One thing we can do to make this a tad safer is to clear the error
2937 * context stack, so that context callbacks are not called. That's a lot
2938 * less code that could be reached here, and the context info is unlikely
2939 * to be very relevant to a SIGQUIT report anyway.
2940 */
2941 error_context_stack = NULL;
2942
2943 /*
2944 * When responding to a postmaster-issued signal, we send the message only
2945 * to the client; sending to the server log just creates log spam, plus
2946 * it's more code that we need to hope will work in a signal handler.
2947 *
2948 * Ideally these should be ereport(FATAL), but then we'd not get control
2949 * back to force the correct type of process exit.
2950 */
2951 switch (GetQuitSignalReason())
2952 {
2953 case PMQUIT_NOT_SENT:
2954 /* Hmm, SIGQUIT arrived out of the blue */
2956 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2957 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2958 break;
2959 case PMQUIT_FOR_CRASH:
2960 /* A crash-and-restart cycle is in progress */
2962 (errcode(ERRCODE_CRASH_SHUTDOWN),
2963 errmsg("terminating connection because of crash of another server process"),
2964 errdetail("The postmaster has commanded this server process to roll back"
2965 " the current transaction and exit, because another"
2966 " server process exited abnormally and possibly corrupted"
2967 " shared memory."),
2968 errhint("In a moment you should be able to reconnect to the"
2969 " database and repeat your command.")));
2970 break;
2971 case PMQUIT_FOR_STOP:
2972 /* Immediate-mode stop */
2974 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2975 errmsg("terminating connection due to immediate shutdown command")));
2976 break;
2977 }
2978
2979 /*
2980 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2981 * because shared memory may be corrupted, so we don't want to try to
2982 * clean up our transaction. Just nail the windows shut and get out of
2983 * town. The callbacks wouldn't be safe to run from a signal handler,
2984 * anyway.
2985 *
2986 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2987 * a system reset cycle if someone sends a manual SIGQUIT to a random
2988 * backend. This is necessary precisely because we don't clean up our
2989 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2990 * should ensure the postmaster sees this as a crash, too, but no harm in
2991 * being doubly sure.)
2992 */
2993 _exit(2);
2994}
sigset_t BlockSig
Definition: pqsignal.c:23
#define WARNING_CLIENT_ONLY
Definition: elog.h:38
QuitSignalReason GetQuitSignalReason(void)
Definition: pmsignal.c:213
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
@ PMQUIT_NOT_SENT
Definition: pmsignal.h:52

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), error_context_stack, GetQuitSignalReason(), HOLD_INTERRUPTS, PMQUIT_FOR_CRASH, PMQUIT_FOR_STOP, PMQUIT_NOT_SENT, SIGQUIT, WARNING, WARNING_CLIENT_ONLY, and whereToSendOutput.

Referenced by PostgresMain().

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 479 of file postgres.c.

480{
481 int result;
482
484 result = SocketBackend(inBuf);
485 else
486 result = InteractiveBackend(inBuf);
487 return result;
488}
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:351
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:235

References DestRemote, InteractiveBackend(), SocketBackend(), and whereToSendOutput.

Referenced by PostgresMain().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3641 of file postgres.c.

3642{
3643 if (debug_flag > 0)
3644 {
3645 char debugstr[64];
3646
3647 sprintf(debugstr, "debug%d", debug_flag);
3648 SetConfigOption("log_min_messages", debugstr, context, source);
3649 }
3650 else
3651 SetConfigOption("log_min_messages", "notice", context, source);
3652
3653 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3654 {
3655 SetConfigOption("log_connections", "true", context, source);
3656 SetConfigOption("log_disconnections", "true", context, source);
3657 }
3658 if (debug_flag >= 2)
3659 SetConfigOption("log_statement", "all", context, source);
3660 if (debug_flag >= 3)
3661 SetConfigOption("debug_print_parse", "true", context, source);
3662 if (debug_flag >= 4)
3663 SetConfigOption("debug_print_plan", "true", context, source);
3664 if (debug_flag >= 5)
3665 SetConfigOption("debug_print_rewritten", "true", context, source);
3666}
static rewind_source * source
Definition: pg_rewind.c:89
#define sprintf
Definition: port.h:240

References PGC_POSTMASTER, SetConfigOption(), source, and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3670 of file postgres.c.

3671{
3672 const char *tmp = NULL;
3673
3674 switch (arg[0])
3675 {
3676 case 's': /* seqscan */
3677 tmp = "enable_seqscan";
3678 break;
3679 case 'i': /* indexscan */
3680 tmp = "enable_indexscan";
3681 break;
3682 case 'o': /* indexonlyscan */
3683 tmp = "enable_indexonlyscan";
3684 break;
3685 case 'b': /* bitmapscan */
3686 tmp = "enable_bitmapscan";
3687 break;
3688 case 't': /* tidscan */
3689 tmp = "enable_tidscan";
3690 break;
3691 case 'n': /* nestloop */
3692 tmp = "enable_nestloop";
3693 break;
3694 case 'm': /* mergejoin */
3695 tmp = "enable_mergejoin";
3696 break;
3697 case 'h': /* hashjoin */
3698 tmp = "enable_hashjoin";
3699 break;
3700 }
3701 if (tmp)
3702 {
3703 SetConfigOption(tmp, "false", context, source);
3704 return true;
3705 }
3706 else
3707 return false;
3708}

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4984 of file postgres.c.

4985{
4987 struct timeval user,
4988 sys;
4989 struct timeval elapse_t;
4990 struct rusage r;
4991
4993 gettimeofday(&elapse_t, NULL);
4994 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4995 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4996 if (elapse_t.tv_usec < Save_t.tv_usec)
4997 {
4998 elapse_t.tv_sec--;
4999 elapse_t.tv_usec += 1000000;
5000 }
5001 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5002 {
5003 r.ru_utime.tv_sec--;
5004 r.ru_utime.tv_usec += 1000000;
5005 }
5006 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5007 {
5008 r.ru_stime.tv_sec--;
5009 r.ru_stime.tv_usec += 1000000;
5010 }
5011
5012 /*
5013 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5014 * some work to interpret them, and most platforms don't fill them in.
5015 */
5017
5018 appendStringInfoString(&str, "! system usage stats:\n");
5020 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5021 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5022 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5023 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5024 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5025 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5026 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5028 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5029 (long) user.tv_sec,
5030 (long) user.tv_usec,
5031 (long) sys.tv_sec,
5032 (long) sys.tv_usec);
5033#ifndef WIN32
5034
5035 /*
5036 * The following rusage fields are not defined by POSIX, but they're
5037 * present on all current Unix-like systems so we use them without any
5038 * special checks. Some of these could be provided in our Windows
5039 * emulation in src/port/win32getrusage.c with more work.
5040 */
5042 "!\t%ld kB max resident size\n",
5043#if defined(__darwin__)
5044 /* in bytes on macOS */
5045 r.ru_maxrss / 1024
5046#else
5047 /* in kilobytes on most other platforms */
5048 r.ru_maxrss
5049#endif
5050 );
5052 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5053 r.ru_inblock - Save_r.ru_inblock,
5054 /* they only drink coffee at dec */
5055 r.ru_oublock - Save_r.ru_oublock,
5056 r.ru_inblock, r.ru_oublock);
5058 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5059 r.ru_majflt - Save_r.ru_majflt,
5060 r.ru_minflt - Save_r.ru_minflt,
5061 r.ru_majflt, r.ru_minflt,
5062 r.ru_nswap - Save_r.ru_nswap,
5063 r.ru_nswap);
5065 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5066 r.ru_nsignals -