PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 "commands/repack.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_trace.h"
#include "pgstat.h"
#include "port/pg_getopt_ctx.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/slotsync.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/fd.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem_internal.h"
#include "storage/sinval.h"
#include "storage/standby.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 ERRDETAIL_SIGNAL_SENDER(pid, uid)
 
#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 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 ProcessRecoveryConflictInterrupts (void)
 
static void ProcessRecoveryConflictInterrupt (RecoveryConflictReason reason)
 
static void report_recovery_conflict (RecoveryConflictReason reason)
 
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 (RecoveryConflictReason 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 (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 MemoryContext row_description_context = NULL
 
static StringInfoData row_description_buf
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Macro Definition Documentation

◆ ERRDETAIL_SIGNAL_SENDER

#define ERRDETAIL_SIGNAL_SENDER (   pid,
  uid 
)
Value:
((pid) == 0 ? 0 : \
errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
int errdetail(const char *fmt,...) pg_attribute_printf(1

Definition at line 117 of file postgres.c.

118 : \
119 errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))

◆ valgrind_report_error_query

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

Definition at line 228 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 3735 of file postgres.c.

3736{
3737 int *flags = (int *) extra;
3738
3740}
int restrict_nonsystem_relation_kind
Definition postgres.c:111

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3664 of file postgres.c.

3665{
3666 if (IsTransactionState())
3667 {
3668 /*
3669 * If transaction_timeout GUC has changed within the transaction block
3670 * enable or disable the timer correspondingly.
3671 */
3676 }
3677}
#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:389

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

2592{
2595 char *quotedval;
2596
2597 if (data->paramno < 0)
2598 return;
2599
2600 /* If we have a textual value, quote it, and trim if necessary */
2601 if (data->paramval)
2602 {
2606 quotedval = buf.data;
2607 }
2608 else
2609 quotedval = NULL;
2610
2611 if (data->portalName && data->portalName[0] != '\0')
2612 {
2613 if (quotedval)
2614 errcontext("portal \"%s\" parameter $%d = %s",
2615 data->portalName, data->paramno + 1, quotedval);
2616 else
2617 errcontext("portal \"%s\" parameter $%d",
2618 data->portalName, data->paramno + 1);
2619 }
2620 else
2621 {
2622 if (quotedval)
2623 errcontext("unnamed portal parameter $%d = %s",
2624 data->paramno + 1, quotedval);
2625 else
2626 errcontext("unnamed portal parameter $%d",
2627 data->paramno + 1);
2628 }
2629
2630 if (quotedval)
2631 pfree(quotedval);
2632}
Datum arg
Definition elog.c:1322
#define errcontext
Definition elog.h:200
int log_parameter_max_length_on_error
Definition guc_tables.c:572
void pfree(void *pointer)
Definition mcxt.c:1616
const void * data
static char buf[DEFAULT_XLOG_SEG_SIZE]
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)

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

3615{
3616 if (!WaitEventSetCanReportClosed() && *newval != 0)
3617 {
3618 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3619 return false;
3620 }
3621 return true;
3622}
#define GUC_check_errdetail
Definition guc.h:507
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 2436 of file postgres.c.

2437{
2440 {
2441 long secs;
2442 int usecs;
2443 int msecs;
2444 bool exceeded_duration;
2445 bool exceeded_sample_duration;
2446 bool in_sample = false;
2447
2450 &secs, &usecs);
2451 msecs = usecs / 1000;
2452
2453 /*
2454 * This odd-looking test for log_min_duration_* being exceeded is
2455 * designed to avoid integer overflow with very long durations: don't
2456 * compute secs * 1000 until we've verified it will fit in int.
2457 */
2458 exceeded_duration = (log_min_duration_statement == 0 ||
2460 (secs > log_min_duration_statement / 1000 ||
2461 secs * 1000 + msecs >= log_min_duration_statement)));
2462
2463 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2465 (secs > log_min_duration_sample / 1000 ||
2466 secs * 1000 + msecs >= log_min_duration_sample)));
2467
2468 /*
2469 * Do not log if log_statement_sample_rate = 0. Log a sample if
2470 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2471 * log_statement_sample_rate = 1.
2472 */
2473 if (exceeded_sample_duration)
2474 in_sample = log_statement_sample_rate != 0 &&
2477
2478 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2479 {
2480 snprintf(msec_str, 32, "%ld.%03d",
2481 secs * 1000 + msecs, usecs % 1000);
2482 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2483 return 2;
2484 else
2485 return 1;
2486 }
2487 }
2488
2489 return 0;
2490}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1715
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
int log_min_duration_statement
Definition guc_tables.c:570
int log_min_duration_sample
Definition guc_tables.c:569
double log_statement_sample_rate
Definition guc_tables.c:574
bool log_duration
Definition guc_tables.c:535
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:260
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition xact.c:881
bool xact_is_sampled
Definition xact.c:298

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

2398{
2399 ListCell *stmt_item;
2400
2402 return false;
2404 return true;
2405
2406 /* Else we have to inspect the statement(s) to see whether to log */
2407 foreach(stmt_item, stmt_list)
2408 {
2409 Node *stmt = (Node *) lfirst(stmt_item);
2410
2412 return true;
2413 }
2414
2415 return false;
2416}
#define stmt
#define lfirst(lc)
Definition pg_list.h:172
int log_statement
Definition postgres.c:102
Definition nodes.h:135
@ LOGSTMT_NONE
Definition tcopprot.h:34
@ LOGSTMT_ALL
Definition tcopprot.h:37
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition utility.c:3289

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

3650{
3651 if (*newval &&
3653 {
3654 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3655 "\"log_parser_stats\", \"log_planner_stats\", "
3656 "or \"log_executor_stats\" is true.");
3657 return false;
3658 }
3659 return true;
3660}
bool log_parser_stats
Definition guc_tables.c:548
bool log_planner_stats
Definition guc_tables.c:549
bool log_executor_stats
Definition guc_tables.c:550

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

3684{
3685 char *rawstring;
3686 List *elemlist;
3687 ListCell *l;
3688 int flags = 0;
3689
3690 /* Need a modifiable copy of string */
3691 rawstring = pstrdup(*newval);
3692
3693 if (!SplitIdentifierString(rawstring, ',', &elemlist))
3694 {
3695 /* syntax error in list */
3696 GUC_check_errdetail("List syntax is invalid.");
3697 pfree(rawstring);
3698 list_free(elemlist);
3699 return false;
3700 }
3701
3702 foreach(l, elemlist)
3703 {
3704 char *tok = (char *) lfirst(l);
3705
3706 if (pg_strcasecmp(tok, "view") == 0)
3707 flags |= RESTRICT_RELKIND_VIEW;
3708 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3710 else
3711 {
3712 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3713 pfree(rawstring);
3714 list_free(elemlist);
3715 return false;
3716 }
3717 }
3718
3719 pfree(rawstring);
3720 list_free(elemlist);
3721
3722 /* Save the flags in *extra, for use by the assign function */
3723 *extra = guc_malloc(LOG, sizeof(int));
3724 if (!*extra)
3725 return false;
3726 *((int *) *extra) = flags;
3727
3728 return true;
3729}
#define LOG
Definition elog.h:32
void * guc_malloc(int elevel, size_t size)
Definition guc.c:637
void list_free(List *list)
Definition list.c:1546
char * pstrdup(const char *in)
Definition mcxt.c:1781
int pg_strcasecmp(const char *s1, const char *s2)
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:2867

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

3636{
3638 {
3639 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3640 return false;
3641 }
3642 return true;
3643}
bool log_statement_stats
Definition guc_tables.c:551

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3023 of file postgres.c.

3024{
3025 /* Don't joggle the elbow of proc_exit */
3027 {
3028 InterruptPending = true;
3029 ProcDiePending = true;
3030 }
3031
3032 /* for the cumulative stats system */
3034
3035 /* If we're still here, waken anything waiting on the process latch */
3037
3038 /*
3039 * If we're in single user mode, we want to quit immediately - we can't
3040 * rely on latches as they wouldn't work when stdin/stdout is a file.
3041 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3042 * effort just for the benefit of single user mode.
3043 */
3046}
@ DestRemote
Definition dest.h:89
volatile sig_atomic_t InterruptPending
Definition globals.c:32
struct Latch * MyLatch
Definition globals.c:65
volatile sig_atomic_t ProcDiePending
Definition globals.c:34
bool proc_exit_inprogress
Definition ipc.c:41
void SetLatch(Latch *latch)
Definition latch.c:290
@ DISCONNECT_KILLED
Definition pgstat.h:64
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition postgres.c:97
static bool DoingCommandRead
Definition postgres.c:150
void ProcessInterrupts(void)
Definition postgres.c:3350

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

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2901 of file postgres.c.

2902{
2903 /* paranoia to avoid a dangling pointer in case of error */
2905 {
2907
2908 unnamed_stmt_psrc = NULL;
2909 DropCachedPlan(psrc);
2910 }
2911}
void DropCachedPlan(CachedPlanSource *plansource)
Definition plancache.c:591
static CachedPlanSource * unnamed_stmt_psrc
Definition postgres.c:164

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

5283{
5284 /* must be within an xact */
5286
5287 if (StatementTimeout > 0
5289 {
5292 }
5293 else
5294 {
5297 }
5298}
#define Assert(condition)
Definition c.h:943
static bool xact_started
Definition postgres.c:143
int StatementTimeout
Definition proc.c:63
int TransactionTimeout
Definition proc.c:66

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

Referenced by start_xact_command().

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2499 of file postgres.c.

2500{
2501 ListCell *parsetree_item;
2502
2503 foreach(parsetree_item, raw_parsetree_list)
2504 {
2505 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2506
2507 if (IsA(parsetree->stmt, ExecuteStmt))
2508 {
2509 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2510 PreparedStatement *pstmt;
2511
2512 pstmt = FetchPreparedStatement(stmt->name, false);
2513 if (pstmt)
2514 {
2515 errdetail("prepare: %s", pstmt->plansource->query_string);
2516 return 0;
2517 }
2518 }
2519 }
2520
2521 return 0;
2522}
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition prepare.c:436
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define lfirst_node(type, lc)
Definition pg_list.h:176
const char * query_string
Definition plancache.h:110
CachedPlanSource * plansource
Definition prepare.h:32
Node * stmt

References errdetail(), FetchPreparedStatement(), IsA, lfirst_node, PreparedStatement::plansource, CachedPlanSource::query_string, RawStmt::stmt, and stmt.

Referenced by exec_simple_query().

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2532 of file postgres.c.

2533{
2534 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2535 {
2536 char *str;
2537
2539 if (str && str[0] != '\0')
2540 errdetail("Parameters: %s", str);
2541 }
2542
2543 return 0;
2544}
int log_parameter_max_length
Definition guc_tables.c:571
const char * str
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition params.c:333

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 ( RecoveryConflictReason  reason)
static

Definition at line 2552 of file postgres.c.

2553{
2554 switch (reason)
2555 {
2557 errdetail("User was holding shared buffer pin for too long.");
2558 break;
2560 errdetail("User was holding a relation lock for too long.");
2561 break;
2563 errdetail("User was or might have been using tablespace that must be dropped.");
2564 break;
2566 errdetail("User query might have needed to see row versions that must be removed.");
2567 break;
2569 errdetail("User was using a logical replication slot that must be invalidated.");
2570 break;
2572 errdetail("User transaction caused deadlock with recovery.");
2573 break;
2575 errdetail("User transaction caused buffer deadlock with recovery.");
2576 break;
2578 errdetail("User was connected to a database that must be dropped.");
2579 break;
2580 }
2581
2582 return 0;
2583}
@ RECOVERY_CONFLICT_TABLESPACE
Definition standby.h:37
@ RECOVERY_CONFLICT_SNAPSHOT
Definition standby.h:43
@ RECOVERY_CONFLICT_LOCK
Definition standby.h:40
@ RECOVERY_CONFLICT_DATABASE
Definition standby.h:34
@ RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition standby.h:56
@ RECOVERY_CONFLICT_BUFFERPIN
Definition standby.h:49
@ RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK
Definition standby.h:64
@ RECOVERY_CONFLICT_LOGICALSLOT
Definition standby.h:46

References errdetail(), RECOVERY_CONFLICT_BUFFERPIN, RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK, RECOVERY_CONFLICT_DATABASE, RECOVERY_CONFLICT_LOCK, RECOVERY_CONFLICT_LOGICALSLOT, RECOVERY_CONFLICT_SNAPSHOT, RECOVERY_CONFLICT_STARTUP_DEADLOCK, and RECOVERY_CONFLICT_TABLESPACE.

Referenced by report_recovery_conflict().

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1639 of file postgres.c.

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

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

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

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

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

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

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

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

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, DestRemote, disable_statement_timeout(), drop_unnamed_stmt(), EndCommand(), EndImplicitTransactionBlock(), ereport, errcode(), errdetail_execute(), errhidestmt(), errmsg, ERROR, FETCH_ALL, finish_xact_command(), format, GetCommandTagNameAndLen(), GetPortalByName(), GetTransactionSnapshot(), 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 2822 of file postgres.c.

2823{
2824 /* cancel active statement timeout after each command */
2826
2827 if (xact_started)
2828 {
2830
2831#ifdef MEMORY_CONTEXT_CHECKING
2832 /* Check all memory contexts that weren't freed during commit */
2833 /* (those that were, were checked before being deleted) */
2834 MemoryContextCheck(TopMemoryContext);
2835#endif
2836
2837#ifdef SHOW_MEMORY_STATS
2838 /* Print mem stats after each commit for leak tracking */
2840#endif
2841
2842 xact_started = false;
2843 }
2844}
MemoryContext TopMemoryContext
Definition mcxt.c:166
void MemoryContextStats(MemoryContext context)
Definition mcxt.c:863
void CommitTransactionCommand(void)
Definition xact.c:3207

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

3071{
3072 /* We're not returning, so no need to save errno */
3073 ereport(ERROR,
3074 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3075 errmsg("floating-point exception"),
3076 errdetail("An invalid floating-point operation was signaled. "
3077 "This probably means an out-of-range result or an "
3078 "invalid operation, such as division by zero.")));
3079}

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

5111{
5112 if (am_walsender)
5113 {
5114 if (firstchar == PqMsg_FunctionCall)
5115 ereport(ERROR,
5117 errmsg("fastpath function calls not supported in a replication connection")));
5118 else
5119 ereport(ERROR,
5121 errmsg("extended query protocol not supported in a replication connection")));
5122 }
5123}
#define PqMsg_FunctionCall
Definition protocol.h:23
bool am_walsender
Definition walsender.c:135

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

Referenced by PostgresMain().

◆ get_stats_option_name()

const char * get_stats_option_name ( const char *  arg)

Definition at line 3823 of file postgres.c.

3824{
3825 switch (arg[0])
3826 {
3827 case 'p':
3828 if (arg[1] == 'a') /* "parser" */
3829 return "log_parser_stats";
3830 else if (arg[1] == 'l') /* "planner" */
3831 return "log_planner_stats";
3832 break;
3833
3834 case 'e': /* "executor" */
3835 return "log_executor_stats";
3836 break;
3837 }
3838
3839 return NULL;
3840}

References arg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( void  )

Definition at line 3086 of file postgres.c.

3087{
3089 InterruptPending = true;
3090 /* latch will be set by procsignal_sigusr1_handler */
3091}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
PGPROC * MyProc
Definition proc.c:71
pg_atomic_uint32 pendingRecoveryConflicts
Definition proc.h:270

References InterruptPending, MyProc, PGPROC::pendingRecoveryConflicts, and pg_atomic_read_u32().

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 336 of file postgres.c.

337{
338 int c;
339
340 /*
341 * This will not process catchup interrupts or notifications while
342 * reading. But those can't really be relevant for a standalone backend
343 * anyway. To properly handle SIGTERM there's a hack in die() that
344 * directly processes interrupts at this stage...
345 */
347
348 c = getc(stdin);
349
351
352 return c;
353}
void ProcessClientReadInterrupt(bool blocked)
Definition postgres.c:513
char * c

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 248 of file postgres.c.

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

Referenced by ReadCommand().

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2854 of file postgres.c.

2855{
2856 if (parsetree && IsA(parsetree, TransactionStmt))
2857 {
2858 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2859
2860 if (stmt->kind == TRANS_STMT_COMMIT ||
2861 stmt->kind == TRANS_STMT_PREPARE ||
2862 stmt->kind == TRANS_STMT_ROLLBACK ||
2864 return true;
2865 }
2866 return false;
2867}
@ TRANS_STMT_ROLLBACK_TO
@ TRANS_STMT_ROLLBACK
@ TRANS_STMT_COMMIT
@ TRANS_STMT_PREPARE

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

2872{
2873 if (list_length(pstmts) == 1)
2874 {
2875 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2876
2877 if (pstmt->commandType == CMD_UTILITY &&
2879 return true;
2880 }
2881 return false;
2882}
@ CMD_UTILITY
Definition nodes.h:280
CmdType commandType
Definition plannodes.h:66
Node * utilityStmt
Definition plannodes.h:153

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

2887{
2888 if (list_length(pstmts) == 1)
2889 {
2890 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2891
2892 if (pstmt->commandType == CMD_UTILITY &&
2894 return true;
2895 }
2896 return false;
2897}

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

5247{
5248 Port *port = MyProcPort;
5249 long secs;
5250 int usecs;
5251 int msecs;
5252 int hours,
5253 minutes,
5254 seconds;
5255
5258 &secs, &usecs);
5259 msecs = usecs / 1000;
5260
5261 hours = secs / SECS_PER_HOUR;
5262 secs %= SECS_PER_HOUR;
5263 minutes = secs / SECS_PER_MINUTE;
5264 seconds = secs % SECS_PER_MINUTE;
5265
5266 ereport(LOG,
5267 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5268 "user=%s database=%s host=%s%s%s",
5269 hours, minutes, seconds, msecs,
5270 port->user_name, port->database_name, port->remote_host,
5271 port->remote_port[0] ? " port=" : "", port->remote_port)));
5272}
#define SECS_PER_HOUR
Definition timestamp.h:127
#define SECS_PER_MINUTE
Definition timestamp.h:128
TimestampTz MyStartTimestamp
Definition globals.c:51
struct Port * MyProcPort
Definition globals.c:53
static int port
Definition pg_regress.c:117

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

686{
687 Query *query;
688 List *querytree_list;
689
690 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
691
692 /*
693 * (1) Perform parse analysis.
694 */
696 ResetUsage();
697
698 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
699 queryEnv);
700
702 ShowUsage("PARSE ANALYSIS STATISTICS");
703
704 /*
705 * (2) Rewrite the queries, as necessary
706 */
707 querytree_list = pg_rewrite_query(query);
708
709 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
710
711 return querytree_list;
712}
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition analyze.c:127
List * pg_rewrite_query(Query *query)
Definition postgres.c:814

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

725{
726 Query *query;
727 List *querytree_list;
728
729 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
730
731 /*
732 * (1) Perform parse analysis.
733 */
735 ResetUsage();
736
737 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
738 queryEnv);
739
740 /*
741 * Check all parameter types got determined.
742 */
743 for (int i = 0; i < *numParams; i++)
744 {
745 Oid ptype = (*paramTypes)[i];
746
747 if (ptype == InvalidOid || ptype == UNKNOWNOID)
749 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
750 errmsg("could not determine data type of parameter $%d",
751 i + 1)));
752 }
753
755 ShowUsage("PARSE ANALYSIS STATISTICS");
756
757 /*
758 * (2) Rewrite the queries, as necessary
759 */
760 querytree_list = pg_rewrite_query(query);
761
762 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
763
764 return querytree_list;
765}
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition analyze.c:167
#define InvalidOid

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

779{
780 Query *query;
781 List *querytree_list;
782
783 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
784
785 /*
786 * (1) Perform parse analysis.
787 */
789 ResetUsage();
790
791 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
792 queryEnv);
793
795 ShowUsage("PARSE ANALYSIS STATISTICS");
796
797 /*
798 * (2) Rewrite the queries, as necessary
799 */
800 querytree_list = pg_rewrite_query(query);
801
802 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
803
804 return querytree_list;
805}
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition analyze.c:208

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_sql_function_in_from(), prepare_next_query(), RevalidateCachedQuery(), and test_inline_in_from_support_func().

◆ pg_parse_query()

List * pg_parse_query ( const char *  query_string)

Definition at line 615 of file postgres.c.

616{
617 List *raw_parsetree_list;
618
619 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
620
622 ResetUsage();
623
624 raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
625
627 ShowUsage("PARSER STATISTICS");
628
629#ifdef DEBUG_NODE_TESTS_ENABLED
630
631 /* Optional debugging check: pass raw parsetrees through copyObject() */
632 if (Debug_copy_parse_plan_trees)
633 {
634 List *new_list = copyObject(raw_parsetree_list);
635
636 /* This checks both copyObject() and the equal() routines... */
637 if (!equal(new_list, raw_parsetree_list))
638 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
639 else
640 raw_parsetree_list = new_list;
641 }
642
643 /*
644 * Optional debugging check: pass raw parsetrees through
645 * outfuncs/readfuncs
646 */
647 if (Debug_write_read_parse_plan_trees)
648 {
649 char *str = nodeToStringWithLocations(raw_parsetree_list);
650 List *new_list = stringToNodeWithLocations(str);
651
652 pfree(str);
653 /* This checks both outfuncs/readfuncs and the equal() routines... */
654 if (!equal(new_list, raw_parsetree_list))
655 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
656 else
657 raw_parsetree_list = new_list;
658 }
659
660#endif /* DEBUG_NODE_TESTS_ENABLED */
661
662 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
663
665 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
667
668 return raw_parsetree_list;
669}
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:37
#define elog(elevel,...)
Definition elog.h:228
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool Debug_print_raw_parse
Definition guc_tables.c:538
bool Debug_pretty_print
Definition guc_tables.c:540
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:817
@ 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_sql_function_in_from(), sql_compile_callback(), and test_inline_in_from_support_func().

◆ pg_plan_queries()

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

Definition at line 986 of file postgres.c.

988{
989 List *stmt_list = NIL;
990 ListCell *query_list;
991
992 foreach(query_list, querytrees)
993 {
994 Query *query = lfirst_node(Query, query_list);
996
997 if (query->commandType == CMD_UTILITY)
998 {
999 /* Utility commands require no planning. */
1001 stmt->commandType = CMD_UTILITY;
1002 stmt->canSetTag = query->canSetTag;
1003 stmt->utilityStmt = query->utilityStmt;
1004 stmt->stmt_location = query->stmt_location;
1005 stmt->stmt_len = query->stmt_len;
1006 stmt->queryId = query->queryId;
1007 stmt->planOrigin = PLAN_STMT_INTERNAL;
1008 }
1009 else
1010 {
1011 stmt = pg_plan_query(query, query_string, cursorOptions,
1012 boundParams, NULL);
1013 }
1014
1015 stmt_list = lappend(stmt_list, stmt);
1016 }
1017
1018 return stmt_list;
1019}
List * lappend(List *list, void *datum)
Definition list.c:339
#define makeNode(_type_)
Definition nodes.h:161
@ PLAN_STMT_INTERNAL
Definition plannodes.h:38
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition postgres.c:898
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
ParseLoc stmt_location
Definition parsenodes.h:258

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

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

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

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

4263{
4264 sigjmp_buf local_sigjmp_buf;
4265
4266 /* these must be volatile to ensure state is preserved across longjmp: */
4267 volatile bool send_ready_for_query = true;
4268 volatile bool idle_in_transaction_timeout_enabled = false;
4269 volatile bool idle_session_timeout_enabled = false;
4270
4271 Assert(dbname != NULL);
4272 Assert(username != NULL);
4273
4275
4276 /*
4277 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4278 * has already set up BlockSig and made that the active signal mask.)
4279 *
4280 * Note that postmaster blocked all signals before forking child process,
4281 * so there is no race condition whereby we might receive a signal before
4282 * we have set up the handler.
4283 *
4284 * Also note: it's best not to use any signals that are SIG_IGNored in the
4285 * postmaster. If such a signal arrives before we are able to change the
4286 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4287 * handler in the postmaster to reserve the signal. (Of course, this isn't
4288 * an issue for signals that are locally generated, such as SIGALRM and
4289 * SIGPIPE.)
4290 */
4291 if (am_walsender)
4292 WalSndSignals();
4293 else
4294 {
4296 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4297 pqsignal(SIGTERM, die); /* cancel current query and exit */
4298
4299 /*
4300 * In a postmaster child backend, replace SignalHandlerForCrashExit
4301 * with quickdie, so we can tell the client we're dying.
4302 *
4303 * In a standalone backend, SIGQUIT can be generated from the keyboard
4304 * easily, while SIGTERM cannot, so we make both signals do die()
4305 * rather than quickdie().
4306 */
4308 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4309 else
4310 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4311 InitializeTimeouts(); /* establishes SIGALRM handler */
4312
4313 /*
4314 * Ignore failure to write to frontend. Note: if frontend closes
4315 * connection, we will notice it and exit cleanly when control next
4316 * returns to outer loop. This seems safer than forcing exit in the
4317 * midst of output during who-knows-what operation...
4318 */
4319 pqsignal(SIGPIPE, SIG_IGN);
4321 pqsignal(SIGUSR2, SIG_IGN);
4323
4324 /*
4325 * Reset some signals that are accepted by postmaster but not by
4326 * backend
4327 */
4328 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4329 * platforms */
4330 }
4331
4332 /* Early initialization */
4333 BaseInit();
4334
4335 /* We need to allow SIGINT, etc during the initial transaction */
4336 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4337
4338 /*
4339 * Generate a random cancel key, if this is a backend serving a
4340 * connection. InitPostgres() will advertise it in shared memory.
4341 */
4344 {
4345 int len;
4346
4347 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4350 {
4351 ereport(ERROR,
4352 (errcode(ERRCODE_INTERNAL_ERROR),
4353 errmsg("could not generate random cancel key")));
4354 }
4356 }
4357
4358 /*
4359 * General initialization.
4360 *
4361 * NOTE: if you are tempted to add code in this vicinity, consider putting
4362 * it inside InitPostgres() instead. In particular, anything that
4363 * involves database access should be there, not here.
4364 *
4365 * Honor session_preload_libraries if not dealing with a WAL sender.
4366 */
4367 InitPostgres(dbname, InvalidOid, /* database to connect to */
4368 username, InvalidOid, /* role to connect as */
4370 NULL); /* no out_dbname */
4371
4372 /*
4373 * If the PostmasterContext is still around, recycle the space; we don't
4374 * need it anymore after InitPostgres completes.
4375 */
4377 {
4379 PostmasterContext = NULL;
4380 }
4381
4383
4384 /*
4385 * Now all GUC states are fully set up. Report them to client if
4386 * appropriate.
4387 */
4389
4390 /*
4391 * Also set up handler to log session end; we have to wait till now to be
4392 * sure Log_disconnections has its final value.
4393 */
4396
4398
4399 /* Perform initialization specific to a WAL sender process. */
4400 if (am_walsender)
4401 InitWalSender();
4402
4403 /*
4404 * Send this backend's cancellation info to the frontend.
4405 */
4407 {
4409
4413
4416 /* Need not flush since ReadyForQuery will do it. */
4417 }
4418
4419 /* Welcome banner for standalone case */
4421 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4422
4423 /*
4424 * Create the memory context we will use in the main loop.
4425 *
4426 * MessageContext is reset once per iteration of the main loop, ie, upon
4427 * completion of processing of each command message from the client.
4428 */
4430 "MessageContext",
4432
4433 /*
4434 * Create memory context and buffer used for RowDescription messages. As
4435 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4436 * frequently executed for every single statement, we don't want to
4437 * allocate a separate buffer every time.
4438 */
4440 "RowDescriptionContext",
4445
4446 /* Fire any defined login event triggers, if appropriate */
4448
4449 /*
4450 * POSTGRES main processing loop begins here
4451 *
4452 * If an exception is encountered, processing resumes here so we abort the
4453 * current transaction and start a new one.
4454 *
4455 * You might wonder why this isn't coded as an infinite loop around a
4456 * PG_TRY construct. The reason is that this is the bottom of the
4457 * exception stack, and so with PG_TRY there would be no exception handler
4458 * in force at all during the CATCH part. By leaving the outermost setjmp
4459 * always active, we have at least some chance of recovering from an error
4460 * during error recovery. (If we get into an infinite loop thereby, it
4461 * will soon be stopped by overflow of elog.c's internal state stack.)
4462 *
4463 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4464 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4465 * is essential in case we longjmp'd out of a signal handler on a platform
4466 * where that leaves the signal blocked. It's not redundant with the
4467 * unblock in AbortTransaction() because the latter is only called if we
4468 * were inside a transaction.
4469 */
4470
4471 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4472 {
4473 /*
4474 * NOTE: if you are tempted to add more code in this if-block,
4475 * consider the high probability that it should be in
4476 * AbortTransaction() instead. The only stuff done directly here
4477 * should be stuff that is guaranteed to apply *only* for outer-level
4478 * error recovery, such as adjusting the FE/BE protocol status.
4479 */
4480
4481 /* Since not using PG_TRY, must reset error stack by hand */
4482 error_context_stack = NULL;
4483
4484 /* Prevent interrupts while cleaning up */
4486
4487 /*
4488 * Forget any pending QueryCancel request, since we're returning to
4489 * the idle loop anyway, and cancel any active timeout requests. (In
4490 * future we might want to allow some timeout requests to survive, but
4491 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4492 * we got here because of a query cancel interrupting the SIGALRM
4493 * interrupt handler.) Note in particular that we must clear the
4494 * statement and lock timeout indicators, to prevent any future plain
4495 * query cancels from being misreported as timeouts in case we're
4496 * forgetting a timeout cancel.
4497 */
4498 disable_all_timeouts(false); /* do first to avoid race condition */
4499 QueryCancelPending = false;
4500 idle_in_transaction_timeout_enabled = false;
4501 idle_session_timeout_enabled = false;
4502
4503 /* Not reading from the client anymore. */
4504 DoingCommandRead = false;
4505
4506 /* Make sure libpq is in a good state */
4507 pq_comm_reset();
4508
4509 /* Report the error to the client and/or server log */
4511
4512 /*
4513 * If Valgrind noticed something during the erroneous query, print the
4514 * query string, assuming we have one.
4515 */
4517
4518 /*
4519 * Make sure debug_query_string gets reset before we possibly clobber
4520 * the storage it points at.
4521 */
4522 debug_query_string = NULL;
4523
4524 /*
4525 * Abort the current transaction in order to recover.
4526 */
4528
4529 if (am_walsender)
4531
4533
4534 /*
4535 * We can't release replication slots inside AbortTransaction() as we
4536 * need to be able to start and abort transactions while having a slot
4537 * acquired. But we never need to hold them across top level errors,
4538 * so releasing here is fine. There also is a before_shmem_exit()
4539 * callback ensuring correct cleanup on FATAL errors.
4540 */
4541 if (MyReplicationSlot != NULL)
4543
4544 /* We also want to cleanup temporary slots on error. */
4546
4548
4549 /*
4550 * Now return to normal top-level context and clear ErrorContext for
4551 * next time.
4552 */
4555
4556 /*
4557 * If we were handling an extended-query-protocol message, initiate
4558 * skip till next Sync. This also causes us not to issue
4559 * ReadyForQuery (until we get Sync).
4560 */
4562 ignore_till_sync = true;
4563
4564 /* We don't have a transaction command open anymore */
4565 xact_started = false;
4566
4567 /*
4568 * If an error occurred while we were reading a message from the
4569 * client, we have potentially lost track of where the previous
4570 * message ends and the next one begins. Even though we have
4571 * otherwise recovered from the error, we cannot safely read any more
4572 * messages from the client, so there isn't much we can do with the
4573 * connection anymore.
4574 */
4575 if (pq_is_reading_msg())
4576 ereport(FATAL,
4578 errmsg("terminating connection because protocol synchronization was lost")));
4579
4580 /* Now we can allow interrupts again */
4582 }
4583
4584 /* We can now handle ereport(ERROR) */
4585 PG_exception_stack = &local_sigjmp_buf;
4586
4587 if (!ignore_till_sync)
4588 send_ready_for_query = true; /* initially, or after error */
4589
4590 /*
4591 * Non-error queries loop here.
4592 */
4593
4594 for (;;)
4595 {
4596 int firstchar;
4597 StringInfoData input_message;
4598
4599 /*
4600 * At top of loop, reset extended-query-message flag, so that any
4601 * errors encountered in "idle" state don't provoke skip.
4602 */
4604
4605 /*
4606 * For valgrind reporting purposes, the "current query" begins here.
4607 */
4608#ifdef USE_VALGRIND
4609 old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4610#endif
4611
4612 /*
4613 * Release storage left over from prior query cycle, and create a new
4614 * query input buffer in the cleared MessageContext.
4615 */
4618
4619 initStringInfo(&input_message);
4620
4621 /*
4622 * Also consider releasing our catalog snapshot if any, so that it's
4623 * not preventing advance of global xmin while we wait for the client.
4624 */
4626
4627 /*
4628 * (1) If we've reached idle state, tell the frontend we're ready for
4629 * a new query.
4630 *
4631 * Note: this includes fflush()'ing the last of the prior output.
4632 *
4633 * This is also a good time to flush out collected statistics to the
4634 * cumulative stats system, and to update the PS stats display. We
4635 * avoid doing those every time through the message loop because it'd
4636 * slow down processing of batched messages, and because we don't want
4637 * to report uncommitted updates (that confuses autovacuum). The
4638 * notification processor wants a call too, if we are not in a
4639 * transaction block.
4640 *
4641 * Also, if an idle timeout is enabled, start the timer for that.
4642 */
4643 if (send_ready_for_query)
4644 {
4646 {
4647 set_ps_display("idle in transaction (aborted)");
4649
4650 /* Start the idle-in-transaction timer */
4653 {
4654 idle_in_transaction_timeout_enabled = true;
4657 }
4658 }
4660 {
4661 set_ps_display("idle in transaction");
4663
4664 /* Start the idle-in-transaction timer */
4667 {
4668 idle_in_transaction_timeout_enabled = true;
4671 }
4672 }
4673 else
4674 {
4675 long stats_timeout;
4676
4677 /*
4678 * Process incoming notifies (including self-notifies), if
4679 * any, and send relevant messages to the client. Doing it
4680 * here helps ensure stable behavior in tests: if any notifies
4681 * were received during the just-finished transaction, they'll
4682 * be seen by the client before ReadyForQuery is.
4683 */
4686
4687 /*
4688 * Check if we need to report stats. If pgstat_report_stat()
4689 * decides it's too soon to flush out pending stats / lock
4690 * contention prevented reporting, it'll tell us when we
4691 * should try to report stats again (so that stats updates
4692 * aren't unduly delayed if the connection goes idle for a
4693 * long time). We only enable the timeout if we don't already
4694 * have a timeout in progress, because we don't disable the
4695 * timeout below. enable_timeout_after() needs to determine
4696 * the current timestamp, which can have a negative
4697 * performance impact. That's OK because pgstat_report_stat()
4698 * won't have us wake up sooner than a prior call.
4699 */
4700 stats_timeout = pgstat_report_stat(false);
4701 if (stats_timeout > 0)
4702 {
4705 stats_timeout);
4706 }
4707 else
4708 {
4709 /* all stats flushed, no need for the timeout */
4712 }
4713
4714 set_ps_display("idle");
4716
4717 /* Start the idle-session timer */
4718 if (IdleSessionTimeout > 0)
4719 {
4720 idle_session_timeout_enabled = true;
4723 }
4724 }
4725
4726 /* Report any recently-changed GUC options */
4728
4729 /*
4730 * The first time this backend is ready for query, log the
4731 * durations of the different components of connection
4732 * establishment and setup.
4733 */
4737 {
4738 uint64 total_duration,
4739 fork_duration,
4740 auth_duration;
4741
4743
4744 total_duration =
4747 fork_duration =
4750 auth_duration =
4753
4754 ereport(LOG,
4755 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4756 (double) total_duration / NS_PER_US,
4757 (double) fork_duration / NS_PER_US,
4758 (double) auth_duration / NS_PER_US));
4759 }
4760
4762 send_ready_for_query = false;
4763 }
4764
4765 /*
4766 * (2) Allow asynchronous signals to be executed immediately if they
4767 * come in while we are waiting for client input. (This must be
4768 * conditional since we don't want, say, reads on behalf of COPY FROM
4769 * STDIN doing the same thing.)
4770 */
4771 DoingCommandRead = true;
4772
4773 /*
4774 * (3) read a command (loop blocks here)
4775 */
4776 firstchar = ReadCommand(&input_message);
4777
4778 /*
4779 * (4) turn off the idle-in-transaction and idle-session timeouts if
4780 * active. We do this before step (5) so that any last-moment timeout
4781 * is certain to be detected in step (5).
4782 *
4783 * At most one of these timeouts will be active, so there's no need to
4784 * worry about combining the timeout.c calls into one.
4785 */
4786 if (idle_in_transaction_timeout_enabled)
4787 {
4789 idle_in_transaction_timeout_enabled = false;
4790 }
4791 if (idle_session_timeout_enabled)
4792 {
4794 idle_session_timeout_enabled = false;
4795 }
4796
4797 /*
4798 * (5) disable async signal conditions again.
4799 *
4800 * Query cancel is supposed to be a no-op when there is no query in
4801 * progress, so if a query cancel arrived while we were idle, just
4802 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4803 * it's called when DoingCommandRead is set, so check for interrupts
4804 * before resetting DoingCommandRead.
4805 */
4807 DoingCommandRead = false;
4808
4809 /*
4810 * (6) check for any other interesting events that happened while we
4811 * slept.
4812 */
4814 {
4815 ConfigReloadPending = false;
4817 }
4818
4819 /*
4820 * (7) process the command. But ignore it if we're skipping till
4821 * Sync.
4822 */
4823 if (ignore_till_sync && firstchar != EOF)
4824 continue;
4825
4826 switch (firstchar)
4827 {
4828 case PqMsg_Query:
4829 {
4830 const char *query_string;
4831
4832 /* Set statement_timestamp() */
4834
4835 query_string = pq_getmsgstring(&input_message);
4836 pq_getmsgend(&input_message);
4837
4838 if (am_walsender)
4839 {
4840 if (!exec_replication_command(query_string))
4841 exec_simple_query(query_string);
4842 }
4843 else
4844 exec_simple_query(query_string);
4845
4846 valgrind_report_error_query(query_string);
4847
4848 send_ready_for_query = true;
4849 }
4850 break;
4851
4852 case PqMsg_Parse:
4853 {
4854 const char *stmt_name;
4855 const char *query_string;
4856 int numParams;
4857 Oid *paramTypes = NULL;
4858
4859 forbidden_in_wal_sender(firstchar);
4860
4861 /* Set statement_timestamp() */
4863
4864 stmt_name = pq_getmsgstring(&input_message);
4865 query_string = pq_getmsgstring(&input_message);
4866 numParams = pq_getmsgint(&input_message, 2);
4867 if (numParams > 0)
4868 {
4869 paramTypes = palloc_array(Oid, numParams);
4870 for (int i = 0; i < numParams; i++)
4871 paramTypes[i] = pq_getmsgint(&input_message, 4);
4872 }
4873 pq_getmsgend(&input_message);
4874
4875 exec_parse_message(query_string, stmt_name,
4876 paramTypes, numParams);
4877
4878 valgrind_report_error_query(query_string);
4879 }
4880 break;
4881
4882 case PqMsg_Bind:
4883 forbidden_in_wal_sender(firstchar);
4884
4885 /* Set statement_timestamp() */
4887
4888 /*
4889 * this message is complex enough that it seems best to put
4890 * the field extraction out-of-line
4891 */
4892 exec_bind_message(&input_message);
4893
4894 /* exec_bind_message does valgrind_report_error_query */
4895 break;
4896
4897 case PqMsg_Execute:
4898 {
4899 const char *portal_name;
4900 int max_rows;
4901
4902 forbidden_in_wal_sender(firstchar);
4903
4904 /* Set statement_timestamp() */
4906
4907 portal_name = pq_getmsgstring(&input_message);
4908 max_rows = pq_getmsgint(&input_message, 4);
4909 pq_getmsgend(&input_message);
4910
4911 exec_execute_message(portal_name, max_rows);
4912
4913 /* exec_execute_message does valgrind_report_error_query */
4914 }
4915 break;
4916
4917 case PqMsg_FunctionCall:
4918 forbidden_in_wal_sender(firstchar);
4919
4920 /* Set statement_timestamp() */
4922
4923 /* Report query to various monitoring facilities. */
4925 set_ps_display("<FASTPATH>");
4926
4927 /* start an xact for this function invocation */
4929
4930 /*
4931 * Note: we may at this point be inside an aborted
4932 * transaction. We can't throw error for that until we've
4933 * finished reading the function-call message, so
4934 * HandleFunctionRequest() must check for it after doing so.
4935 * Be careful not to do anything that assumes we're inside a
4936 * valid transaction here.
4937 */
4938
4939 /* switch back to message context */
4941
4942 HandleFunctionRequest(&input_message);
4943
4944 /* commit the function-invocation transaction */
4946
4947 valgrind_report_error_query("fastpath function call");
4948
4949 send_ready_for_query = true;
4950 break;
4951
4952 case PqMsg_Close:
4953 {
4954 int close_type;
4955 const char *close_target;
4956
4957 forbidden_in_wal_sender(firstchar);
4958
4959 close_type = pq_getmsgbyte(&input_message);
4960 close_target = pq_getmsgstring(&input_message);
4961 pq_getmsgend(&input_message);
4962
4963 switch (close_type)
4964 {
4965 case 'S':
4966 if (close_target[0] != '\0')
4967 DropPreparedStatement(close_target, false);
4968 else
4969 {
4970 /* special-case the unnamed statement */
4972 }
4973 break;
4974 case 'P':
4975 {
4976 Portal portal;
4977
4978 portal = GetPortalByName(close_target);
4979 if (PortalIsValid(portal))
4980 PortalDrop(portal, false);
4981 }
4982 break;
4983 default:
4984 ereport(ERROR,
4986 errmsg("invalid CLOSE message subtype %d",
4987 close_type)));
4988 break;
4989 }
4990
4993
4994 valgrind_report_error_query("CLOSE message");
4995 }
4996 break;
4997
4998 case PqMsg_Describe:
4999 {
5000 int describe_type;
5001 const char *describe_target;
5002
5003 forbidden_in_wal_sender(firstchar);
5004
5005 /* Set statement_timestamp() (needed for xact) */
5007
5008 describe_type = pq_getmsgbyte(&input_message);
5009 describe_target = pq_getmsgstring(&input_message);
5010 pq_getmsgend(&input_message);
5011
5012 switch (describe_type)
5013 {
5014 case 'S':
5015 exec_describe_statement_message(describe_target);
5016 break;
5017 case 'P':
5018 exec_describe_portal_message(describe_target);
5019 break;
5020 default:
5021 ereport(ERROR,
5023 errmsg("invalid DESCRIBE message subtype %d",
5024 describe_type)));
5025 break;
5026 }
5027
5028 valgrind_report_error_query("DESCRIBE message");
5029 }
5030 break;
5031
5032 case PqMsg_Flush:
5033 pq_getmsgend(&input_message);
5035 pq_flush();
5036 break;
5037
5038 case PqMsg_Sync:
5039 pq_getmsgend(&input_message);
5040
5041 /*
5042 * If pipelining was used, we may be in an implicit
5043 * transaction block. Close it before calling
5044 * finish_xact_command.
5045 */
5048 valgrind_report_error_query("SYNC message");
5049 send_ready_for_query = true;
5050 break;
5051
5052 /*
5053 * PqMsg_Terminate means that the frontend is closing down the
5054 * socket. EOF means unexpected loss of frontend connection.
5055 * Either way, perform normal shutdown.
5056 */
5057 case EOF:
5058
5059 /* for the cumulative statistics system */
5061
5063
5064 case PqMsg_Terminate:
5065
5066 /*
5067 * Reset whereToSendOutput to prevent ereport from attempting
5068 * to send any more messages to client.
5069 */
5072
5073 /*
5074 * NOTE: if you are tempted to add more code here, DON'T!
5075 * Whatever you had in mind to do should be set up as an
5076 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5077 * it will fail to be called during other backend-shutdown
5078 * scenarios.
5079 */
5080 proc_exit(0);
5081
5082 case PqMsg_CopyData:
5083 case PqMsg_CopyDone:
5084 case PqMsg_CopyFail:
5085
5086 /*
5087 * Accept but ignore these messages, per protocol spec; we
5088 * probably got here because a COPY failed, and the frontend
5089 * is still sending data.
5090 */
5091 break;
5092
5093 default:
5094 ereport(FATAL,
5096 errmsg("invalid frontend message type %d",
5097 firstchar)));
5098 }
5099 } /* end of input-reading loop */
5100}
void ProcessNotifyInterrupt(bool flush)
Definition async.c:2579
volatile sig_atomic_t notifyInterruptPending
Definition async.c:552
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition prepare.c:521
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:625
#define pg_fallthrough
Definition c.h:161
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition dest.c:257
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
void EmitErrorReport(void)
Definition elog.c:1882
void FlushErrorState(void)
Definition elog.c:2062
sigjmp_buf * PG_exception_stack
Definition elog.c:101
#define FATAL
Definition elog.h:42
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition fastpath.c:188
int MyCancelKeyLength
Definition globals.c:55
int MyProcPid
Definition globals.c:49
bool IsUnderPostmaster
Definition globals.c:122
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
uint8 MyCancelKey[MAX_CANCEL_KEY_LENGTH]
Definition globals.c:54
Oid MyDatabaseId
Definition globals.c:96
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
void BeginReportingGUCOptions(void)
Definition guc.c:2453
void ReportChangedGUCOptions(void)
Definition guc.c:2503
@ 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:316
void proc_exit(int code)
Definition ipc.c:105
void jit_reset_after_error(void)
Definition jit.c:128
#define pq_flush()
Definition libpq.h:49
#define pq_comm_reset()
Definition libpq.h:48
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
MemoryContext PostmasterContext
Definition mcxt.c:168
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
@ NormalProcessing
Definition miscadmin.h:490
@ InitProcessing
Definition miscadmin.h:489
#define IsExternalConnectionBackend(backend_type)
Definition miscadmin.h:423
#define GetProcessingMode()
Definition miscadmin.h:499
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:517
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define SetProcessingMode(mode)
Definition miscadmin.h:501
BackendType MyBackendType
Definition miscinit.c:65
const void size_t len
#define die(msg)
long pgstat_report_stat(bool force)
Definition pgstat.c:722
@ DISCONNECT_CLIENT_EOF
Definition pgstat.h:62
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition port.h:547
bool pg_strong_random(void *buf, size_t len)
void PortalErrorCleanup(void)
Definition portalmem.c:919
static void exec_describe_statement_message(const char *stmt_name)
Definition postgres.c:2640
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2926
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5246
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5110
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2121
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3070
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3053
static bool ignore_till_sync
Definition postgres.c:157
static void exec_simple_query(const char *query_string)
Definition postgres.c:1028
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1405
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1639
static MemoryContext row_description_context
Definition postgres.c:172
static bool doing_extended_query_message
Definition postgres.c:156
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2732
bool Log_disconnections
Definition postgres.c:100
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:492
void BaseInit(void)
Definition postinit.c:616
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:719
bool pq_is_reading_msg(void)
Definition pqcomm.c:1182
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
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:398
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:688
#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:158
void ReplicationSlotRelease(void)
Definition slot.c:769
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:868
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
int IdleSessionTimeout
Definition proc.c:67
int IdleInTransactionSessionTimeout
Definition proc.c:65
char * dbname
Definition streamutil.c:49
TimestampTz ready_for_use
TimestampTz auth_start
TimestampTz socket_create
TimestampTz fork_start
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:370
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2058
void InitWalSender(void)
Definition walsender.c:323
void WalSndSignals(void)
Definition walsender.c:3892
#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:5040
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void AbortCurrentTransaction(void)
Definition xact.c:3501

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(), ERRCODE_PROTOCOL_VIOLATION, 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_fallthrough, 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 4119 of file postgres.c.

4121{
4122 const char *dbname = NULL;
4123
4125
4126 /* Initialize startup process environment. */
4127 InitStandaloneProcess(argv[0]);
4128
4129 /*
4130 * Set default values for command-line options.
4131 */
4133
4134 /*
4135 * Parse command-line options.
4136 */
4138
4139 /* Must have gotten a database name, or have a default (the username) */
4140 if (dbname == NULL)
4141 {
4142 dbname = username;
4143 if (dbname == NULL)
4144 ereport(FATAL,
4145 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4146 errmsg("%s: no database nor user name specified",
4147 progname)));
4148 }
4149
4150 /* Acquire configuration parameters */
4152 proc_exit(1);
4153
4154 /*
4155 * Validate we have been given a reasonable-looking DataDir and change
4156 * into it.
4157 */
4158 checkDataDir();
4160
4161 /*
4162 * Create lockfile for data directory.
4163 */
4164 CreateDataDirLockFile(false);
4165
4166 /* read control file (error checking and contains config ) */
4168
4169 /* Register the shared memory needs of all core subsystems. */
4171
4172 /*
4173 * process any libraries that should be preloaded at postmaster start
4174 */
4176
4177 /* Initialize MaxBackends */
4179
4180 /*
4181 * We don't need postmaster child slots in single-user mode, but
4182 * initialize them anyway to avoid having special handling.
4183 */
4185
4186 /* Initialize size of fast-path lock cache. */
4188
4189 /*
4190 * Also call any legacy shmem request hooks that might'be been installed
4191 * by preloaded libraries.
4192 *
4193 * Note: this must be done before ShmemCallRequestCallbacks(), because the
4194 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4195 * turn affects the size of the LWLock array calculated in lwlock.c.
4196 */
4198
4199 /*
4200 * Before computing the total size needed, give all subsystems, including
4201 * add-ins, a chance to chance to adjust their requested shmem sizes.
4202 */
4204
4205 /*
4206 * Now that loadable modules have had their chance to request additional
4207 * shared memory, determine the value of any runtime-computed GUCs that
4208 * depend on the amount of shared memory required.
4209 */
4211
4212 /*
4213 * Now that modules have been loaded, we can process any custom resource
4214 * managers specified in the wal_consistency_checking GUC.
4215 */
4217
4218 /*
4219 * Create shared memory etc. (Nothing's really "shared" in single-user
4220 * mode, but we must have these data structures anyway.)
4221 */
4223
4224 /*
4225 * Estimate number of openable files. This must happen after setting up
4226 * semaphores, because on some platforms semaphores count as open files.
4227 */
4229
4230 /*
4231 * Remember stand-alone backend startup time,roughly at the same point
4232 * during startup that postmaster does so.
4233 */
4235
4236 /*
4237 * Create a per-backend PGPROC struct in shared memory. We must do this
4238 * before we can use LWLocks.
4239 */
4240 InitProcess();
4241
4242 /*
4243 * Now that sufficient infrastructure has been initialized, PostgresMain()
4244 * can do the rest.
4245 */
4247}
TimestampTz PgStartTime
Definition timestamp.c:45
void set_max_safe_fds(void)
Definition fd.c:1045
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition guc.c:1656
void InitializeGUCOptions(void)
Definition guc.c:1408
@ PGC_POSTMASTER
Definition guc.h:74
void RegisterBuiltinShmemCallbacks(void)
Definition ipci.c:168
void InitializeShmemGUCs(void)
Definition ipci.c:189
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:120
const char * progname
Definition main.c:44
void ChangeToDataDir(void)
Definition miscinit.c:410
void process_shmem_requests(void)
Definition miscinit.c:1881
void InitStandaloneProcess(const char *argv0)
Definition miscinit.c:176
void process_shared_preload_libraries(void)
Definition miscinit.c:1853
void checkDataDir(void)
Definition miscinit.c:297
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1465
void InitPostmasterChildSlots(void)
Definition pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3863
static const char * userDoption
Definition postgres.c:167
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4262
void InitializeMaxBackends(void)
Definition postinit.c:559
void InitializeFastPathLocks(void)
Definition postinit.c:584
void ShmemCallRequestCallbacks(void)
Definition shmem.c:979
void InitProcess(void)
Definition proc.c:392
void InitializeWalConsistencyChecking(void)
Definition xlog.c:5188
void LocalProcessControlFile(bool reset)
Definition xlog.c:5269

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, RegisterBuiltinShmemCallbacks(), SelectConfigFiles(), set_max_safe_fds(), ShmemCallRequestCallbacks(), 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 3863 of file postgres.c.

3865{
3866 bool secure = (ctx == PGC_POSTMASTER);
3867 int errs = 0;
3868 GucSource gucsource;
3869 int flag;
3870 pg_getopt_ctx optctx;
3871
3872 if (secure)
3873 {
3874 gucsource = PGC_S_ARGV; /* switches came from command line */
3875
3876 /* Ignore the initial --single argument, if present */
3877 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3878 {
3879 argv++;
3880 argc--;
3881 }
3882 }
3883 else
3884 {
3885 gucsource = PGC_S_CLIENT; /* switches came from client */
3886 }
3887
3888 /*
3889 * Parse command-line options. CAUTION: keep this in sync with
3890 * postmaster/postmaster.c (the option sets should not conflict) and with
3891 * the common help() function in main/main.c.
3892 */
3893 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3894
3895 /*
3896 * Turn this off because it's either printed to stderr and not the log
3897 * where we'd want it, or argv[0] is now "--single", which would make for
3898 * a weird error message. We print our own error message below.
3899 */
3900 optctx.opterr = 0;
3901
3902 while ((flag = pg_getopt_next(&optctx)) != -1)
3903 {
3904 switch (flag)
3905 {
3906 case 'B':
3907 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
3908 break;
3909
3910 case 'b':
3911 /* Undocumented flag used for binary upgrades */
3912 if (secure)
3913 IsBinaryUpgrade = true;
3914 break;
3915
3916 case 'C':
3917 /* ignored for consistency with the postmaster */
3918 break;
3919
3920 case '-':
3921
3922 /*
3923 * Error if the user misplaced a special must-be-first option
3924 * for dispatching to a subprogram. parse_dispatch_option()
3925 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3926 * error for anything else.
3927 */
3929 ereport(ERROR,
3930 (errcode(ERRCODE_SYNTAX_ERROR),
3931 errmsg("--%s must be first argument", optctx.optarg)));
3932
3934 case 'c':
3935 {
3936 char *name,
3937 *value;
3938
3939 ParseLongOption(optctx.optarg, &name, &value);
3940 if (!value)
3941 {
3942 if (flag == '-')
3943 ereport(ERROR,
3944 (errcode(ERRCODE_SYNTAX_ERROR),
3945 errmsg("--%s requires a value",
3946 optctx.optarg)));
3947 else
3948 ereport(ERROR,
3949 (errcode(ERRCODE_SYNTAX_ERROR),
3950 errmsg("-c %s requires a value",
3951 optctx.optarg)));
3952 }
3953 SetConfigOption(name, value, ctx, gucsource);
3954 pfree(name);
3955 pfree(value);
3956 break;
3957 }
3958
3959 case 'D':
3960 if (secure)
3961 userDoption = strdup(optctx.optarg);
3962 break;
3963
3964 case 'd':
3965 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
3966 break;
3967
3968 case 'E':
3969 if (secure)
3970 EchoQuery = true;
3971 break;
3972
3973 case 'e':
3974 SetConfigOption("datestyle", "euro", ctx, gucsource);
3975 break;
3976
3977 case 'F':
3978 SetConfigOption("fsync", "false", ctx, gucsource);
3979 break;
3980
3981 case 'f':
3982 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
3983 errs++;
3984 break;
3985
3986 case 'h':
3987 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
3988 break;
3989
3990 case 'i':
3991 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3992 break;
3993
3994 case 'j':
3995 if (secure)
3996 UseSemiNewlineNewline = true;
3997 break;
3998
3999 case 'k':
4000 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4001 break;
4002
4003 case 'l':
4004 SetConfigOption("ssl", "true", ctx, gucsource);
4005 break;
4006
4007 case 'N':
4008 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4009 break;
4010
4011 case 'n':
4012 /* ignored for consistency with postmaster */
4013 break;
4014
4015 case 'O':
4016 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4017 break;
4018
4019 case 'P':
4020 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4021 break;
4022
4023 case 'p':
4024 SetConfigOption("port", optctx.optarg, ctx, gucsource);
4025 break;
4026
4027 case 'r':
4028 /* send output (stdout and stderr) to the given file */
4029 if (secure)
4031 break;
4032
4033 case 'S':
4034 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4035 break;
4036
4037 case 's':
4038 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4039 break;
4040
4041 case 'T':
4042 /* ignored for consistency with the postmaster */
4043 break;
4044
4045 case 't':
4046 {
4047 const char *tmp = get_stats_option_name(optctx.optarg);
4048
4049 if (tmp)
4050 SetConfigOption(tmp, "true", ctx, gucsource);
4051 else
4052 errs++;
4053 break;
4054 }
4055
4056 case 'v':
4057
4058 /*
4059 * -v is no longer used in normal operation, since
4060 * FrontendProtocol is already set before we get here. We keep
4061 * the switch only for possible use in standalone operation,
4062 * in case we ever support using normal FE/BE protocol with a
4063 * standalone backend.
4064 */
4065 if (secure)
4066 FrontendProtocol = (ProtocolVersion) atoi(optctx.optarg);
4067 break;
4068
4069 case 'W':
4070 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4071 break;
4072
4073 default:
4074 errs++;
4075 break;
4076 }
4077
4078 if (errs)
4079 break;
4080 }
4081
4082 /*
4083 * Optional database name should be there only if *dbname is NULL.
4084 */
4085 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4086 *dbname = strdup(argv[optctx.optind++]);
4087
4088 if (errs || argc != optctx.optind)
4089 {
4090 if (errs)
4091 optctx.optind--; /* complain about the previous argument */
4092
4093 /* spell the error message a bit differently depending on context */
4095 ereport(FATAL,
4096 errcode(ERRCODE_SYNTAX_ERROR),
4097 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4098 errhint("Try \"%s --help\" for more information.", progname));
4099 else
4100 ereport(FATAL,
4101 errcode(ERRCODE_SYNTAX_ERROR),
4102 errmsg("%s: invalid command-line argument: %s",
4103 progname, argv[optctx.optind]),
4104 errhint("Try \"%s --help\" for more information.", progname));
4105 }
4106}
int errhint(const char *fmt,...) pg_attribute_printf(1
bool IsBinaryUpgrade
Definition globals.c:123
ProtocolVersion FrontendProtocol
Definition globals.c:30
char OutputFileName[MAXPGPATH]
Definition globals.c:81
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
void ParseLongOption(const char *string, char **name, char **value)
Definition guc.c:6243
GucSource
Definition guc.h:112
@ PGC_S_ARGV
Definition guc.h:117
@ PGC_S_CLIENT
Definition guc.h:122
static struct @177 value
DispatchOption parse_dispatch_option(const char *name)
Definition main.c:244
#define MAXPGPATH
int pg_getopt_next(pg_getopt_ctx *ctx)
void pg_getopt_start(pg_getopt_ctx *ctx, int nargc, char *const *nargv, const char *ostr)
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:3749
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3781
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3823
@ DISPATCH_POSTMASTER
Definition postmaster.h:139
uint32 ProtocolVersion
Definition pqcomm.h:132
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(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, pg_getopt_ctx::optarg, pg_getopt_ctx::opterr, pg_getopt_ctx::optind, OutputFileName, parse_dispatch_option(), ParseLongOption(), pfree(), pg_fallthrough, pg_getopt_next(), pg_getopt_start(), 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 513 of file postgres.c.

514{
515 int save_errno = errno;
516
518 {
519 /* Check for general interrupts that arrived before/while reading */
521
522 /* Process sinval catchup interrupts, if any */
525
526 /* Process notify interrupts, if any */
529 }
530 else if (ProcDiePending)
531 {
532 /*
533 * We're dying. If there is no data available to read, then it's safe
534 * (and sane) to handle that now. If we haven't tried to read yet,
535 * make sure the process latch is set, so that if there is no data
536 * then we'll come back here and die. If we're done reading, also
537 * make sure the process latch is set, as we might've undesirably
538 * cleared it while reading.
539 */
540 if (blocked)
542 else
544 }
545
546 errno = save_errno;
547}
void ProcessCatchupInterrupt(void)
Definition sinval.c:173
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 559 of file postgres.c.

560{
561 int save_errno = errno;
562
563 if (ProcDiePending)
564 {
565 /*
566 * We're dying. If it's not possible to write, then we should handle
567 * that immediately, else a stuck client could indefinitely delay our
568 * response to the signal. If we haven't tried to write yet, make
569 * sure the process latch is set, so that if the write would block
570 * then we'll come back here and die. If we're done writing, also
571 * make sure the process latch is set, as we might've undesirably
572 * cleared it while writing.
573 */
574 if (blocked)
575 {
576 /*
577 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
578 * service ProcDiePending.
579 */
581 {
582 /*
583 * We don't want to send the client the error message, as a)
584 * that would possibly block again, and b) it would likely
585 * lead to loss of protocol sync because we may have already
586 * sent a partial protocol message.
587 */
590
592 }
593 }
594 else
596 }
597
598 errno = save_errno;
599}
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 3350 of file postgres.c.

3351{
3352 /* OK to accept any interrupts now? */
3353 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3354 return;
3355 InterruptPending = false;
3356
3357 if (ProcDiePending)
3358 {
3359 int sender_pid = ProcDieSenderPid;
3360 int sender_uid = ProcDieSenderUid;
3361
3362 ProcDiePending = false;
3363 ProcDieSenderPid = 0;
3364 ProcDieSenderUid = 0;
3365 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3367 /* As in quickdie, don't risk sending to client during auth */
3371 ereport(FATAL,
3372 (errcode(ERRCODE_QUERY_CANCELED),
3373 errmsg("canceling authentication due to timeout")));
3374 else if (AmAutoVacuumWorkerProcess())
3375 ereport(FATAL,
3376 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3377 errmsg("terminating autovacuum process due to administrator command"),
3378 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3379 else if (IsLogicalWorker())
3380 ereport(FATAL,
3381 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3382 errmsg("terminating logical replication worker due to administrator command"),
3383 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3384 else if (IsLogicalLauncher())
3385 {
3387 (errmsg_internal("logical replication launcher shutting down"),
3388 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3389
3390 /*
3391 * The logical replication launcher can be stopped at any time.
3392 * Use exit status 1 so the background worker is restarted.
3393 */
3394 proc_exit(1);
3395 }
3396 else if (AmWalReceiverProcess())
3397 ereport(FATAL,
3398 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3399 errmsg("terminating walreceiver process due to administrator command"),
3400 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3401 else if (AmBackgroundWorkerProcess())
3402 ereport(FATAL,
3403 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3404 errmsg("terminating background worker \"%s\" due to administrator command",
3406 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3407 else if (AmIoWorkerProcess())
3408 {
3410 (errmsg_internal("io worker shutting down due to administrator command"),
3411 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3412
3413 proc_exit(0);
3414 }
3415 else
3416 ereport(FATAL,
3417 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3418 errmsg("terminating connection due to administrator command"),
3419 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3420 }
3421
3423 {
3425
3426 /*
3427 * Check for lost connection and re-arm, if still configured, but not
3428 * if we've arrived back at DoingCommandRead state. We don't want to
3429 * wake up idle sessions, and they already know how to detect lost
3430 * connections.
3431 */
3433 {
3434 if (!pq_check_connection())
3435 ClientConnectionLost = true;
3436 else
3439 }
3440 }
3441
3443 {
3444 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3446 /* don't send to client, we already know the connection to be dead. */
3448 ereport(FATAL,
3449 (errcode(ERRCODE_CONNECTION_FAILURE),
3450 errmsg("connection to client lost")));
3451 }
3452
3453 /*
3454 * Don't allow query cancel interrupts while reading input from the
3455 * client, because we might lose sync in the FE/BE protocol. (Die
3456 * interrupts are OK, because we won't read any further messages from the
3457 * client in that case.)
3458 *
3459 * See similar logic in ProcessRecoveryConflictInterrupts().
3460 */
3462 {
3463 /*
3464 * Re-arm InterruptPending so that we process the cancel request as
3465 * soon as we're done reading the message. (XXX this is seriously
3466 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3467 * can't use that macro directly as the initial test in this function,
3468 * meaning that this code also creates opportunities for other bugs to
3469 * appear.)
3470 */
3471 InterruptPending = true;
3472 }
3473 else if (QueryCancelPending)
3474 {
3475 bool lock_timeout_occurred;
3476 bool stmt_timeout_occurred;
3477
3478 QueryCancelPending = false;
3479
3480 /*
3481 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3482 * need to clear both, so always fetch both.
3483 */
3484 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3485 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3486
3487 /*
3488 * If both were set, we want to report whichever timeout completed
3489 * earlier; this ensures consistent behavior if the machine is slow
3490 * enough that the second timeout triggers before we get here. A tie
3491 * is arbitrarily broken in favor of reporting a lock timeout.
3492 */
3493 if (lock_timeout_occurred && stmt_timeout_occurred &&
3495 lock_timeout_occurred = false; /* report stmt timeout */
3496
3497 if (lock_timeout_occurred)
3498 {
3500 ereport(ERROR,
3501 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3502 errmsg("canceling statement due to lock timeout")));
3503 }
3504 if (stmt_timeout_occurred)
3505 {
3507 ereport(ERROR,
3508 (errcode(ERRCODE_QUERY_CANCELED),
3509 errmsg("canceling statement due to statement timeout")));
3510 }
3512 {
3514 ereport(ERROR,
3515 (errcode(ERRCODE_QUERY_CANCELED),
3516 errmsg("canceling autovacuum task")));
3517 }
3518
3519 /*
3520 * If we are reading a command from the client, just ignore the cancel
3521 * request --- sending an extra error message won't accomplish
3522 * anything. Otherwise, go ahead and throw the error.
3523 */
3524 if (!DoingCommandRead)
3525 {
3527 ereport(ERROR,
3528 (errcode(ERRCODE_QUERY_CANCELED),
3529 errmsg("canceling statement due to user request")));
3530 }
3531 }
3532
3535
3537 {
3538 /*
3539 * If the GUC has been reset to zero, ignore the signal. This is
3540 * important because the GUC update itself won't disable any pending
3541 * interrupt. We need to unset the flag before the injection point,
3542 * otherwise we could loop in interrupts checking.
3543 */
3546 {
3547 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3548 ereport(FATAL,
3549 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3550 errmsg("terminating connection due to idle-in-transaction timeout")));
3551 }
3552 }
3553
3555 {
3556 /* As above, ignore the signal if the GUC has been reset to zero. */
3558 if (TransactionTimeout > 0)
3559 {
3560 INJECTION_POINT("transaction-timeout", NULL);
3561 ereport(FATAL,
3562 (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3563 errmsg("terminating connection due to transaction timeout")));
3564 }
3565 }
3566
3568 {
3569 /* As above, ignore the signal if the GUC has been reset to zero. */
3571 if (IdleSessionTimeout > 0)
3572 {
3573 INJECTION_POINT("idle-session-timeout", NULL);
3574 ereport(FATAL,
3575 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3576 errmsg("terminating connection due to idle-session timeout")));
3577 }
3578 }
3579
3580 /*
3581 * If there are pending stats updates and we currently are truly idle
3582 * (matching the conditions in PostgresMain(), report stats now.
3583 */
3586 {
3588 pgstat_report_stat(true);
3589 }
3590
3593
3596
3599
3602
3605
3608}
volatile sig_atomic_t ParallelApplyMessagePending
void ProcessParallelApplyMessages(void)
void ProcessParallelMessages(void)
Definition parallel.c:1057
volatile sig_atomic_t ParallelMessagePending
Definition parallel.c:120
bool IsLogicalWorker(void)
Definition worker.c:6065
#define DEBUG1
Definition elog.h:31
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 int ProcDieSenderPid
Definition globals.c:46
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 int ProcDieSenderUid
Definition globals.c:47
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:1587
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1340
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:398
#define AmBackgroundWorkerProcess()
Definition miscadmin.h:399
#define AmWalReceiverProcess()
Definition miscadmin.h:406
#define AmIoWorkerProcess()
Definition miscadmin.h:409
int client_connection_check_interval
Definition postgres.c:108
#define ERRDETAIL_SIGNAL_SENDER(pid, uid)
Definition postgres.c:117
static void ProcessRecoveryConflictInterrupts(void)
Definition postgres.c:3299
bool ClientAuthInProgress
Definition postmaster.c:373
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:201
bool pq_check_connection(void)
Definition pqcomm.c:2057
void ProcessProcSignalBarrier(void)
Definition procsignal.c:503
volatile sig_atomic_t RepackMessagePending
Definition repack.c:146
void ProcessRepackMessages(void)
Definition repack.c:3515
void ProcessSlotSyncMessage(void)
Definition slotsync.c:1335
volatile sig_atomic_t SlotSyncShutdownPending
Definition slotsync.c:159
void LockErrorCleanup(void)
Definition proc.c:818
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
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(), ERRDETAIL_SIGNAL_SENDER, 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, MyProc, ParallelApplyMessagePending, ParallelMessagePending, PGPROC::pendingRecoveryConflicts, pg_atomic_read_u32(), pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcDieSenderPid, ProcDieSenderUid, ProcessLogMemoryContextInterrupt(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessProcSignalBarrier(), ProcessRecoveryConflictInterrupts(), ProcessRepackMessages(), ProcessSlotSyncMessage(), ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RepackMessagePending, SlotSyncShutdownPending, STATEMENT_TIMEOUT, TransactionTimeout, TransactionTimeoutPending, and whereToSendOutput.

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( RecoveryConflictReason  reason)
static

Definition at line 3097 of file postgres.c.

3098{
3099 switch (reason)
3100 {
3102
3103 /*
3104 * The startup process is waiting on a lock held by us, and has
3105 * requested us to check if it is a deadlock (i.e. the deadlock
3106 * timeout expired).
3107 *
3108 * If we aren't waiting for a lock we can never deadlock.
3109 */
3110 if (GetAwaitedLock() == NULL)
3111 return;
3112
3113 /* Set the flag so that ProcSleep() will check for deadlocks. */
3115 return;
3116
3118
3119 /*
3120 * The startup process is waiting on a buffer pin, and has
3121 * requested us to check if there is a deadlock involving the pin.
3122 *
3123 * If we're not waiting on a lock, there can be no deadlock.
3124 */
3125 if (GetAwaitedLock() == NULL)
3126 return;
3127
3128 /*
3129 * If we're not holding the buffer pin, also no deadlock. (The
3130 * startup process doesn't know who's holding the pin, and sends
3131 * this signal to *all* backends, so this is the common case.)
3132 */
3134 return;
3135
3136 /*
3137 * Otherwise, we probably have a deadlock. Unfortunately the
3138 * normal deadlock detector doesn't know about buffer pins, so we
3139 * cannot perform comprehensively deadlock check. Instead, we
3140 * just assume that it is a deadlock if the above two conditions
3141 * are met. In principle this can lead to false positives, but
3142 * it's rare in practice because sessions in a hot standby server
3143 * rarely hold locks that can block other backends.
3144 */
3146 return;
3147
3149
3150 /*
3151 * Someone is holding a buffer pin that the startup process is
3152 * waiting for, and it got tired of waiting. If that's us, error
3153 * out to release the pin.
3154 */
3156 return;
3157
3159 return;
3160
3164
3165 /*
3166 * If we aren't in a transaction any longer then ignore.
3167 */
3169 return;
3170
3172 return;
3173
3176 return;
3177
3179
3180 /* The database is being dropped; terminate the session */
3182 return;
3183 }
3184 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3185}
bool HoldingBufferPinThatDelaysRecovery(void)
Definition bufmgr.c:6817
LOCALLOCK * GetAwaitedLock(void)
Definition lock.c:1907
static void report_recovery_conflict(RecoveryConflictReason reason)
Definition postgres.c:3193
void CheckDeadLockAlert(void)
Definition proc.c:1914

References CheckDeadLockAlert(), elog, FATAL, GetAwaitedLock(), HoldingBufferPinThatDelaysRecovery(), IsTransactionOrTransactionBlock(), RECOVERY_CONFLICT_BUFFERPIN, RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK, RECOVERY_CONFLICT_DATABASE, RECOVERY_CONFLICT_LOCK, RECOVERY_CONFLICT_LOGICALSLOT, RECOVERY_CONFLICT_SNAPSHOT, RECOVERY_CONFLICT_STARTUP_DEADLOCK, RECOVERY_CONFLICT_TABLESPACE, and report_recovery_conflict().

Referenced by ProcessRecoveryConflictInterrupts().

◆ ProcessRecoveryConflictInterrupts()

static void ProcessRecoveryConflictInterrupts ( void  )
static

Definition at line 3299 of file postgres.c.

3300{
3301 uint32 pending;
3302
3303 /*
3304 * We don't need to worry about joggling the elbow of proc_exit, because
3305 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3306 * us.
3307 */
3310
3311 /* Are any recovery conflict pending? */
3313 if (pending == 0)
3314 return;
3315
3316 /*
3317 * Check the conflicts one by one, clearing each flag only before
3318 * processing the particular conflict. This ensures that if multiple
3319 * conflicts are pending, we come back here to process the remaining
3320 * conflicts, if an error is thrown during processing one of them.
3321 */
3322 for (RecoveryConflictReason reason = 0;
3324 reason++)
3325 {
3326 if ((pending & (1 << reason)) != 0)
3327 {
3328 /* clear the flag */
3330
3332 }
3333 }
3334}
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition atomics.h:396
static uint32 pg_atomic_read_membarrier_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:256
uint32_t uint32
Definition c.h:624
static void ProcessRecoveryConflictInterrupt(RecoveryConflictReason reason)
Definition postgres.c:3097
RecoveryConflictReason
Definition standby.h:32
#define NUM_RECOVERY_CONFLICT_REASONS
Definition standby.h:67

References Assert, InterruptHoldoffCount, MyProc, NUM_RECOVERY_CONFLICT_REASONS, PGPROC::pendingRecoveryConflicts, pg_atomic_fetch_and_u32(), pg_atomic_read_membarrier_u32(), proc_exit_inprogress, and ProcessRecoveryConflictInterrupt().

Referenced by ProcessInterrupts().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2926 of file postgres.c.

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

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

493{
494 int result;
495
497 result = SocketBackend(inBuf);
498 else
499 result = InteractiveBackend(inBuf);
500 return result;
501}
uint32 result
static int SocketBackend(StringInfo inBuf)
Definition postgres.c:364
static int InteractiveBackend(StringInfo inBuf)
Definition postgres.c:248

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

Referenced by PostgresMain().

◆ report_recovery_conflict()

static void report_recovery_conflict ( RecoveryConflictReason  reason)
static

Definition at line 3193 of file postgres.c.

3194{
3195 bool fatal;
3196
3197 if (reason == RECOVERY_CONFLICT_DATABASE)
3198 {
3199 /* note: no hint about reconnecting, and different errcode */
3201 ereport(FATAL,
3202 (errcode(ERRCODE_DATABASE_DROPPED),
3203 errmsg("terminating connection due to conflict with recovery"),
3205 }
3206 if (reason == RECOVERY_CONFLICT_LOGICALSLOT)
3207 {
3208 /*
3209 * RECOVERY_CONFLICT_LOGICALSLOT is a special case that always throws
3210 * an ERROR (ie never promotes to FATAL), though it still has to
3211 * respect QueryCancelHoldoffCount, so it shares this code path.
3212 * Logical decoding slots are only acquired while performing logical
3213 * decoding. During logical decoding no user controlled code is run.
3214 * During [sub]transaction abort, the slot is released. Therefore
3215 * user controlled code cannot intercept an error before the
3216 * replication slot is released.
3217 */
3218 fatal = false;
3219 }
3220 else
3221 {
3222 fatal = IsSubTransaction();
3223 }
3224
3225 /*
3226 * If we're not in a subtransaction then we are OK to throw an ERROR to
3227 * resolve the conflict.
3228 *
3229 * XXX other times that we can throw just an ERROR *may* be
3230 * RECOVERY_CONFLICT_LOCK if no locks are held in parent transactions
3231 *
3232 * RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by parent
3233 * transactions and the transaction is not transaction-snapshot mode
3234 *
3235 * RECOVERY_CONFLICT_TABLESPACE if no temp files or cursors open in parent
3236 * transactions
3237 */
3238 if (!fatal)
3239 {
3240 /*
3241 * If we already aborted then we no longer need to cancel. We do this
3242 * here since we do not wish to ignore aborted subtransactions, which
3243 * must cause FATAL, currently.
3244 */
3246 return;
3247
3248 /*
3249 * If a recovery conflict happens while we are waiting for input from
3250 * the client, the client is presumably just sitting idle in a
3251 * transaction, preventing recovery from making progress. We'll drop
3252 * through to the FATAL case below to dislodge it, in that case.
3253 */
3254 if (!DoingCommandRead)
3255 {
3256 /* Avoid losing sync in the FE/BE protocol. */
3257 if (QueryCancelHoldoffCount != 0)
3258 {
3259 /*
3260 * Re-arm and defer this interrupt until later. See similar
3261 * code in ProcessInterrupts().
3262 */
3264 InterruptPending = true;
3265 return;
3266 }
3267
3268 /*
3269 * We are cleared to throw an ERROR. Either it's the logical slot
3270 * case, or we have a top-level transaction that we can abort and
3271 * a conflict that isn't inherently non-retryable.
3272 */
3275 ereport(ERROR,
3277 errmsg("canceling statement due to conflict with recovery"),
3279 }
3280 }
3281
3282 /*
3283 * We couldn't resolve the conflict with ERROR, so terminate the whole
3284 * session.
3285 */
3287 ereport(FATAL,
3289 errmsg("terminating connection due to conflict with recovery"),
3291 errhint("In a moment you should be able to reconnect to the"
3292 " database and repeat your command.")));
3293}
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition atomics.h:410
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition pgbench.c:77
void pgstat_report_recovery_conflict(int reason)
static int errdetail_recovery_conflict(RecoveryConflictReason reason)
Definition postgres.c:2552
bool IsSubTransaction(void)
Definition xact.c:5095

References DoingCommandRead, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), errmsg, ERROR, FATAL, InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), LockErrorCleanup(), MyProc, PGPROC::pendingRecoveryConflicts, pg_atomic_fetch_or_u32(), pgstat_report_recovery_conflict(), QueryCancelHoldoffCount, RECOVERY_CONFLICT_DATABASE, and RECOVERY_CONFLICT_LOGICALSLOT.

Referenced by ProcessRecoveryConflictInterrupt().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

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

Definition at line 3749 of file postgres.c.

3750{
3751 if (debug_flag > 0)
3752 {
3753 char debugstr[64];
3754
3755 sprintf(debugstr, "debug%d", debug_flag);
3756 SetConfigOption("log_min_messages", debugstr, context, source);
3757 }
3758 else
3759 SetConfigOption("log_min_messages", "notice", context, source);
3760
3761 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3762 {
3763 SetConfigOption("log_connections", "all", context, source);
3764 SetConfigOption("log_disconnections", "true", context, source);
3765 }
3766 if (debug_flag >= 2)
3767 SetConfigOption("log_statement", "all", context, source);
3768 if (debug_flag >= 3)
3769 {
3770 SetConfigOption("debug_print_raw_parse", "true", context, source);
3771 SetConfigOption("debug_print_parse", "true", context, source);
3772 }
3773 if (debug_flag >= 4)
3774 SetConfigOption("debug_print_plan", "true", context, source);
3775 if (debug_flag >= 5)
3776 SetConfigOption("debug_print_rewritten", "true", context, source);
3777}
static rewind_source * source
Definition pg_rewind.c:89
#define sprintf
Definition port.h:262

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

3782{
3783 const char *tmp = NULL;
3784
3785 switch (arg[0])
3786 {
3787 case 's': /* seqscan */
3788 tmp = "enable_seqscan";
3789 break;
3790 case 'i': /* indexscan */
3791 tmp = "enable_indexscan";
3792 break;
3793 case 'o': /* indexonlyscan */
3794 tmp = "enable_indexonlyscan";
3795 break;
3796 case 'b': /* bitmapscan */
3797 tmp = "enable_bitmapscan";
3798 break;
3799 case 't': /* tidscan */
3800 tmp = "enable_tidscan";
3801 break;
3802 case 'n': /* nestloop */
3803 tmp = "enable_nestloop";
3804 break;
3805 case 'm': /* mergejoin */
3806 tmp = "enable_mergejoin";
3807 break;
3808 case 'h': /* hashjoin */
3809 tmp = "enable_hashjoin";
3810 break;
3811 }
3812 if (tmp)
3813 {
3814 SetConfigOption(tmp, "false", context, source);
3815 return true;
3816 }
3817 else
3818 return false;
3819}

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 5137 of file postgres.c.

5138{
5140 struct timeval user,
5141 sys;
5142 struct timeval elapse_t;
5143 struct rusage r;
5144
5146 gettimeofday(&elapse_t, NULL);
5147 memcpy(&user, &r.ru_utime, sizeof(user));
5148 memcpy(&sys, &r.ru_stime, sizeof(sys));
5149 if (elapse_t.tv_usec < Save_t.tv_usec)
5150 {
5151 elapse_t.tv_sec--;
5152 elapse_t.tv_usec += 1000000;
5153 }
5154 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5155 {
5156 r.ru_utime.tv_sec--;
5157 r.ru_utime.tv_usec += 1000000;
5158 }
5159 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5160 {
5161 r.ru_stime.tv_sec--;
5162 r.ru_stime.tv_usec += 1000000;
5163 }
5164
5165 /*
5166 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5167 * some work to interpret them, and most platforms don't fill them in.
5168 */
5170
5171 appendStringInfoString(&str, "! system usage stats:\n");
5173 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5174 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5175 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5176 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5177 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5178 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5179 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5181 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5182 (long) user.tv_sec,
5183 (long) user.tv_usec,
5184 (long) sys.tv_sec,
5185 (long) sys.tv_usec);
5186#ifndef WIN32
5187
5188 /*
5189 * The following rusage fields are not defined by POSIX, but they're
5190 * present on all current Unix-like systems so we use them without any
5191 * special checks. Some of these could be provided in our Windows
5192 * emulation in src/port/win32getrusage.c with more work.
5193 */
5195 "!\t%ld kB max resident size\n",
5196#if defined(__darwin__)
5197 /* in bytes on macOS */
5198 r.ru_maxrss / 1024
5199#else
5200 /* in kilobytes on most other platforms */
5201 r.ru_maxrss
5202#endif
5203 );
5205 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5206 r.ru_inblock - Save_r.ru_inblock,
5207 /* they only drink coffee at dec */
5208 r.ru_oublock - Save_r.ru_oublock,
5209 r.ru_inblock, r.ru_oublock);
5211 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5212 r.ru_majflt - Save_r.ru_majflt,
5213 r.ru_minflt - Save_r.ru_minflt,
5214 r.ru_majflt, r.ru_minflt,
5215 r.ru_nswap - Save_r.ru_nswap,
5216 r.ru_nswap);
5218 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5219 r.ru_nsignals - Save_r.ru_nsignals,
5220 r.ru_nsignals,
5221 r.ru_msgrcv - Save_r.ru_msgrcv,
5222 r.ru_msgsnd - Save_r.ru_msgsnd,
5223 r.ru_msgrcv, r.ru_msgsnd);
5225 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5226 r.ru_nvcsw - Save_r.ru_nvcsw,
5227 r.ru_nivcsw - Save_r.ru_nivcsw,
5228 r.ru_nvcsw, r.ru_nivcsw);
5229#endif /* !WIN32 */
5230
5231 /* remove trailing newline */
5232 if (str.data[str.len - 1] == '\n')
5233 str.data[--str.len] = '\0';
5234
5235 ereport(LOG,
5236 (errmsg_internal("%s", title),
5237 errdetail_internal("%s", str.data)));
5238
5239 pfree(str.data);
5240}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define __darwin__
Definition darwin.h:3
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
static char * user
Definition pg_regress.c:121
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, memcpy(), 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 364 of file postgres.c.

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

References COMMERROR, DEBUG1, DestNone, doing_extended_query_message, ereport, errcode(), ERRCODE_PROTOCOL_VIOLATION, 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 2783 of file postgres.c.

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

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

3054{
3055 /*
3056 * Don't joggle the elbow of proc_exit
3057 */
3059 {
3060 InterruptPending = true;
3061 QueryCancelPending = true;
3062 }
3063
3064 /* If we're still here, waken anything waiting on the process latch */
3066}

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

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

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval = 0

Definition at line 108 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 156 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ DoingCommandRead

bool DoingCommandRead = false
static

◆ EchoQuery

bool EchoQuery = false
static

Definition at line 168 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ ignore_till_sync

bool ignore_till_sync = false
static

Definition at line 157 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ Log_disconnections

bool Log_disconnections = false

Definition at line 100 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

int log_statement = LOGSTMT_NONE

Definition at line 102 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

int PostAuthDelay = 0

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

Referenced by PostgresMain().

◆ Save_r

struct rusage Save_r
static

Definition at line 5126 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ Save_t

struct timeval Save_t
static

Definition at line 5127 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 169 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ whereToSendOutput

◆ xact_started

bool xact_started = false
static