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/explain_state.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/backend_startup.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, ExplainState *es)
 
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 217 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 3671 of file postgres.c.

3672{
3673 int *flags = (int *) extra;
3674
3676}
int restrict_nonsystem_relation_kind
Definition: postgres.c:106

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3600 of file postgres.c.

3601{
3602 if (IsTransactionState())
3603 {
3604 /*
3605 * If transaction_timeout GUC has changed within the transaction block
3606 * enable or disable the timer correspondingly.
3607 */
3612 }
3613}
#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:387

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 2598 of file postgres.c.

2599{
2602 char *quotedval;
2603
2604 if (data->paramno < 0)
2605 return;
2606
2607 /* If we have a textual value, quote it, and trim if necessary */
2608 if (data->paramval)
2609 {
2613 quotedval = buf.data;
2614 }
2615 else
2616 quotedval = NULL;
2617
2618 if (data->portalName && data->portalName[0] != '\0')
2619 {
2620 if (quotedval)
2621 errcontext("portal \"%s\" parameter $%d = %s",
2622 data->portalName, data->paramno + 1, quotedval);
2623 else
2624 errcontext("portal \"%s\" parameter $%d",
2625 data->portalName, data->paramno + 1);
2626 }
2627 else
2628 {
2629 if (quotedval)
2630 errcontext("unnamed portal parameter $%d = %s",
2631 data->paramno + 1, quotedval);
2632 else
2633 errcontext("unnamed portal parameter $%d",
2634 data->paramno + 1);
2635 }
2636
2637 if (quotedval)
2638 pfree(quotedval);
2639}
#define errcontext
Definition: elog.h:198
int log_parameter_max_length_on_error
Definition: guc_tables.c:545
void pfree(void *pointer)
Definition: mcxt.c:1594
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 3550 of file postgres.c.

3551{
3552 if (!WaitEventSetCanReportClosed() && *newval != 0)
3553 {
3554 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3555 return false;
3556 }
3557 return true;
3558}
#define GUC_check_errdetail
Definition: guc.h:505
bool WaitEventSetCanReportClosed(void)

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2429 of file postgres.c.

2430{
2433 {
2434 long secs;
2435 int usecs;
2436 int msecs;
2437 bool exceeded_duration;
2438 bool exceeded_sample_duration;
2439 bool in_sample = false;
2440
2443 &secs, &usecs);
2444 msecs = usecs / 1000;
2445
2446 /*
2447 * This odd-looking test for log_min_duration_* being exceeded is
2448 * designed to avoid integer overflow with very long durations: don't
2449 * compute secs * 1000 until we've verified it will fit in int.
2450 */
2451 exceeded_duration = (log_min_duration_statement == 0 ||
2453 (secs > log_min_duration_statement / 1000 ||
2454 secs * 1000 + msecs >= log_min_duration_statement)));
2455
2456 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2458 (secs > log_min_duration_sample / 1000 ||
2459 secs * 1000 + msecs >= log_min_duration_sample)));
2460
2461 /*
2462 * Do not log if log_statement_sample_rate = 0. Log a sample if
2463 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2464 * log_statement_sample_rate = 1.
2465 */
2466 if (exceeded_sample_duration)
2467 in_sample = log_statement_sample_rate != 0 &&
2470
2471 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2472 {
2473 snprintf(msec_str, 32, "%ld.%03d",
2474 secs * 1000 + msecs, usecs % 1000);
2475 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2476 return 2;
2477 else
2478 return 1;
2479 }
2480 }
2481
2482 return 0;
2483}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1721
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
int log_min_duration_statement
Definition: guc_tables.c:543
int log_min_duration_sample
Definition: guc_tables.c:542
double log_statement_sample_rate
Definition: guc_tables.c:547
bool log_duration
Definition: guc_tables.c:507
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:239
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:879
bool xact_is_sampled
Definition: xact.c:296

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 2390 of file postgres.c.

2391{
2392 ListCell *stmt_item;
2393
2395 return false;
2397 return true;
2398
2399 /* Else we have to inspect the statement(s) to see whether to log */
2400 foreach(stmt_item, stmt_list)
2401 {
2402 Node *stmt = (Node *) lfirst(stmt_item);
2403
2405 return true;
2406 }
2407
2408 return false;
2409}
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:97
Definition: nodes.h:135
@ LOGSTMT_NONE
Definition: tcopprot.h:34
@ LOGSTMT_ALL
Definition: tcopprot.h:37
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3241

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 3585 of file postgres.c.

3586{
3587 if (*newval &&
3589 {
3590 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3591 "\"log_parser_stats\", \"log_planner_stats\", "
3592 "or \"log_executor_stats\" is true.");
3593 return false;
3594 }
3595 return true;
3596}
bool log_parser_stats
Definition: guc_tables.c:520
bool log_planner_stats
Definition: guc_tables.c:521
bool log_executor_stats
Definition: guc_tables.c:522

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 3619 of file postgres.c.

3620{
3621 char *rawstring;
3622 List *elemlist;
3623 ListCell *l;
3624 int flags = 0;
3625
3626 /* Need a modifiable copy of string */
3627 rawstring = pstrdup(*newval);
3628
3629 if (!SplitIdentifierString(rawstring, ',', &elemlist))
3630 {
3631 /* syntax error in list */
3632 GUC_check_errdetail("List syntax is invalid.");
3633 pfree(rawstring);
3634 list_free(elemlist);
3635 return false;
3636 }
3637
3638 foreach(l, elemlist)
3639 {
3640 char *tok = (char *) lfirst(l);
3641
3642 if (pg_strcasecmp(tok, "view") == 0)
3643 flags |= RESTRICT_RELKIND_VIEW;
3644 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3646 else
3647 {
3648 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3649 pfree(rawstring);
3650 list_free(elemlist);
3651 return false;
3652 }
3653 }
3654
3655 pfree(rawstring);
3656 list_free(elemlist);
3657
3658 /* Save the flags in *extra, for use by the assign function */
3659 *extra = guc_malloc(LOG, sizeof(int));
3660 if (!*extra)
3661 return false;
3662 *((int *) *extra) = flags;
3663
3664 return true;
3665}
#define LOG
Definition: elog.h:31
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:636
void list_free(List *list)
Definition: list.c:1546
char * pstrdup(const char *in)
Definition: mcxt.c:1759
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:45
#define RESTRICT_RELKIND_VIEW
Definition: tcopprot.h:44
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2744

References GUC_check_errdetail, guc_malloc(), lfirst, list_free(), LOG, 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 3571 of file postgres.c.

3572{
3574 {
3575 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3576 return false;
3577 }
3578 return true;
3579}
bool log_statement_stats
Definition: guc_tables.c:523

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3032 of file postgres.c.

3033{
3034 /* Don't joggle the elbow of proc_exit */
3036 {
3037 InterruptPending = true;
3038 ProcDiePending = true;
3039 }
3040
3041 /* for the cumulative stats system */
3043
3044 /* If we're still here, waken anything waiting on the process latch */
3046
3047 /*
3048 * If we're in single user mode, we want to quit immediately - we can't
3049 * rely on latches as they wouldn't work when stdin/stdout is a file.
3050 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3051 * effort just for the benefit of single user mode.
3052 */
3055}
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:63
volatile sig_atomic_t ProcDiePending
Definition: globals.c:34
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:290
@ DISCONNECT_KILLED
Definition: pgstat.h:59
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:92
static bool DoingCommandRead
Definition: postgres.c:137
void ProcessInterrupts(void)
Definition: postgres.c:3304

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 2910 of file postgres.c.

2911{
2912 /* paranoia to avoid a dangling pointer in case of error */
2914 {
2916
2917 unnamed_stmt_psrc = NULL;
2918 DropCachedPlan(psrc);
2919 }
2920}
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:589
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:151

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 5213 of file postgres.c.

5214{
5215 /* must be within an xact */
5217
5218 if (StatementTimeout > 0
5220 {
5223 }
5224 else
5225 {
5228 }
5229}
Assert(PointerIsAligned(start, uint64))
static bool xact_started
Definition: postgres.c:130
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 2545 of file postgres.c.

2546{
2548 errdetail("Abort reason: recovery conflict");
2549
2550 return 0;
2551}
int errdetail(const char *fmt,...)
Definition: elog.c:1216
PGPROC * MyProc
Definition: proc.c:66
bool recoveryConflictPending
Definition: proc.h:237

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 2492 of file postgres.c.

2493{
2494 ListCell *parsetree_item;
2495
2496 foreach(parsetree_item, raw_parsetree_list)
2497 {
2498 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2499
2500 if (IsA(parsetree->stmt, ExecuteStmt))
2501 {
2502 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2503 PreparedStatement *pstmt;
2504
2505 pstmt = FetchPreparedStatement(stmt->name, false);
2506 if (pstmt)
2507 {
2508 errdetail("prepare: %s", pstmt->plansource->query_string);
2509 return 0;
2510 }
2511 }
2512 }
2513
2514 return 0;
2515}
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:434
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define lfirst_node(type, lc)
Definition: pg_list.h:176
Node * stmt
Definition: parsenodes.h:2088

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 2525 of file postgres.c.

2526{
2527 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2528 {
2529 char *str;
2530
2532 if (str && str[0] != '\0')
2533 errdetail("Parameters: %s", str);
2534 }
2535
2536 return 0;
2537}
int log_parameter_max_length
Definition: guc_tables.c:544
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 2559 of file postgres.c.

2560{
2561 switch (reason)
2562 {
2564 errdetail("User was holding shared buffer pin for too long.");
2565 break;
2567 errdetail("User was holding a relation lock for too long.");
2568 break;
2570 errdetail("User was or might have been using tablespace that must be dropped.");
2571 break;
2573 errdetail("User query might have needed to see row versions that must be removed.");
2574 break;
2576 errdetail("User was using a logical replication slot that must be invalidated.");
2577 break;
2579 errdetail("User transaction caused buffer deadlock with recovery.");
2580 break;
2582 errdetail("User was connected to a database that must be dropped.");
2583 break;
2584 default:
2585 break;
2586 /* no errdetail */
2587 }
2588
2589 return 0;
2590}
@ 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 1630 of file postgres.c.

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

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(), INT64CONST, 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_plan_id(), pgstat_report_query_id(), plan, 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, PortalData::stmts, 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 2740 of file postgres.c.

2741{
2742 Portal portal;
2743
2744 /*
2745 * Start up a transaction command. (Note that this will normally change
2746 * current memory context.) Nothing happens if we are already in one.
2747 */
2749
2750 /* Switch back to message context */
2752
2753 portal = GetPortalByName(portal_name);
2754 if (!PortalIsValid(portal))
2755 ereport(ERROR,
2756 (errcode(ERRCODE_UNDEFINED_CURSOR),
2757 errmsg("portal \"%s\" does not exist", portal_name)));
2758
2759 /*
2760 * If we are in aborted transaction state, we can't run
2761 * SendRowDescriptionMessage(), because that needs catalog accesses.
2762 * Hence, refuse to Describe portals that return data. (We shouldn't just
2763 * refuse all Describes, since that might break the ability of some
2764 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2765 * blindly Describes whatever it does.)
2766 */
2768 portal->tupDesc)
2769 ereport(ERROR,
2770 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2771 errmsg("current transaction is aborted, "
2772 "commands ignored until end of transaction block"),
2773 errdetail_abort()));
2774
2776 return; /* can't actually do anything... */
2777
2778 if (portal->tupDesc)
2780 portal->tupDesc,
2781 FetchPortalTargetList(portal),
2782 portal->formats);
2783 else
2785}
#define PortalIsValid(p)
Definition: portal.h:211
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
static StringInfoData row_description_buf
Definition: postgres.c:164
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:327
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:167
#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 2647 of file postgres.c.

2648{
2649 CachedPlanSource *psrc;
2650
2651 /*
2652 * Start up a transaction command. (Note that this will normally change
2653 * current memory context.) Nothing happens if we are already in one.
2654 */
2656
2657 /* Switch back to message context */
2659
2660 /* Find prepared statement */
2661 if (stmt_name[0] != '\0')
2662 {
2663 PreparedStatement *pstmt;
2664
2665 pstmt = FetchPreparedStatement(stmt_name, true);
2666 psrc = pstmt->plansource;
2667 }
2668 else
2669 {
2670 /* special-case the unnamed statement */
2671 psrc = unnamed_stmt_psrc;
2672 if (!psrc)
2673 ereport(ERROR,
2674 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2675 errmsg("unnamed prepared statement does not exist")));
2676 }
2677
2678 /* Prepared statements shouldn't have changeable result descs */
2679 Assert(psrc->fixed_result);
2680
2681 /*
2682 * If we are in aborted transaction state, we can't run
2683 * SendRowDescriptionMessage(), because that needs catalog accesses.
2684 * Hence, refuse to Describe statements that return data. (We shouldn't
2685 * just refuse all Describes, since that might break the ability of some
2686 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2687 * blindly Describes whatever it does.) We can Describe parameters
2688 * without doing anything dangerous, so we don't restrict that.
2689 */
2691 psrc->resultDesc)
2692 ereport(ERROR,
2693 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2694 errmsg("current transaction is aborted, "
2695 "commands ignored until end of transaction block"),
2696 errdetail_abort()));
2697
2699 return; /* can't actually do anything... */
2700
2701 /*
2702 * First describe the parameters...
2703 */
2706
2707 for (int i = 0; i < psrc->num_params; i++)
2708 {
2709 Oid ptype = psrc->param_types[i];
2710
2711 pq_sendint32(&row_description_buf, (int) ptype);
2712 }
2714
2715 /*
2716 * Next send RowDescription or NoData to describe the result...
2717 */
2718 if (psrc->resultDesc)
2719 {
2720 List *tlist;
2721
2722 /* Get the plan's primary targetlist */
2723 tlist = CachedPlanGetTargetList(psrc, NULL);
2724
2726 psrc->resultDesc,
2727 tlist,
2728 NULL);
2729 }
2730 else
2732}
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1778
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:120

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 2113 of file postgres.c.

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

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(), INT64CONST, IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), lfirst_node, LOG, log_statement_stats, MyXactFlags, PortalData::name, NIL, NullCommand(), ParamsErrorCbData::params, ParamsErrorCallback(), pgstat_report_activity(), pgstat_report_plan_id(), 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, 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 1395 of file postgres.c.

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

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 1017 of file postgres.c.

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

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_plan_id(), 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 2831 of file postgres.c.

2832{
2833 /* cancel active statement timeout after each command */
2835
2836 if (xact_started)
2837 {
2839
2840#ifdef MEMORY_CONTEXT_CHECKING
2841 /* Check all memory contexts that weren't freed during commit */
2842 /* (those that were, were checked before being deleted) */
2843 MemoryContextCheck(TopMemoryContext);
2844#endif
2845
2846#ifdef SHOW_MEMORY_STATS
2847 /* Print mem stats after each commit for leak tracking */
2849#endif
2850
2851 xact_started = false;
2852 }
2853}
MemoryContext TopMemoryContext
Definition: mcxt.c:166
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:860
void CommitTransactionCommand(void)
Definition: xact.c:3169

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 3079 of file postgres.c.

3080{
3081 /* We're not returning, so no need to save errno */
3082 ereport(ERROR,
3083 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3084 errmsg("floating-point exception"),
3085 errdetail("An invalid floating-point operation was signaled. "
3086 "This probably means an out-of-range result or an "
3087 "invalid operation, such as division by zero.")));
3088}

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

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

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 5041 of file postgres.c.

5042{
5043 if (am_walsender)
5044 {
5045 if (firstchar == PqMsg_FunctionCall)
5046 ereport(ERROR,
5047 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5048 errmsg("fastpath function calls not supported in a replication connection")));
5049 else
5050 ereport(ERROR,
5051 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5052 errmsg("extended query protocol not supported in a replication connection")));
5053 }
5054}
#define PqMsg_FunctionCall
Definition: protocol.h:23
bool am_walsender
Definition: walsender.c:123

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 3759 of file postgres.c.

3760{
3761 switch (arg[0])
3762 {
3763 case 'p':
3764 if (optarg[1] == 'a') /* "parser" */
3765 return "log_parser_stats";
3766 else if (optarg[1] == 'l') /* "planner" */
3767 return "log_planner_stats";
3768 break;
3769
3770 case 'e': /* "executor" */
3771 return "log_executor_stats";
3772 break;
3773 }
3774
3775 return NULL;
3776}
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 3095 of file postgres.c.

3096{
3097 RecoveryConflictPendingReasons[reason] = true;
3099 InterruptPending = true;
3100 /* latch will be set by procsignal_sigusr1_handler */
3101}
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:160
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:159

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 325 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 237 of file postgres.c.

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

2864{
2865 if (parsetree && IsA(parsetree, TransactionStmt))
2866 {
2867 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2868
2869 if (stmt->kind == TRANS_STMT_COMMIT ||
2870 stmt->kind == TRANS_STMT_PREPARE ||
2871 stmt->kind == TRANS_STMT_ROLLBACK ||
2873 return true;
2874 }
2875 return false;
2876}
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3797
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3794
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3793
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3798

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 2880 of file postgres.c.

2881{
2882 if (list_length(pstmts) == 1)
2883 {
2884 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2885
2886 if (pstmt->commandType == CMD_UTILITY &&
2888 return true;
2889 }
2890 return false;
2891}
@ CMD_UTILITY
Definition: nodes.h:280
CmdType commandType
Definition: plannodes.h:68
Node * utilityStmt
Definition: plannodes.h:150

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 2895 of file postgres.c.

2896{
2897 if (list_length(pstmts) == 1)
2898 {
2899 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2900
2901 if (pstmt->commandType == CMD_UTILITY &&
2903 return true;
2904 }
2905 return false;
2906}

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 5177 of file postgres.c.

5178{
5179 Port *port = MyProcPort;
5180 long secs;
5181 int usecs;
5182 int msecs;
5183 int hours,
5184 minutes,
5185 seconds;
5186
5189 &secs, &usecs);
5190 msecs = usecs / 1000;
5191
5192 hours = secs / SECS_PER_HOUR;
5193 secs %= SECS_PER_HOUR;
5194 minutes = secs / SECS_PER_MINUTE;
5195 seconds = secs % SECS_PER_MINUTE;
5196
5197 ereport(LOG,
5198 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5199 "user=%s database=%s host=%s%s%s",
5200 hours, minutes, seconds, msecs,
5201 port->user_name, port->database_name, port->remote_host,
5202 port->remote_port[0] ? " port=" : "", port->remote_port)));
5203}
#define SECS_PER_HOUR
Definition: timestamp.h:127
#define SECS_PER_MINUTE
Definition: timestamp.h:128
TimestampTz MyStartTimestamp
Definition: globals.c:49
struct Port * MyProcPort
Definition: globals.c:51
static int port
Definition: pg_regress.c:115
Definition: libpq-be.h:129

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 670 of file postgres.c.

675{
676 Query *query;
677 List *querytree_list;
678
679 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
680
681 /*
682 * (1) Perform parse analysis.
683 */
685 ResetUsage();
686
687 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
688 queryEnv);
689
691 ShowUsage("PARSE ANALYSIS STATISTICS");
692
693 /*
694 * (2) Rewrite the queries, as necessary
695 */
696 querytree_list = pg_rewrite_query(query);
697
698 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
699
700 return querytree_list;
701}
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:116
List * pg_rewrite_query(Query *query)
Definition: postgres.c:803

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 709 of file postgres.c.

714{
715 Query *query;
716 List *querytree_list;
717
718 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
719
720 /*
721 * (1) Perform parse analysis.
722 */
724 ResetUsage();
725
726 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
727 queryEnv);
728
729 /*
730 * Check all parameter types got determined.
731 */
732 for (int i = 0; i < *numParams; i++)
733 {
734 Oid ptype = (*paramTypes)[i];
735
736 if (ptype == InvalidOid || ptype == UNKNOWNOID)
738 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
739 errmsg("could not determine data type of parameter $%d",
740 i + 1)));
741 }
742
744 ShowUsage("PARSE ANALYSIS STATISTICS");
745
746 /*
747 * (2) Rewrite the queries, as necessary
748 */
749 querytree_list = pg_rewrite_query(query);
750
751 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
752
753 return querytree_list;
754}
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:156
#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 763 of file postgres.c.

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

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

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

◆ pg_parse_query()

List * pg_parse_query ( const char *  query_string)

Definition at line 604 of file postgres.c.

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

References copyObject, Debug_pretty_print, Debug_print_raw_parse, elog, elog_node_display(), equal(), LOG, 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(), inline_function(), inline_set_returning_function(), and sql_compile_callback().

◆ pg_plan_queries()

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

Definition at line 975 of file postgres.c.

977{
978 List *stmt_list = NIL;
979 ListCell *query_list;
980
981 foreach(query_list, querytrees)
982 {
983 Query *query = lfirst_node(Query, query_list);
985
986 if (query->commandType == CMD_UTILITY)
987 {
988 /* Utility commands require no planning. */
990 stmt->commandType = CMD_UTILITY;
991 stmt->canSetTag = query->canSetTag;
992 stmt->utilityStmt = query->utilityStmt;
993 stmt->stmt_location = query->stmt_location;
994 stmt->stmt_len = query->stmt_len;
995 stmt->queryId = query->queryId;
996 stmt->planOrigin = PLAN_STMT_INTERNAL;
997 }
998 else
999 {
1000 stmt = pg_plan_query(query, query_string, cursorOptions,
1001 boundParams, NULL);
1002 }
1003
1004 stmt_list = lappend(stmt_list, stmt);
1005 }
1006
1007 return stmt_list;
1008}
List * lappend(List *list, void *datum)
Definition: list.c:339
#define makeNode(_type_)
Definition: nodes.h:161
@ PLAN_STMT_INTERNAL
Definition: plannodes.h:40
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition: postgres.c:887
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:141
ParseLoc stmt_location
Definition: parsenodes.h:255

References CMD_UTILITY, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PLAN_STMT_INTERNAL, 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,
ExplainState es 
)

Definition at line 887 of file postgres.c.

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

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(), PerformCursorOpen(), pg_plan_queries(), refresh_matview_datafill(), and standard_ExplainOneQuery().

◆ pg_rewrite_query()

List * pg_rewrite_query ( Query query)

Definition at line 803 of file postgres.c.

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

◆ PostgresMain()

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

Definition at line 4193 of file postgres.c.

4194{
4195 sigjmp_buf local_sigjmp_buf;
4196
4197 /* these must be volatile to ensure state is preserved across longjmp: */
4198 volatile bool send_ready_for_query = true;
4199 volatile bool idle_in_transaction_timeout_enabled = false;
4200 volatile bool idle_session_timeout_enabled = false;
4201
4202 Assert(dbname != NULL);
4203 Assert(username != NULL);
4204
4206
4207 /*
4208 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4209 * has already set up BlockSig and made that the active signal mask.)
4210 *
4211 * Note that postmaster blocked all signals before forking child process,
4212 * so there is no race condition whereby we might receive a signal before
4213 * we have set up the handler.
4214 *
4215 * Also note: it's best not to use any signals that are SIG_IGNored in the
4216 * postmaster. If such a signal arrives before we are able to change the
4217 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4218 * handler in the postmaster to reserve the signal. (Of course, this isn't
4219 * an issue for signals that are locally generated, such as SIGALRM and
4220 * SIGPIPE.)
4221 */
4222 if (am_walsender)
4223 WalSndSignals();
4224 else
4225 {
4227 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4228 pqsignal(SIGTERM, die); /* cancel current query and exit */
4229
4230 /*
4231 * In a postmaster child backend, replace SignalHandlerForCrashExit
4232 * with quickdie, so we can tell the client we're dying.
4233 *
4234 * In a standalone backend, SIGQUIT can be generated from the keyboard
4235 * easily, while SIGTERM cannot, so we make both signals do die()
4236 * rather than quickdie().
4237 */
4239 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4240 else
4241 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4242 InitializeTimeouts(); /* establishes SIGALRM handler */
4243
4244 /*
4245 * Ignore failure to write to frontend. Note: if frontend closes
4246 * connection, we will notice it and exit cleanly when control next
4247 * returns to outer loop. This seems safer than forcing exit in the
4248 * midst of output during who-knows-what operation...
4249 */
4250 pqsignal(SIGPIPE, SIG_IGN);
4252 pqsignal(SIGUSR2, SIG_IGN);
4254
4255 /*
4256 * Reset some signals that are accepted by postmaster but not by
4257 * backend
4258 */
4259 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4260 * platforms */
4261 }
4262
4263 /* Early initialization */
4264 BaseInit();
4265
4266 /* We need to allow SIGINT, etc during the initial transaction */
4267 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4268
4269 /*
4270 * Generate a random cancel key, if this is a backend serving a
4271 * connection. InitPostgres() will advertise it in shared memory.
4272 */
4275 {
4276 int len;
4277
4278 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4281 {
4282 ereport(ERROR,
4283 (errcode(ERRCODE_INTERNAL_ERROR),
4284 errmsg("could not generate random cancel key")));
4285 }
4287 }
4288
4289 /*
4290 * General initialization.
4291 *
4292 * NOTE: if you are tempted to add code in this vicinity, consider putting
4293 * it inside InitPostgres() instead. In particular, anything that
4294 * involves database access should be there, not here.
4295 *
4296 * Honor session_preload_libraries if not dealing with a WAL sender.
4297 */
4298 InitPostgres(dbname, InvalidOid, /* database to connect to */
4299 username, InvalidOid, /* role to connect as */
4301 NULL); /* no out_dbname */
4302
4303 /*
4304 * If the PostmasterContext is still around, recycle the space; we don't
4305 * need it anymore after InitPostgres completes.
4306 */
4308 {
4310 PostmasterContext = NULL;
4311 }
4312
4314
4315 /*
4316 * Now all GUC states are fully set up. Report them to client if
4317 * appropriate.
4318 */
4320
4321 /*
4322 * Also set up handler to log session end; we have to wait till now to be
4323 * sure Log_disconnections has its final value.
4324 */
4327
4329
4330 /* Perform initialization specific to a WAL sender process. */
4331 if (am_walsender)
4332 InitWalSender();
4333
4334 /*
4335 * Send this backend's cancellation info to the frontend.
4336 */
4338 {
4340
4344
4347 /* Need not flush since ReadyForQuery will do it. */
4348 }
4349
4350 /* Welcome banner for standalone case */
4352 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4353
4354 /*
4355 * Create the memory context we will use in the main loop.
4356 *
4357 * MessageContext is reset once per iteration of the main loop, ie, upon
4358 * completion of processing of each command message from the client.
4359 */
4361 "MessageContext",
4363
4364 /*
4365 * Create memory context and buffer used for RowDescription messages. As
4366 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4367 * frequently executed for ever single statement, we don't want to
4368 * allocate a separate buffer every time.
4369 */
4371 "RowDescriptionContext",
4376
4377 /* Fire any defined login event triggers, if appropriate */
4379
4380 /*
4381 * POSTGRES main processing loop begins here
4382 *
4383 * If an exception is encountered, processing resumes here so we abort the
4384 * current transaction and start a new one.
4385 *
4386 * You might wonder why this isn't coded as an infinite loop around a
4387 * PG_TRY construct. The reason is that this is the bottom of the
4388 * exception stack, and so with PG_TRY there would be no exception handler
4389 * in force at all during the CATCH part. By leaving the outermost setjmp
4390 * always active, we have at least some chance of recovering from an error
4391 * during error recovery. (If we get into an infinite loop thereby, it
4392 * will soon be stopped by overflow of elog.c's internal state stack.)
4393 *
4394 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4395 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4396 * is essential in case we longjmp'd out of a signal handler on a platform
4397 * where that leaves the signal blocked. It's not redundant with the
4398 * unblock in AbortTransaction() because the latter is only called if we
4399 * were inside a transaction.
4400 */
4401
4402 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4403 {
4404 /*
4405 * NOTE: if you are tempted to add more code in this if-block,
4406 * consider the high probability that it should be in
4407 * AbortTransaction() instead. The only stuff done directly here
4408 * should be stuff that is guaranteed to apply *only* for outer-level
4409 * error recovery, such as adjusting the FE/BE protocol status.
4410 */
4411
4412 /* Since not using PG_TRY, must reset error stack by hand */
4413 error_context_stack = NULL;
4414
4415 /* Prevent interrupts while cleaning up */
4417
4418 /*
4419 * Forget any pending QueryCancel request, since we're returning to
4420 * the idle loop anyway, and cancel any active timeout requests. (In
4421 * future we might want to allow some timeout requests to survive, but
4422 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4423 * we got here because of a query cancel interrupting the SIGALRM
4424 * interrupt handler.) Note in particular that we must clear the
4425 * statement and lock timeout indicators, to prevent any future plain
4426 * query cancels from being misreported as timeouts in case we're
4427 * forgetting a timeout cancel.
4428 */
4429 disable_all_timeouts(false); /* do first to avoid race condition */
4430 QueryCancelPending = false;
4431 idle_in_transaction_timeout_enabled = false;
4432 idle_session_timeout_enabled = false;
4433
4434 /* Not reading from the client anymore. */
4435 DoingCommandRead = false;
4436
4437 /* Make sure libpq is in a good state */
4438 pq_comm_reset();
4439
4440 /* Report the error to the client and/or server log */
4442
4443 /*
4444 * If Valgrind noticed something during the erroneous query, print the
4445 * query string, assuming we have one.
4446 */
4448
4449 /*
4450 * Make sure debug_query_string gets reset before we possibly clobber
4451 * the storage it points at.
4452 */
4453 debug_query_string = NULL;
4454
4455 /*
4456 * Abort the current transaction in order to recover.
4457 */
4459
4460 if (am_walsender)
4462
4464
4465 /*
4466 * We can't release replication slots inside AbortTransaction() as we
4467 * need to be able to start and abort transactions while having a slot
4468 * acquired. But we never need to hold them across top level errors,
4469 * so releasing here is fine. There also is a before_shmem_exit()
4470 * callback ensuring correct cleanup on FATAL errors.
4471 */
4472 if (MyReplicationSlot != NULL)
4474
4475 /* We also want to cleanup temporary slots on error. */
4477
4479
4480 /*
4481 * Now return to normal top-level context and clear ErrorContext for
4482 * next time.
4483 */
4486
4487 /*
4488 * If we were handling an extended-query-protocol message, initiate
4489 * skip till next Sync. This also causes us not to issue
4490 * ReadyForQuery (until we get Sync).
4491 */
4493 ignore_till_sync = true;
4494
4495 /* We don't have a transaction command open anymore */
4496 xact_started = false;
4497
4498 /*
4499 * If an error occurred while we were reading a message from the
4500 * client, we have potentially lost track of where the previous
4501 * message ends and the next one begins. Even though we have
4502 * otherwise recovered from the error, we cannot safely read any more
4503 * messages from the client, so there isn't much we can do with the
4504 * connection anymore.
4505 */
4506 if (pq_is_reading_msg())
4507 ereport(FATAL,
4508 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4509 errmsg("terminating connection because protocol synchronization was lost")));
4510
4511 /* Now we can allow interrupts again */
4513 }
4514
4515 /* We can now handle ereport(ERROR) */
4516 PG_exception_stack = &local_sigjmp_buf;
4517
4518 if (!ignore_till_sync)
4519 send_ready_for_query = true; /* initially, or after error */
4520
4521 /*
4522 * Non-error queries loop here.
4523 */
4524
4525 for (;;)
4526 {
4527 int firstchar;
4528 StringInfoData input_message;
4529
4530 /*
4531 * At top of loop, reset extended-query-message flag, so that any
4532 * errors encountered in "idle" state don't provoke skip.
4533 */
4535
4536 /*
4537 * For valgrind reporting purposes, the "current query" begins here.
4538 */
4539#ifdef USE_VALGRIND
4540 old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4541#endif
4542
4543 /*
4544 * Release storage left over from prior query cycle, and create a new
4545 * query input buffer in the cleared MessageContext.
4546 */
4549
4550 initStringInfo(&input_message);
4551
4552 /*
4553 * Also consider releasing our catalog snapshot if any, so that it's
4554 * not preventing advance of global xmin while we wait for the client.
4555 */
4557
4558 /*
4559 * (1) If we've reached idle state, tell the frontend we're ready for
4560 * a new query.
4561 *
4562 * Note: this includes fflush()'ing the last of the prior output.
4563 *
4564 * This is also a good time to flush out collected statistics to the
4565 * cumulative stats system, and to update the PS stats display. We
4566 * avoid doing those every time through the message loop because it'd
4567 * slow down processing of batched messages, and because we don't want
4568 * to report uncommitted updates (that confuses autovacuum). The
4569 * notification processor wants a call too, if we are not in a
4570 * transaction block.
4571 *
4572 * Also, if an idle timeout is enabled, start the timer for that.
4573 */
4574 if (send_ready_for_query)
4575 {
4577 {
4578 set_ps_display("idle in transaction (aborted)");
4580
4581 /* Start the idle-in-transaction timer */
4584 {
4585 idle_in_transaction_timeout_enabled = true;
4588 }
4589 }
4591 {
4592 set_ps_display("idle in transaction");
4594
4595 /* Start the idle-in-transaction timer */
4598 {
4599 idle_in_transaction_timeout_enabled = true;
4602 }
4603 }
4604 else
4605 {
4606 long stats_timeout;
4607
4608 /*
4609 * Process incoming notifies (including self-notifies), if
4610 * any, and send relevant messages to the client. Doing it
4611 * here helps ensure stable behavior in tests: if any notifies
4612 * were received during the just-finished transaction, they'll
4613 * be seen by the client before ReadyForQuery is.
4614 */
4617
4618 /*
4619 * Check if we need to report stats. If pgstat_report_stat()
4620 * decides it's too soon to flush out pending stats / lock
4621 * contention prevented reporting, it'll tell us when we
4622 * should try to report stats again (so that stats updates
4623 * aren't unduly delayed if the connection goes idle for a
4624 * long time). We only enable the timeout if we don't already
4625 * have a timeout in progress, because we don't disable the
4626 * timeout below. enable_timeout_after() needs to determine
4627 * the current timestamp, which can have a negative
4628 * performance impact. That's OK because pgstat_report_stat()
4629 * won't have us wake up sooner than a prior call.
4630 */
4631 stats_timeout = pgstat_report_stat(false);
4632 if (stats_timeout > 0)
4633 {
4636 stats_timeout);
4637 }
4638 else
4639 {
4640 /* all stats flushed, no need for the timeout */
4643 }
4644
4645 set_ps_display("idle");
4647
4648 /* Start the idle-session timer */
4649 if (IdleSessionTimeout > 0)
4650 {
4651 idle_session_timeout_enabled = true;
4654 }
4655 }
4656
4657 /* Report any recently-changed GUC options */
4659
4660 /*
4661 * The first time this backend is ready for query, log the
4662 * durations of the different components of connection
4663 * establishment and setup.
4664 */
4668 {
4669 uint64 total_duration,
4670 fork_duration,
4671 auth_duration;
4672
4674
4675 total_duration =
4678 fork_duration =
4681 auth_duration =
4684
4685 ereport(LOG,
4686 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4687 (double) total_duration / NS_PER_US,
4688 (double) fork_duration / NS_PER_US,
4689 (double) auth_duration / NS_PER_US));
4690 }
4691
4693 send_ready_for_query = false;
4694 }
4695
4696 /*
4697 * (2) Allow asynchronous signals to be executed immediately if they
4698 * come in while we are waiting for client input. (This must be
4699 * conditional since we don't want, say, reads on behalf of COPY FROM
4700 * STDIN doing the same thing.)
4701 */
4702 DoingCommandRead = true;
4703
4704 /*
4705 * (3) read a command (loop blocks here)
4706 */
4707 firstchar = ReadCommand(&input_message);
4708
4709 /*
4710 * (4) turn off the idle-in-transaction and idle-session timeouts if
4711 * active. We do this before step (5) so that any last-moment timeout
4712 * is certain to be detected in step (5).
4713 *
4714 * At most one of these timeouts will be active, so there's no need to
4715 * worry about combining the timeout.c calls into one.
4716 */
4717 if (idle_in_transaction_timeout_enabled)
4718 {
4720 idle_in_transaction_timeout_enabled = false;
4721 }
4722 if (idle_session_timeout_enabled)
4723 {
4725 idle_session_timeout_enabled = false;
4726 }
4727
4728 /*
4729 * (5) disable async signal conditions again.
4730 *
4731 * Query cancel is supposed to be a no-op when there is no query in
4732 * progress, so if a query cancel arrived while we were idle, just
4733 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4734 * it's called when DoingCommandRead is set, so check for interrupts
4735 * before resetting DoingCommandRead.
4736 */
4738 DoingCommandRead = false;
4739
4740 /*
4741 * (6) check for any other interesting events that happened while we
4742 * slept.
4743 */
4745 {
4746 ConfigReloadPending = false;
4748 }
4749
4750 /*
4751 * (7) process the command. But ignore it if we're skipping till
4752 * Sync.
4753 */
4754 if (ignore_till_sync && firstchar != EOF)
4755 continue;
4756
4757 switch (firstchar)
4758 {
4759 case PqMsg_Query:
4760 {
4761 const char *query_string;
4762
4763 /* Set statement_timestamp() */
4765
4766 query_string = pq_getmsgstring(&input_message);
4767 pq_getmsgend(&input_message);
4768
4769 if (am_walsender)
4770 {
4771 if (!exec_replication_command(query_string))
4772 exec_simple_query(query_string);
4773 }
4774 else
4775 exec_simple_query(query_string);
4776
4777 valgrind_report_error_query(query_string);
4778
4779 send_ready_for_query = true;
4780 }
4781 break;
4782
4783 case PqMsg_Parse:
4784 {
4785 const char *stmt_name;
4786 const char *query_string;
4787 int numParams;
4788 Oid *paramTypes = NULL;
4789
4790 forbidden_in_wal_sender(firstchar);
4791
4792 /* Set statement_timestamp() */
4794
4795 stmt_name = pq_getmsgstring(&input_message);
4796 query_string = pq_getmsgstring(&input_message);
4797 numParams = pq_getmsgint(&input_message, 2);
4798 if (numParams > 0)
4799 {
4800 paramTypes = palloc_array(Oid, numParams);
4801 for (int i = 0; i < numParams; i++)
4802 paramTypes[i] = pq_getmsgint(&input_message, 4);
4803 }
4804 pq_getmsgend(&input_message);
4805
4806 exec_parse_message(query_string, stmt_name,
4807 paramTypes, numParams);
4808
4809 valgrind_report_error_query(query_string);
4810 }
4811 break;
4812
4813 case PqMsg_Bind:
4814 forbidden_in_wal_sender(firstchar);
4815
4816 /* Set statement_timestamp() */
4818
4819 /*
4820 * this message is complex enough that it seems best to put
4821 * the field extraction out-of-line
4822 */
4823 exec_bind_message(&input_message);
4824
4825 /* exec_bind_message does valgrind_report_error_query */
4826 break;
4827
4828 case PqMsg_Execute:
4829 {
4830 const char *portal_name;
4831 int max_rows;
4832
4833 forbidden_in_wal_sender(firstchar);
4834
4835 /* Set statement_timestamp() */
4837
4838 portal_name = pq_getmsgstring(&input_message);
4839 max_rows = pq_getmsgint(&input_message, 4);
4840 pq_getmsgend(&input_message);
4841
4842 exec_execute_message(portal_name, max_rows);
4843
4844 /* exec_execute_message does valgrind_report_error_query */
4845 }
4846 break;
4847
4848 case PqMsg_FunctionCall:
4849 forbidden_in_wal_sender(firstchar);
4850
4851 /* Set statement_timestamp() */
4853
4854 /* Report query to various monitoring facilities. */
4856 set_ps_display("<FASTPATH>");
4857
4858 /* start an xact for this function invocation */
4860
4861 /*
4862 * Note: we may at this point be inside an aborted
4863 * transaction. We can't throw error for that until we've
4864 * finished reading the function-call message, so
4865 * HandleFunctionRequest() must check for it after doing so.
4866 * Be careful not to do anything that assumes we're inside a
4867 * valid transaction here.
4868 */
4869
4870 /* switch back to message context */
4872
4873 HandleFunctionRequest(&input_message);
4874
4875 /* commit the function-invocation transaction */
4877
4878 valgrind_report_error_query("fastpath function call");
4879
4880 send_ready_for_query = true;
4881 break;
4882
4883 case PqMsg_Close:
4884 {
4885 int close_type;
4886 const char *close_target;
4887
4888 forbidden_in_wal_sender(firstchar);
4889
4890 close_type = pq_getmsgbyte(&input_message);
4891 close_target = pq_getmsgstring(&input_message);
4892 pq_getmsgend(&input_message);
4893
4894 switch (close_type)
4895 {
4896 case 'S':
4897 if (close_target[0] != '\0')
4898 DropPreparedStatement(close_target, false);
4899 else
4900 {
4901 /* special-case the unnamed statement */
4903 }
4904 break;
4905 case 'P':
4906 {
4907 Portal portal;
4908
4909 portal = GetPortalByName(close_target);
4910 if (PortalIsValid(portal))
4911 PortalDrop(portal, false);
4912 }
4913 break;
4914 default:
4915 ereport(ERROR,
4916 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4917 errmsg("invalid CLOSE message subtype %d",
4918 close_type)));
4919 break;
4920 }
4921
4924
4925 valgrind_report_error_query("CLOSE message");
4926 }
4927 break;
4928
4929 case PqMsg_Describe:
4930 {
4931 int describe_type;
4932 const char *describe_target;
4933
4934 forbidden_in_wal_sender(firstchar);
4935
4936 /* Set statement_timestamp() (needed for xact) */
4938
4939 describe_type = pq_getmsgbyte(&input_message);
4940 describe_target = pq_getmsgstring(&input_message);
4941 pq_getmsgend(&input_message);
4942
4943 switch (describe_type)
4944 {
4945 case 'S':
4946 exec_describe_statement_message(describe_target);
4947 break;
4948 case 'P':
4949 exec_describe_portal_message(describe_target);
4950 break;
4951 default:
4952 ereport(ERROR,
4953 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4954 errmsg("invalid DESCRIBE message subtype %d",
4955 describe_type)));
4956 break;
4957 }
4958
4959 valgrind_report_error_query("DESCRIBE message");
4960 }
4961 break;
4962
4963 case PqMsg_Flush:
4964 pq_getmsgend(&input_message);
4966 pq_flush();
4967 break;
4968
4969 case PqMsg_Sync:
4970 pq_getmsgend(&input_message);
4971
4972 /*
4973 * If pipelining was used, we may be in an implicit
4974 * transaction block. Close it before calling
4975 * finish_xact_command.
4976 */
4979 valgrind_report_error_query("SYNC message");
4980 send_ready_for_query = true;
4981 break;
4982
4983 /*
4984 * PqMsg_Terminate means that the frontend is closing down the
4985 * socket. EOF means unexpected loss of frontend connection.
4986 * Either way, perform normal shutdown.
4987 */
4988 case EOF:
4989
4990 /* for the cumulative statistics system */
4992
4993 /* FALLTHROUGH */
4994
4995 case PqMsg_Terminate:
4996
4997 /*
4998 * Reset whereToSendOutput to prevent ereport from attempting
4999 * to send any more messages to client.
5000 */
5003
5004 /*
5005 * NOTE: if you are tempted to add more code here, DON'T!
5006 * Whatever you had in mind to do should be set up as an
5007 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5008 * it will fail to be called during other backend-shutdown
5009 * scenarios.
5010 */
5011 proc_exit(0);
5012
5013 case PqMsg_CopyData:
5014 case PqMsg_CopyDone:
5015 case PqMsg_CopyFail:
5016
5017 /*
5018 * Accept but ignore these messages, per protocol spec; we
5019 * probably got here because a COPY failed, and the frontend
5020 * is still sending data.
5021 */
5022 break;
5023
5024 default:
5025 ereport(FATAL,
5026 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5027 errmsg("invalid frontend message type %d",
5028 firstchar)));
5029 }
5030 } /* end of input-reading loop */
5031}
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:519
sigset_t UnBlockSig
Definition: pqsignal.c:22
uint32 log_connections
ConnectionTiming conn_timing
@ LOG_CONNECTION_SETUP_DURATIONS
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
uint64_t uint64
Definition: c.h:539
#define TIMESTAMP_MINUS_INFINITY
Definition: timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition: dest.c:256
@ DestDebug
Definition: dest.h:88
@ DestNone
Definition: dest.h:87
void EmitErrorReport(void)
Definition: elog.c:1704
void FlushErrorState(void)
Definition: elog.c:1884
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
#define FATAL
Definition: elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:188
int MyCancelKeyLength
Definition: globals.c:53
int MyProcPid
Definition: globals.c:47
bool IsUnderPostmaster
Definition: globals.c:120
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:33
uint8 MyCancelKey[MAX_CANCEL_KEY_LENGTH]
Definition: globals.c:52
Oid MyDatabaseId
Definition: globals.c:94
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
void BeginReportingGUCOptions(void)
Definition: guc.c:2489
void ReportChangedGUCOptions(void)
Definition: guc.c:2539
@ PGC_SIGHUP
Definition: guc.h:75
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:400
MemoryContext PostmasterContext
Definition: mcxt.c:168
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:471
@ InitProcessing
Definition: miscadmin.h:470
#define IsExternalConnectionBackend(backend_type)
Definition: miscadmin.h:404
#define GetProcessingMode()
Definition: miscadmin.h:480
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:498
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:482
BackendType MyBackendType
Definition: miscinit.c:64
const void size_t len
long pgstat_report_stat(bool force)
Definition: pgstat.c:694
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:57
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition: port.h:531
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:2647
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2935
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5177
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:5041
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2113
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3079
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3062
static bool ignore_till_sync
Definition: postgres.c:144
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1017
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1395
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1630
void die(SIGNAL_ARGS)
Definition: postgres.c:3032
static MemoryContext row_description_context
Definition: postgres.c:163
static bool doing_extended_query_message
Definition: postgres.c:143
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2740
bool Log_disconnections
Definition: postgres.c:95
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:481
void BaseInit(void)
Definition: postinit.c:611
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:711
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1181
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:90
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition: pqformat.c:126
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:674
#define MAX_CANCEL_KEY_LENGTH
Definition: procsignal.h:67
#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:148
void ReplicationSlotRelease(void)
Definition: slot.c:731
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:820
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:475
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
char * dbname
Definition: streamutil.c:49
TimestampTz ready_for_use
TimestampTz auth_start
TimestampTz socket_create
TimestampTz fork_start
TimestampTz auth_end
TimestampTz fork_end
ProtocolVersion proto
Definition: libpq-be.h:132
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
static uint64 TimestampDifferenceMicroseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.h:90
#define NS_PER_US
Definition: uuid.c:33
void WalSndErrorCleanup(void)
Definition: walsender.c:334
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1974
void InitWalSender(void)
Definition: walsender.c:287
void WalSndSignals(void)
Definition: walsender.c:3703
#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:5001
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:914
void AbortCurrentTransaction(void)
Definition: xact.c:3463

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert(), ConnectionTiming::auth_end, ConnectionTiming::auth_start, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, conn_timing, 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(), ConnectionTiming::fork_end, ConnectionTiming::fork_start, get_timeout_active(), GetCurrentTimestamp(), 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(), IsExternalConnectionBackend, IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), len, LOG, LOG_CONNECTION_SETUP_DURATIONS, log_connections, Log_disconnections, log_disconnections(), MAX_CANCEL_KEY_LENGTH, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), MessageContext, MyBackendType, MyCancelKey, MyCancelKeyLength, MyDatabaseId, MyProcPid, MyProcPort, MyReplicationSlot, NormalProcessing, notifyInterruptPending, NS_PER_US, on_proc_exit(), palloc_array, PG_exception_stack, PG_PROTOCOL, 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_sendbytes(), 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(), Port::proto, QueryCancelPending, quickdie(), ReadCommand(), ConnectionTiming::ready_for_use, ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, ConnectionTiming::socket_create, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TIMESTAMP_MINUS_INFINITY, TimestampDifferenceMicroseconds(), 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 4064 of file postgres.c.

4066{
4067 const char *dbname = NULL;
4068
4070
4071 /* Initialize startup process environment. */
4072 InitStandaloneProcess(argv[0]);
4073
4074 /*
4075 * Set default values for command-line options.
4076 */
4078
4079 /*
4080 * Parse command-line options.
4081 */
4083
4084 /* Must have gotten a database name, or have a default (the username) */
4085 if (dbname == NULL)
4086 {
4087 dbname = username;
4088 if (dbname == NULL)
4089 ereport(FATAL,
4090 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4091 errmsg("%s: no database nor user name specified",
4092 progname)));
4093 }
4094
4095 /* Acquire configuration parameters */
4097 proc_exit(1);
4098
4099 /*
4100 * Validate we have been given a reasonable-looking DataDir and change
4101 * into it.
4102 */
4103 checkDataDir();
4105
4106 /*
4107 * Create lockfile for data directory.
4108 */
4109 CreateDataDirLockFile(false);
4110
4111 /* read control file (error checking and contains config ) */
4113
4114 /*
4115 * process any libraries that should be preloaded at postmaster start
4116 */
4118
4119 /* Initialize MaxBackends */
4121
4122 /*
4123 * We don't need postmaster child slots in single-user mode, but
4124 * initialize them anyway to avoid having special handling.
4125 */
4127
4128 /* Initialize size of fast-path lock cache. */
4130
4131 /*
4132 * Give preloaded libraries a chance to request additional shared memory.
4133 */
4135
4136 /*
4137 * Now that loadable modules have had their chance to request additional
4138 * shared memory, determine the value of any runtime-computed GUCs that
4139 * depend on the amount of shared memory required.
4140 */
4142
4143 /*
4144 * Now that modules have been loaded, we can process any custom resource
4145 * managers specified in the wal_consistency_checking GUC.
4146 */
4148
4149 /*
4150 * Create shared memory etc. (Nothing's really "shared" in single-user
4151 * mode, but we must have these data structures anyway.)
4152 */
4154
4155 /*
4156 * Estimate number of openable files. This must happen after setting up
4157 * semaphores, because on some platforms semaphores count as open files.
4158 */
4160
4161 /*
4162 * Remember stand-alone backend startup time,roughly at the same point
4163 * during startup that postmaster does so.
4164 */
4166
4167 /*
4168 * Create a per-backend PGPROC struct in shared memory. We must do this
4169 * before we can use LWLocks.
4170 */
4171 InitProcess();
4172
4173 /*
4174 * Now that sufficient infrastructure has been initialized, PostgresMain()
4175 * can do the rest.
4176 */
4178}
TimestampTz PgStartTime
Definition: timestamp.c:54
void set_max_safe_fds(void)
Definition: fd.c:1041
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1723
void InitializeGUCOptions(void)
Definition: guc.c:1475
@ PGC_POSTMASTER
Definition: guc.h:74
void InitializeShmemGUCs(void)
Definition: ipci.c:355
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:200
const char * progname
Definition: main.c:44
void ChangeToDataDir(void)
Definition: miscinit.c:409
void process_shmem_requests(void)
Definition: miscinit.c:1879
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void process_shared_preload_libraries(void)
Definition: miscinit.c:1851
void checkDataDir(void)
Definition: miscinit.c:296
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1463
void InitPostmasterChildSlots(void)
Definition: pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3799
static const char * userDoption
Definition: postgres.c:154
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4193
void InitializeMaxBackends(void)
Definition: postinit.c:554
void InitializeFastPathLocks(void)
Definition: postinit.c:579
void InitProcess(void)
Definition: proc.c:390
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4826
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4888

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 3799 of file postgres.c.

3801{
3802 bool secure = (ctx == PGC_POSTMASTER);
3803 int errs = 0;
3804 GucSource gucsource;
3805 int flag;
3806
3807 if (secure)
3808 {
3809 gucsource = PGC_S_ARGV; /* switches came from command line */
3810
3811 /* Ignore the initial --single argument, if present */
3812 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3813 {
3814 argv++;
3815 argc--;
3816 }
3817 }
3818 else
3819 {
3820 gucsource = PGC_S_CLIENT; /* switches came from client */
3821 }
3822
3823#ifdef HAVE_INT_OPTERR
3824
3825 /*
3826 * Turn this off because it's either printed to stderr and not the log
3827 * where we'd want it, or argv[0] is now "--single", which would make for
3828 * a weird error message. We print our own error message below.
3829 */
3830 opterr = 0;
3831#endif
3832
3833 /*
3834 * Parse command-line options. CAUTION: keep this in sync with
3835 * postmaster/postmaster.c (the option sets should not conflict) and with
3836 * the common help() function in main/main.c.
3837 */
3838 while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3839 {
3840 switch (flag)
3841 {
3842 case 'B':
3843 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3844 break;
3845
3846 case 'b':
3847 /* Undocumented flag used for binary upgrades */
3848 if (secure)
3849 IsBinaryUpgrade = true;
3850 break;
3851
3852 case 'C':
3853 /* ignored for consistency with the postmaster */
3854 break;
3855
3856 case '-':
3857
3858 /*
3859 * Error if the user misplaced a special must-be-first option
3860 * for dispatching to a subprogram. parse_dispatch_option()
3861 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3862 * error for anything else.
3863 */
3865 ereport(ERROR,
3866 (errcode(ERRCODE_SYNTAX_ERROR),
3867 errmsg("--%s must be first argument", optarg)));
3868
3869 /* FALLTHROUGH */
3870 case 'c':
3871 {
3872 char *name,
3873 *value;
3874
3876 if (!value)
3877 {
3878 if (flag == '-')
3879 ereport(ERROR,
3880 (errcode(ERRCODE_SYNTAX_ERROR),
3881 errmsg("--%s requires a value",
3882 optarg)));
3883 else
3884 ereport(ERROR,
3885 (errcode(ERRCODE_SYNTAX_ERROR),
3886 errmsg("-c %s requires a value",
3887 optarg)));
3888 }
3889 SetConfigOption(name, value, ctx, gucsource);
3890 pfree(name);
3891 pfree(value);
3892 break;
3893 }
3894
3895 case 'D':
3896 if (secure)
3897 userDoption = strdup(optarg);
3898 break;
3899
3900 case 'd':
3901 set_debug_options(atoi(optarg), ctx, gucsource);
3902 break;
3903
3904 case 'E':
3905 if (secure)
3906 EchoQuery = true;
3907 break;
3908
3909 case 'e':
3910 SetConfigOption("datestyle", "euro", ctx, gucsource);
3911 break;
3912
3913 case 'F':
3914 SetConfigOption("fsync", "false", ctx, gucsource);
3915 break;
3916
3917 case 'f':
3918 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3919 errs++;
3920 break;
3921
3922 case 'h':
3923 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3924 break;
3925
3926 case 'i':
3927 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3928 break;
3929
3930 case 'j':
3931 if (secure)
3932 UseSemiNewlineNewline = true;
3933 break;
3934
3935 case 'k':
3936 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3937 break;
3938
3939 case 'l':
3940 SetConfigOption("ssl", "true", ctx, gucsource);
3941 break;
3942
3943 case 'N':
3944 SetConfigOption("max_connections", optarg, ctx, gucsource);
3945 break;
3946
3947 case 'n':
3948 /* ignored for consistency with postmaster */
3949 break;
3950
3951 case 'O':
3952 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3953 break;
3954
3955 case 'P':
3956 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3957 break;
3958
3959 case 'p':
3960 SetConfigOption("port", optarg, ctx, gucsource);
3961 break;
3962
3963 case 'r':
3964 /* send output (stdout and stderr) to the given file */
3965 if (secure)
3967 break;
3968
3969 case 'S':
3970 SetConfigOption("work_mem", optarg, ctx, gucsource);
3971 break;
3972
3973 case 's':
3974 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3975 break;
3976
3977 case 'T':
3978 /* ignored for consistency with the postmaster */
3979 break;
3980
3981 case 't':
3982 {
3983 const char *tmp = get_stats_option_name(optarg);
3984
3985 if (tmp)
3986 SetConfigOption(tmp, "true", ctx, gucsource);
3987 else
3988 errs++;
3989 break;
3990 }
3991
3992 case 'v':
3993
3994 /*
3995 * -v is no longer used in normal operation, since
3996 * FrontendProtocol is already set before we get here. We keep
3997 * the switch only for possible use in standalone operation,
3998 * in case we ever support using normal FE/BE protocol with a
3999 * standalone backend.
4000 */
4001 if (secure)
4003 break;
4004
4005 case 'W':
4006 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
4007 break;
4008
4009 default:
4010 errs++;
4011 break;
4012 }
4013
4014 if (errs)
4015 break;
4016 }
4017
4018 /*
4019 * Optional database name should be there only if *dbname is NULL.
4020 */
4021 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
4022 *dbname = strdup(argv[optind++]);
4023
4024 if (errs || argc != optind)
4025 {
4026 if (errs)
4027 optind--; /* complain about the previous argument */
4028
4029 /* spell the error message a bit differently depending on context */
4031 ereport(FATAL,
4032 errcode(ERRCODE_SYNTAX_ERROR),
4033 errmsg("invalid command-line argument for server process: %s", argv[optind]),
4034 errhint("Try \"%s --help\" for more information.", progname));
4035 else
4036 ereport(FATAL,
4037 errcode(ERRCODE_SYNTAX_ERROR),
4038 errmsg("%s: invalid command-line argument: %s",
4039 progname, argv[optind]),
4040 errhint("Try \"%s --help\" for more information.", progname));
4041 }
4042
4043 /*
4044 * Reset getopt(3) library so that it will work correctly in subprocesses
4045 * or when this function is called a second time with another array.
4046 */
4047 optind = 1;
4048#ifdef HAVE_INT_OPTRESET
4049 optreset = 1; /* some systems need this too */
4050#endif
4051}
int errhint(const char *fmt,...)
Definition: elog.c:1330
bool IsBinaryUpgrade
Definition: globals.c:121
ProtocolVersion FrontendProtocol
Definition: globals.c:30
char OutputFileName[MAXPGPATH]
Definition: globals.c:79
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4257
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6277
GucSource
Definition: guc.h:112
@ PGC_S_ARGV
Definition: guc.h:117
@ PGC_S_CLIENT
Definition: guc.h:122
static struct @169 value
DispatchOption parse_dispatch_option(const char *name)
Definition: main.c:244
#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:3685
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3717
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3759
@ DISPATCH_POSTMASTER
Definition: postmaster.h:139
uint32 ProtocolVersion
Definition: pqcomm.h:99
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 502 of file postgres.c.

503{
504 int save_errno = errno;
505
507 {
508 /* Check for general interrupts that arrived before/while reading */
510
511 /* Process sinval catchup interrupts, if any */
514
515 /* Process notify interrupts, if any */
518 }
519 else if (ProcDiePending)
520 {
521 /*
522 * We're dying. If there is no data available to read, then it's safe
523 * (and sane) to handle that now. If we haven't tried to read yet,
524 * make sure the process latch is set, so that if there is no data
525 * then we'll come back here and die. If we're done reading, also
526 * make sure the process latch is set, as we might've undesirably
527 * cleared it while reading.
528 */
529 if (blocked)
531 else
533 }
534
535 errno = save_errno;
536}
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 548 of file postgres.c.

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

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

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3304 of file postgres.c.

3305{
3306 /* OK to accept any interrupts now? */
3307 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3308 return;
3309 InterruptPending = false;
3310
3311 if (ProcDiePending)
3312 {
3313 ProcDiePending = false;
3314 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3316 /* As in quickdie, don't risk sending to client during auth */
3320 ereport(FATAL,
3321 (errcode(ERRCODE_QUERY_CANCELED),
3322 errmsg("canceling authentication due to timeout")));
3323 else if (AmAutoVacuumWorkerProcess())
3324 ereport(FATAL,
3325 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3326 errmsg("terminating autovacuum process due to administrator command")));
3327 else if (IsLogicalWorker())
3328 ereport(FATAL,
3329 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3330 errmsg("terminating logical replication worker due to administrator command")));
3331 else if (IsLogicalLauncher())
3332 {
3334 (errmsg_internal("logical replication launcher shutting down")));
3335
3336 /*
3337 * The logical replication launcher can be stopped at any time.
3338 * Use exit status 1 so the background worker is restarted.
3339 */
3340 proc_exit(1);
3341 }
3342 else if (AmWalReceiverProcess())
3343 ereport(FATAL,
3344 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3345 errmsg("terminating walreceiver process due to administrator command")));
3346 else if (AmBackgroundWorkerProcess())
3347 ereport(FATAL,
3348 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3349 errmsg("terminating background worker \"%s\" due to administrator command",
3351 else if (AmIoWorkerProcess())
3352 {
3354 (errmsg_internal("io worker shutting down due to administrator command")));
3355
3356 proc_exit(0);
3357 }
3358 else
3359 ereport(FATAL,
3360 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3361 errmsg("terminating connection due to administrator command")));
3362 }
3363
3365 {
3367
3368 /*
3369 * Check for lost connection and re-arm, if still configured, but not
3370 * if we've arrived back at DoingCommandRead state. We don't want to
3371 * wake up idle sessions, and they already know how to detect lost
3372 * connections.
3373 */
3375 {
3376 if (!pq_check_connection())
3377 ClientConnectionLost = true;
3378 else
3381 }
3382 }
3383
3385 {
3386 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3388 /* don't send to client, we already know the connection to be dead. */
3390 ereport(FATAL,
3391 (errcode(ERRCODE_CONNECTION_FAILURE),
3392 errmsg("connection to client lost")));
3393 }
3394
3395 /*
3396 * Don't allow query cancel interrupts while reading input from the
3397 * client, because we might lose sync in the FE/BE protocol. (Die
3398 * interrupts are OK, because we won't read any further messages from the
3399 * client in that case.)
3400 *
3401 * See similar logic in ProcessRecoveryConflictInterrupts().
3402 */
3404 {
3405 /*
3406 * Re-arm InterruptPending so that we process the cancel request as
3407 * soon as we're done reading the message. (XXX this is seriously
3408 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3409 * can't use that macro directly as the initial test in this function,
3410 * meaning that this code also creates opportunities for other bugs to
3411 * appear.)
3412 */
3413 InterruptPending = true;
3414 }
3415 else if (QueryCancelPending)
3416 {
3417 bool lock_timeout_occurred;
3418 bool stmt_timeout_occurred;
3419
3420 QueryCancelPending = false;
3421
3422 /*
3423 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3424 * need to clear both, so always fetch both.
3425 */
3426 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3427 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3428
3429 /*
3430 * If both were set, we want to report whichever timeout completed
3431 * earlier; this ensures consistent behavior if the machine is slow
3432 * enough that the second timeout triggers before we get here. A tie
3433 * is arbitrarily broken in favor of reporting a lock timeout.
3434 */
3435 if (lock_timeout_occurred && stmt_timeout_occurred &&
3437 lock_timeout_occurred = false; /* report stmt timeout */
3438
3439 if (lock_timeout_occurred)
3440 {
3442 ereport(ERROR,
3443 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3444 errmsg("canceling statement due to lock timeout")));
3445 }
3446 if (stmt_timeout_occurred)
3447 {
3449 ereport(ERROR,
3450 (errcode(ERRCODE_QUERY_CANCELED),
3451 errmsg("canceling statement due to statement timeout")));
3452 }
3454 {
3456 ereport(ERROR,
3457 (errcode(ERRCODE_QUERY_CANCELED),
3458 errmsg("canceling autovacuum task")));
3459 }
3460
3461 /*
3462 * If we are reading a command from the client, just ignore the cancel
3463 * request --- sending an extra error message won't accomplish
3464 * anything. Otherwise, go ahead and throw the error.
3465 */
3466 if (!DoingCommandRead)
3467 {
3469 ereport(ERROR,
3470 (errcode(ERRCODE_QUERY_CANCELED),
3471 errmsg("canceling statement due to user request")));
3472 }
3473 }
3474
3477
3479 {
3480 /*
3481 * If the GUC has been reset to zero, ignore the signal. This is
3482 * important because the GUC update itself won't disable any pending
3483 * interrupt. We need to unset the flag before the injection point,
3484 * otherwise we could loop in interrupts checking.
3485 */
3488 {
3489 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3490 ereport(FATAL,
3491 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3492 errmsg("terminating connection due to idle-in-transaction timeout")));
3493 }
3494 }
3495
3497 {
3498 /* As above, ignore the signal if the GUC has been reset to zero. */
3500 if (TransactionTimeout > 0)
3501 {
3502 INJECTION_POINT("transaction-timeout", NULL);
3503 ereport(FATAL,
3504 (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3505 errmsg("terminating connection due to transaction timeout")));
3506 }
3507 }
3508
3510 {
3511 /* As above, ignore the signal if the GUC has been reset to zero. */
3513 if (IdleSessionTimeout > 0)
3514 {
3515 INJECTION_POINT("idle-session-timeout", NULL);
3516 ereport(FATAL,
3517 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3518 errmsg("terminating connection due to idle-session timeout")));
3519 }
3520 }
3521
3522 /*
3523 * If there are pending stats updates and we currently are truly idle
3524 * (matching the conditions in PostgresMain(), report stats now.
3525 */
3528 {
3530 pgstat_report_stat(true);
3531 }
3532
3535
3538
3541
3544}
volatile sig_atomic_t ParallelApplyMessagePending
void ProcessParallelApplyMessages(void)
void ProcessParallelMessages(void)
Definition: parallel.c:1048
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:118
bool IsLogicalWorker(void)
Definition: worker.c:5961
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:42
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:40
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:39
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:44
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:37
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:38
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:36
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:35
#define INJECTION_POINT(name, arg)
bool IsLogicalLauncher(void)
Definition: launcher.c:1531
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1337
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:382
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:383
#define AmWalReceiverProcess()
Definition: miscadmin.h:390
#define AmIoWorkerProcess()
Definition: miscadmin.h:393
int client_connection_check_interval
Definition: postgres.c:103
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3265
bool ClientAuthInProgress
Definition: postmaster.c:372
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:200
bool pq_check_connection(void)
Definition: pqcomm.c:2056
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:499
void LockErrorCleanup(void)
Definition: proc.c:813
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, AmIoWorkerProcess, AmWalReceiverProcess, 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(), 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(), ProcessParallelApplyMessages(), ProcessParallelMessages(), 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 3107 of file postgres.c.

3108{
3109 switch (reason)
3110 {
3112
3113 /*
3114 * If we aren't waiting for a lock we can never deadlock.
3115 */
3116 if (GetAwaitedLock() == NULL)
3117 return;
3118
3119 /* Intentional fall through to check wait for pin */
3120 /* FALLTHROUGH */
3121
3123
3124 /*
3125 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3126 * aren't blocking the Startup process there is nothing more to
3127 * do.
3128 *
3129 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3130 * if we're waiting for locks and the startup process is not
3131 * waiting for buffer pin (i.e., also waiting for locks), we set
3132 * the flag so that ProcSleep() will check for deadlocks.
3133 */
3135 {
3139 return;
3140 }
3141
3143
3144 /* Intentional fall through to error handling */
3145 /* FALLTHROUGH */
3146
3150
3151 /*
3152 * If we aren't in a transaction any longer then ignore.
3153 */
3155 return;
3156
3157 /* FALLTHROUGH */
3158
3160
3161 /*
3162 * If we're not in a subtransaction then we are OK to throw an
3163 * ERROR to resolve the conflict. Otherwise drop through to the
3164 * FATAL case.
3165 *
3166 * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3167 * always throws an ERROR (ie never promotes to FATAL), though it
3168 * still has to respect QueryCancelHoldoffCount, so it shares this
3169 * code path. Logical decoding slots are only acquired while
3170 * performing logical decoding. During logical decoding no user
3171 * controlled code is run. During [sub]transaction abort, the
3172 * slot is released. Therefore user controlled code cannot
3173 * intercept an error before the replication slot is released.
3174 *
3175 * XXX other times that we can throw just an ERROR *may* be
3176 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3177 * transactions
3178 *
3179 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3180 * parent transactions and the transaction is not
3181 * transaction-snapshot mode
3182 *
3183 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3184 * cursors open in parent transactions
3185 */
3188 {
3189 /*
3190 * If we already aborted then we no longer need to cancel. We
3191 * do this here since we do not wish to ignore aborted
3192 * subtransactions, which must cause FATAL, currently.
3193 */
3195 return;
3196
3197 /*
3198 * If a recovery conflict happens while we are waiting for
3199 * input from the client, the client is presumably just
3200 * sitting idle in a transaction, preventing recovery from
3201 * making progress. We'll drop through to the FATAL case
3202 * below to dislodge it, in that case.
3203 */
3204 if (!DoingCommandRead)
3205 {
3206 /* Avoid losing sync in the FE/BE protocol. */
3207 if (QueryCancelHoldoffCount != 0)
3208 {
3209 /*
3210 * Re-arm and defer this interrupt until later. See
3211 * similar code in ProcessInterrupts().
3212 */
3213 RecoveryConflictPendingReasons[reason] = true;
3215 InterruptPending = true;
3216 return;
3217 }
3218
3219 /*
3220 * We are cleared to throw an ERROR. Either it's the
3221 * logical slot case, or we have a top-level transaction
3222 * that we can abort and a conflict that isn't inherently
3223 * non-retryable.
3224 */
3227 ereport(ERROR,
3229 errmsg("canceling statement due to conflict with recovery"),
3231 break;
3232 }
3233 }
3234
3235 /* Intentional fall through to session cancel */
3236 /* FALLTHROUGH */
3237
3239
3240 /*
3241 * Retrying is not possible because the database is dropped, or we
3242 * decided above that we couldn't resolve the conflict with an
3243 * ERROR and fell through. Terminate the session.
3244 */
3246 ereport(FATAL,
3248 ERRCODE_DATABASE_DROPPED :
3250 errmsg("terminating connection due to conflict with recovery"),
3252 errhint("In a moment you should be able to reconnect to the"
3253 " database and repeat your command.")));
3254 break;
3255
3256 default:
3257 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3258 }
3259}
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:5832
LOCALLOCK * GetAwaitedLock(void)
Definition: lock.c:1898
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:77
void pgstat_report_recovery_conflict(int reason)
static int errdetail_recovery_conflict(ProcSignalReason reason)
Definition: postgres.c:2559
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:766
void CheckDeadLockAlert(void)
Definition: proc.c:1873
bool IsSubTransaction(void)
Definition: xact.c:5056

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 3265 of file postgres.c.

3266{
3267 /*
3268 * We don't need to worry about joggling the elbow of proc_exit, because
3269 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3270 * us.
3271 */
3275
3277
3280 reason++)
3281 {
3283 {
3284 RecoveryConflictPendingReasons[reason] = false;
3286 }
3287 }
3288}
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3107
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 2935 of file postgres.c.

2936{
2937 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2938 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2939
2940 /*
2941 * Prevent interrupts while exiting; though we just blocked signals that
2942 * would queue new interrupts, one may have been pending. We don't want a
2943 * quickdie() downgraded to a mere query cancel.
2944 */
2946
2947 /*
2948 * If we're aborting out of client auth, don't risk trying to send
2949 * anything to the client; we will likely violate the protocol, not to
2950 * mention that we may have interrupted the guts of OpenSSL or some
2951 * authentication library.
2952 */
2955
2956 /*
2957 * Notify the client before exiting, to give a clue on what happened.
2958 *
2959 * It's dubious to call ereport() from a signal handler. It is certainly
2960 * not async-signal safe. But it seems better to try, than to disconnect
2961 * abruptly and leave the client wondering what happened. It's remotely
2962 * possible that we crash or hang while trying to send the message, but
2963 * receiving a SIGQUIT is a sign that something has already gone badly
2964 * wrong, so there's not much to lose. Assuming the postmaster is still
2965 * running, it will SIGKILL us soon if we get stuck for some reason.
2966 *
2967 * One thing we can do to make this a tad safer is to clear the error
2968 * context stack, so that context callbacks are not called. That's a lot
2969 * less code that could be reached here, and the context info is unlikely
2970 * to be very relevant to a SIGQUIT report anyway.
2971 */
2972 error_context_stack = NULL;
2973
2974 /*
2975 * When responding to a postmaster-issued signal, we send the message only
2976 * to the client; sending to the server log just creates log spam, plus
2977 * it's more code that we need to hope will work in a signal handler.
2978 *
2979 * Ideally these should be ereport(FATAL), but then we'd not get control
2980 * back to force the correct type of process exit.
2981 */
2982 switch (GetQuitSignalReason())
2983 {
2984 case PMQUIT_NOT_SENT:
2985 /* Hmm, SIGQUIT arrived out of the blue */
2987 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2988 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2989 break;
2990 case PMQUIT_FOR_CRASH:
2991 /* A crash-and-restart cycle is in progress */
2993 (errcode(ERRCODE_CRASH_SHUTDOWN),
2994 errmsg("terminating connection because of crash of another server process"),
2995 errdetail("The postmaster has commanded this server process to roll back"
2996 " the current transaction and exit, because another"
2997 " server process exited abnormally and possibly corrupted"
2998 " shared memory."),
2999 errhint("In a moment you should be able to reconnect to the"
3000 " database and repeat your command.")));
3001 break;
3002 case PMQUIT_FOR_STOP:
3003 /* Immediate-mode stop */
3005 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3006 errmsg("terminating connection due to immediate shutdown command")));
3007 break;
3008 }
3009
3010 /*
3011 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
3012 * because shared memory may be corrupted, so we don't want to try to
3013 * clean up our transaction. Just nail the windows shut and get out of
3014 * town. The callbacks wouldn't be safe to run from a signal handler,
3015 * anyway.
3016 *
3017 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3018 * a system reset cycle if someone sends a manual SIGQUIT to a random
3019 * backend. This is necessary precisely because we don't clean up our
3020 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3021 * should ensure the postmaster sees this as a crash, too, but no harm in
3022 * being doubly sure.)
3023 */
3024 _exit(2);
3025}
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:56
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:55
@ PMQUIT_NOT_SENT
Definition: pmsignal.h:54

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 481 of file postgres.c.

482{
483 int result;
484
486 result = SocketBackend(inBuf);
487 else
488 result = InteractiveBackend(inBuf);
489 return result;
490}
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:353
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:237

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 3685 of file postgres.c.

3686{
3687 if (debug_flag > 0)
3688 {
3689 char debugstr[64];
3690
3691 sprintf(debugstr, "debug%d", debug_flag);
3692 SetConfigOption("log_min_messages", debugstr, context, source);
3693 }
3694 else
3695 SetConfigOption("log_min_messages", "notice", context, source);
3696
3697 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3698 {
3699 SetConfigOption("log_connections", "all", context, source);
3700 SetConfigOption("log_disconnections", "true", context, source);
3701 }
3702 if (debug_flag >= 2)
3703 SetConfigOption("log_statement", "all", context, source);
3704 if (debug_flag >= 3)
3705 {
3706 SetConfigOption("debug_print_raw_parse", "true", context, source);
3707 SetConfigOption("debug_print_parse", "true", context, source);
3708 }
3709 if (debug_flag >= 4)
3710 SetConfigOption("debug_print_plan", "true", context, source);
3711 if (debug_flag >= 5)
3712 SetConfigOption("debug_print_rewritten", "true", context, source);
3713}
static rewind_source * source
Definition: pg_rewind.c:89
#define sprintf
Definition: port.h:241

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 3717 of file postgres.c.

3718{
3719 const char *tmp = NULL;
3720
3721 switch (arg[0])
3722 {
3723 case 's': /* seqscan */
3724 tmp = "enable_seqscan";
3725 break;
3726 case 'i': /* indexscan */
3727 tmp = "enable_indexscan";
3728 break;
3729 case 'o': /* indexonlyscan */
3730 tmp = "enable_indexonlyscan";
3731 break;
3732 case 'b': /* bitmapscan */
3733 tmp = "enable_bitmapscan";
3734 break;
3735 case 't': /* tidscan */
3736 tmp = "enable_tidscan";
3737 break;
3738 case 'n': /* nestloop */
3739 tmp = "enable_nestloop";
3740 break;
3741 case 'm': /* mergejoin */
3742 tmp = "enable_mergejoin";
3743 break;
3744 case 'h': /* hashjoin */
3745 tmp = "enable_hashjoin";
3746 break;
3747 }
3748 if (tmp)
3749 {
3750 SetConfigOption(tmp, "false", context, source);
3751 return true;
3752 }
3753 else
3754 return false;
3755}

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 5068 of file postgres.c.

5069{
5071 struct timeval user,
5072 sys;
5073 struct timeval elapse_t;
5074 struct rusage r;
5075
5077 gettimeofday(&elapse_t, NULL);
5078 memcpy(&user, &r.ru_utime, sizeof(user));
5079 memcpy(&sys, &r.ru_stime, sizeof(sys));
5080 if (elapse_t.tv_usec < Save_t.tv_usec)
5081 {
5082 elapse_t.tv_sec--;
5083 elapse_t.tv_usec += 1000000;
5084 }
5085 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5086 {
5087 r.ru_utime.tv_sec--;
5088 r.ru_utime.tv_usec += 1000000;
5089 }
5090 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5091 {
5092 r.ru_stime.tv_sec--;
5093 r.ru_stime.tv_usec += 1000000;
5094 }
5095
5096 /*
5097 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5098 * some work to interpret them, and most platforms don't fill them in.
5099 */
5101
5102 appendStringInfoString(&str, "! system usage stats:\n");
5104 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5105 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5106 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5107 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5108 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5109 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5110 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5112 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5113 (long) user.tv_sec,
5114 (long) user.tv_usec,
5115 (long) sys.tv_sec,
5116 (long) sys.tv_usec);
5117#ifndef WIN32
5118
5119 /*
5120 * The following rusage fields are not defined by POSIX, but they're
5121 * present on all current Unix-like systems so we use them without any
5122 * special checks. Some of these could be provided in our Windows
5123 * emulation in src/port/win32getrusage.c with more work.
5124 */
5126 "!\t%ld kB max resident size\n",
5127#if defined(__darwin__)
5128 /* in bytes on macOS */
5129 r.ru_maxrss / 1024
5130#else
5131 /* in kilobytes on most other platforms */
5132 r.ru_maxrss
5133#endif
5134 );
5136 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5137 r.ru_inblock - Save_r.ru_inblock,
5138 /* they only drink coffee at dec */
5139 r.ru_oublock - Save_r.ru_oublock,
5140 r.ru_inblock, r.ru_oublock);
5142 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5143 r.ru_majflt - Save_r.ru_majflt,
5144 r.ru_minflt - Save_r.ru_minflt,
5145 r.ru_majflt, r.ru_minflt,
5146 r.ru_nswap - Save_r.ru_nswap,
5147 r.ru_nswap);
5149 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5150 r.ru_nsignals - Save_r.ru_nsignals,
5151 r.ru_nsignals,
5152 r.ru_msgrcv - Save_r.ru_msgrcv,
5153 r.ru_msgsnd - Save_r.ru_msgsnd,
5154 r.ru_msgrcv, r.ru_msgsnd);
5156 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5157 r.ru_nvcsw - Save_r.ru_nvcsw,
5158 r.ru_nivcsw - Save_r.ru_nivcsw,
5159 r.ru_nvcsw, r.ru_nivcsw);
5160#endif /* !WIN32 */
5161
5162 /* remove trailing newline */
5163 if (str.data[str.len - 1] == '\n')
5164 str.data[--str.len] = '\0';
5165
5166 ereport(LOG,
5167 (errmsg_internal("%s", title),
5168 errdetail_internal("%s", str.data)));
5169
5170 pfree(str.data);
5171}
#define __darwin__
Definition: darwin.h:3
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1243
static char * user
Definition: pg_regress.c:119
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
struct timeval ru_utime
Definition: resource.h:14
struct timeval ru_stime
Definition: resource.h:15

References __darwin__, appendStringInfo(), appendStringInfoString(), ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, str, and user.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ SocketBackend()

static int SocketBackend ( StringInfo  inBuf)
static

Definition at line 353 of file postgres.c.

354{
355 int qtype;
356 int maxmsglen;
357
358 /*
359 * Get message type code from the frontend.
360 */
363 qtype = pq_getbyte();
364
365 if (qtype == EOF) /* frontend disconnected */
366 {
367 if (IsTransactionState())
369 (errcode(ERRCODE_CONNECTION_FAILURE),
370 errmsg("unexpected EOF on client connection with an open transaction")));
371 else
372 {
373 /*
374 * Can't send DEBUG log messages to client at this point. Since
375 * we're disconnecting right away, we don't need to restore
376 * whereToSendOutput.
377 */
380 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
381 errmsg_internal("unexpected EOF on client connection")));
382 }
383 return qtype;
384 }
385
386 /*
387 * Validate message type code before trying to read body; if we have lost
388 * sync, better to say "command unknown" than to run out of memory because
389 * we used garbage as a length word. We can also select a type-dependent
390 * limit on what a sane length word could be. (The limit could be chosen
391 * more granularly, but it's not clear it's worth fussing over.)
392 *
393 * This also gives us a place to set the doing_extended_query_message flag
394 * as soon as possible.
395 */
396 switch (qtype)
397 {
398 case PqMsg_Query:
399 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
401 break;
402
404 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
406 break;
407
408 case PqMsg_Terminate:
409 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
411 ignore_till_sync = false;
412 break;
413
414 case PqMsg_Bind:
415 case PqMsg_Parse:
416 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
418 break;
419
420 case PqMsg_Close:
421 case PqMsg_Describe:
422 case PqMsg_Execute:
423 case PqMsg_Flush:
424 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
426 break;
427
428 case PqMsg_Sync:
429 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
430 /* stop any active skip-till-Sync */
431 ignore_till_sync = false;
432 /* mark not-extended, so that a new error doesn't begin skip */
434 break;
435
436 case PqMsg_CopyData:
437 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
439 break;
440
441 case PqMsg_CopyDone:
442 case PqMsg_CopyFail:
443 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
445 break;
446
447 default:
448
449 /*
450 * Otherwise we got garbage from the frontend. We treat this as
451 * fatal because we have probably lost message boundary sync, and
452 * there's no good way to recover.
453 */
455 (errcode(ERRCODE_PROTOCOL_VIOLATION),
456 errmsg("invalid frontend message type %d", qtype)));
457 maxmsglen = 0; /* keep compiler quiet */
458 break;
459 }
460
461 /*
462 * In protocol version 3, all frontend messages have a length word next
463 * after the type code; we can read the message contents independently of
464 * the type.
465 */
466 if (pq_getmessage(inBuf, maxmsglen))
467 return EOF; /* suitable message already logged */
469
470 return qtype;
471}
#define COMMERROR
Definition: elog.h:33
#define PQ_SMALL_MESSAGE_LIMIT
Definition: libpq.h:30
#define PQ_LARGE_MESSAGE_LIMIT
Definition: libpq.h:31
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:141
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:143
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1203
int pq_getbyte(void)
Definition: pqcomm.c:963
void pq_startmsgread(void)
Definition: pqcomm.c:1141

References COMMERROR, DEBUG1, DestNone, doing_extended_query_message, ereport, errcode(), errmsg(), errmsg_internal(), FATAL, HOLD_CANCEL_INTERRUPTS, ignore_till_sync, IsTransactionState(), pq_getbyte(), pq_getmessage(), PQ_LARGE_MESSAGE_LIMIT, PQ_SMALL_MESSAGE_LIMIT, pq_startmsgread(), PqMsg_Bind, PqMsg_Close, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, RESUME_CANCEL_INTERRUPTS, and whereToSendOutput.

Referenced by ReadCommand().

◆ start_xact_command()

static void start_xact_command ( void  )
static

Definition at line 2792 of file postgres.c.

2793{
2794 if (!xact_started)
2795 {
2797
2798 xact_started = true;
2799 }
2801 {
2802 /*
2803 * When the first Execute message is completed, following commands
2804 * will be done in an implicit transaction block created via
2805 * pipelining. The transaction state needs to be updated to an
2806 * implicit block if we're not already in a transaction block (like
2807 * one started by an explicit BEGIN).
2808 */
2810 }
2811
2812 /*
2813 * Start statement timeout if necessary. Note that this'll intentionally
2814 * not reset the clock on an already started timeout, to avoid the timing
2815 * overhead when start_xact_command() is invoked repeatedly, without an
2816 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2817 * not desired, the timeout has to be disabled explicitly.
2818 */
2820
2821 /* Start timeout for checking if the client has gone away if necessary. */
2824 MyProcPort &&
2828}
static void enable_statement_timeout(void)
Definition: postgres.c:5213
void StartTransactionCommand(void)
Definition: xact.c:3071

References BeginImplicitTransactionBlock(), client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, enable_statement_timeout(), enable_timeout_after(), get_timeout_active(), IsUnderPostmaster, MyProcPort, MyXactFlags, StartTransactionCommand(), XACT_FLAGS_PIPELINING, and xact_started.

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

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 3062 of file postgres.c.

3063{
3064 /*
3065 * Don't joggle the elbow of proc_exit
3066 */
3068 {
3069 InterruptPending = true;
3070 QueryCancelPending = true;
3071 }
3072
3073 /* If we're still here, waken anything waiting on the process latch */
3075}

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), BackgroundWorkerMain(), PostgresMain(), and WalSndSignals().

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval = 0

Definition at line 103 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ doing_extended_query_message

bool doing_extended_query_message = false
static

Definition at line 143 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ DoingCommandRead

bool DoingCommandRead = false
static

◆ EchoQuery

bool EchoQuery = false
static

Definition at line 155 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ ignore_till_sync

bool ignore_till_sync = false
static

Definition at line 144 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ Log_disconnections

bool Log_disconnections = false

Definition at line 95 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

int log_statement = LOGSTMT_NONE

Definition at line 97 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

int PostAuthDelay = 0

◆ RecoveryConflictPending

volatile sig_atomic_t RecoveryConflictPending = false
static

◆ RecoveryConflictPendingReasons

volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
static

◆ restrict_nonsystem_relation_kind

int restrict_nonsystem_relation_kind

◆ row_description_buf

StringInfoData row_description_buf
static

◆ row_description_context

MemoryContext row_description_context = NULL
static

Definition at line 163 of file postgres.c.

Referenced by PostgresMain().

◆ Save_r

struct rusage Save_r
static

Definition at line 5057 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ Save_t

struct timeval Save_t
static

Definition at line 5058 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ unnamed_stmt_psrc

CachedPlanSource* unnamed_stmt_psrc = NULL
static

◆ userDoption

const char* userDoption = NULL
static

◆ UseSemiNewlineNewline

bool UseSemiNewlineNewline = false
static

Definition at line 156 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ whereToSendOutput

◆ xact_started

bool xact_started = false
static