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

Go to the source code of this file.

Data Structures

struct  BindParamCbData
 

Macros

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

Typedefs

typedef struct BindParamCbData BindParamCbData
 

Functions

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

Variables

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

Macro Definition Documentation

◆ valgrind_report_error_query

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

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

3671{
3672 int *flags = (int *) extra;
3673
3675}
int restrict_nonsystem_relation_kind
Definition: postgres.c:105

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3599 of file postgres.c.

3600{
3601 if (IsTransactionState())
3602 {
3603 /*
3604 * If transaction_timeout GUC has changed within the transaction block
3605 * enable or disable the timer correspondingly.
3606 */
3611 }
3612}
#define newval
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:780
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
bool IsTransactionState(void)
Definition: xact.c:387

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

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2594 of file postgres.c.

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

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

Referenced by exec_bind_message().

◆ check_client_connection_check_interval()

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

Definition at line 3549 of file postgres.c.

3550{
3551 if (!WaitEventSetCanReportClosed() && *newval != 0)
3552 {
3553 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3554 return false;
3555 }
3556 return true;
3557}
#define GUC_check_errdetail
Definition: guc.h:481
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 2425 of file postgres.c.

2426{
2429 {
2430 long secs;
2431 int usecs;
2432 int msecs;
2433 bool exceeded_duration;
2434 bool exceeded_sample_duration;
2435 bool in_sample = false;
2436
2439 &secs, &usecs);
2440 msecs = usecs / 1000;
2441
2442 /*
2443 * This odd-looking test for log_min_duration_* being exceeded is
2444 * designed to avoid integer overflow with very long durations: don't
2445 * compute secs * 1000 until we've verified it will fit in int.
2446 */
2447 exceeded_duration = (log_min_duration_statement == 0 ||
2449 (secs > log_min_duration_statement / 1000 ||
2450 secs * 1000 + msecs >= log_min_duration_statement)));
2451
2452 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2454 (secs > log_min_duration_sample / 1000 ||
2455 secs * 1000 + msecs >= log_min_duration_sample)));
2456
2457 /*
2458 * Do not log if log_statement_sample_rate = 0. Log a sample if
2459 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2460 * log_statement_sample_rate = 1.
2461 */
2462 if (exceeded_sample_duration)
2463 in_sample = log_statement_sample_rate != 0 &&
2466
2467 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2468 {
2469 snprintf(msec_str, 32, "%ld.%03d",
2470 secs * 1000 + msecs, usecs % 1000);
2471 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2472 return 2;
2473 else
2474 return 1;
2475 }
2476 }
2477
2478 return 0;
2479}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1721
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
int log_min_duration_statement
Definition: guc_tables.c:542
int log_min_duration_sample
Definition: guc_tables.c:541
double log_statement_sample_rate
Definition: guc_tables.c:546
bool log_duration
Definition: guc_tables.c:507
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:239
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:879
bool xact_is_sampled
Definition: xact.c:296

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

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

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2386 of file postgres.c.

2387{
2388 ListCell *stmt_item;
2389
2391 return false;
2393 return true;
2394
2395 /* Else we have to inspect the statement(s) to see whether to log */
2396 foreach(stmt_item, stmt_list)
2397 {
2398 Node *stmt = (Node *) lfirst(stmt_item);
2399
2401 return true;
2402 }
2403
2404 return false;
2405}
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:96
Definition: nodes.h:135
@ LOGSTMT_NONE
Definition: tcopprot.h:33
@ LOGSTMT_ALL
Definition: tcopprot.h:36
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3249

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

Referenced by exec_execute_message(), and exec_simple_query().

◆ check_log_stats()

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

Definition at line 3584 of file postgres.c.

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

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

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

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

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

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3028 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2906 of file postgres.c.

2907{
2908 /* paranoia to avoid a dangling pointer in case of error */
2910 {
2912
2913 unnamed_stmt_psrc = NULL;
2914 DropCachedPlan(psrc);
2915 }
2916}
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:575
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:150

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

5210{
5211 /* must be within an xact */
5213
5214 if (StatementTimeout > 0
5216 {
5219 }
5220 else
5221 {
5224 }
5225}
Assert(PointerIsAligned(start, uint64))
static bool xact_started
Definition: postgres.c:129
int StatementTimeout
Definition: proc.c:59
int TransactionTimeout
Definition: proc.c:62

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

Referenced by start_xact_command().

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2541 of file postgres.c.

2542{
2544 errdetail("Abort reason: recovery conflict");
2545
2546 return 0;
2547}
int errdetail(const char *fmt,...)
Definition: elog.c:1204
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:221

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

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

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2488 of file postgres.c.

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

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

Referenced by exec_simple_query().

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2521 of file postgres.c.

2522{
2523 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2524 {
2525 char *str;
2526
2528 if (str && str[0] != '\0')
2529 errdetail("Parameters: %s", str);
2530 }
2531
2532 return 0;
2533}
int log_parameter_max_length
Definition: guc_tables.c:543
const char * str
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

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

Referenced by exec_bind_message(), and exec_execute_message().

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( ProcSignalReason  reason)
static

Definition at line 2555 of file postgres.c.

2556{
2557 switch (reason)
2558 {
2560 errdetail("User was holding shared buffer pin for too long.");
2561 break;
2563 errdetail("User was holding a relation lock for too long.");
2564 break;
2566 errdetail("User was or might have been using tablespace that must be dropped.");
2567 break;
2569 errdetail("User query might have needed to see row versions that must be removed.");
2570 break;
2572 errdetail("User was using a logical replication slot that must be invalidated.");
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 default:
2581 break;
2582 /* no errdetail */
2583 }
2584
2585 return 0;
2586}
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:48
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:45
@ PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
Definition: procsignal.h:47
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:46
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:49

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

Referenced by ProcessRecoveryConflictInterrupt().

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1625 of file postgres.c.

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

References analyze_requires_snapshot(), ErrorContextCallback::arg, bind_param_error_callback(), BuildParamLogString(), ErrorContextCallback::callback, check_log_duration(), CachedPlanSource::commandTag, CreatePortal(), StringInfoData::cursor, StringInfoData::data, DEBUG2, debug_query_string, DestRemote, ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), errmsg_internal(), ERROR, error_context_stack, FetchPreparedStatement(), GetCachedPlan(), GetTransactionSnapshot(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, initReadOnlyStringInfo(), 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, UINT64CONST, unconstify, unnamed_stmt_psrc, valgrind_report_error_query, ParamExternData::value, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2736 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2643 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ exec_execute_message()

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

Definition at line 2109 of file postgres.c.

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

References _, ErrorContextCallback::arg, Assert(), PortalData::atStart, BeginCommand(), ErrorContextCallback::callback, CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), PortalData::commandTag, CreateDestReceiver(), debug_query_string, generate_unaccent_rules::dest, DestRemote, DestRemoteExecute, disable_statement_timeout(), EndCommand(), ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, error_context_stack, FETCH_ALL, finish_xact_command(), GetCommandTagNameAndLen(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), lfirst_node, LOG, log_statement_stats, MyXactFlags, PortalData::name, NIL, NullCommand(), ParamsErrorCbData::params, ParamsErrorCallback(), pgstat_report_activity(), pgstat_report_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, UINT64CONST, valgrind_report_error_query, whereToSendOutput, XACT_FLAGS_NEEDIMMEDIATECOMMIT, and XACT_FLAGS_PIPELINING.

Referenced by PostgresMain().

◆ exec_parse_message()

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

Definition at line 1390 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 1011 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2827 of file postgres.c.

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

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

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

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

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

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

Referenced by PostgresMain().

◆ get_stats_option_name()

const char * get_stats_option_name ( const char *  arg)

Definition at line 3755 of file postgres.c.

3756{
3757 switch (arg[0])
3758 {
3759 case 'p':
3760 if (optarg[1] == 'a') /* "parser" */
3761 return "log_parser_stats";
3762 else if (optarg[1] == 'l') /* "planner" */
3763 return "log_planner_stats";
3764 break;
3765
3766 case 'e': /* "executor" */
3767 return "log_executor_stats";
3768 break;
3769 }
3770
3771 return NULL;
3772}
PGDLLIMPORT char * optarg
Definition: getopt.c:53

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3091 of file postgres.c.

3092{
3093 RecoveryConflictPendingReasons[reason] = true;
3095 InterruptPending = true;
3096 /* latch will be set by procsignal_sigusr1_handler */
3097}
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:159
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:158

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 324 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 236 of file postgres.c.

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

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

Referenced by ReadCommand().

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2859 of file postgres.c.

2860{
2861 if (parsetree && IsA(parsetree, TransactionStmt))
2862 {
2863 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2864
2865 if (stmt->kind == TRANS_STMT_COMMIT ||
2866 stmt->kind == TRANS_STMT_PREPARE ||
2867 stmt->kind == TRANS_STMT_ROLLBACK ||
2869 return true;
2870 }
2871 return false;
2872}
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3757
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3754
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3753
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3758

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

2877{
2878 if (list_length(pstmts) == 1)
2879 {
2880 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2881
2882 if (pstmt->commandType == CMD_UTILITY &&
2884 return true;
2885 }
2886 return false;
2887}
@ CMD_UTILITY
Definition: nodes.h:276
CmdType commandType
Definition: plannodes.h:53
Node * utilityStmt
Definition: plannodes.h:139

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

2892{
2893 if (list_length(pstmts) == 1)
2894 {
2895 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2896
2897 if (pstmt->commandType == CMD_UTILITY &&
2899 return true;
2900 }
2901 return false;
2902}

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

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

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

Referenced by PostgresMain().

◆ pg_analyze_and_rewrite_fixedparams()

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

Definition at line 665 of file postgres.c.

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

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

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

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

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

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

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

◆ pg_parse_query()

List * pg_parse_query ( const char *  query_string)

Definition at line 603 of file postgres.c.

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

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

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

◆ pg_plan_queries()

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

Definition at line 970 of file postgres.c.

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

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

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

◆ pg_plan_query()

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

Definition at line 882 of file postgres.c.

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

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

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

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

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

◆ PostgresMain()

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

Definition at line 4189 of file postgres.c.

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

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

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4060 of file postgres.c.

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

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

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3795 of file postgres.c.

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

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

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 501 of file postgres.c.

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

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 547 of file postgres.c.

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

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

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3300 of file postgres.c.

3301{
3302 /* OK to accept any interrupts now? */
3303 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3304 return;
3305 InterruptPending = false;
3306
3307 if (ProcDiePending)
3308 {
3309 ProcDiePending = false;
3310 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3312 /* As in quickdie, don't risk sending to client during auth */
3316 ereport(FATAL,
3317 (errcode(ERRCODE_QUERY_CANCELED),
3318 errmsg("canceling authentication due to timeout")));
3319 else if (AmAutoVacuumWorkerProcess())
3320 ereport(FATAL,
3321 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3322 errmsg("terminating autovacuum process due to administrator command")));
3323 else if (IsLogicalWorker())
3324 ereport(FATAL,
3325 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3326 errmsg("terminating logical replication worker due to administrator command")));
3327 else if (IsLogicalLauncher())
3328 {
3330 (errmsg_internal("logical replication launcher shutting down")));
3331
3332 /*
3333 * The logical replication launcher can be stopped at any time.
3334 * Use exit status 1 so the background worker is restarted.
3335 */
3336 proc_exit(1);
3337 }
3338 else if (AmWalReceiverProcess())
3339 ereport(FATAL,
3340 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3341 errmsg("terminating walreceiver process due to administrator command")));
3342 else if (AmBackgroundWorkerProcess())
3343 ereport(FATAL,
3344 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3345 errmsg("terminating background worker \"%s\" due to administrator command",
3347 else if (AmIoWorkerProcess())
3348 {
3350 (errmsg_internal("io worker shutting down due to administrator command")));
3351
3352 proc_exit(0);
3353 }
3354 else
3355 ereport(FATAL,
3356 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3357 errmsg("terminating connection due to administrator command")));
3358 }
3359
3361 {
3363
3364 /*
3365 * Check for lost connection and re-arm, if still configured, but not
3366 * if we've arrived back at DoingCommandRead state. We don't want to
3367 * wake up idle sessions, and they already know how to detect lost
3368 * connections.
3369 */
3371 {
3372 if (!pq_check_connection())
3373 ClientConnectionLost = true;
3374 else
3377 }
3378 }
3379
3381 {
3382 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3384 /* don't send to client, we already know the connection to be dead. */
3386 ereport(FATAL,
3387 (errcode(ERRCODE_CONNECTION_FAILURE),
3388 errmsg("connection to client lost")));
3389 }
3390
3391 /*
3392 * Don't allow query cancel interrupts while reading input from the
3393 * client, because we might lose sync in the FE/BE protocol. (Die
3394 * interrupts are OK, because we won't read any further messages from the
3395 * client in that case.)
3396 *
3397 * See similar logic in ProcessRecoveryConflictInterrupts().
3398 */
3400 {
3401 /*
3402 * Re-arm InterruptPending so that we process the cancel request as
3403 * soon as we're done reading the message. (XXX this is seriously
3404 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3405 * can't use that macro directly as the initial test in this function,
3406 * meaning that this code also creates opportunities for other bugs to
3407 * appear.)
3408 */
3409 InterruptPending = true;
3410 }
3411 else if (QueryCancelPending)
3412 {
3413 bool lock_timeout_occurred;
3414 bool stmt_timeout_occurred;
3415
3416 QueryCancelPending = false;
3417
3418 /*
3419 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3420 * need to clear both, so always fetch both.
3421 */
3422 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3423 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3424
3425 /*
3426 * If both were set, we want to report whichever timeout completed
3427 * earlier; this ensures consistent behavior if the machine is slow
3428 * enough that the second timeout triggers before we get here. A tie
3429 * is arbitrarily broken in favor of reporting a lock timeout.
3430 */
3431 if (lock_timeout_occurred && stmt_timeout_occurred &&
3433 lock_timeout_occurred = false; /* report stmt timeout */
3434
3435 if (lock_timeout_occurred)
3436 {
3438 ereport(ERROR,
3439 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3440 errmsg("canceling statement due to lock timeout")));
3441 }
3442 if (stmt_timeout_occurred)
3443 {
3445 ereport(ERROR,
3446 (errcode(ERRCODE_QUERY_CANCELED),
3447 errmsg("canceling statement due to statement timeout")));
3448 }
3450 {
3452 ereport(ERROR,
3453 (errcode(ERRCODE_QUERY_CANCELED),
3454 errmsg("canceling autovacuum task")));
3455 }
3456
3457 /*
3458 * If we are reading a command from the client, just ignore the cancel
3459 * request --- sending an extra error message won't accomplish
3460 * anything. Otherwise, go ahead and throw the error.
3461 */
3462 if (!DoingCommandRead)
3463 {
3465 ereport(ERROR,
3466 (errcode(ERRCODE_QUERY_CANCELED),
3467 errmsg("canceling statement due to user request")));
3468 }
3469 }
3470
3473
3475 {
3476 /*
3477 * If the GUC has been reset to zero, ignore the signal. This is
3478 * important because the GUC update itself won't disable any pending
3479 * interrupt. We need to unset the flag before the injection point,
3480 * otherwise we could loop in interrupts checking.
3481 */
3484 {
3485 INJECTION_POINT("idle-in-transaction-session-timeout");
3486 ereport(FATAL,
3487 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3488 errmsg("terminating connection due to idle-in-transaction timeout")));
3489 }
3490 }
3491
3493 {
3494 /* As above, ignore the signal if the GUC has been reset to zero. */
3496 if (TransactionTimeout > 0)
3497 {
3498 INJECTION_POINT("transaction-timeout");
3499 ereport(FATAL,
3500 (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3501 errmsg("terminating connection due to transaction timeout")));
3502 }
3503 }
3504
3506 {
3507 /* As above, ignore the signal if the GUC has been reset to zero. */
3509 if (IdleSessionTimeout > 0)
3510 {
3511 INJECTION_POINT("idle-session-timeout");
3512 ereport(FATAL,
3513 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3514 errmsg("terminating connection due to idle-session timeout")));
3515 }
3516 }
3517
3518 /*
3519 * If there are pending stats updates and we currently are truly idle
3520 * (matching the conditions in PostgresMain(), report stats now.
3521 */
3524 {
3526 pgstat_report_stat(true);
3527 }
3528
3531
3534
3537
3540
3543}
volatile sig_atomic_t ParallelApplyMessagePending
void ProcessParallelApplyMessages(void)
void ProcessParallelMessages(void)
Definition: parallel.c:1048
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:118
bool IsLogicalWorker(void)
Definition: worker.c:4855
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:43
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:40
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:39
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:45
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:37
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:38
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:36
volatile sig_atomic_t PublishMemoryContextPending
Definition: globals.c:42
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:35
#define INJECTION_POINT(name)
bool IsLogicalLauncher(void)
Definition: launcher.c:1240
void ProcessGetMemoryContextInterrupt(void)
Definition: mcxt.c:1432
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1380
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:383
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:384
#define AmWalReceiverProcess()
Definition: miscadmin.h:391
#define AmIoWorkerProcess()
Definition: miscadmin.h:394
int client_connection_check_interval
Definition: postgres.c:102
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3261
bool ClientAuthInProgress
Definition: postmaster.c:372
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:200
bool pq_check_connection(void)
Definition: pqcomm.c:2057
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:498
void LockErrorCleanup(void)
Definition: proc.c:814
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:793
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37

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

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( ProcSignalReason  reason)
static

Definition at line 3103 of file postgres.c.

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

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

Referenced by ProcessRecoveryConflictInterrupts().

◆ ProcessRecoveryConflictInterrupts()

static void ProcessRecoveryConflictInterrupts ( void  )
static

Definition at line 3261 of file postgres.c.

3262{
3263 /*
3264 * We don't need to worry about joggling the elbow of proc_exit, because
3265 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3266 * us.
3267 */
3271
3273
3276 reason++)
3277 {
3279 {
3280 RecoveryConflictPendingReasons[reason] = false;
3282 }
3283 }
3284}
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3103
ProcSignalReason
Definition: procsignal.h:31
@ PROCSIG_RECOVERY_CONFLICT_LAST
Definition: procsignal.h:50
@ PROCSIG_RECOVERY_CONFLICT_FIRST
Definition: procsignal.h:42

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

Referenced by ProcessInterrupts().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2931 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 480 of file postgres.c.

481{
482 int result;
483
485 result = SocketBackend(inBuf);
486 else
487 result = InteractiveBackend(inBuf);
488 return result;
489}
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:352
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:236

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

Referenced by PostgresMain().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

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

Definition at line 3684 of file postgres.c.

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

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

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

Definition at line 3713 of file postgres.c.

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

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 5064 of file postgres.c.

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

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

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

◆ SocketBackend()

static int SocketBackend ( StringInfo  inBuf)
static

Definition at line 352 of file postgres.c.

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

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

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

3059{
3060 /*
3061 * Don't joggle the elbow of proc_exit
3062 */
3064 {
3065 InterruptPending = true;
3066 QueryCancelPending = true;
3067 }
3068
3069 /* If we're still here, waken anything waiting on the process latch */
3071}

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

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

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval = 0

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

Referenced by PostgresMain(), and SocketBackend().

◆ DoingCommandRead

bool DoingCommandRead = false
static

◆ EchoQuery

bool EchoQuery = false
static

Definition at line 154 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ ignore_till_sync

bool ignore_till_sync = false
static

Definition at line 143 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ Log_disconnections

bool Log_disconnections = false

Definition at line 94 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

int log_statement = LOGSTMT_NONE

Definition at line 96 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

int PostAuthDelay = 0

◆ RecoveryConflictPending

volatile sig_atomic_t RecoveryConflictPending = false
static

◆ RecoveryConflictPendingReasons

volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
static

◆ restrict_nonsystem_relation_kind

int restrict_nonsystem_relation_kind

◆ row_description_buf

StringInfoData row_description_buf
static

◆ row_description_context

MemoryContext row_description_context = NULL
static

Definition at line 162 of file postgres.c.

Referenced by PostgresMain().

◆ Save_r

struct rusage Save_r
static

Definition at line 5053 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ Save_t

struct timeval Save_t
static

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

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ whereToSendOutput

◆ xact_started

bool xact_started = false
static