PostgreSQL Source Code git master
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/multibitmapset.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "parser/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/jsonb.h"
#include "utils/jsonpath.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_srf_parameters_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */
 
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9
 
#define ece_generic_processing(node)
 
#define ece_all_arguments_const(node)    (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
 
#define ece_evaluate_expr(node)
 

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_exec_param_walker (Node *node, List *param_ids)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static bool convert_saop_to_hashed_saop_walker (Node *node, void *context)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Listreorder_function_arguments (List *args, int pronargs, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, int pronargs, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool pull_paramids_walker (Node *node, Bitmapset **context)
 
bool contain_agg_clause (Node *clause)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (PlannerInfo *root, Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_mutable_functions_after_planning (Expr *expr)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_after_planning (Expr *expr)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_exec_param (Node *clause, List *param_ids)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (PlannerInfo *root, Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
void convert_saop_to_hashed_saop (Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Listexpand_function_arguments (List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 
Bitmapsetpull_paramids (Expr *expr)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */

Definition at line 1185 of file clauses.c.

◆ ece_all_arguments_const

#define ece_all_arguments_const (   node)     (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))

Definition at line 2426 of file clauses.c.

◆ ece_evaluate_expr

#define ece_evaluate_expr (   node)
Value:
((Node *) evaluate_expr((Expr *) (node), \
exprType((Node *) (node)), \
exprTypmod((Node *) (node)), \
exprCollation((Node *) (node))))
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4974
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Definition: nodes.h:129

Definition at line 2430 of file clauses.c.

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:
context)
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2440
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155

Definition at line 2417 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

Definition at line 2269 of file clauses.c.

Function Documentation

◆ add_function_defaults()

static List * add_function_defaults ( List args,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 4328 of file clauses.c.

4329{
4330 int nargsprovided = list_length(args);
4331 List *defaults;
4332 int ndelete;
4333
4334 /* Get all the default expressions from the pg_proc tuple */
4335 defaults = fetch_function_defaults(func_tuple);
4336
4337 /* Delete any unused defaults from the list */
4338 ndelete = nargsprovided + list_length(defaults) - pronargs;
4339 if (ndelete < 0)
4340 elog(ERROR, "not enough default arguments");
4341 if (ndelete > 0)
4342 defaults = list_delete_first_n(defaults, ndelete);
4343
4344 /* And form the combined argument list, not modifying the input list */
4345 return list_concat_copy(args, defaults);
4346}
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4352
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
List * list_delete_first_n(List *list, int n)
Definition: list.c:983
static int list_length(const List *l)
Definition: pg_list.h:152
int16 pronargs
Definition: pg_proc.h:81
Definition: pg_list.h:54

References generate_unaccent_rules::args, elog, ERROR, fetch_function_defaults(), list_concat_copy(), list_delete_first_n(), list_length(), and pronargs.

Referenced by expand_function_arguments().

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2147 of file clauses.c.

2148{
2149 Oid opoid;
2150 Node *temp;
2151
2152 /* Sanity checks: caller is at fault if these fail */
2153 if (!is_opclause(clause) ||
2154 list_length(clause->args) != 2)
2155 elog(ERROR, "cannot commute non-binary-operator clause");
2156
2157 opoid = get_commutator(clause->opno);
2158
2159 if (!OidIsValid(opoid))
2160 elog(ERROR, "could not find commutator for operator %u",
2161 clause->opno);
2162
2163 /*
2164 * modify the clause in-place!
2165 */
2166 clause->opno = opoid;
2167 clause->opfuncid = InvalidOid;
2168 /* opresulttype, opretset, opcollid, inputcollid need not change */
2169
2170 temp = linitial(clause->args);
2171 linitial(clause->args) = lsecond(clause->args);
2172 lsecond(clause->args) = temp;
2173}
#define OidIsValid(objectId)
Definition: c.h:732
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:76
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
Oid opno
Definition: primnodes.h:834
List * args
Definition: primnodes.h:852

References OpExpr::args, elog, ERROR, get_commutator(), InvalidOid, is_opclause(), linitial, list_length(), lsecond, OidIsValid, and OpExpr::opno.

Referenced by get_switched_clauses().

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 177 of file clauses.c.

178{
179 return contain_agg_clause_walker(clause, NULL);
180}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:183

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), mark_nullable_by_grouping(), and subquery_planner().

◆ contain_agg_clause_walker()

static bool contain_agg_clause_walker ( Node node,
void *  context 
)
static

Definition at line 183 of file clauses.c.

184{
185 if (node == NULL)
186 return false;
187 if (IsA(node, Aggref))
188 {
189 Assert(((Aggref *) node)->agglevelsup == 0);
190 return true; /* abort the tree traversal and return true */
191 }
192 if (IsA(node, GroupingFunc))
193 {
194 Assert(((GroupingFunc *) node)->agglevelsup == 0);
195 return true; /* abort the tree traversal and return true */
196 }
197 Assert(!IsA(node, SubLink));
199}
#define Assert(condition)
Definition: c.h:815
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define IsA(nodeptr, _type_)
Definition: nodes.h:158

References Assert, contain_agg_clause_walker(), expression_tree_walker, and IsA.

Referenced by contain_agg_clause(), and contain_agg_clause_walker().

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1178 of file clauses.c.

1179{
1180 int flags = 0;
1181
1182 return contain_context_dependent_node_walker(clause, &flags);
1183}
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1188

References contain_context_dependent_node_walker().

Referenced by inline_function().

◆ contain_context_dependent_node_walker()

static bool contain_context_dependent_node_walker ( Node node,
int *  flags 
)
static

Definition at line 1188 of file clauses.c.

1189{
1190 if (node == NULL)
1191 return false;
1192 if (IsA(node, CaseTestExpr))
1193 return !(*flags & CCDN_CASETESTEXPR_OK);
1194 else if (IsA(node, CaseExpr))
1195 {
1196 CaseExpr *caseexpr = (CaseExpr *) node;
1197
1198 /*
1199 * If this CASE doesn't have a test expression, then it doesn't create
1200 * a context in which CaseTestExprs should appear, so just fall
1201 * through and treat it as a generic expression node.
1202 */
1203 if (caseexpr->arg)
1204 {
1205 int save_flags = *flags;
1206 bool res;
1207
1208 /*
1209 * Note: in principle, we could distinguish the various sub-parts
1210 * of a CASE construct and set the flag bit only for some of them,
1211 * since we are only expecting CaseTestExprs to appear in the
1212 * "expr" subtree of the CaseWhen nodes. But it doesn't really
1213 * seem worth any extra code. If there are any bare CaseTestExprs
1214 * elsewhere in the CASE, something's wrong already.
1215 */
1216 *flags |= CCDN_CASETESTEXPR_OK;
1219 flags);
1220 *flags = save_flags;
1221 return res;
1222 }
1223 }
1224 else if (IsA(node, ArrayCoerceExpr))
1225 {
1226 ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1227 int save_flags;
1228 bool res;
1229
1230 /* Check the array expression */
1232 return true;
1233
1234 /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1235 save_flags = *flags;
1236 *flags |= CCDN_CASETESTEXPR_OK;
1238 flags);
1239 *flags = save_flags;
1240 return res;
1241 }
1243 flags);
1244}
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1185
Expr * arg
Definition: primnodes.h:1329

References ArrayCoerceExpr::arg, CaseExpr::arg, CCDN_CASETESTEXPR_OK, contain_context_dependent_node_walker(), ArrayCoerceExpr::elemexpr, expression_tree_walker, IsA, and res.

Referenced by contain_context_dependent_node(), and contain_context_dependent_node_walker().

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1136 of file clauses.c.

1137{
1138 return contain_exec_param_walker(clause, param_ids);
1139}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1142

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1142 of file clauses.c.

1143{
1144 if (node == NULL)
1145 return false;
1146 if (IsA(node, Param))
1147 {
1148 Param *p = (Param *) node;
1149
1150 if (p->paramkind == PARAM_EXEC &&
1151 list_member_int(param_ids, p->paramid))
1152 return true;
1153 }
1154 return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1155}
bool list_member_int(const List *list, int datum)
Definition: list.c:702
@ PARAM_EXEC
Definition: primnodes.h:384
int paramid
Definition: primnodes.h:393
ParamKind paramkind
Definition: primnodes.h:392

References contain_exec_param_walker(), expression_tree_walker, IsA, list_member_int(), PARAM_EXEC, Param::paramid, and Param::paramkind.

Referenced by contain_exec_param(), and contain_exec_param_walker().

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1262 of file clauses.c.

1263{
1264 return contain_leaked_vars_walker(clause, NULL);
1265}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1274

References contain_leaked_vars_walker().

Referenced by make_plain_restrictinfo(), and qual_is_pushdown_safe().

◆ contain_leaked_vars_checker()

static bool contain_leaked_vars_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 1268 of file clauses.c.

1269{
1270 return !get_func_leakproof(func_id);
1271}
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1837

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

◆ contain_leaked_vars_walker()

static bool contain_leaked_vars_walker ( Node node,
void *  context 
)
static

Definition at line 1274 of file clauses.c.

1275{
1276 if (node == NULL)
1277 return false;
1278
1279 switch (nodeTag(node))
1280 {
1281 case T_Var:
1282 case T_Const:
1283 case T_Param:
1284 case T_ArrayExpr:
1285 case T_FieldSelect:
1286 case T_FieldStore:
1287 case T_NamedArgExpr:
1288 case T_BoolExpr:
1289 case T_RelabelType:
1290 case T_CollateExpr:
1291 case T_CaseExpr:
1292 case T_CaseTestExpr:
1293 case T_RowExpr:
1294 case T_SQLValueFunction:
1295 case T_NullTest:
1296 case T_BooleanTest:
1297 case T_NextValueExpr:
1298 case T_ReturningExpr:
1299 case T_List:
1300
1301 /*
1302 * We know these node types don't contain function calls; but
1303 * something further down in the node tree might.
1304 */
1305 break;
1306
1307 case T_FuncExpr:
1308 case T_OpExpr:
1309 case T_DistinctExpr:
1310 case T_NullIfExpr:
1311 case T_ScalarArrayOpExpr:
1312 case T_CoerceViaIO:
1313 case T_ArrayCoerceExpr:
1314
1315 /*
1316 * If node contains a leaky function call, and there's any Var
1317 * underneath it, reject.
1318 */
1320 context) &&
1321 contain_var_clause(node))
1322 return true;
1323 break;
1324
1325 case T_SubscriptingRef:
1326 {
1327 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1328 const SubscriptRoutines *sbsroutines;
1329
1330 /* Consult the subscripting support method info */
1331 sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1332 NULL);
1333 if (!sbsroutines ||
1334 !(sbsref->refassgnexpr != NULL ?
1335 sbsroutines->store_leakproof :
1336 sbsroutines->fetch_leakproof))
1337 {
1338 /* Node is leaky, so reject if it contains Vars */
1339 if (contain_var_clause(node))
1340 return true;
1341 }
1342 }
1343 break;
1344
1345 case T_RowCompareExpr:
1346 {
1347 /*
1348 * It's worth special-casing this because a leaky comparison
1349 * function only compromises one pair of row elements, which
1350 * might not contain Vars while others do.
1351 */
1352 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1353 ListCell *opid;
1354 ListCell *larg;
1355 ListCell *rarg;
1356
1357 forthree(opid, rcexpr->opnos,
1358 larg, rcexpr->largs,
1359 rarg, rcexpr->rargs)
1360 {
1361 Oid funcid = get_opcode(lfirst_oid(opid));
1362
1363 if (!get_func_leakproof(funcid) &&
1364 (contain_var_clause((Node *) lfirst(larg)) ||
1365 contain_var_clause((Node *) lfirst(rarg))))
1366 return true;
1367 }
1368 }
1369 break;
1370
1371 case T_MinMaxExpr:
1372 {
1373 /*
1374 * MinMaxExpr is leakproof if the comparison function it calls
1375 * is leakproof.
1376 */
1377 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1378 TypeCacheEntry *typentry;
1379 bool leakproof;
1380
1381 /* Look up the btree comparison function for the datatype */
1382 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1384 if (OidIsValid(typentry->cmp_proc))
1385 leakproof = get_func_leakproof(typentry->cmp_proc);
1386 else
1387 {
1388 /*
1389 * The executor will throw an error, but here we just
1390 * treat the missing function as leaky.
1391 */
1392 leakproof = false;
1393 }
1394
1395 if (!leakproof &&
1396 contain_var_clause((Node *) minmaxexpr->args))
1397 return true;
1398 }
1399 break;
1400
1401 case T_CurrentOfExpr:
1402
1403 /*
1404 * WHERE CURRENT OF doesn't contain leaky function calls.
1405 * Moreover, it is essential that this is considered non-leaky,
1406 * since the planner must always generate a TID scan when CURRENT
1407 * OF is present -- cf. cost_tidscan.
1408 */
1409 return false;
1410
1411 default:
1412
1413 /*
1414 * If we don't recognize the node tag, assume it might be leaky.
1415 * This prevents an unexpected security hole if someone adds a new
1416 * node type that can call a function.
1417 */
1418 return true;
1419 }
1421 context);
1422}
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1268
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3130
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1910
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define lfirst(lc)
Definition: pg_list.h:172
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:563
#define lfirst_oid(lc)
Definition: pg_list.h:174
List * args
Definition: primnodes.h:1549
Expr * refassgnexpr
Definition: primnodes.h:719
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
#define TYPECACHE_CMP_PROC
Definition: typcache.h:140
bool contain_var_clause(Node *node)
Definition: var.c:406

References MinMaxExpr::args, check_functions_in_node(), TypeCacheEntry::cmp_proc, contain_leaked_vars_checker(), contain_leaked_vars_walker(), contain_var_clause(), expression_tree_walker, SubscriptRoutines::fetch_leakproof, forthree, get_func_leakproof(), get_opcode(), getSubscriptingRoutines(), RowCompareExpr::largs, lfirst, lfirst_oid, lookup_type_cache(), nodeTag, OidIsValid, RowCompareExpr::rargs, SubscriptingRef::refassgnexpr, SubscriptRoutines::store_leakproof, and TYPECACHE_CMP_PROC.

Referenced by contain_leaked_vars(), and contain_leaked_vars_walker().

◆ contain_mutable_functions()

◆ contain_mutable_functions_after_planning()

bool contain_mutable_functions_after_planning ( Expr expr)

Definition at line 489 of file clauses.c.

490{
491 /* We assume here that expression_planner() won't scribble on its input */
492 expr = expression_planner(expr);
493
494 /* Now we can search for non-immutable functions */
495 return contain_mutable_functions((Node *) expr);
496}
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:369
Expr * expression_planner(Expr *expr)
Definition: planner.c:6570

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), ComputeIndexAttrs(), and cookDefault().

◆ contain_mutable_functions_checker()

static bool contain_mutable_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 375 of file clauses.c.

376{
377 return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
378}
char func_volatile(Oid funcid)
Definition: lsyscache.c:1780

References func_volatile().

Referenced by contain_mutable_functions_walker().

◆ contain_mutable_functions_walker()

static bool contain_mutable_functions_walker ( Node node,
void *  context 
)
static

Definition at line 381 of file clauses.c.

382{
383 if (node == NULL)
384 return false;
385 /* Check for mutable functions in node itself */
387 context))
388 return true;
389
390 if (IsA(node, JsonConstructorExpr))
391 {
392 const JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
393 ListCell *lc;
394 bool is_jsonb;
395
396 is_jsonb = ctor->returning->format->format_type == JS_FORMAT_JSONB;
397
398 /*
399 * Check argument_type => json[b] conversions specifically. We still
400 * recurse to check 'args' below, but here we want to specifically
401 * check whether or not the emitted clause would fail to be immutable
402 * because of TimeZone, for example.
403 */
404 foreach(lc, ctor->args)
405 {
406 Oid typid = exprType(lfirst(lc));
407
408 if (is_jsonb ?
409 !to_jsonb_is_immutable(typid) :
410 !to_json_is_immutable(typid))
411 return true;
412 }
413
414 /* Check all subnodes */
415 }
416
417 if (IsA(node, JsonExpr))
418 {
419 JsonExpr *jexpr = castNode(JsonExpr, node);
420 Const *cnst;
421
422 if (!IsA(jexpr->path_spec, Const))
423 return true;
424
425 cnst = castNode(Const, jexpr->path_spec);
426
427 Assert(cnst->consttype == JSONPATHOID);
428 if (cnst->constisnull)
429 return false;
430
431 if (jspIsMutable(DatumGetJsonPathP(cnst->constvalue),
432 jexpr->passing_names, jexpr->passing_values))
433 return true;
434 }
435
436 if (IsA(node, SQLValueFunction))
437 {
438 /* all variants of SQLValueFunction are stable */
439 return true;
440 }
441
442 if (IsA(node, NextValueExpr))
443 {
444 /* NextValueExpr is volatile */
445 return true;
446 }
447
448 /*
449 * It should be safe to treat MinMaxExpr as immutable, because it will
450 * depend on a non-cross-type btree comparison function, and those should
451 * always be immutable. Treating XmlExpr as immutable is more dubious,
452 * and treating CoerceToDomain as immutable is outright dangerous. But we
453 * have done so historically, and changing this would probably cause more
454 * problems than it would fix. In practice, if you have a non-immutable
455 * domain constraint you are in for pain anyhow.
456 */
457
458 /* Recurse to check arguments */
459 if (IsA(node, Query))
460 {
461 /* Recurse into subselects */
462 return query_tree_walker((Query *) node,
464 context, 0);
465 }
467 context);
468}
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:375
bool to_json_is_immutable(Oid typoid)
Definition: json.c:700
bool to_jsonb_is_immutable(Oid typoid)
Definition: jsonb.c:1049
bool jspIsMutable(JsonPath *path, List *varnames, List *varexprs)
Definition: jsonpath.c:1280
static JsonPath * DatumGetJsonPathP(Datum d)
Definition: jsonpath.h:35
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ JS_FORMAT_JSONB
Definition: primnodes.h:1671
Oid consttype
Definition: primnodes.h:328
JsonReturning * returning
Definition: primnodes.h:1741
List * passing_values
Definition: primnodes.h:1867
List * passing_names
Definition: primnodes.h:1866
Node * path_spec
Definition: primnodes.h:1860
JsonFormatType format_type
Definition: primnodes.h:1682
JsonFormat * format
Definition: primnodes.h:1694

References JsonConstructorExpr::args, Assert, castNode, check_functions_in_node(), Const::consttype, contain_mutable_functions_checker(), contain_mutable_functions_walker(), DatumGetJsonPathP(), expression_tree_walker, exprType(), JsonReturning::format, JsonFormat::format_type, IsA, JS_FORMAT_JSONB, jspIsMutable(), lfirst, JsonExpr::passing_names, JsonExpr::passing_values, JsonExpr::path_spec, query_tree_walker, JsonConstructorExpr::returning, to_json_is_immutable(), and to_jsonb_is_immutable().

Referenced by contain_mutable_functions(), and contain_mutable_functions_walker().

◆ contain_non_const_walker()

static bool contain_non_const_walker ( Node node,
void *  context 
)
static

Definition at line 3738 of file clauses.c.

3739{
3740 if (node == NULL)
3741 return false;
3742 if (IsA(node, Const))
3743 return false;
3744 if (IsA(node, List))
3745 return expression_tree_walker(node, contain_non_const_walker, context);
3746 /* Otherwise, abort the tree traversal and return true */
3747 return true;
3748}
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3738

References contain_non_const_walker(), expression_tree_walker, and IsA.

Referenced by contain_non_const_walker().

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 992 of file clauses.c.

993{
994 return contain_nonstrict_functions_walker(clause, NULL);
995}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1004

References contain_nonstrict_functions_walker().

Referenced by inline_function(), and pullup_replace_vars_callback().

◆ contain_nonstrict_functions_checker()

static bool contain_nonstrict_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 998 of file clauses.c.

999{
1000 return !func_strict(func_id);
1001}
bool func_strict(Oid funcid)
Definition: lsyscache.c:1761

References func_strict().

Referenced by contain_nonstrict_functions_walker().

◆ contain_nonstrict_functions_walker()

static bool contain_nonstrict_functions_walker ( Node node,
void *  context 
)
static

Definition at line 1004 of file clauses.c.

1005{
1006 if (node == NULL)
1007 return false;
1008 if (IsA(node, Aggref))
1009 {
1010 /* an aggregate could return non-null with null input */
1011 return true;
1012 }
1013 if (IsA(node, GroupingFunc))
1014 {
1015 /*
1016 * A GroupingFunc doesn't evaluate its arguments, and therefore must
1017 * be treated as nonstrict.
1018 */
1019 return true;
1020 }
1021 if (IsA(node, WindowFunc))
1022 {
1023 /* a window function could return non-null with null input */
1024 return true;
1025 }
1026 if (IsA(node, SubscriptingRef))
1027 {
1028 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1029 const SubscriptRoutines *sbsroutines;
1030
1031 /* Subscripting assignment is always presumed nonstrict */
1032 if (sbsref->refassgnexpr != NULL)
1033 return true;
1034 /* Otherwise we must look up the subscripting support methods */
1035 sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
1036 if (!(sbsroutines && sbsroutines->fetch_strict))
1037 return true;
1038 /* else fall through to check args */
1039 }
1040 if (IsA(node, DistinctExpr))
1041 {
1042 /* IS DISTINCT FROM is inherently non-strict */
1043 return true;
1044 }
1045 if (IsA(node, NullIfExpr))
1046 {
1047 /* NULLIF is inherently non-strict */
1048 return true;
1049 }
1050 if (IsA(node, BoolExpr))
1051 {
1052 BoolExpr *expr = (BoolExpr *) node;
1053
1054 switch (expr->boolop)
1055 {
1056 case AND_EXPR:
1057 case OR_EXPR:
1058 /* AND, OR are inherently non-strict */
1059 return true;
1060 default:
1061 break;
1062 }
1063 }
1064 if (IsA(node, SubLink))
1065 {
1066 /* In some cases a sublink might be strict, but in general not */
1067 return true;
1068 }
1069 if (IsA(node, SubPlan))
1070 return true;
1071 if (IsA(node, AlternativeSubPlan))
1072 return true;
1073 if (IsA(node, FieldStore))
1074 return true;
1075 if (IsA(node, CoerceViaIO))
1076 {
1077 /*
1078 * CoerceViaIO is strict regardless of whether the I/O functions are,
1079 * so just go look at its argument; asking check_functions_in_node is
1080 * useless expense and could deliver the wrong answer.
1081 */
1083 context);
1084 }
1085 if (IsA(node, ArrayCoerceExpr))
1086 {
1087 /*
1088 * ArrayCoerceExpr is strict at the array level, regardless of what
1089 * the per-element expression is; so we should ignore elemexpr and
1090 * recurse only into the arg.
1091 */
1093 context);
1094 }
1095 if (IsA(node, CaseExpr))
1096 return true;
1097 if (IsA(node, ArrayExpr))
1098 return true;
1099 if (IsA(node, RowExpr))
1100 return true;
1101 if (IsA(node, RowCompareExpr))
1102 return true;
1103 if (IsA(node, CoalesceExpr))
1104 return true;
1105 if (IsA(node, MinMaxExpr))
1106 return true;
1107 if (IsA(node, XmlExpr))
1108 return true;
1109 if (IsA(node, NullTest))
1110 return true;
1111 if (IsA(node, BooleanTest))
1112 return true;
1113
1114 /* Check other function-containing nodes */
1116 context))
1117 return true;
1118
1120 context);
1121}
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:998
void * arg
@ AND_EXPR
Definition: primnodes.h:947
@ OR_EXPR
Definition: primnodes.h:947
BoolExprType boolop
Definition: primnodes.h:955

References AND_EXPR, arg, BoolExpr::boolop, check_functions_in_node(), contain_nonstrict_functions_checker(), contain_nonstrict_functions_walker(), expression_tree_walker, SubscriptRoutines::fetch_strict, getSubscriptingRoutines(), IsA, OR_EXPR, and SubscriptingRef::refassgnexpr.

Referenced by contain_nonstrict_functions(), and contain_nonstrict_functions_walker().

◆ contain_subplans()

bool contain_subplans ( Node clause)

◆ contain_subplans_walker()

static bool contain_subplans_walker ( Node node,
void *  context 
)
static

Definition at line 335 of file clauses.c.

336{
337 if (node == NULL)
338 return false;
339 if (IsA(node, SubPlan) ||
340 IsA(node, AlternativeSubPlan) ||
341 IsA(node, SubLink))
342 return true; /* abort the tree traversal and return true */
343 return expression_tree_walker(node, contain_subplans_walker, context);
344}

References contain_subplans_walker(), expression_tree_walker, and IsA.

Referenced by contain_subplans(), and contain_subplans_walker().

◆ contain_volatile_functions()

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 658 of file clauses.c.

659{
660 /* We assume here that expression_planner() won't scribble on its input */
661 expr = expression_planner(expr);
662
663 /* Now we can search for volatile functions */
664 return contain_volatile_functions((Node *) expr);
665}
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:537

References contain_volatile_functions(), and expression_planner().

Referenced by AddRelationNewConstraints().

◆ contain_volatile_functions_checker()

static bool contain_volatile_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 543 of file clauses.c.

544{
545 return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
546}

References func_volatile().

Referenced by contain_volatile_functions_walker().

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 672 of file clauses.c.

673{
675}
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:685

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

◆ contain_volatile_functions_not_nextval_checker()

static bool contain_volatile_functions_not_nextval_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 678 of file clauses.c.

679{
680 return (func_id != F_NEXTVAL &&
681 func_volatile(func_id) == PROVOLATILE_VOLATILE);
682}

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

◆ contain_volatile_functions_not_nextval_walker()

static bool contain_volatile_functions_not_nextval_walker ( Node node,
void *  context 
)
static

Definition at line 685 of file clauses.c.

686{
687 if (node == NULL)
688 return false;
689 /* Check for volatile functions in node itself */
692 context))
693 return true;
694
695 /*
696 * See notes in contain_mutable_functions_walker about why we treat
697 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
698 * SQLValueFunction is stable. Hence, none of them are of interest here.
699 * Also, since we're intentionally ignoring nextval(), presumably we
700 * should ignore NextValueExpr.
701 */
702
703 /* Recurse to check arguments */
704 if (IsA(node, Query))
705 {
706 /* Recurse into subselects */
707 return query_tree_walker((Query *) node,
709 context, 0);
710 }
711 return expression_tree_walker(node,
713 context);
714}
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:678

References check_functions_in_node(), contain_volatile_functions_not_nextval_checker(), contain_volatile_functions_not_nextval_walker(), expression_tree_walker, IsA, and query_tree_walker.

Referenced by contain_volatile_functions_not_nextval(), and contain_volatile_functions_not_nextval_walker().

◆ contain_volatile_functions_walker()

static bool contain_volatile_functions_walker ( Node node,
void *  context 
)
static

Definition at line 549 of file clauses.c.

550{
551 if (node == NULL)
552 return false;
553 /* Check for volatile functions in node itself */
555 context))
556 return true;
557
558 if (IsA(node, NextValueExpr))
559 {
560 /* NextValueExpr is volatile */
561 return true;
562 }
563
564 if (IsA(node, RestrictInfo))
565 {
566 RestrictInfo *rinfo = (RestrictInfo *) node;
567
568 /*
569 * For RestrictInfo, check if we've checked the volatility of it
570 * before. If so, we can just use the cached value and not bother
571 * checking it again. Otherwise, check it and cache if whether we
572 * found any volatile functions.
573 */
574 if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
575 return false;
576 else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
577 return true;
578 else
579 {
580 bool hasvolatile;
581
582 hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
583 context);
584 if (hasvolatile)
585 rinfo->has_volatile = VOLATILITY_VOLATILE;
586 else
587 rinfo->has_volatile = VOLATILITY_NOVOLATILE;
588
589 return hasvolatile;
590 }
591 }
592
593 if (IsA(node, PathTarget))
594 {
595 PathTarget *target = (PathTarget *) node;
596
597 /*
598 * We also do caching for PathTarget the same as we do above for
599 * RestrictInfos.
600 */
602 return false;
603 else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
604 return true;
605 else
606 {
607 bool hasvolatile;
608
609 hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
610 context);
611
612 if (hasvolatile)
614 else
616
617 return hasvolatile;
618 }
619 }
620
621 /*
622 * See notes in contain_mutable_functions_walker about why we treat
623 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
624 * SQLValueFunction is stable. Hence, none of them are of interest here.
625 */
626
627 /* Recurse to check arguments */
628 if (IsA(node, Query))
629 {
630 /* Recurse into subselects */
631 return query_tree_walker((Query *) node,
633 context, 0);
634 }
636 context);
637}
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:543
@ VOLATILITY_NOVOLATILE
Definition: pathnodes.h:1511
@ VOLATILITY_VOLATILE
Definition: pathnodes.h:1510
VolatileFunctionStatus has_volatile_expr
Definition: pathnodes.h:1556
List * exprs
Definition: pathnodes.h:1544
Expr * clause
Definition: pathnodes.h:2575

References check_functions_in_node(), RestrictInfo::clause, contain_volatile_functions_checker(), contain_volatile_functions_walker(), expression_tree_walker, PathTarget::exprs, PathTarget::has_volatile_expr, IsA, query_tree_walker, VOLATILITY_NOVOLATILE, and VOLATILITY_VOLATILE.

Referenced by contain_volatile_functions(), and contain_volatile_functions_walker().

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 214 of file clauses.c.

215{
216 return contain_windowfuncs(clause);
217}
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:214

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and mark_nullable_by_grouping().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2287 of file clauses.c.

2288{
2289 (void) convert_saop_to_hashed_saop_walker(node, NULL);
2290}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2293

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

◆ convert_saop_to_hashed_saop_walker()

static bool convert_saop_to_hashed_saop_walker ( Node node,
void *  context 
)
static

Definition at line 2293 of file clauses.c.

2294{
2295 if (node == NULL)
2296 return false;
2297
2298 if (IsA(node, ScalarArrayOpExpr))
2299 {
2300 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2301 Expr *arrayarg = (Expr *) lsecond(saop->args);
2302 Oid lefthashfunc;
2303 Oid righthashfunc;
2304
2305 if (arrayarg && IsA(arrayarg, Const) &&
2306 !((Const *) arrayarg)->constisnull)
2307 {
2308 if (saop->useOr)
2309 {
2310 if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2311 lefthashfunc == righthashfunc)
2312 {
2313 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2314 ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2315 int nitems;
2316
2317 /*
2318 * Only fill in the hash functions if the array looks
2319 * large enough for it to be worth hashing instead of
2320 * doing a linear search.
2321 */
2322 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2323
2325 {
2326 /* Looks good. Fill in the hash functions */
2327 saop->hashfuncid = lefthashfunc;
2328 }
2329 return true;
2330 }
2331 }
2332 else /* !saop->useOr */
2333 {
2334 Oid negator = get_negator(saop->opno);
2335
2336 /*
2337 * Check if this is a NOT IN using an operator whose negator
2338 * is hashable. If so we can still build a hash table and
2339 * just ensure the lookup items are not in the hash table.
2340 */
2341 if (OidIsValid(negator) &&
2342 get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2343 lefthashfunc == righthashfunc)
2344 {
2345 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2346 ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2347 int nitems;
2348
2349 /*
2350 * Only fill in the hash functions if the array looks
2351 * large enough for it to be worth hashing instead of
2352 * doing a linear search.
2353 */
2354 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2355
2357 {
2358 /* Looks good. Fill in the hash functions */
2359 saop->hashfuncid = lefthashfunc;
2360
2361 /*
2362 * Also set the negfuncid. The executor will need
2363 * that to perform hashtable lookups.
2364 */
2365 saop->negfuncid = get_opcode(negator);
2366 }
2367 return true;
2368 }
2369 }
2370 }
2371 }
2372
2374}
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2269
#define nitems(x)
Definition: indent.h:31
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:510
Oid get_negator(Oid opno)
Definition: lsyscache.c:1533
uintptr_t Datum
Definition: postgres.h:69
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), convert_saop_to_hashed_saop_walker(), DatumGetPointer(), expression_tree_walker, get_negator(), get_op_hash_functions(), get_opcode(), IsA, lsecond, MIN_ARRAY_SIZE_FOR_HASHED_SAOP, nitems, OidIsValid, ScalarArrayOpExpr::opno, and ScalarArrayOpExpr::useOr.

Referenced by convert_saop_to_hashed_saop(), and convert_saop_to_hashed_saop_walker().

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3754 of file clauses.c.

3755{
3756 char provolatile = func_volatile(funcid);
3757
3758 /*
3759 * Ordinarily we are only allowed to simplify immutable functions. But for
3760 * purposes of estimation, we consider it okay to simplify functions that
3761 * are merely stable; the risk that the result might change from planning
3762 * time to execution time is worth taking in preference to not being able
3763 * to estimate the value at all.
3764 */
3765 if (provolatile == PROVOLATILE_IMMUTABLE)
3766 return true;
3767 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3768 return true;
3769 return false;
3770}

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

◆ estimate_expression_value()

Node * estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2395 of file clauses.c.

2396{
2398
2399 context.boundParams = root->glob->boundParams; /* bound Params */
2400 /* we do not need to mark the plan as depending on inlined functions */
2401 context.root = NULL;
2402 context.active_fns = NIL; /* nothing being recursively simplified */
2403 context.case_val = NULL; /* no CASE being examined */
2404 context.estimate = true; /* unsafe transformations OK */
2405 return eval_const_expressions_mutator(node, &context);
2406}
#define NIL
Definition: pg_list.h:68
tree ctl root
Definition: radixtree.h:1857
ParamListInfo boundParams
Definition: clauses.c:61

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), NIL, eval_const_expressions_context::root, and root.

Referenced by array_unnest_support(), bernoulli_samplescangetsamplesize(), clause_selectivity_ext(), generate_series_int4_support(), generate_series_int8_support(), generate_series_numeric_support(), generate_series_timestamp_support(), get_restriction_variable(), gincost_opexpr(), gincost_scalararrayopexpr(), preprocess_limit(), scalararraysel(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ eval_const_expressions()

◆ eval_const_expressions_mutator()

static Node * eval_const_expressions_mutator ( Node node,
eval_const_expressions_context context 
)
static

Definition at line 2440 of file clauses.c.

2442{
2443
2444 /* since this function recurses, it could be driven to stack overflow */
2446
2447 if (node == NULL)
2448 return NULL;
2449 switch (nodeTag(node))
2450 {
2451 case T_Param:
2452 {
2453 Param *param = (Param *) node;
2454 ParamListInfo paramLI = context->boundParams;
2455
2456 /* Look to see if we've been given a value for this Param */
2457 if (param->paramkind == PARAM_EXTERN &&
2458 paramLI != NULL &&
2459 param->paramid > 0 &&
2460 param->paramid <= paramLI->numParams)
2461 {
2462 ParamExternData *prm;
2463 ParamExternData prmdata;
2464
2465 /*
2466 * Give hook a chance in case parameter is dynamic. Tell
2467 * it that this fetch is speculative, so it should avoid
2468 * erroring out if parameter is unavailable.
2469 */
2470 if (paramLI->paramFetch != NULL)
2471 prm = paramLI->paramFetch(paramLI, param->paramid,
2472 true, &prmdata);
2473 else
2474 prm = &paramLI->params[param->paramid - 1];
2475
2476 /*
2477 * We don't just check OidIsValid, but insist that the
2478 * fetched type match the Param, just in case the hook did
2479 * something unexpected. No need to throw an error here
2480 * though; leave that for runtime.
2481 */
2482 if (OidIsValid(prm->ptype) &&
2483 prm->ptype == param->paramtype)
2484 {
2485 /* OK to substitute parameter value? */
2486 if (context->estimate ||
2487 (prm->pflags & PARAM_FLAG_CONST))
2488 {
2489 /*
2490 * Return a Const representing the param value.
2491 * Must copy pass-by-ref datatypes, since the
2492 * Param might be in a memory context
2493 * shorter-lived than our output plan should be.
2494 */
2495 int16 typLen;
2496 bool typByVal;
2497 Datum pval;
2498 Const *con;
2499
2501 &typLen, &typByVal);
2502 if (prm->isnull || typByVal)
2503 pval = prm->value;
2504 else
2505 pval = datumCopy(prm->value, typByVal, typLen);
2506 con = makeConst(param->paramtype,
2507 param->paramtypmod,
2508 param->paramcollid,
2509 (int) typLen,
2510 pval,
2511 prm->isnull,
2512 typByVal);
2513 con->location = param->location;
2514 return (Node *) con;
2515 }
2516 }
2517 }
2518
2519 /*
2520 * Not replaceable, so just copy the Param (no need to
2521 * recurse)
2522 */
2523 return (Node *) copyObject(param);
2524 }
2525 case T_WindowFunc:
2526 {
2527 WindowFunc *expr = (WindowFunc *) node;
2528 Oid funcid = expr->winfnoid;
2529 List *args;
2530 Expr *aggfilter;
2531 HeapTuple func_tuple;
2532 WindowFunc *newexpr;
2533
2534 /*
2535 * We can't really simplify a WindowFunc node, but we mustn't
2536 * just fall through to the default processing, because we
2537 * have to apply expand_function_arguments to its argument
2538 * list. That takes care of inserting default arguments and
2539 * expanding named-argument notation.
2540 */
2541 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2542 if (!HeapTupleIsValid(func_tuple))
2543 elog(ERROR, "cache lookup failed for function %u", funcid);
2544
2546 false, expr->wintype,
2547 func_tuple);
2548
2549 ReleaseSysCache(func_tuple);
2550
2551 /* Now, recursively simplify the args (which are a List) */
2552 args = (List *)
2555 context);
2556 /* ... and the filter expression, which isn't */
2557 aggfilter = (Expr *)
2559 context);
2560
2561 /* And build the replacement WindowFunc node */
2562 newexpr = makeNode(WindowFunc);
2563 newexpr->winfnoid = expr->winfnoid;
2564 newexpr->wintype = expr->wintype;
2565 newexpr->wincollid = expr->wincollid;
2566 newexpr->inputcollid = expr->inputcollid;
2567 newexpr->args = args;
2568 newexpr->aggfilter = aggfilter;
2569 newexpr->runCondition = expr->runCondition;
2570 newexpr->winref = expr->winref;
2571 newexpr->winstar = expr->winstar;
2572 newexpr->winagg = expr->winagg;
2573 newexpr->location = expr->location;
2574
2575 return (Node *) newexpr;
2576 }
2577 case T_FuncExpr:
2578 {
2579 FuncExpr *expr = (FuncExpr *) node;
2580 List *args = expr->args;
2581 Expr *simple;
2582 FuncExpr *newexpr;
2583
2584 /*
2585 * Code for op/func reduction is pretty bulky, so split it out
2586 * as a separate function. Note: exprTypmod normally returns
2587 * -1 for a FuncExpr, but not when the node is recognizably a
2588 * length coercion; we want to preserve the typmod in the
2589 * eventual Const if so.
2590 */
2591 simple = simplify_function(expr->funcid,
2592 expr->funcresulttype,
2593 exprTypmod(node),
2594 expr->funccollid,
2595 expr->inputcollid,
2596 &args,
2597 expr->funcvariadic,
2598 true,
2599 true,
2600 context);
2601 if (simple) /* successfully simplified it */
2602 return (Node *) simple;
2603
2604 /*
2605 * The expression cannot be simplified any further, so build
2606 * and return a replacement FuncExpr node using the
2607 * possibly-simplified arguments. Note that we have also
2608 * converted the argument list to positional notation.
2609 */
2610 newexpr = makeNode(FuncExpr);
2611 newexpr->funcid = expr->funcid;
2612 newexpr->funcresulttype = expr->funcresulttype;
2613 newexpr->funcretset = expr->funcretset;
2614 newexpr->funcvariadic = expr->funcvariadic;
2615 newexpr->funcformat = expr->funcformat;
2616 newexpr->funccollid = expr->funccollid;
2617 newexpr->inputcollid = expr->inputcollid;
2618 newexpr->args = args;
2619 newexpr->location = expr->location;
2620 return (Node *) newexpr;
2621 }
2622 case T_OpExpr:
2623 {
2624 OpExpr *expr = (OpExpr *) node;
2625 List *args = expr->args;
2626 Expr *simple;
2627 OpExpr *newexpr;
2628
2629 /*
2630 * Need to get OID of underlying function. Okay to scribble
2631 * on input to this extent.
2632 */
2633 set_opfuncid(expr);
2634
2635 /*
2636 * Code for op/func reduction is pretty bulky, so split it out
2637 * as a separate function.
2638 */
2639 simple = simplify_function(expr->opfuncid,
2640 expr->opresulttype, -1,
2641 expr->opcollid,
2642 expr->inputcollid,
2643 &args,
2644 false,
2645 true,
2646 true,
2647 context);
2648 if (simple) /* successfully simplified it */
2649 return (Node *) simple;
2650
2651 /*
2652 * If the operator is boolean equality or inequality, we know
2653 * how to simplify cases involving one constant and one
2654 * non-constant argument.
2655 */
2656 if (expr->opno == BooleanEqualOperator ||
2657 expr->opno == BooleanNotEqualOperator)
2658 {
2659 simple = (Expr *) simplify_boolean_equality(expr->opno,
2660 args);
2661 if (simple) /* successfully simplified it */
2662 return (Node *) simple;
2663 }
2664
2665 /*
2666 * The expression cannot be simplified any further, so build
2667 * and return a replacement OpExpr node using the
2668 * possibly-simplified arguments.
2669 */
2670 newexpr = makeNode(OpExpr);
2671 newexpr->opno = expr->opno;
2672 newexpr->opfuncid = expr->opfuncid;
2673 newexpr->opresulttype = expr->opresulttype;
2674 newexpr->opretset = expr->opretset;
2675 newexpr->opcollid = expr->opcollid;
2676 newexpr->inputcollid = expr->inputcollid;
2677 newexpr->args = args;
2678 newexpr->location = expr->location;
2679 return (Node *) newexpr;
2680 }
2681 case T_DistinctExpr:
2682 {
2683 DistinctExpr *expr = (DistinctExpr *) node;
2684 List *args;
2685 ListCell *arg;
2686 bool has_null_input = false;
2687 bool all_null_input = true;
2688 bool has_nonconst_input = false;
2689 Expr *simple;
2690 DistinctExpr *newexpr;
2691
2692 /*
2693 * Reduce constants in the DistinctExpr's arguments. We know
2694 * args is either NIL or a List node, so we can call
2695 * expression_tree_mutator directly rather than recursing to
2696 * self.
2697 */
2698 args = (List *) expression_tree_mutator((Node *) expr->args,
2700 context);
2701
2702 /*
2703 * We must do our own check for NULLs because DistinctExpr has
2704 * different results for NULL input than the underlying
2705 * operator does.
2706 */
2707 foreach(arg, args)
2708 {
2709 if (IsA(lfirst(arg), Const))
2710 {
2711 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2712 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2713 }
2714 else
2715 has_nonconst_input = true;
2716 }
2717
2718 /* all constants? then can optimize this out */
2719 if (!has_nonconst_input)
2720 {
2721 /* all nulls? then not distinct */
2722 if (all_null_input)
2723 return makeBoolConst(false, false);
2724
2725 /* one null? then distinct */
2726 if (has_null_input)
2727 return makeBoolConst(true, false);
2728
2729 /* otherwise try to evaluate the '=' operator */
2730 /* (NOT okay to try to inline it, though!) */
2731
2732 /*
2733 * Need to get OID of underlying function. Okay to
2734 * scribble on input to this extent.
2735 */
2736 set_opfuncid((OpExpr *) expr); /* rely on struct
2737 * equivalence */
2738
2739 /*
2740 * Code for op/func reduction is pretty bulky, so split it
2741 * out as a separate function.
2742 */
2743 simple = simplify_function(expr->opfuncid,
2744 expr->opresulttype, -1,
2745 expr->opcollid,
2746 expr->inputcollid,
2747 &args,
2748 false,
2749 false,
2750 false,
2751 context);
2752 if (simple) /* successfully simplified it */
2753 {
2754 /*
2755 * Since the underlying operator is "=", must negate
2756 * its result
2757 */
2758 Const *csimple = castNode(Const, simple);
2759
2760 csimple->constvalue =
2761 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2762 return (Node *) csimple;
2763 }
2764 }
2765
2766 /*
2767 * The expression cannot be simplified any further, so build
2768 * and return a replacement DistinctExpr node using the
2769 * possibly-simplified arguments.
2770 */
2771 newexpr = makeNode(DistinctExpr);
2772 newexpr->opno = expr->opno;
2773 newexpr->opfuncid = expr->opfuncid;
2774 newexpr->opresulttype = expr->opresulttype;
2775 newexpr->opretset = expr->opretset;
2776 newexpr->opcollid = expr->opcollid;
2777 newexpr->inputcollid = expr->inputcollid;
2778 newexpr->args = args;
2779 newexpr->location = expr->location;
2780 return (Node *) newexpr;
2781 }
2782 case T_NullIfExpr:
2783 {
2784 NullIfExpr *expr;
2785 ListCell *arg;
2786 bool has_nonconst_input = false;
2787
2788 /* Copy the node and const-simplify its arguments */
2789 expr = (NullIfExpr *) ece_generic_processing(node);
2790
2791 /* If either argument is NULL they can't be equal */
2792 foreach(arg, expr->args)
2793 {
2794 if (!IsA(lfirst(arg), Const))
2795 has_nonconst_input = true;
2796 else if (((Const *) lfirst(arg))->constisnull)
2797 return (Node *) linitial(expr->args);
2798 }
2799
2800 /*
2801 * Need to get OID of underlying function before checking if
2802 * the function is OK to evaluate.
2803 */
2804 set_opfuncid((OpExpr *) expr);
2805
2806 if (!has_nonconst_input &&
2807 ece_function_is_safe(expr->opfuncid, context))
2808 return ece_evaluate_expr(expr);
2809
2810 return (Node *) expr;
2811 }
2812 case T_ScalarArrayOpExpr:
2813 {
2814 ScalarArrayOpExpr *saop;
2815
2816 /* Copy the node and const-simplify its arguments */
2818
2819 /* Make sure we know underlying function */
2820 set_sa_opfuncid(saop);
2821
2822 /*
2823 * If all arguments are Consts, and it's a safe function, we
2824 * can fold to a constant
2825 */
2826 if (ece_all_arguments_const(saop) &&
2827 ece_function_is_safe(saop->opfuncid, context))
2828 return ece_evaluate_expr(saop);
2829 return (Node *) saop;
2830 }
2831 case T_BoolExpr:
2832 {
2833 BoolExpr *expr = (BoolExpr *) node;
2834
2835 switch (expr->boolop)
2836 {
2837 case OR_EXPR:
2838 {
2839 List *newargs;
2840 bool haveNull = false;
2841 bool forceTrue = false;
2842
2843 newargs = simplify_or_arguments(expr->args,
2844 context,
2845 &haveNull,
2846 &forceTrue);
2847 if (forceTrue)
2848 return makeBoolConst(true, false);
2849 if (haveNull)
2850 newargs = lappend(newargs,
2851 makeBoolConst(false, true));
2852 /* If all the inputs are FALSE, result is FALSE */
2853 if (newargs == NIL)
2854 return makeBoolConst(false, false);
2855
2856 /*
2857 * If only one nonconst-or-NULL input, it's the
2858 * result
2859 */
2860 if (list_length(newargs) == 1)
2861 return (Node *) linitial(newargs);
2862 /* Else we still need an OR node */
2863 return (Node *) make_orclause(newargs);
2864 }
2865 case AND_EXPR:
2866 {
2867 List *newargs;
2868 bool haveNull = false;
2869 bool forceFalse = false;
2870
2871 newargs = simplify_and_arguments(expr->args,
2872 context,
2873 &haveNull,
2874 &forceFalse);
2875 if (forceFalse)
2876 return makeBoolConst(false, false);
2877 if (haveNull)
2878 newargs = lappend(newargs,
2879 makeBoolConst(false, true));
2880 /* If all the inputs are TRUE, result is TRUE */
2881 if (newargs == NIL)
2882 return makeBoolConst(true, false);
2883
2884 /*
2885 * If only one nonconst-or-NULL input, it's the
2886 * result
2887 */
2888 if (list_length(newargs) == 1)
2889 return (Node *) linitial(newargs);
2890 /* Else we still need an AND node */
2891 return (Node *) make_andclause(newargs);
2892 }
2893 case NOT_EXPR:
2894 {
2895 Node *arg;
2896
2897 Assert(list_length(expr->args) == 1);
2899 context);
2900
2901 /*
2902 * Use negate_clause() to see if we can simplify
2903 * away the NOT.
2904 */
2905 return negate_clause(arg);
2906 }
2907 default:
2908 elog(ERROR, "unrecognized boolop: %d",
2909 (int) expr->boolop);
2910 break;
2911 }
2912 break;
2913 }
2914
2915 case T_JsonValueExpr:
2916 {
2917 JsonValueExpr *jve = (JsonValueExpr *) node;
2918 Node *raw_expr = (Node *) jve->raw_expr;
2919 Node *formatted_expr = (Node *) jve->formatted_expr;
2920
2921 /*
2922 * If we can fold formatted_expr to a constant, we can elide
2923 * the JsonValueExpr altogether. Otherwise we must process
2924 * raw_expr too. But JsonFormat is a flat node and requires
2925 * no simplification, only copying.
2926 */
2927 formatted_expr = eval_const_expressions_mutator(formatted_expr,
2928 context);
2929 if (formatted_expr && IsA(formatted_expr, Const))
2930 return formatted_expr;
2931
2932 raw_expr = eval_const_expressions_mutator(raw_expr, context);
2933
2934 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
2935 (Expr *) formatted_expr,
2936 copyObject(jve->format));
2937 }
2938
2939 case T_SubPlan:
2940 case T_AlternativeSubPlan:
2941
2942 /*
2943 * Return a SubPlan unchanged --- too late to do anything with it.
2944 *
2945 * XXX should we ereport() here instead? Probably this routine
2946 * should never be invoked after SubPlan creation.
2947 */
2948 return node;
2949 case T_RelabelType:
2950 {
2951 RelabelType *relabel = (RelabelType *) node;
2952 Node *arg;
2953
2954 /* Simplify the input ... */
2956 context);
2957 /* ... and attach a new RelabelType node, if needed */
2958 return applyRelabelType(arg,
2959 relabel->resulttype,
2960 relabel->resulttypmod,
2961 relabel->resultcollid,
2962 relabel->relabelformat,
2963 relabel->location,
2964 true);
2965 }
2966 case T_CoerceViaIO:
2967 {
2968 CoerceViaIO *expr = (CoerceViaIO *) node;
2969 List *args;
2970 Oid outfunc;
2971 bool outtypisvarlena;
2972 Oid infunc;
2973 Oid intypioparam;
2974 Expr *simple;
2975 CoerceViaIO *newexpr;
2976
2977 /* Make a List so we can use simplify_function */
2978 args = list_make1(expr->arg);
2979
2980 /*
2981 * CoerceViaIO represents calling the source type's output
2982 * function then the result type's input function. So, try to
2983 * simplify it as though it were a stack of two such function
2984 * calls. First we need to know what the functions are.
2985 *
2986 * Note that the coercion functions are assumed not to care
2987 * about input collation, so we just pass InvalidOid for that.
2988 */
2990 &outfunc, &outtypisvarlena);
2992 &infunc, &intypioparam);
2993
2994 simple = simplify_function(outfunc,
2995 CSTRINGOID, -1,
2996 InvalidOid,
2997 InvalidOid,
2998 &args,
2999 false,
3000 true,
3001 true,
3002 context);
3003 if (simple) /* successfully simplified output fn */
3004 {
3005 /*
3006 * Input functions may want 1 to 3 arguments. We always
3007 * supply all three, trusting that nothing downstream will
3008 * complain.
3009 */
3010 args = list_make3(simple,
3011 makeConst(OIDOID,
3012 -1,
3013 InvalidOid,
3014 sizeof(Oid),
3015 ObjectIdGetDatum(intypioparam),
3016 false,
3017 true),
3018 makeConst(INT4OID,
3019 -1,
3020 InvalidOid,
3021 sizeof(int32),
3022 Int32GetDatum(-1),
3023 false,
3024 true));
3025
3026 simple = simplify_function(infunc,
3027 expr->resulttype, -1,
3028 expr->resultcollid,
3029 InvalidOid,
3030 &args,
3031 false,
3032 false,
3033 true,
3034 context);
3035 if (simple) /* successfully simplified input fn */
3036 return (Node *) simple;
3037 }
3038
3039 /*
3040 * The expression cannot be simplified any further, so build
3041 * and return a replacement CoerceViaIO node using the
3042 * possibly-simplified argument.
3043 */
3044 newexpr = makeNode(CoerceViaIO);
3045 newexpr->arg = (Expr *) linitial(args);
3046 newexpr->resulttype = expr->resulttype;
3047 newexpr->resultcollid = expr->resultcollid;
3048 newexpr->coerceformat = expr->coerceformat;
3049 newexpr->location = expr->location;
3050 return (Node *) newexpr;
3051 }
3052 case T_ArrayCoerceExpr:
3053 {
3055 Node *save_case_val;
3056
3057 /*
3058 * Copy the node and const-simplify its arguments. We can't
3059 * use ece_generic_processing() here because we need to mess
3060 * with case_val only while processing the elemexpr.
3061 */
3062 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3063 ac->arg = (Expr *)
3065 context);
3066
3067 /*
3068 * Set up for the CaseTestExpr node contained in the elemexpr.
3069 * We must prevent it from absorbing any outer CASE value.
3070 */
3071 save_case_val = context->case_val;
3072 context->case_val = NULL;
3073
3074 ac->elemexpr = (Expr *)
3076 context);
3077
3078 context->case_val = save_case_val;
3079
3080 /*
3081 * If constant argument and the per-element expression is
3082 * immutable, we can simplify the whole thing to a constant.
3083 * Exception: although contain_mutable_functions considers
3084 * CoerceToDomain immutable for historical reasons, let's not
3085 * do so here; this ensures coercion to an array-over-domain
3086 * does not apply the domain's constraints until runtime.
3087 */
3088 if (ac->arg && IsA(ac->arg, Const) &&
3089 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3091 return ece_evaluate_expr(ac);
3092
3093 return (Node *) ac;
3094 }
3095 case T_CollateExpr:
3096 {
3097 /*
3098 * We replace CollateExpr with RelabelType, so as to improve
3099 * uniformity of expression representation and thus simplify
3100 * comparison of expressions. Hence this looks very nearly
3101 * the same as the RelabelType case, and we can apply the same
3102 * optimizations to avoid unnecessary RelabelTypes.
3103 */
3104 CollateExpr *collate = (CollateExpr *) node;
3105 Node *arg;
3106
3107 /* Simplify the input ... */
3109 context);
3110 /* ... and attach a new RelabelType node, if needed */
3111 return applyRelabelType(arg,
3112 exprType(arg),
3113 exprTypmod(arg),
3114 collate->collOid,
3116 collate->location,
3117 true);
3118 }
3119 case T_CaseExpr:
3120 {
3121 /*----------
3122 * CASE expressions can be simplified if there are constant
3123 * condition clauses:
3124 * FALSE (or NULL): drop the alternative
3125 * TRUE: drop all remaining alternatives
3126 * If the first non-FALSE alternative is a constant TRUE,
3127 * we can simplify the entire CASE to that alternative's
3128 * expression. If there are no non-FALSE alternatives,
3129 * we simplify the entire CASE to the default result (ELSE).
3130 *
3131 * If we have a simple-form CASE with constant test
3132 * expression, we substitute the constant value for contained
3133 * CaseTestExpr placeholder nodes, so that we have the
3134 * opportunity to reduce constant test conditions. For
3135 * example this allows
3136 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3137 * to reduce to 1 rather than drawing a divide-by-0 error.
3138 * Note that when the test expression is constant, we don't
3139 * have to include it in the resulting CASE; for example
3140 * CASE 0 WHEN x THEN y ELSE z END
3141 * is transformed by the parser to
3142 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3143 * which we can simplify to
3144 * CASE WHEN 0 = x THEN y ELSE z END
3145 * It is not necessary for the executor to evaluate the "arg"
3146 * expression when executing the CASE, since any contained
3147 * CaseTestExprs that might have referred to it will have been
3148 * replaced by the constant.
3149 *----------
3150 */
3151 CaseExpr *caseexpr = (CaseExpr *) node;
3152 CaseExpr *newcase;
3153 Node *save_case_val;
3154 Node *newarg;
3155 List *newargs;
3156 bool const_true_cond;
3157 Node *defresult = NULL;
3158 ListCell *arg;
3159
3160 /* Simplify the test expression, if any */
3161 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
3162 context);
3163
3164 /* Set up for contained CaseTestExpr nodes */
3165 save_case_val = context->case_val;
3166 if (newarg && IsA(newarg, Const))
3167 {
3168 context->case_val = newarg;
3169 newarg = NULL; /* not needed anymore, see above */
3170 }
3171 else
3172 context->case_val = NULL;
3173
3174 /* Simplify the WHEN clauses */
3175 newargs = NIL;
3176 const_true_cond = false;
3177 foreach(arg, caseexpr->args)
3178 {
3179 CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
3180 Node *casecond;
3181 Node *caseresult;
3182
3183 /* Simplify this alternative's test condition */
3184 casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
3185 context);
3186
3187 /*
3188 * If the test condition is constant FALSE (or NULL), then
3189 * drop this WHEN clause completely, without processing
3190 * the result.
3191 */
3192 if (casecond && IsA(casecond, Const))
3193 {
3194 Const *const_input = (Const *) casecond;
3195
3196 if (const_input->constisnull ||
3197 !DatumGetBool(const_input->constvalue))
3198 continue; /* drop alternative with FALSE cond */
3199 /* Else it's constant TRUE */
3200 const_true_cond = true;
3201 }
3202
3203 /* Simplify this alternative's result value */
3204 caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
3205 context);
3206
3207 /* If non-constant test condition, emit a new WHEN node */
3208 if (!const_true_cond)
3209 {
3210 CaseWhen *newcasewhen = makeNode(CaseWhen);
3211
3212 newcasewhen->expr = (Expr *) casecond;
3213 newcasewhen->result = (Expr *) caseresult;
3214 newcasewhen->location = oldcasewhen->location;
3215 newargs = lappend(newargs, newcasewhen);
3216 continue;
3217 }
3218
3219 /*
3220 * Found a TRUE condition, so none of the remaining
3221 * alternatives can be reached. We treat the result as
3222 * the default result.
3223 */
3224 defresult = caseresult;
3225 break;
3226 }
3227
3228 /* Simplify the default result, unless we replaced it above */
3229 if (!const_true_cond)
3230 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3231 context);
3232
3233 context->case_val = save_case_val;
3234
3235 /*
3236 * If no non-FALSE alternatives, CASE reduces to the default
3237 * result
3238 */
3239 if (newargs == NIL)
3240 return defresult;
3241 /* Otherwise we need a new CASE node */
3242 newcase = makeNode(CaseExpr);
3243 newcase->casetype = caseexpr->casetype;
3244 newcase->casecollid = caseexpr->casecollid;
3245 newcase->arg = (Expr *) newarg;
3246 newcase->args = newargs;
3247 newcase->defresult = (Expr *) defresult;
3248 newcase->location = caseexpr->location;
3249 return (Node *) newcase;
3250 }
3251 case T_CaseTestExpr:
3252 {
3253 /*
3254 * If we know a constant test value for the current CASE
3255 * construct, substitute it for the placeholder. Else just
3256 * return the placeholder as-is.
3257 */
3258 if (context->case_val)
3259 return copyObject(context->case_val);
3260 else
3261 return copyObject(node);
3262 }
3263 case T_SubscriptingRef:
3264 case T_ArrayExpr:
3265 case T_RowExpr:
3266 case T_MinMaxExpr:
3267 {
3268 /*
3269 * Generic handling for node types whose own processing is
3270 * known to be immutable, and for which we need no smarts
3271 * beyond "simplify if all inputs are constants".
3272 *
3273 * Treating SubscriptingRef this way assumes that subscripting
3274 * fetch and assignment are both immutable. This constrains
3275 * type-specific subscripting implementations; maybe we should
3276 * relax it someday.
3277 *
3278 * Treating MinMaxExpr this way amounts to assuming that the
3279 * btree comparison function it calls is immutable; see the
3280 * reasoning in contain_mutable_functions_walker.
3281 */
3282
3283 /* Copy the node and const-simplify its arguments */
3284 node = ece_generic_processing(node);
3285 /* If all arguments are Consts, we can fold to a constant */
3286 if (ece_all_arguments_const(node))
3287 return ece_evaluate_expr(node);
3288 return node;
3289 }
3290 case T_CoalesceExpr:
3291 {
3292 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3293 CoalesceExpr *newcoalesce;
3294 List *newargs;
3295 ListCell *arg;
3296
3297 newargs = NIL;
3298 foreach(arg, coalesceexpr->args)
3299 {
3300 Node *e;
3301
3303 context);
3304
3305 /*
3306 * We can remove null constants from the list. For a
3307 * non-null constant, if it has not been preceded by any
3308 * other non-null-constant expressions then it is the
3309 * result. Otherwise, it's the next argument, but we can
3310 * drop following arguments since they will never be
3311 * reached.
3312 */
3313 if (IsA(e, Const))
3314 {
3315 if (((Const *) e)->constisnull)
3316 continue; /* drop null constant */
3317 if (newargs == NIL)
3318 return e; /* first expr */
3319 newargs = lappend(newargs, e);
3320 break;
3321 }
3322 newargs = lappend(newargs, e);
3323 }
3324
3325 /*
3326 * If all the arguments were constant null, the result is just
3327 * null
3328 */
3329 if (newargs == NIL)
3330 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3331 -1,
3332 coalesceexpr->coalescecollid);
3333
3334 newcoalesce = makeNode(CoalesceExpr);
3335 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3336 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3337 newcoalesce->args = newargs;
3338 newcoalesce->location = coalesceexpr->location;
3339 return (Node *) newcoalesce;
3340 }
3341 case T_SQLValueFunction:
3342 {
3343 /*
3344 * All variants of SQLValueFunction are stable, so if we are
3345 * estimating the expression's value, we should evaluate the
3346 * current function value. Otherwise just copy.
3347 */
3348 SQLValueFunction *svf = (SQLValueFunction *) node;
3349
3350 if (context->estimate)
3351 return (Node *) evaluate_expr((Expr *) svf,
3352 svf->type,
3353 svf->typmod,
3354 InvalidOid);
3355 else
3356 return copyObject((Node *) svf);
3357 }
3358 case T_FieldSelect:
3359 {
3360 /*
3361 * We can optimize field selection from a whole-row Var into a
3362 * simple Var. (This case won't be generated directly by the
3363 * parser, because ParseComplexProjection short-circuits it.
3364 * But it can arise while simplifying functions.) Also, we
3365 * can optimize field selection from a RowExpr construct, or
3366 * of course from a constant.
3367 *
3368 * However, replacing a whole-row Var in this way has a
3369 * pitfall: if we've already built the rel targetlist for the
3370 * source relation, then the whole-row Var is scheduled to be
3371 * produced by the relation scan, but the simple Var probably
3372 * isn't, which will lead to a failure in setrefs.c. This is
3373 * not a problem when handling simple single-level queries, in
3374 * which expression simplification always happens first. It
3375 * is a risk for lateral references from subqueries, though.
3376 * To avoid such failures, don't optimize uplevel references.
3377 *
3378 * We must also check that the declared type of the field is
3379 * still the same as when the FieldSelect was created --- this
3380 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3381 * If it isn't, we skip the optimization; the case will
3382 * probably fail at runtime, but that's not our problem here.
3383 */
3384 FieldSelect *fselect = (FieldSelect *) node;
3385 FieldSelect *newfselect;
3386 Node *arg;
3387
3389 context);
3390 if (arg && IsA(arg, Var) &&
3391 ((Var *) arg)->varattno == InvalidAttrNumber &&
3392 ((Var *) arg)->varlevelsup == 0)
3393 {
3394 if (rowtype_field_matches(((Var *) arg)->vartype,
3395 fselect->fieldnum,
3396 fselect->resulttype,
3397 fselect->resulttypmod,
3398 fselect->resultcollid))
3399 {
3400 Var *newvar;
3401
3402 newvar = makeVar(((Var *) arg)->varno,
3403 fselect->fieldnum,
3404 fselect->resulttype,
3405 fselect->resulttypmod,
3406 fselect->resultcollid,
3407 ((Var *) arg)->varlevelsup);
3408 /* New Var has same OLD/NEW returning as old one */
3409 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3410 /* New Var is nullable by same rels as the old one */
3411 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3412 return (Node *) newvar;
3413 }
3414 }
3415 if (arg && IsA(arg, RowExpr))
3416 {
3417 RowExpr *rowexpr = (RowExpr *) arg;
3418
3419 if (fselect->fieldnum > 0 &&
3420 fselect->fieldnum <= list_length(rowexpr->args))
3421 {
3422 Node *fld = (Node *) list_nth(rowexpr->args,
3423 fselect->fieldnum - 1);
3424
3425 if (rowtype_field_matches(rowexpr->row_typeid,
3426 fselect->fieldnum,
3427 fselect->resulttype,
3428 fselect->resulttypmod,
3429 fselect->resultcollid) &&
3430 fselect->resulttype == exprType(fld) &&
3431 fselect->resulttypmod == exprTypmod(fld) &&
3432 fselect->resultcollid == exprCollation(fld))
3433 return fld;
3434 }
3435 }
3436 newfselect = makeNode(FieldSelect);
3437 newfselect->arg = (Expr *) arg;
3438 newfselect->fieldnum = fselect->fieldnum;
3439 newfselect->resulttype = fselect->resulttype;
3440 newfselect->resulttypmod = fselect->resulttypmod;
3441 newfselect->resultcollid = fselect->resultcollid;
3442 if (arg && IsA(arg, Const))
3443 {
3444 Const *con = (Const *) arg;
3445
3447 newfselect->fieldnum,
3448 newfselect->resulttype,
3449 newfselect->resulttypmod,
3450 newfselect->resultcollid))
3451 return ece_evaluate_expr(newfselect);
3452 }
3453 return (Node *) newfselect;
3454 }
3455 case T_NullTest:
3456 {
3457 NullTest *ntest = (NullTest *) node;
3458 NullTest *newntest;
3459 Node *arg;
3460
3462 context);
3463 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3464 {
3465 /*
3466 * We break ROW(...) IS [NOT] NULL into separate tests on
3467 * its component fields. This form is usually more
3468 * efficient to evaluate, as well as being more amenable
3469 * to optimization.
3470 */
3471 RowExpr *rarg = (RowExpr *) arg;
3472 List *newargs = NIL;
3473 ListCell *l;
3474
3475 foreach(l, rarg->args)
3476 {
3477 Node *relem = (Node *) lfirst(l);
3478
3479 /*
3480 * A constant field refutes the whole NullTest if it's
3481 * of the wrong nullness; else we can discard it.
3482 */
3483 if (relem && IsA(relem, Const))
3484 {
3485 Const *carg = (Const *) relem;
3486
3487 if (carg->constisnull ?
3488 (ntest->nulltesttype == IS_NOT_NULL) :
3489 (ntest->nulltesttype == IS_NULL))
3490 return makeBoolConst(false, false);
3491 continue;
3492 }
3493
3494 /*
3495 * Else, make a scalar (argisrow == false) NullTest
3496 * for this field. Scalar semantics are required
3497 * because IS [NOT] NULL doesn't recurse; see comments
3498 * in ExecEvalRowNullInt().
3499 */
3500 newntest = makeNode(NullTest);
3501 newntest->arg = (Expr *) relem;
3502 newntest->nulltesttype = ntest->nulltesttype;
3503 newntest->argisrow = false;
3504 newntest->location = ntest->location;
3505 newargs = lappend(newargs, newntest);
3506 }
3507 /* If all the inputs were constants, result is TRUE */
3508 if (newargs == NIL)
3509 return makeBoolConst(true, false);
3510 /* If only one nonconst input, it's the result */
3511 if (list_length(newargs) == 1)
3512 return (Node *) linitial(newargs);
3513 /* Else we need an AND node */
3514 return (Node *) make_andclause(newargs);
3515 }
3516 if (!ntest->argisrow && arg && IsA(arg, Const))
3517 {
3518 Const *carg = (Const *) arg;
3519 bool result;
3520
3521 switch (ntest->nulltesttype)
3522 {
3523 case IS_NULL:
3524 result = carg->constisnull;
3525 break;
3526 case IS_NOT_NULL:
3527 result = !carg->constisnull;
3528 break;
3529 default:
3530 elog(ERROR, "unrecognized nulltesttype: %d",
3531 (int) ntest->nulltesttype);
3532 result = false; /* keep compiler quiet */
3533 break;
3534 }
3535
3536 return makeBoolConst(result, false);
3537 }
3538
3539 newntest = makeNode(NullTest);
3540 newntest->arg = (Expr *) arg;
3541 newntest->nulltesttype = ntest->nulltesttype;
3542 newntest->argisrow = ntest->argisrow;
3543 newntest->location = ntest->location;
3544 return (Node *) newntest;
3545 }
3546 case T_BooleanTest:
3547 {
3548 /*
3549 * This case could be folded into the generic handling used
3550 * for ArrayExpr etc. But because the simplification logic is
3551 * so trivial, applying evaluate_expr() to perform it would be
3552 * a heavy overhead. BooleanTest is probably common enough to
3553 * justify keeping this bespoke implementation.
3554 */
3555 BooleanTest *btest = (BooleanTest *) node;
3556 BooleanTest *newbtest;
3557 Node *arg;
3558
3560 context);
3561 if (arg && IsA(arg, Const))
3562 {
3563 Const *carg = (Const *) arg;
3564 bool result;
3565
3566 switch (btest->booltesttype)
3567 {
3568 case IS_TRUE:
3569 result = (!carg->constisnull &&
3570 DatumGetBool(carg->constvalue));
3571 break;
3572 case IS_NOT_TRUE:
3573 result = (carg->constisnull ||
3574 !DatumGetBool(carg->constvalue));
3575 break;
3576 case IS_FALSE:
3577 result = (!carg->constisnull &&
3578 !DatumGetBool(carg->constvalue));
3579 break;
3580 case IS_NOT_FALSE:
3581 result = (carg->constisnull ||
3582 DatumGetBool(carg->constvalue));
3583 break;
3584 case IS_UNKNOWN:
3585 result = carg->constisnull;
3586 break;
3587 case IS_NOT_UNKNOWN:
3588 result = !carg->constisnull;
3589 break;
3590 default:
3591 elog(ERROR, "unrecognized booltesttype: %d",
3592 (int) btest->booltesttype);
3593 result = false; /* keep compiler quiet */
3594 break;
3595 }
3596
3597 return makeBoolConst(result, false);
3598 }
3599
3600 newbtest = makeNode(BooleanTest);
3601 newbtest->arg = (Expr *) arg;
3602 newbtest->booltesttype = btest->booltesttype;
3603 newbtest->location = btest->location;
3604 return (Node *) newbtest;
3605 }
3606 case T_CoerceToDomain:
3607 {
3608 /*
3609 * If the domain currently has no constraints, we replace the
3610 * CoerceToDomain node with a simple RelabelType, which is
3611 * both far faster to execute and more amenable to later
3612 * optimization. We must then mark the plan as needing to be
3613 * rebuilt if the domain's constraints change.
3614 *
3615 * Also, in estimation mode, always replace CoerceToDomain
3616 * nodes, effectively assuming that the coercion will succeed.
3617 */
3618 CoerceToDomain *cdomain = (CoerceToDomain *) node;
3619 CoerceToDomain *newcdomain;
3620 Node *arg;
3621
3623 context);
3624 if (context->estimate ||
3626 {
3627 /* Record dependency, if this isn't estimation mode */
3628 if (context->root && !context->estimate)
3630 cdomain->resulttype);
3631
3632 /* Generate RelabelType to substitute for CoerceToDomain */
3633 return applyRelabelType(arg,
3634 cdomain->resulttype,
3635 cdomain->resulttypmod,
3636 cdomain->resultcollid,
3637 cdomain->coercionformat,
3638 cdomain->location,
3639 true);
3640 }
3641
3642 newcdomain = makeNode(CoerceToDomain);
3643 newcdomain->arg = (Expr *) arg;
3644 newcdomain->resulttype = cdomain->resulttype;
3645 newcdomain->resulttypmod = cdomain->resulttypmod;
3646 newcdomain->resultcollid = cdomain->resultcollid;
3647 newcdomain->coercionformat = cdomain->coercionformat;
3648 newcdomain->location = cdomain->location;
3649 return (Node *) newcdomain;
3650 }
3651 case T_PlaceHolderVar:
3652
3653 /*
3654 * In estimation mode, just strip the PlaceHolderVar node
3655 * altogether; this amounts to estimating that the contained value
3656 * won't be forced to null by an outer join. In regular mode we
3657 * just use the default behavior (ie, simplify the expression but
3658 * leave the PlaceHolderVar node intact).
3659 */
3660 if (context->estimate)
3661 {
3662 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3663
3664 return eval_const_expressions_mutator((Node *) phv->phexpr,
3665 context);
3666 }
3667 break;
3668 case T_ConvertRowtypeExpr:
3669 {
3671 Node *arg;
3672 ConvertRowtypeExpr *newcre;
3673
3675 context);
3676
3677 newcre = makeNode(ConvertRowtypeExpr);
3678 newcre->resulttype = cre->resulttype;
3679 newcre->convertformat = cre->convertformat;
3680 newcre->location = cre->location;
3681
3682 /*
3683 * In case of a nested ConvertRowtypeExpr, we can convert the
3684 * leaf row directly to the topmost row format without any
3685 * intermediate conversions. (This works because
3686 * ConvertRowtypeExpr is used only for child->parent
3687 * conversion in inheritance trees, which works by exact match
3688 * of column name, and a column absent in an intermediate
3689 * result can't be present in the final result.)
3690 *
3691 * No need to check more than one level deep, because the
3692 * above recursion will have flattened anything else.
3693 */
3694 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3695 {
3697
3698 arg = (Node *) argcre->arg;
3699
3700 /*
3701 * Make sure an outer implicit conversion can't hide an
3702 * inner explicit one.
3703 */
3704 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3705 newcre->convertformat = argcre->convertformat;
3706 }
3707
3708 newcre->arg = (Expr *) arg;
3709
3710 if (arg != NULL && IsA(arg, Const))
3711 return ece_evaluate_expr((Node *) newcre);
3712 return (Node *) newcre;
3713 }
3714 default:
3715 break;
3716 }
3717
3718 /*
3719 * For any node type not handled above, copy the node unchanged but
3720 * const-simplify its subexpressions. This is the correct thing for node
3721 * types whose behavior might change between planning and execution, such
3722 * as CurrentOfExpr. It's also a safe default for new node types not
3723 * known to this routine.
3724 */
3725 return ece_generic_processing(node);
3726}
#define InvalidAttrNumber
Definition: attnum.h:23
int16_t int16
Definition: c.h:483
int32_t int32
Definition: c.h:484
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition: clauses.c:3792
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition: clauses.c:2186
#define ece_all_arguments_const(node)
Definition: clauses.c:2426
#define ece_evaluate_expr(node)
Definition: clauses.c:2430
#define ece_generic_processing(node)
Definition: clauses.c:2417
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition: clauses.c:3754
static List * simplify_and_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
Definition: clauses.c:3898
static Expr * simplify_function(Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
Definition: clauses.c:4061
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4177
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition: clauses.c:3992
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
List * lappend(List *list, void *datum)
Definition: list.c:339
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2251
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2874
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:696
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:341
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:361
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:680
JsonValueExpr * makeJsonValueExpr(Expr *raw_expr, Expr *formatted_expr, JsonFormat *format)
Definition: makefuncs.c:891
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:303
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition: nodeFuncs.c:636
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1883
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1872
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
#define PARAM_FLAG_CONST
Definition: params.h:88
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define list_make1(x1)
Definition: pg_list.h:212
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
Node * negate_clause(Node *node)
Definition: prepqual.c:73
e
Definition: preproc-init.c:82
@ IS_NOT_TRUE
Definition: primnodes.h:2007
@ IS_NOT_FALSE
Definition: primnodes.h:2007
@ IS_NOT_UNKNOWN
Definition: primnodes.h:2007
@ IS_TRUE
Definition: primnodes.h:2007
@ IS_UNKNOWN
Definition: primnodes.h:2007
@ IS_FALSE
Definition: primnodes.h:2007
@ NOT_EXPR
Definition: primnodes.h:947
@ PARAM_EXTERN
Definition: primnodes.h:383
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:752
@ IS_NULL
Definition: primnodes.h:1983
@ IS_NOT_NULL
Definition: primnodes.h:1983
struct Const Const
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition: setrefs.c:3543
void check_stack_depth(void)
Definition: stack_depth.c:95
List * args
Definition: primnodes.h:956
ParseLoc location
Definition: primnodes.h:2015
BoolTestType booltesttype
Definition: primnodes.h:2014
Expr * arg
Definition: primnodes.h:2013
ParseLoc location
Definition: primnodes.h:1332
Expr * defresult
Definition: primnodes.h:1331
List * args
Definition: primnodes.h:1330
Expr * result
Definition: primnodes.h:1342
Expr * expr
Definition: primnodes.h:1341
ParseLoc location
Definition: primnodes.h:1343
List * args
Definition: primnodes.h:1523
ParseLoc location
Definition: primnodes.h:1525
ParseLoc location
Definition: primnodes.h:2067
Expr * arg
Definition: primnodes.h:1223
ParseLoc location
Definition: primnodes.h:1230
Oid resulttype
Definition: primnodes.h:1224
Expr * arg
Definition: primnodes.h:1295
ParseLoc location
Definition: primnodes.h:1297
AttrNumber fieldnum
Definition: primnodes.h:1145
Expr * arg
Definition: primnodes.h:1144
ParseLoc location
Definition: primnodes.h:786
Oid funcid
Definition: primnodes.h:766
List * args
Definition: primnodes.h:784
Expr * formatted_expr
Definition: primnodes.h:1715
JsonFormat * format
Definition: primnodes.h:1716
Expr * raw_expr
Definition: primnodes.h:1714
NullTestType nulltesttype
Definition: primnodes.h:1990
ParseLoc location
Definition: primnodes.h:1993
Expr * arg
Definition: primnodes.h:1989
ParseLoc location
Definition: primnodes.h:855
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
ParamFetchHook paramFetch
Definition: params.h:112
ParseLoc location
Definition: primnodes.h:400
Oid paramtype
Definition: primnodes.h:394
Oid resulttype
Definition: primnodes.h:1201
ParseLoc location
Definition: primnodes.h:1208
Expr * arg
Definition: primnodes.h:1200
List * args
Definition: primnodes.h:1427
Definition: primnodes.h:261
VarReturningType varreturningtype
Definition: primnodes.h:296
List * args
Definition: primnodes.h:591
Index winref
Definition: primnodes.h:597
Expr * aggfilter
Definition: primnodes.h:593
ParseLoc location
Definition: primnodes.h:603
Oid winfnoid
Definition: primnodes.h:583
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1487

References WindowFunc::aggfilter, AND_EXPR, applyRelabelType(), arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, CoerceToDomain::arg, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, Assert, BoolGetDatum(), BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, castNode, check_stack_depth(), COERCE_IMPLICIT_CAST, CollateExpr::collOid, Const::consttype, contain_mutable_functions(), copyObject, datumCopy(), DatumGetBool(), CaseExpr::defresult, DomainHasConstraints(), ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, ArrayCoerceExpr::elemexpr, elog, ERROR, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator, exprType(), exprTypmod(), FieldSelect::fieldnum, JsonValueExpr::format, JsonValueExpr::formatted_expr, FuncExpr::funcid, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, if(), Int32GetDatum(), InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, ParamExternData::isnull, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), Param::location, WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, ConvertRowtypeExpr::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, CoerceToDomain::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeJsonValueExpr(), makeNode, makeNullConst(), makeVar(), negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum(), OidIsValid, OpExpr::opno, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, ParamExternData::pflags, ParamExternData::ptype, JsonValueExpr::raw_expr, record_plan_type_dependency(), ReleaseSysCache(), CaseWhen::result, RelabelType::resulttype, CoerceViaIO::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, eval_const_expressions_context::root, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), SQLValueFunction::typmod, ParamExternData::value, Var::varreturningtype, WindowFunc::winfnoid, and WindowFunc::winref.

Referenced by estimate_expression_value(), eval_const_expressions(), eval_const_expressions_mutator(), inline_function(), simplify_and_arguments(), simplify_function(), and simplify_or_arguments().

◆ evaluate_expr()

Expr * evaluate_expr ( Expr expr,
Oid  result_type,
int32  result_typmod,
Oid  result_collation 
)

Definition at line 4974 of file clauses.c.

4976{
4977 EState *estate;
4978 ExprState *exprstate;
4979 MemoryContext oldcontext;
4980 Datum const_val;
4981 bool const_is_null;
4982 int16 resultTypLen;
4983 bool resultTypByVal;
4984
4985 /*
4986 * To use the executor, we need an EState.
4987 */
4988 estate = CreateExecutorState();
4989
4990 /* We can use the estate's working context to avoid memory leaks. */
4991 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4992
4993 /* Make sure any opfuncids are filled in. */
4994 fix_opfuncids((Node *) expr);
4995
4996 /*
4997 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4998 * because it'd result in recursively invoking eval_const_expressions.)
4999 */
5000 exprstate = ExecInitExpr(expr, NULL);
5001
5002 /*
5003 * And evaluate it.
5004 *
5005 * It is OK to use a default econtext because none of the ExecEvalExpr()
5006 * code used in this situation will use econtext. That might seem
5007 * fortuitous, but it's not so unreasonable --- a constant expression does
5008 * not depend on context, by definition, n'est ce pas?
5009 */
5010 const_val = ExecEvalExprSwitchContext(exprstate,
5011 GetPerTupleExprContext(estate),
5012 &const_is_null);
5013
5014 /* Get info needed about result datatype */
5015 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
5016
5017 /* Get back to outer memory context */
5018 MemoryContextSwitchTo(oldcontext);
5019
5020 /*
5021 * Must copy result out of sub-context used by expression eval.
5022 *
5023 * Also, if it's varlena, forcibly detoast it. This protects us against
5024 * storing TOAST pointers into plans that might outlive the referenced
5025 * data. (makeConst would handle detoasting anyway, but it's worth a few
5026 * extra lines here so that we can do the copy and detoast in one step.)
5027 */
5028 if (!const_is_null)
5029 {
5030 if (resultTypLen == -1)
5031 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
5032 else
5033 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
5034 }
5035
5036 /* Release all the junk we just created */
5037 FreeExecutorState(estate);
5038
5039 /*
5040 * Make the constant result node.
5041 */
5042 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5043 resultTypLen,
5044 const_val, const_is_null,
5045 resultTypByVal);
5046}
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:143
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:563
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:361
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1841
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
MemoryContext es_query_cxt
Definition: execnodes.h:691

References CreateExecutorState(), datumCopy(), EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fix_opfuncids(), FreeExecutorState(), get_typlenbyval(), GetPerTupleExprContext, makeConst(), MemoryContextSwitchTo(), PG_DETOAST_DATUM_COPY, and PointerGetDatum().

Referenced by eval_const_expressions_mutator(), evaluate_function(), and transformPartitionBoundValue().

◆ evaluate_function()

static Expr * evaluate_function ( Oid  funcid,
Oid  result_type,
int32  result_typmod,
Oid  result_collid,
Oid  input_collid,
List args,
bool  funcvariadic,
HeapTuple  func_tuple,
eval_const_expressions_context context 
)
static

Definition at line 4427 of file clauses.c.

4432{
4433 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4434 bool has_nonconst_input = false;
4435 bool has_null_input = false;
4436 ListCell *arg;
4437 FuncExpr *newexpr;
4438
4439 /*
4440 * Can't simplify if it returns a set.
4441 */
4442 if (funcform->proretset)
4443 return NULL;
4444
4445 /*
4446 * Can't simplify if it returns RECORD. The immediate problem is that it
4447 * will be needing an expected tupdesc which we can't supply here.
4448 *
4449 * In the case where it has OUT parameters, we could build an expected
4450 * tupdesc from those, but there may be other gotchas lurking. In
4451 * particular, if the function were to return NULL, we would produce a
4452 * null constant with no remaining indication of which concrete record
4453 * type it is. For now, seems best to leave the function call unreduced.
4454 */
4455 if (funcform->prorettype == RECORDOID)
4456 return NULL;
4457
4458 /*
4459 * Check for constant inputs and especially constant-NULL inputs.
4460 */
4461 foreach(arg, args)
4462 {
4463 if (IsA(lfirst(arg), Const))
4464 has_null_input |= ((Const *) lfirst(arg))->constisnull;
4465 else
4466 has_nonconst_input = true;
4467 }
4468
4469 /*
4470 * If the function is strict and has a constant-NULL input, it will never
4471 * be called at all, so we can replace the call by a NULL constant, even
4472 * if there are other inputs that aren't constant, and even if the
4473 * function is not otherwise immutable.
4474 */
4475 if (funcform->proisstrict && has_null_input)
4476 return (Expr *) makeNullConst(result_type, result_typmod,
4477 result_collid);
4478
4479 /*
4480 * Otherwise, can simplify only if all inputs are constants. (For a
4481 * non-strict function, constant NULL inputs are treated the same as
4482 * constant non-NULL inputs.)
4483 */
4484 if (has_nonconst_input)
4485 return NULL;
4486
4487 /*
4488 * Ordinarily we are only allowed to simplify immutable functions. But for
4489 * purposes of estimation, we consider it okay to simplify functions that
4490 * are merely stable; the risk that the result might change from planning
4491 * time to execution time is worth taking in preference to not being able
4492 * to estimate the value at all.
4493 */
4494 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4495 /* okay */ ;
4496 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4497 /* okay */ ;
4498 else
4499 return NULL;
4500
4501 /*
4502 * OK, looks like we can simplify this operator/function.
4503 *
4504 * Build a new FuncExpr node containing the already-simplified arguments.
4505 */
4506 newexpr = makeNode(FuncExpr);
4507 newexpr->funcid = funcid;
4508 newexpr->funcresulttype = result_type;
4509 newexpr->funcretset = false;
4510 newexpr->funcvariadic = funcvariadic;
4511 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4512 newexpr->funccollid = result_collid; /* doesn't matter */
4513 newexpr->inputcollid = input_collid;
4514 newexpr->args = args;
4515 newexpr->location = -1;
4516
4517 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4518 result_collid);
4519}
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:750

References arg, generate_unaccent_rules::args, FuncExpr::args, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), FuncExpr::funcid, GETSTRUCT, IsA, lfirst, FuncExpr::location, makeNode, and makeNullConst().

Referenced by simplify_function().

◆ expand_function_arguments()

List * expand_function_arguments ( List args,
bool  include_out_arguments,
Oid  result_type,
HeapTuple  func_tuple 
)

Definition at line 4177 of file clauses.c.

4179{
4180 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4181 Oid *proargtypes = funcform->proargtypes.values;
4182 int pronargs = funcform->pronargs;
4183 bool has_named_args = false;
4184 ListCell *lc;
4185
4186 /*
4187 * If we are asked to match to OUT arguments, then use the proallargtypes
4188 * array (which includes those); otherwise use proargtypes (which
4189 * doesn't). Of course, if proallargtypes is null, we always use
4190 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4191 * considering that we may have nothing to do here, but fortunately the
4192 * common case is include_out_arguments == false.)
4193 */
4194 if (include_out_arguments)
4195 {
4196 Datum proallargtypes;
4197 bool isNull;
4198
4199 proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4200 Anum_pg_proc_proallargtypes,
4201 &isNull);
4202 if (!isNull)
4203 {
4204 ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4205
4206 pronargs = ARR_DIMS(arr)[0];
4207 if (ARR_NDIM(arr) != 1 ||
4208 pronargs < 0 ||
4209 ARR_HASNULL(arr) ||
4210 ARR_ELEMTYPE(arr) != OIDOID)
4211 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4212 Assert(pronargs >= funcform->pronargs);
4213 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4214 }
4215 }
4216
4217 /* Do we have any named arguments? */
4218 foreach(lc, args)
4219 {
4220 Node *arg = (Node *) lfirst(lc);
4221
4222 if (IsA(arg, NamedArgExpr))
4223 {
4224 has_named_args = true;
4225 break;
4226 }
4227 }
4228
4229 /* If so, we must apply reorder_function_arguments */
4230 if (has_named_args)
4231 {
4233 /* Recheck argument types and add casts if needed */
4234 recheck_cast_function_args(args, result_type,
4235 proargtypes, pronargs,
4236 func_tuple);
4237 }
4238 else if (list_length(args) < pronargs)
4239 {
4240 /* No named args, but we seem to be short some defaults */
4241 args = add_function_defaults(args, pronargs, func_tuple);
4242 /* Recheck argument types and add casts if needed */
4243 recheck_cast_function_args(args, result_type,
4244 proargtypes, pronargs,
4245 func_tuple);
4246 }
4247
4248 return args;
4249}
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_HASNULL(a)
Definition: array.h:291
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4328
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4258
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4382
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600

References add_function_defaults(), arg, generate_unaccent_rules::args, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, DatumGetArrayTypeP, elog, ERROR, GETSTRUCT, IsA, lfirst, list_length(), pronargs, recheck_cast_function_args(), reorder_function_arguments(), and SysCacheGetAttr().

Referenced by eval_const_expressions_mutator(), simplify_function(), and transformCallStmt().

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 288 of file clauses.c.

289{
290 if (clause == NULL)
291 return 1.0;
292 if (IsA(clause, FuncExpr))
293 {
294 FuncExpr *expr = (FuncExpr *) clause;
295
296 if (expr->funcretset)
297 return clamp_row_est(get_function_rows(root, expr->funcid, clause));
298 }
299 if (IsA(clause, OpExpr))
300 {
301 OpExpr *expr = (OpExpr *) clause;
302
303 if (expr->opretset)
304 {
305 set_opfuncid(expr);
306 return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
307 }
308 }
309 return 1.0;
310}
double clamp_row_est(double nrows)
Definition: costsize.c:213
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:2170

References clamp_row_est(), FuncExpr::funcid, get_function_rows(), IsA, root, and set_opfuncid().

Referenced by create_set_projection_path(), estimate_num_groups(), and set_function_size_estimates().

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4352 of file clauses.c.

4353{
4354 List *defaults;
4355 Datum proargdefaults;
4356 char *str;
4357
4358 proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4359 Anum_pg_proc_proargdefaults);
4360 str = TextDatumGetCString(proargdefaults);
4361 defaults = castNode(List, stringToNode(str));
4362 pfree(str);
4363 return defaults;
4364}
#define TextDatumGetCString(d)
Definition: builtins.h:98
const char * str
void pfree(void *pointer)
Definition: mcxt.c:1521
void * stringToNode(const char *str)
Definition: read.c:90
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:631

References castNode, pfree(), str, stringToNode(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

Referenced by add_function_defaults(), and reorder_function_arguments().

◆ find_forced_null_var()

Var * find_forced_null_var ( Node node)

Definition at line 1977 of file clauses.c.

1978{
1979 if (node == NULL)
1980 return NULL;
1981 if (IsA(node, NullTest))
1982 {
1983 /* check for var IS NULL */
1984 NullTest *expr = (NullTest *) node;
1985
1986 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1987 {
1988 Var *var = (Var *) expr->arg;
1989
1990 if (var && IsA(var, Var) &&
1991 var->varlevelsup == 0)
1992 return var;
1993 }
1994 }
1995 else if (IsA(node, BooleanTest))
1996 {
1997 /* var IS UNKNOWN is equivalent to var IS NULL */
1998 BooleanTest *expr = (BooleanTest *) node;
1999
2000 if (expr->booltesttype == IS_UNKNOWN)
2001 {
2002 Var *var = (Var *) expr->arg;
2003
2004 if (var && IsA(var, Var) &&
2005 var->varlevelsup == 0)
2006 return var;
2007 }
2008 }
2009 return NULL;
2010}
Index varlevelsup
Definition: primnodes.h:293

References NullTest::arg, BooleanTest::arg, BooleanTest::booltesttype, if(), IS_NULL, IS_UNKNOWN, IsA, NullTest::nulltesttype, and Var::varlevelsup.

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

◆ find_forced_null_vars()

List * find_forced_null_vars ( Node node)

Definition at line 1916 of file clauses.c.

1917{
1918 List *result = NIL;
1919 Var *var;
1920 ListCell *l;
1921
1922 if (node == NULL)
1923 return NIL;
1924 /* Check single-clause cases using subroutine */
1925 var = find_forced_null_var(node);
1926 if (var)
1927 {
1928 result = mbms_add_member(result,
1929 var->varno,
1931 }
1932 /* Otherwise, handle AND-conditions */
1933 else if (IsA(node, List))
1934 {
1935 /*
1936 * At top level, we are examining an implicit-AND list: if any of the
1937 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1938 */
1939 foreach(l, (List *) node)
1940 {
1941 result = mbms_add_members(result,
1943 }
1944 }
1945 else if (IsA(node, BoolExpr))
1946 {
1947 BoolExpr *expr = (BoolExpr *) node;
1948
1949 /*
1950 * We don't bother considering the OR case, because it's fairly
1951 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1952 * the NOT case isn't worth expending code on.
1953 */
1954 if (expr->boolop == AND_EXPR)
1955 {
1956 /* At top level we can just recurse (to the List case) */
1957 result = find_forced_null_vars((Node *) expr->args);
1958 }
1959 }
1960 return result;
1961}
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1916
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1977
List * mbms_add_members(List *a, const List *b)
List * mbms_add_member(List *a, int listidx, int bitidx)
AttrNumber varattno
Definition: primnodes.h:273
int varno
Definition: primnodes.h:268
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References AND_EXPR, BoolExpr::args, BoolExpr::boolop, find_forced_null_var(), find_forced_null_vars(), FirstLowInvalidHeapAttributeNumber, IsA, lfirst, mbms_add_member(), mbms_add_members(), NIL, Var::varattno, and Var::varno.

Referenced by find_forced_null_vars(), and reduce_outer_joins_pass2().

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1456 of file clauses.c.

1457{
1458 return find_nonnullable_rels_walker(clause, true);
1459}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1462

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1462 of file clauses.c.

1463{
1464 Relids result = NULL;
1465 ListCell *l;
1466
1467 if (node == NULL)
1468 return NULL;
1469 if (IsA(node, Var))
1470 {
1471 Var *var = (Var *) node;
1472
1473 if (var->varlevelsup == 0)
1474 result = bms_make_singleton(var->varno);
1475 }
1476 else if (IsA(node, List))
1477 {
1478 /*
1479 * At top level, we are examining an implicit-AND list: if any of the
1480 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1481 * not at top level, we are examining the arguments of a strict
1482 * function: if any of them produce NULL then the result of the
1483 * function must be NULL. So in both cases, the set of nonnullable
1484 * rels is the union of those found in the arms, and we pass down the
1485 * top_level flag unmodified.
1486 */
1487 foreach(l, (List *) node)
1488 {
1489 result = bms_join(result,
1491 top_level));
1492 }
1493 }
1494 else if (IsA(node, FuncExpr))
1495 {
1496 FuncExpr *expr = (FuncExpr *) node;
1497
1498 if (func_strict(expr->funcid))
1499 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1500 }
1501 else if (IsA(node, OpExpr))
1502 {
1503 OpExpr *expr = (OpExpr *) node;
1504
1505 set_opfuncid(expr);
1506 if (func_strict(expr->opfuncid))
1507 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1508 }
1509 else if (IsA(node, ScalarArrayOpExpr))
1510 {
1511 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1512
1513 if (is_strict_saop(expr, true))
1514 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1515 }
1516 else if (IsA(node, BoolExpr))
1517 {
1518 BoolExpr *expr = (BoolExpr *) node;
1519
1520 switch (expr->boolop)
1521 {
1522 case AND_EXPR:
1523 /* At top level we can just recurse (to the List case) */
1524 if (top_level)
1525 {
1526 result = find_nonnullable_rels_walker((Node *) expr->args,
1527 top_level);
1528 break;
1529 }
1530
1531 /*
1532 * Below top level, even if one arm produces NULL, the result
1533 * could be FALSE (hence not NULL). However, if *all* the
1534 * arms produce NULL then the result is NULL, so we can take
1535 * the intersection of the sets of nonnullable rels, just as
1536 * for OR. Fall through to share code.
1537 */
1538 /* FALL THRU */
1539 case OR_EXPR:
1540
1541 /*
1542 * OR is strict if all of its arms are, so we can take the
1543 * intersection of the sets of nonnullable rels for each arm.
1544 * This works for both values of top_level.
1545 */
1546 foreach(l, expr->args)
1547 {
1548 Relids subresult;
1549
1550 subresult = find_nonnullable_rels_walker(lfirst(l),
1551 top_level);
1552 if (result == NULL) /* first subresult? */
1553 result = subresult;
1554 else
1555 result = bms_int_members(result, subresult);
1556
1557 /*
1558 * If the intersection is empty, we can stop looking. This
1559 * also justifies the test for first-subresult above.
1560 */
1561 if (bms_is_empty(result))
1562 break;
1563 }
1564 break;
1565 case NOT_EXPR:
1566 /* NOT will return null if its arg is null */
1567 result = find_nonnullable_rels_walker((Node *) expr->args,
1568 false);
1569 break;
1570 default:
1571 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1572 break;
1573 }
1574 }
1575 else if (IsA(node, RelabelType))
1576 {
1577 RelabelType *expr = (RelabelType *) node;
1578
1579 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1580 }
1581 else if (IsA(node, CoerceViaIO))
1582 {
1583 /* not clear this is useful, but it can't hurt */
1584 CoerceViaIO *expr = (CoerceViaIO *) node;
1585
1586 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1587 }
1588 else if (IsA(node, ArrayCoerceExpr))
1589 {
1590 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1591 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1592
1593 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1594 }
1595 else if (IsA(node, ConvertRowtypeExpr))
1596 {
1597 /* not clear this is useful, but it can't hurt */
1598 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1599
1600 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1601 }
1602 else if (IsA(node, CollateExpr))
1603 {
1604 CollateExpr *expr = (CollateExpr *) node;
1605
1606 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1607 }
1608 else if (IsA(node, NullTest))
1609 {
1610 /* IS NOT NULL can be considered strict, but only at top level */
1611 NullTest *expr = (NullTest *) node;
1612
1613 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1614 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1615 }
1616 else if (IsA(node, BooleanTest))
1617 {
1618 /* Boolean tests that reject NULL are strict at top level */
1619 BooleanTest *expr = (BooleanTest *) node;
1620
1621 if (top_level &&
1622 (expr->booltesttype == IS_TRUE ||
1623 expr->booltesttype == IS_FALSE ||
1624 expr->booltesttype == IS_NOT_UNKNOWN))
1625 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1626 }
1627 else if (IsA(node, SubPlan))
1628 {
1629 SubPlan *splan = (SubPlan *) node;
1630
1631 /*
1632 * For some types of SubPlan, we can infer strictness from Vars in the
1633 * testexpr (the LHS of the original SubLink).
1634 *
1635 * For ANY_SUBLINK, if the subquery produces zero rows, the result is
1636 * always FALSE. If the subquery produces more than one row, the
1637 * per-row results of the testexpr are combined using OR semantics.
1638 * Hence ANY_SUBLINK can be strict only at top level, but there it's
1639 * as strict as the testexpr is.
1640 *
1641 * For ROWCOMPARE_SUBLINK, if the subquery produces zero rows, the
1642 * result is always NULL. Otherwise, the result is as strict as the
1643 * testexpr is. So we can check regardless of top_level.
1644 *
1645 * We can't prove anything for other sublink types (in particular,
1646 * note that ALL_SUBLINK will return TRUE if the subquery is empty).
1647 */
1648 if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1649 splan->subLinkType == ROWCOMPARE_SUBLINK)
1650 result = find_nonnullable_rels_walker(splan->testexpr, top_level);
1651 }
1652 else if (IsA(node, PlaceHolderVar))
1653 {
1654 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1655
1656 /*
1657 * If the contained expression forces any rels non-nullable, so does
1658 * the PHV.
1659 */
1660 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1661
1662 /*
1663 * If the PHV's syntactic scope is exactly one rel, it will be forced
1664 * to be evaluated at that rel, and so it will behave like a Var of
1665 * that rel: if the rel's entire output goes to null, so will the PHV.
1666 * (If the syntactic scope is a join, we know that the PHV will go to
1667 * null if the whole join does; but that is AND semantics while we
1668 * need OR semantics for find_nonnullable_rels' result, so we can't do
1669 * anything with the knowledge.)
1670 */
1671 if (phv->phlevelsup == 0 &&
1672 bms_membership(phv->phrels) == BMS_SINGLETON)
1673 result = bms_add_members(result, phv->phrels);
1674 }
1675 return result;
1676}
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1109
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
#define bms_is_empty(a)
Definition: bitmapset.h:118
@ BMS_SINGLETON
Definition: bitmapset.h:72
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2026
@ ANY_SUBLINK
Definition: primnodes.h:1015
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:1016
static SPIPlanPtr splan
Definition: regress.c:267
Index phlevelsup
Definition: pathnodes.h:2808

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, bms_add_members(), bms_int_members(), bms_is_empty, bms_join(), bms_make_singleton(), bms_membership(), BMS_SINGLETON, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, find_nonnullable_rels_walker(), func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, NOT_EXPR, NullTest::nulltesttype, OR_EXPR, PlaceHolderVar::phlevelsup, ROWCOMPARE_SUBLINK, set_opfuncid(), splan, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels(), and find_nonnullable_rels_walker().

◆ find_nonnullable_vars()

List * find_nonnullable_vars ( Node clause)

Definition at line 1707 of file clauses.c.

1708{
1709 return find_nonnullable_vars_walker(clause, true);
1710}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1713

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

◆ find_nonnullable_vars_walker()

static List * find_nonnullable_vars_walker ( Node node,
bool  top_level 
)
static

Definition at line 1713 of file clauses.c.

1714{
1715 List *result = NIL;
1716 ListCell *l;
1717
1718 if (node == NULL)
1719 return NIL;
1720 if (IsA(node, Var))
1721 {
1722 Var *var = (Var *) node;
1723
1724 if (var->varlevelsup == 0)
1725 result = mbms_add_member(result,
1726 var->varno,
1728 }
1729 else if (IsA(node, List))
1730 {
1731 /*
1732 * At top level, we are examining an implicit-AND list: if any of the
1733 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1734 * not at top level, we are examining the arguments of a strict
1735 * function: if any of them produce NULL then the result of the
1736 * function must be NULL. So in both cases, the set of nonnullable
1737 * vars is the union of those found in the arms, and we pass down the
1738 * top_level flag unmodified.
1739 */
1740 foreach(l, (List *) node)
1741 {
1742 result = mbms_add_members(result,
1744 top_level));
1745 }
1746 }
1747 else if (IsA(node, FuncExpr))
1748 {
1749 FuncExpr *expr = (FuncExpr *) node;
1750
1751 if (func_strict(expr->funcid))
1752 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1753 }
1754 else if (IsA(node, OpExpr))
1755 {
1756 OpExpr *expr = (OpExpr *) node;
1757
1758 set_opfuncid(expr);
1759 if (func_strict(expr->opfuncid))
1760 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1761 }
1762 else if (IsA(node, ScalarArrayOpExpr))
1763 {
1764 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1765
1766 if (is_strict_saop(expr, true))
1767 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1768 }
1769 else if (IsA(node, BoolExpr))
1770 {
1771 BoolExpr *expr = (BoolExpr *) node;
1772
1773 switch (expr->boolop)
1774 {
1775 case AND_EXPR:
1776
1777 /*
1778 * At top level we can just recurse (to the List case), since
1779 * the result should be the union of what we can prove in each
1780 * arm.
1781 */
1782 if (top_level)
1783 {
1784 result = find_nonnullable_vars_walker((Node *) expr->args,
1785 top_level);
1786 break;
1787 }
1788
1789 /*
1790 * Below top level, even if one arm produces NULL, the result
1791 * could be FALSE (hence not NULL). However, if *all* the
1792 * arms produce NULL then the result is NULL, so we can take
1793 * the intersection of the sets of nonnullable vars, just as
1794 * for OR. Fall through to share code.
1795 */
1796 /* FALL THRU */
1797 case OR_EXPR:
1798
1799 /*
1800 * OR is strict if all of its arms are, so we can take the
1801 * intersection of the sets of nonnullable vars for each arm.
1802 * This works for both values of top_level.
1803 */
1804 foreach(l, expr->args)
1805 {
1806 List *subresult;
1807
1808 subresult = find_nonnullable_vars_walker(lfirst(l),
1809 top_level);
1810 if (result == NIL) /* first subresult? */
1811 result = subresult;
1812 else
1813 result = mbms_int_members(result, subresult);
1814
1815 /*
1816 * If the intersection is empty, we can stop looking. This
1817 * also justifies the test for first-subresult above.
1818 */
1819 if (result == NIL)
1820 break;
1821 }
1822 break;
1823 case NOT_EXPR:
1824 /* NOT will return null if its arg is null */
1825 result = find_nonnullable_vars_walker((Node *) expr->args,
1826 false);
1827 break;
1828 default:
1829 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1830 break;
1831 }
1832 }
1833 else if (IsA(node, RelabelType))
1834 {
1835 RelabelType *expr = (RelabelType *) node;
1836
1837 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1838 }
1839 else if (IsA(node, CoerceViaIO))
1840 {
1841 /* not clear this is useful, but it can't hurt */
1842 CoerceViaIO *expr = (CoerceViaIO *) node;
1843
1844 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1845 }
1846 else if (IsA(node, ArrayCoerceExpr))
1847 {
1848 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1849 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1850
1851 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1852 }
1853 else if (IsA(node, ConvertRowtypeExpr))
1854 {
1855 /* not clear this is useful, but it can't hurt */
1856 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1857
1858 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1859 }
1860 else if (IsA(node, CollateExpr))
1861 {
1862 CollateExpr *expr = (CollateExpr *) node;
1863
1864 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1865 }
1866 else if (IsA(node, NullTest))
1867 {
1868 /* IS NOT NULL can be considered strict, but only at top level */
1869 NullTest *expr = (NullTest *) node;
1870
1871 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1872 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1873 }
1874 else if (IsA(node, BooleanTest))
1875 {
1876 /* Boolean tests that reject NULL are strict at top level */
1877 BooleanTest *expr = (BooleanTest *) node;
1878
1879 if (top_level &&
1880 (expr->booltesttype == IS_TRUE ||
1881 expr->booltesttype == IS_FALSE ||
1882 expr->booltesttype == IS_NOT_UNKNOWN))
1883 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1884 }
1885 else if (IsA(node, SubPlan))
1886 {
1887 SubPlan *splan = (SubPlan *) node;
1888
1889 /* See analysis in find_nonnullable_rels_walker */
1890 if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1891 splan->subLinkType == ROWCOMPARE_SUBLINK)
1892 result = find_nonnullable_vars_walker(splan->testexpr, top_level);
1893 }
1894 else if (IsA(node, PlaceHolderVar))
1895 {
1896 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1897
1898 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1899 }
1900 return result;
1901}
List * mbms_int_members(List *a, const List *b)

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, find_nonnullable_vars_walker(), FirstLowInvalidHeapAttributeNumber, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, mbms_add_member(), mbms_add_members(), mbms_int_members(), NIL, NOT_EXPR, NullTest::nulltesttype, OR_EXPR, ROWCOMPARE_SUBLINK, set_opfuncid(), splan, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_vars(), and find_nonnullable_vars_walker().

◆ find_window_functions()

WindowFuncLists * find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 227 of file clauses.c.

228{
229 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
230
231 lists->numWindowFuncs = 0;
232 lists->maxWinRef = maxWinRef;
233 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
234 (void) find_window_functions_walker(clause, lists);
235 return lists;
236}
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:239
void * palloc0(Size size)
Definition: mcxt.c:1347
void * palloc(Size size)
Definition: mcxt.c:1317
List ** windowFuncs
Definition: clauses.h:23
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21

References find_window_functions_walker(), WindowFuncLists::maxWinRef, WindowFuncLists::numWindowFuncs, palloc(), palloc0(), and WindowFuncLists::windowFuncs.

Referenced by grouping_planner().

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 239 of file clauses.c.

240{
241 if (node == NULL)
242 return false;
243 if (IsA(node, WindowFunc))
244 {
245 WindowFunc *wfunc = (WindowFunc *) node;
246
247 /* winref is unsigned, so one-sided test is OK */
248 if (wfunc->winref > lists->maxWinRef)
249 elog(ERROR, "WindowFunc contains out-of-range winref %u",
250 wfunc->winref);
251 /* eliminate duplicates, so that we avoid repeated computation */
252 if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
253 {
254 lists->windowFuncs[wfunc->winref] =
255 lappend(lists->windowFuncs[wfunc->winref], wfunc);
256 lists->numWindowFuncs++;
257 }
258
259 /*
260 * We assume that the parser checked that there are no window
261 * functions in the arguments or filter clause. Hence, we need not
262 * recurse into them. (If either the parser or the planner screws up
263 * on this point, the executor will still catch it; see ExecInitExpr.)
264 */
265 return false;
266 }
267 Assert(!IsA(node, SubLink));
269}
bool list_member(const List *list, const void *datum)
Definition: list.c:661

References Assert, elog, ERROR, expression_tree_walker, find_window_functions_walker(), IsA, lappend(), list_member(), WindowFuncLists::maxWinRef, WindowFuncLists::numWindowFuncs, WindowFuncLists::windowFuncs, and WindowFunc::winref.

Referenced by find_window_functions(), and find_window_functions_walker().

◆ inline_function()

static Expr * inline_function ( Oid  funcid,
Oid  result_type,
Oid  result_collid,
Oid  input_collid,
List args,
bool  funcvariadic,
HeapTuple  func_tuple,
eval_const_expressions_context context 
)
static

Definition at line 4553 of file clauses.c.

4558{
4559 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4560 char *src;
4561 Datum tmp;
4562 bool isNull;
4563 MemoryContext oldcxt;
4564 MemoryContext mycxt;
4565 inline_error_callback_arg callback_arg;
4566 ErrorContextCallback sqlerrcontext;
4567 FuncExpr *fexpr;
4569 TupleDesc rettupdesc;
4570 ParseState *pstate;
4571 List *raw_parsetree_list;
4572 List *querytree_list;
4574 Node *newexpr;
4575 int *usecounts;
4576 ListCell *arg;
4577 int i;
4578
4579 /*
4580 * Forget it if the function is not SQL-language or has other showstopper
4581 * properties. (The prokind and nargs checks are just paranoia.)
4582 */
4583 if (funcform->prolang != SQLlanguageId ||
4584 funcform->prokind != PROKIND_FUNCTION ||
4585 funcform->prosecdef ||
4586 funcform->proretset ||
4587 funcform->prorettype == RECORDOID ||
4588 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4589 funcform->pronargs != list_length(args))
4590 return NULL;
4591
4592 /* Check for recursive function, and give up trying to expand if so */
4593 if (list_member_oid(context->active_fns, funcid))
4594 return NULL;
4595
4596 /* Check permission to call function (fail later, if not) */
4597 if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4598 return NULL;
4599
4600 /* Check whether a plugin wants to hook function entry/exit */
4601 if (FmgrHookIsNeeded(funcid))
4602 return NULL;
4603
4604 /*
4605 * Make a temporary memory context, so that we don't leak all the stuff
4606 * that parsing might create.
4607 */
4609 "inline_function",
4611 oldcxt = MemoryContextSwitchTo(mycxt);
4612
4613 /*
4614 * We need a dummy FuncExpr node containing the already-simplified
4615 * arguments. (In some cases we don't really need it, but building it is
4616 * cheap enough that it's not worth contortions to avoid.)
4617 */
4618 fexpr = makeNode(FuncExpr);
4619 fexpr->funcid = funcid;
4620 fexpr->funcresulttype = result_type;
4621 fexpr->funcretset = false;
4622 fexpr->funcvariadic = funcvariadic;
4623 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4624 fexpr->funccollid = result_collid; /* doesn't matter */
4625 fexpr->inputcollid = input_collid;
4626 fexpr->args = args;
4627 fexpr->location = -1;
4628
4629 /* Fetch the function body */
4630 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4631 src = TextDatumGetCString(tmp);
4632
4633 /*
4634 * Setup error traceback support for ereport(). This is so that we can
4635 * finger the function that bad information came from.
4636 */
4637 callback_arg.proname = NameStr(funcform->proname);
4638 callback_arg.prosrc = src;
4639
4640 sqlerrcontext.callback = sql_inline_error_callback;
4641 sqlerrcontext.arg = &callback_arg;
4642 sqlerrcontext.previous = error_context_stack;
4643 error_context_stack = &sqlerrcontext;
4644
4645 /* If we have prosqlbody, pay attention to that not prosrc */
4646 tmp = SysCacheGetAttr(PROCOID,
4647 func_tuple,
4648 Anum_pg_proc_prosqlbody,
4649 &isNull);
4650 if (!isNull)
4651 {
4652 Node *n;
4653 List *query_list;
4654
4656 if (IsA(n, List))
4657 query_list = linitial_node(List, castNode(List, n));
4658 else
4659 query_list = list_make1(n);
4660 if (list_length(query_list) != 1)
4661 goto fail;
4662 querytree = linitial(query_list);
4663
4664 /*
4665 * Because we'll insist below that the querytree have an empty rtable
4666 * and no sublinks, it cannot have any relation references that need
4667 * to be locked or rewritten. So we can omit those steps.
4668 */
4669 }
4670 else
4671 {
4672 /* Set up to handle parameters while parsing the function body. */
4673 pinfo = prepare_sql_fn_parse_info(func_tuple,
4674 (Node *) fexpr,
4675 input_collid);
4676
4677 /*
4678 * We just do parsing and parse analysis, not rewriting, because
4679 * rewriting will not affect table-free-SELECT-only queries, which is
4680 * all that we care about. Also, we can punt as soon as we detect
4681 * more than one command in the function body.
4682 */
4683 raw_parsetree_list = pg_parse_query(src);
4684 if (list_length(raw_parsetree_list) != 1)
4685 goto fail;
4686
4687 pstate = make_parsestate(NULL);
4688 pstate->p_sourcetext = src;
4689 sql_fn_parser_setup(pstate, pinfo);
4690
4691 querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4692
4693 free_parsestate(pstate);
4694 }
4695
4696 /*
4697 * The single command must be a simple "SELECT expression".
4698 *
4699 * Note: if you change the tests involved in this, see also plpgsql's
4700 * exec_simple_check_plan(). That generally needs to have the same idea
4701 * of what's a "simple expression", so that inlining a function that
4702 * previously wasn't inlined won't change plpgsql's conclusion.
4703 */
4704 if (!IsA(querytree, Query) ||
4705 querytree->commandType != CMD_SELECT ||
4706 querytree->hasAggs ||
4707 querytree->hasWindowFuncs ||
4708 querytree->hasTargetSRFs ||
4709 querytree->hasSubLinks ||
4710 querytree->cteList ||
4711 querytree->rtable ||
4712 querytree->jointree->fromlist ||
4713 querytree->jointree->quals ||
4714 querytree->groupClause ||
4715 querytree->groupingSets ||
4716 querytree->havingQual ||
4717 querytree->windowClause ||
4718 querytree->distinctClause ||
4719 querytree->sortClause ||
4720 querytree->limitOffset ||
4721 querytree->limitCount ||
4722 querytree->setOperations ||
4723 list_length(querytree->targetList) != 1)
4724 goto fail;
4725
4726 /* If the function result is composite, resolve it */
4727 (void) get_expr_result_type((Node *) fexpr,
4728 NULL,
4729 &rettupdesc);
4730
4731 /*
4732 * Make sure the function (still) returns what it's declared to. This
4733 * will raise an error if wrong, but that's okay since the function would
4734 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4735 * a coercion if needed to make the tlist expression match the declared
4736 * type of the function.
4737 *
4738 * Note: we do not try this until we have verified that no rewriting was
4739 * needed; that's probably not important, but let's be careful.
4740 */
4741 querytree_list = list_make1(querytree);
4742 if (check_sql_fn_retval(list_make1(querytree_list),
4743 result_type, rettupdesc,
4744 funcform->prokind,
4745 false, NULL))
4746 goto fail; /* reject whole-tuple-result cases */
4747
4748 /*
4749 * Given the tests above, check_sql_fn_retval shouldn't have decided to
4750 * inject a projection step, but let's just make sure.
4751 */
4752 if (querytree != linitial(querytree_list))
4753 goto fail;
4754
4755 /* Now we can grab the tlist expression */
4756 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4757
4758 /*
4759 * If the SQL function returns VOID, we can only inline it if it is a
4760 * SELECT of an expression returning VOID (ie, it's just a redirection to
4761 * another VOID-returning function). In all non-VOID-returning cases,
4762 * check_sql_fn_retval should ensure that newexpr returns the function's
4763 * declared result type, so this test shouldn't fail otherwise; but we may
4764 * as well cope gracefully if it does.
4765 */
4766 if (exprType(newexpr) != result_type)
4767 goto fail;
4768
4769 /*
4770 * Additional validity checks on the expression. It mustn't be more
4771 * volatile than the surrounding function (this is to avoid breaking hacks
4772 * that involve pretending a function is immutable when it really ain't).
4773 * If the surrounding function is declared strict, then the expression
4774 * must contain only strict constructs and must use all of the function
4775 * parameters (this is overkill, but an exact analysis is hard).
4776 */
4777 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4779 goto fail;
4780 else if (funcform->provolatile == PROVOLATILE_STABLE &&
4782 goto fail;
4783
4784 if (funcform->proisstrict &&
4786 goto fail;
4787
4788 /*
4789 * If any parameter expression contains a context-dependent node, we can't
4790 * inline, for fear of putting such a node into the wrong context.
4791 */
4793 goto fail;
4794
4795 /*
4796 * We may be able to do it; there are still checks on parameter usage to
4797 * make, but those are most easily done in combination with the actual
4798 * substitution of the inputs. So start building expression with inputs
4799 * substituted.
4800 */
4801 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4802 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4803 args, usecounts);
4804
4805 /* Now check for parameter usage */
4806 i = 0;
4807 foreach(arg, args)
4808 {
4809 Node *param = lfirst(arg);
4810
4811 if (usecounts[i] == 0)
4812 {
4813 /* Param not used at all: uncool if func is strict */
4814 if (funcform->proisstrict)
4815 goto fail;
4816 }
4817 else if (usecounts[i] != 1)
4818 {
4819 /* Param used multiple times: uncool if expensive or volatile */
4820 QualCost eval_cost;
4821
4822 /*
4823 * We define "expensive" as "contains any subplan or more than 10
4824 * operators". Note that the subplan search has to be done
4825 * explicitly, since cost_qual_eval() will barf on unplanned
4826 * subselects.
4827 */
4828 if (contain_subplans(param))
4829 goto fail;
4830 cost_qual_eval(&eval_cost, list_make1(param), NULL);
4831 if (eval_cost.startup + eval_cost.per_tuple >
4832 10 * cpu_operator_cost)
4833 goto fail;
4834
4835 /*
4836 * Check volatility last since this is more expensive than the
4837 * above tests
4838 */
4839 if (contain_volatile_functions(param))
4840 goto fail;
4841 }
4842 i++;
4843 }
4844
4845 /*
4846 * Whew --- we can make the substitution. Copy the modified expression
4847 * out of the temporary memory context, and clean up.
4848 */
4849 MemoryContextSwitchTo(oldcxt);
4850
4851 newexpr = copyObject(newexpr);
4852
4853 MemoryContextDelete(mycxt);
4854
4855 /*
4856 * If the result is of a collatable type, force the result to expose the
4857 * correct collation. In most cases this does not matter, but it's
4858 * possible that the function result is used directly as a sort key or in
4859 * other places where we expect exprCollation() to tell the truth.
4860 */
4861 if (OidIsValid(result_collid))
4862 {
4863 Oid exprcoll = exprCollation(newexpr);
4864
4865 if (OidIsValid(exprcoll) && exprcoll != result_collid)
4866 {
4867 CollateExpr *newnode = makeNode(CollateExpr);
4868
4869 newnode->arg = (Expr *) newexpr;
4870 newnode->collOid = result_collid;
4871 newnode->location = -1;
4872
4873 newexpr = (Node *) newnode;
4874 }
4875 }
4876
4877 /*
4878 * Since there is now no trace of the function in the plan tree, we must
4879 * explicitly record the plan's dependency on the function.
4880 */
4881 if (context->root)
4882 record_plan_function_dependency(context->root, funcid);
4883
4884 /*
4885 * Recursively try to simplify the modified expression. Here we must add
4886 * the current function to the context list of active functions.
4887 */
4888 context->active_fns = lappend_oid(context->active_fns, funcid);
4889 newexpr = eval_const_expressions_mutator(newexpr, context);
4890 context->active_fns = list_delete_last(context->active_fns);
4891
4892 error_context_stack = sqlerrcontext.previous;
4893
4894 return (Expr *) newexpr;
4895
4896 /* Here if func is not inlinable: release temp memory and return NULL */
4897fail:
4898 MemoryContextSwitchTo(oldcxt);
4899 MemoryContextDelete(mycxt);
4900 error_context_stack = sqlerrcontext.previous;
4901
4902 return NULL;
4903}
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3804
#define NameStr(name)
Definition: c.h:703
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4909
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4950
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1178
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:992
bool contain_subplans(Node *clause)
Definition: clauses.c:329
double cpu_operator_cost
Definition: costsize.c:134
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4732
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:796
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:299
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, char prokind, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1609
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:456
int i
Definition: isn.c:72
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_delete_last(List *list)
Definition: list.c:957
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
Oid GetUserId(void)
Definition: miscinit.c:517
@ CMD_SELECT
Definition: nodes.h:265
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
#define ACL_EXECUTE
Definition: parsenodes.h:83
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:332
#define linitial_node(type, l)
Definition: pg_list.h:181
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3503
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
const char * p_sourcetext
Definition: parse_node.h:209
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, CollateExpr::arg, ErrorContextCallback::arg, generate_unaccent_rules::args, FuncExpr::args, ErrorContextCallback::callback, castNode, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, CurrentMemoryContext, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FuncExpr::funcid, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), i, IsA, lappend_oid(), lfirst, linitial, linitial_node, list_delete_last(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, sql_fn_parser_setup(), sql_inline_error_callback(), QualCost::startup, stringToNode(), substitute_actual_parameters(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and transformTopLevelStmt().

Referenced by simplify_function().

◆ inline_set_returning_function()

Query * inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 5066 of file clauses.c.

5067{
5068 RangeTblFunction *rtfunc;
5069 FuncExpr *fexpr;
5070 Oid func_oid;
5071 HeapTuple func_tuple;
5072 Form_pg_proc funcform;
5073 char *src;
5074 Datum tmp;
5075 bool isNull;
5076 MemoryContext oldcxt;
5077 MemoryContext mycxt;
5078 inline_error_callback_arg callback_arg;
5079 ErrorContextCallback sqlerrcontext;
5081 TypeFuncClass functypclass;
5082 TupleDesc rettupdesc;
5083 List *raw_parsetree_list;
5084 List *querytree_list;
5086
5087 Assert(rte->rtekind == RTE_FUNCTION);
5088
5089 /*
5090 * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
5091 * own FROM clause, since that must cause infinite recursion at runtime.
5092 * It will cause this code to recurse too, so check for stack overflow.
5093 * (There's no need to do more.)
5094 */
5096
5097 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5098 if (rte->funcordinality)
5099 return NULL;
5100
5101 /* Fail if RTE isn't a single, simple FuncExpr */
5102 if (list_length(rte->functions) != 1)
5103 return NULL;
5104 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5105
5106 if (!IsA(rtfunc->funcexpr, FuncExpr))
5107 return NULL;
5108 fexpr = (FuncExpr *) rtfunc->funcexpr;
5109
5110 func_oid = fexpr->funcid;
5111
5112 /*
5113 * The function must be declared to return a set, else inlining would
5114 * change the results if the contained SELECT didn't return exactly one
5115 * row.
5116 */
5117 if (!fexpr->funcretset)
5118 return NULL;
5119
5120 /*
5121 * Refuse to inline if the arguments contain any volatile functions or
5122 * sub-selects. Volatile functions are rejected because inlining may
5123 * result in the arguments being evaluated multiple times, risking a
5124 * change in behavior. Sub-selects are rejected partly for implementation
5125 * reasons (pushing them down another level might change their behavior)
5126 * and partly because they're likely to be expensive and so multiple
5127 * evaluation would be bad.
5128 */
5129 if (contain_volatile_functions((Node *) fexpr->args) ||
5130 contain_subplans((Node *) fexpr->args))
5131 return NULL;
5132
5133 /* Check permission to call function (fail later, if not) */
5134 if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5135 return NULL;
5136
5137 /* Check whether a plugin wants to hook function entry/exit */
5138 if (FmgrHookIsNeeded(func_oid))
5139 return NULL;
5140
5141 /*
5142 * OK, let's take a look at the function's pg_proc entry.
5143 */
5144 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5145 if (!HeapTupleIsValid(func_tuple))
5146 elog(ERROR, "cache lookup failed for function %u", func_oid);
5147 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5148
5149 /*
5150 * Forget it if the function is not SQL-language or has other showstopper
5151 * properties. In particular it mustn't be declared STRICT, since we
5152 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5153 * supposed to cause it to be executed with its own snapshot, rather than
5154 * sharing the snapshot of the calling query. We also disallow returning
5155 * SETOF VOID, because inlining would result in exposing the actual result
5156 * of the function's last SELECT, which should not happen in that case.
5157 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5158 */
5159 if (funcform->prolang != SQLlanguageId ||
5160 funcform->prokind != PROKIND_FUNCTION ||
5161 funcform->proisstrict ||
5162 funcform->provolatile == PROVOLATILE_VOLATILE ||
5163 funcform->prorettype == VOIDOID ||
5164 funcform->prosecdef ||
5165 !funcform->proretset ||
5166 list_length(fexpr->args) != funcform->pronargs ||
5167 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5168 {
5169 ReleaseSysCache(func_tuple);
5170 return NULL;
5171 }
5172
5173 /*
5174 * Make a temporary memory context, so that we don't leak all the stuff
5175 * that parsing might create.
5176 */
5178 "inline_set_returning_function",
5180 oldcxt = MemoryContextSwitchTo(mycxt);
5181
5182 /* Fetch the function body */
5183 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5184 src = TextDatumGetCString(tmp);
5185
5186 /*
5187 * Setup error traceback support for ereport(). This is so that we can
5188 * finger the function that bad information came from.
5189 */
5190 callback_arg.proname = NameStr(funcform->proname);
5191 callback_arg.prosrc = src;
5192
5193 sqlerrcontext.callback = sql_inline_error_callback;
5194 sqlerrcontext.arg = &callback_arg;
5195 sqlerrcontext.previous = error_context_stack;
5196 error_context_stack = &sqlerrcontext;
5197
5198 /* If we have prosqlbody, pay attention to that not prosrc */
5199 tmp = SysCacheGetAttr(PROCOID,
5200 func_tuple,
5201 Anum_pg_proc_prosqlbody,
5202 &isNull);
5203 if (!isNull)
5204 {
5205 Node *n;
5206
5208 if (IsA(n, List))
5209 querytree_list = linitial_node(List, castNode(List, n));
5210 else
5211 querytree_list = list_make1(n);
5212 if (list_length(querytree_list) != 1)
5213 goto fail;
5214 querytree = linitial(querytree_list);
5215
5216 /* Acquire necessary locks, then apply rewriter. */
5217 AcquireRewriteLocks(querytree, true, false);
5218 querytree_list = pg_rewrite_query(querytree);
5219 if (list_length(querytree_list) != 1)
5220 goto fail;
5221 querytree = linitial(querytree_list);
5222 }
5223 else
5224 {
5225 /*
5226 * Set up to handle parameters while parsing the function body. We
5227 * can use the FuncExpr just created as the input for
5228 * prepare_sql_fn_parse_info.
5229 */
5230 pinfo = prepare_sql_fn_parse_info(func_tuple,
5231 (Node *) fexpr,
5232 fexpr->inputcollid);
5233
5234 /*
5235 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5236 * skip rewriting here). We can fail as soon as we find more than one
5237 * query, though.
5238 */
5239 raw_parsetree_list = pg_parse_query(src);
5240 if (list_length(raw_parsetree_list) != 1)
5241 goto fail;
5242
5243 querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5244 src,
5246 pinfo, NULL);
5247 if (list_length(querytree_list) != 1)
5248 goto fail;
5249 querytree = linitial(querytree_list);
5250 }
5251
5252 /*
5253 * Also resolve the actual function result tupdesc, if composite. If we
5254 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5255 * (This logic should match ExecInitFunctionScan.)
5256 */
5257 if (rtfunc->funccolnames != NIL)
5258 {
5259 functypclass = TYPEFUNC_RECORD;
5260 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5261 rtfunc->funccoltypes,
5262 rtfunc->funccoltypmods,
5263 rtfunc->funccolcollations);
5264 }
5265 else
5266 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5267
5268 /*
5269 * The single command must be a plain SELECT.
5270 */
5271 if (!IsA(querytree, Query) ||
5272 querytree->commandType != CMD_SELECT)
5273 goto fail;
5274
5275 /*
5276 * Make sure the function (still) returns what it's declared to. This
5277 * will raise an error if wrong, but that's okay since the function would
5278 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5279 * coercions if needed to make the tlist expression(s) match the declared
5280 * type of the function. We also ask it to insert dummy NULL columns for
5281 * any dropped columns in rettupdesc, so that the elements of the modified
5282 * tlist match up to the attribute numbers.
5283 *
5284 * If the function returns a composite type, don't inline unless the check
5285 * shows it's returning a whole tuple result; otherwise what it's
5286 * returning is a single composite column which is not what we need.
5287 */
5288 if (!check_sql_fn_retval(list_make1(querytree_list),
5289 fexpr->funcresulttype, rettupdesc,
5290 funcform->prokind,
5291 true, NULL) &&
5292 (functypclass == TYPEFUNC_COMPOSITE ||
5293 functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5294 functypclass == TYPEFUNC_RECORD))
5295 goto fail; /* reject not-whole-tuple-result cases */
5296
5297 /*
5298 * check_sql_fn_retval might've inserted a projection step, but that's
5299 * fine; just make sure we use the upper Query.
5300 */
5301 querytree = linitial_node(Query, querytree_list);
5302
5303 /*
5304 * Looks good --- substitute parameters into the query.
5305 */
5307 funcform->pronargs,
5308 fexpr->args);
5309
5310 /*
5311 * Copy the modified query out of the temporary memory context, and clean
5312 * up.
5313 */
5314 MemoryContextSwitchTo(oldcxt);
5315
5317
5318 MemoryContextDelete(mycxt);
5319 error_context_stack = sqlerrcontext.previous;
5320 ReleaseSysCache(func_tuple);
5321
5322 /*
5323 * We don't have to fix collations here because the upper query is already
5324 * parsed, ie, the collations in the RTE are what count.
5325 */
5326
5327 /*
5328 * Since there is now no trace of the function in the plan tree, we must
5329 * explicitly record the plan's dependency on the function.
5330 */
5332
5333 /*
5334 * We must also notice if the inserted query adds a dependency on the
5335 * calling role due to RLS quals.
5336 */
5337 if (querytree->hasRowSecurity)
5338 root->glob->dependsOnRole = true;
5339
5340 return querytree;
5341
5342 /* Here if func is not inlinable: release temp memory and return NULL */
5343fail:
5344 MemoryContextSwitchTo(oldcxt);
5345 MemoryContextDelete(mycxt);
5346 error_context_stack = sqlerrcontext.previous;
5347 ReleaseSysCache(func_tuple);
5348
5349 return NULL;
5350}
static Query * substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
Definition: clauses.c:5359
TypeFuncClass
Definition: funcapi.h:147
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_RECORD
Definition: funcapi.h:151
@ TYPEFUNC_COMPOSITE_DOMAIN
Definition: funcapi.h:150
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
@ RTE_FUNCTION
Definition: parsenodes.h:1029
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:757
List * pg_rewrite_query(Query *query)
Definition: postgres.c:797
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
bool funcordinality
Definition: parsenodes.h:1188
List * functions
Definition: parsenodes.h:1186
RTEKind rtekind
Definition: parsenodes.h:1056
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition: tupdesc.c:1007

References ACL_EXECUTE, ACLCHECK_OK, AcquireRewriteLocks(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert, BuildDescFromLists(), ErrorContextCallback::callback, castNode, check_sql_fn_retval(), check_stack_depth(), CMD_SELECT, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, elog, ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), HeapTupleIsValid, if(), IsA, linitial, linitial_node, list_length(), list_make1, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, NIL, object_aclcheck(), ObjectIdGetDatum(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), root, RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), stringToNode(), substitute_actual_srf_parameters(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by preprocess_function_rtes().

◆ is_parallel_safe()

bool is_parallel_safe ( PlannerInfo root,
Node node 
)

Definition at line 752 of file clauses.c.

753{
755 PlannerInfo *proot;
756 ListCell *l;
757
758 /*
759 * Even if the original querytree contained nothing unsafe, we need to
760 * search the expression if we have generated any PARAM_EXEC Params while
761 * planning, because those are parallel-restricted and there might be one
762 * in this expression. But otherwise we don't need to look.
763 */
764 if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
765 root->glob->paramExecTypes == NIL)
766 return true;
767 /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
768 context.max_hazard = PROPARALLEL_SAFE;
769 context.max_interesting = PROPARALLEL_RESTRICTED;
770 context.safe_param_ids = NIL;
771
772 /*
773 * The params that refer to the same or parent query level are considered
774 * parallel-safe. The idea is that we compute such params at Gather or
775 * Gather Merge node and pass their value to workers.
776 */
777 for (proot = root; proot != NULL; proot = proot->parent_root)
778 {
779 foreach(l, proot->init_plans)
780 {
781 SubPlan *initsubplan = (SubPlan *) lfirst(l);
782
783 context.safe_param_ids = list_concat(context.safe_param_ids,
784 initsubplan->setParam);
785 }
786 }
787
788 return !max_parallel_hazard_walker(node, &context);
789}
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition: clauses.c:828
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * init_plans
Definition: pathnodes.h:299
List * setParam
Definition: primnodes.h:1104

References PlannerInfo::init_plans, lfirst, list_concat(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_context::max_interesting, max_parallel_hazard_walker(), NIL, root, max_parallel_hazard_context::safe_param_ids, and SubPlan::setParam.

Referenced by apply_projection_to_path(), build_join_rel(), create_minmaxagg_path(), create_projection_path(), create_set_projection_path(), create_window_paths(), find_computable_ec_member(), grouping_planner(), make_grouping_rel(), plan_create_index_workers(), query_planner(), relation_can_be_sorted_early(), and set_rel_consider_parallel().

◆ is_pseudo_constant_clause()

bool is_pseudo_constant_clause ( Node clause)

Definition at line 2088 of file clauses.c.

2089{
2090 /*
2091 * We could implement this check in one recursive scan. But since the
2092 * check for volatile functions is both moderately expensive and unlikely
2093 * to fail, it seems better to look for Vars first and only check for
2094 * volatile functions if we find no Vars.
2095 */
2096 if (!contain_var_clause(clause) &&
2098 return true;
2099 return false;
2100}

References contain_var_clause(), and contain_volatile_functions().

Referenced by clauselist_selectivity_ext(), dependency_is_compatible_clause(), dependency_is_compatible_expression(), and find_window_run_conditions().

◆ is_pseudo_constant_clause_relids()

bool is_pseudo_constant_clause_relids ( Node clause,
Relids  relids 
)

Definition at line 2108 of file clauses.c.

2109{
2110 if (bms_is_empty(relids) &&
2112 return true;
2113 return false;
2114}

References bms_is_empty, and contain_volatile_functions().

Referenced by clauselist_selectivity_ext().

◆ is_strict_saop()

static bool is_strict_saop ( ScalarArrayOpExpr expr,
bool  falseOK 
)
static

Definition at line 2026 of file clauses.c.

2027{
2028 Node *rightop;
2029
2030 /* The contained operator must be strict. */
2031 set_sa_opfuncid(expr);
2032 if (!func_strict(expr->opfuncid))
2033 return false;
2034 /* If ANY and falseOK, that's all we need to check. */
2035 if (expr->useOr && falseOK)
2036 return true;
2037 /* Else, we have to see if the array is provably non-empty. */
2038 Assert(list_length(expr->args) == 2);
2039 rightop = (Node *) lsecond(expr->args);
2040 if (rightop && IsA(rightop, Const))
2041 {
2042 Datum arraydatum = ((Const *) rightop)->constvalue;
2043 bool arrayisnull = ((Const *) rightop)->constisnull;
2044 ArrayType *arrayval;
2045 int nitems;
2046
2047 if (arrayisnull)
2048 return false;
2049 arrayval = DatumGetArrayTypeP(arraydatum);
2050 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2051 if (nitems > 0)
2052 return true;
2053 }
2054 else if (rightop && IsA(rightop, ArrayExpr))
2055 {
2056 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2057
2058 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2059 return true;
2060 }
2061 return false;
2062}
List * elements
Definition: primnodes.h:1396

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), Assert, DatumGetArrayTypeP, ArrayExpr::elements, func_strict(), IsA, list_length(), lsecond, NIL, nitems, set_sa_opfuncid(), and ScalarArrayOpExpr::useOr.

Referenced by find_nonnullable_rels_walker(), and find_nonnullable_vars_walker().

◆ max_parallel_hazard()

char max_parallel_hazard ( Query parse)

Definition at line 733 of file clauses.c.

734{
736
737 context.max_hazard = PROPARALLEL_SAFE;
738 context.max_interesting = PROPARALLEL_UNSAFE;
739 context.safe_param_ids = NIL;
740 (void) max_parallel_hazard_walker((Node *) parse, &context);
741 return context.max_hazard;
742}
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717

References max_parallel_hazard_context::max_hazard, max_parallel_hazard_context::max_interesting, max_parallel_hazard_walker(), NIL, parse(), and max_parallel_hazard_context::safe_param_ids.

Referenced by standard_planner().

◆ max_parallel_hazard_checker()

static bool max_parallel_hazard_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 821 of file clauses.c.

822{
824 (max_parallel_hazard_context *) context);
825}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:793
char func_parallel(Oid funcid)
Definition: lsyscache.c:1799

References func_parallel(), and max_parallel_hazard_test().

Referenced by max_parallel_hazard_walker().

◆ max_parallel_hazard_test()

static bool max_parallel_hazard_test ( char  proparallel,
max_parallel_hazard_context context 
)
static

Definition at line 793 of file clauses.c.

794{
795 switch (proparallel)
796 {
797 case PROPARALLEL_SAFE:
798 /* nothing to see here, move along */
799 break;
800 case PROPARALLEL_RESTRICTED:
801 /* increase max_hazard to RESTRICTED */
802 Assert(context->max_hazard != PROPARALLEL_UNSAFE);
803 context->max_hazard = proparallel;
804 /* done if we are not expecting any unsafe functions */
805 if (context->max_interesting == proparallel)
806 return true;
807 break;
808 case PROPARALLEL_UNSAFE:
809 context->max_hazard = proparallel;
810 /* we're always done at the first unsafe construct */
811 return true;
812 default:
813 elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
814 break;
815 }
816 return false;
817}

References Assert, elog, ERROR, max_parallel_hazard_context::max_hazard, and max_parallel_hazard_context::max_interesting.

Referenced by max_parallel_hazard_checker(), and max_parallel_hazard_walker().

◆ max_parallel_hazard_walker()

static bool max_parallel_hazard_walker ( Node node,
max_parallel_hazard_context context 
)
static

Definition at line 828 of file clauses.c.

829{
830 if (node == NULL)
831 return false;
832
833 /* Check for hazardous functions in node itself */
835 context))
836 return true;
837
838 /*
839 * It should be OK to treat MinMaxExpr as parallel-safe, since btree
840 * opclass support functions are generally parallel-safe. XmlExpr is a
841 * bit more dubious but we can probably get away with it. We err on the
842 * side of caution by treating CoerceToDomain as parallel-restricted.
843 * (Note: in principle that's wrong because a domain constraint could
844 * contain a parallel-unsafe function; but useful constraints probably
845 * never would have such, and assuming they do would cripple use of
846 * parallel query in the presence of domain types.) SQLValueFunction
847 * should be safe in all cases. NextValueExpr is parallel-unsafe.
848 */
849 if (IsA(node, CoerceToDomain))
850 {
851 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
852 return true;
853 }
854
855 else if (IsA(node, NextValueExpr))
856 {
857 if (max_parallel_hazard_test(PROPARALLEL_UNSAFE, context))
858 return true;
859 }
860
861 /*
862 * Treat window functions as parallel-restricted because we aren't sure
863 * whether the input row ordering is fully deterministic, and the output
864 * of window functions might vary across workers if not. (In some cases,
865 * like where the window frame orders by a primary key, we could relax
866 * this restriction. But it doesn't currently seem worth expending extra
867 * effort to do so.)
868 */
869 else if (IsA(node, WindowFunc))
870 {
871 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
872 return true;
873 }
874
875 /*
876 * As a notational convenience for callers, look through RestrictInfo.
877 */
878 else if (IsA(node, RestrictInfo))
879 {
880 RestrictInfo *rinfo = (RestrictInfo *) node;
881
882 return max_parallel_hazard_walker((Node *) rinfo->clause, context);
883 }
884
885 /*
886 * Really we should not see SubLink during a max_interesting == restricted
887 * scan, but if we do, return true.
888 */
889 else if (IsA(node, SubLink))
890 {
891 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
892 return true;
893 }
894
895 /*
896 * Only parallel-safe SubPlans can be sent to workers. Within the
897 * testexpr of the SubPlan, Params representing the output columns of the
898 * subplan can be treated as parallel-safe, so temporarily add their IDs
899 * to the safe_param_ids list while examining the testexpr.
900 */
901 else if (IsA(node, SubPlan))
902 {
903 SubPlan *subplan = (SubPlan *) node;
904 List *save_safe_param_ids;
905
906 if (!subplan->parallel_safe &&
907 max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
908 return true;
909 save_safe_param_ids = context->safe_param_ids;
911 subplan->paramIds);
912 if (max_parallel_hazard_walker(subplan->testexpr, context))
913 return true; /* no need to restore safe_param_ids */
914 list_free(context->safe_param_ids);
915 context->safe_param_ids = save_safe_param_ids;
916 /* we must also check args, but no special Param treatment there */
917 if (max_parallel_hazard_walker((Node *) subplan->args, context))
918 return true;
919 /* don't want to recurse normally, so we're done */
920 return false;
921 }
922
923 /*
924 * We can't pass Params to workers at the moment either, so they are also
925 * parallel-restricted, unless they are PARAM_EXTERN Params or are
926 * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
927 * either generated within workers or can be computed by the leader and
928 * then their value can be passed to workers.
929 */
930 else if (IsA(node, Param))
931 {
932 Param *param = (Param *) node;
933
934 if (param->paramkind == PARAM_EXTERN)
935 return false;
936
937 if (param->paramkind != PARAM_EXEC ||
938 !list_member_int(context->safe_param_ids, param->paramid))
939 {
940 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
941 return true;
942 }
943 return false; /* nothing to recurse to */
944 }
945
946 /*
947 * When we're first invoked on a completely unplanned tree, we must
948 * recurse into subqueries so to as to locate parallel-unsafe constructs
949 * anywhere in the tree.
950 */
951 else if (IsA(node, Query))
952 {
953 Query *query = (Query *) node;
954
955 /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
956 if (query->rowMarks != NULL)
957 {
958 context->max_hazard = PROPARALLEL_UNSAFE;
959 return true;
960 }
961
962 /* Recurse into subselects */
963 return query_tree_walker(query,
965 context, 0);
966 }
967
968 /* Recurse to check arguments */
969 return expression_tree_walker(node,
971 context);
972}
static bool max_parallel_hazard_checker(Oid func_id, void *context)
Definition: clauses.c:821
void list_free(List *list)
Definition: list.c:1546
List * rowMarks
Definition: parsenodes.h:228
List * args
Definition: primnodes.h:1107
List * paramIds
Definition: primnodes.h:1084
Node * testexpr
Definition: primnodes.h:1083
bool parallel_safe
Definition: primnodes.h:1100

References SubPlan::args, check_functions_in_node(), RestrictInfo::clause, expression_tree_walker, IsA, list_concat_copy(), list_free(), list_member_int(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_checker(), max_parallel_hazard_test(), max_parallel_hazard_walker(), SubPlan::parallel_safe, PARAM_EXEC, PARAM_EXTERN, Param::paramid, SubPlan::paramIds, Param::paramkind, query_tree_walker, Query::rowMarks, max_parallel_hazard_context::safe_param_ids, and SubPlan::testexpr.

Referenced by is_parallel_safe(), max_parallel_hazard(), and max_parallel_hazard_walker().

◆ NumRelids()

int NumRelids ( PlannerInfo root,
Node clause 
)

Definition at line 2130 of file clauses.c.

2131{
2132 int result;
2133 Relids varnos = pull_varnos(root, clause);
2134
2135 varnos = bms_del_members(varnos, root->outer_join_rels);
2136 result = bms_num_members(varnos);
2137 bms_free(varnos);
2138 return result;
2139}
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1161
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114

References bms_del_members(), bms_free(), bms_num_members(), pull_varnos(), and root.

Referenced by clauselist_selectivity_ext(), rowcomparesel(), and treat_as_join_clause().

◆ pull_paramids()

Bitmapset * pull_paramids ( Expr expr)

Definition at line 5419 of file clauses.c.

5420{
5421 Bitmapset *result = NULL;
5422
5423 (void) pull_paramids_walker((Node *) expr, &result);
5424
5425 return result;
5426}
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition: clauses.c:5429

References pull_paramids_walker().

Referenced by create_memoize_plan().

◆ pull_paramids_walker()

static bool pull_paramids_walker ( Node node,
Bitmapset **  context 
)
static

Definition at line 5429 of file clauses.c.

5430{
5431 if (node == NULL)
5432 return false;
5433 if (IsA(node, Param))
5434 {
5435 Param *param = (Param *) node;
5436
5437 *context = bms_add_member(*context, param->paramid);
5438 return false;
5439 }
5440 return expression_tree_walker(node, pull_paramids_walker, context);
5441}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815

References bms_add_member(), expression_tree_walker, IsA, Param::paramid, and pull_paramids_walker().

Referenced by pull_paramids(), and pull_paramids_walker().

◆ recheck_cast_function_args()

static void recheck_cast_function_args ( List args,
Oid  result_type,
Oid proargtypes,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 4382 of file clauses.c.

4385{
4386 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4387 int nargs;
4388 Oid actual_arg_types[FUNC_MAX_ARGS];
4389 Oid declared_arg_types[FUNC_MAX_ARGS];
4390 Oid rettype;
4391 ListCell *lc;
4392
4394 elog(ERROR, "too many function arguments");
4395 nargs = 0;
4396 foreach(lc, args)
4397 {
4398 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4399 }
4400 Assert(nargs == pronargs);
4401 memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4402 rettype = enforce_generic_type_consistency(actual_arg_types,
4403 declared_arg_types,
4404 nargs,
4405 funcform->prorettype,
4406 false);
4407 /* let's just check we got the same answer as the parser did ... */
4408 if (rettype != result_type)
4409 elog(ERROR, "function's resolved result type changed during planning");
4410
4411 /* perform any necessary typecasting of arguments */
4412 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4413}
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1825
#define FUNC_MAX_ARGS

References generate_unaccent_rules::args, Assert, elog, enforce_generic_type_consistency(), ERROR, exprType(), FUNC_MAX_ARGS, GETSTRUCT, lfirst, list_length(), make_fn_arguments(), and pronargs.

Referenced by expand_function_arguments().

◆ reorder_function_arguments()

static List * reorder_function_arguments ( List args,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 4258 of file clauses.c.

4259{
4260 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4261 int nargsprovided = list_length(args);
4262 Node *argarray[FUNC_MAX_ARGS];
4263 ListCell *lc;
4264 int i;
4265
4266 Assert(nargsprovided <= pronargs);
4267 if (pronargs < 0 || pronargs > FUNC_MAX_ARGS)
4268 elog(ERROR, "too many function arguments");
4269 memset(argarray, 0, pronargs * sizeof(Node *));
4270
4271 /* Deconstruct the argument list into an array indexed by argnumber */
4272 i = 0;
4273 foreach(lc, args)
4274 {
4275 Node *arg = (Node *) lfirst(lc);
4276
4277 if (!IsA(arg, NamedArgExpr))
4278 {
4279 /* positional argument, assumed to precede all named args */
4280 Assert(argarray[i] == NULL);
4281 argarray[i++] = arg;
4282 }
4283 else
4284 {
4285 NamedArgExpr *na = (NamedArgExpr *) arg;
4286
4287 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4288 Assert(argarray[na->argnumber] == NULL);
4289 argarray[na->argnumber] = (Node *) na->arg;
4290 }
4291 }
4292
4293 /*
4294 * Fetch default expressions, if needed, and insert into array at proper
4295 * locations (they aren't necessarily consecutive or all used)
4296 */
4297 if (nargsprovided < pronargs)
4298 {
4299 List *defaults = fetch_function_defaults(func_tuple);
4300
4301 i = pronargs - funcform->pronargdefaults;
4302 foreach(lc, defaults)
4303 {
4304 if (argarray[i] == NULL)
4305 argarray[i] = (Node *) lfirst(lc);
4306 i++;
4307 }
4308 }
4309
4310 /* Now reconstruct the args list in proper order */
4311 args = NIL;
4312 for (i = 0; i < pronargs; i++)
4313 {
4314 Assert(argarray[i] != NULL);
4315 args = lappend(args, argarray[i]);
4316 }
4317
4318 return args;
4319}
Expr * arg
Definition: primnodes.h:807

References arg, NamedArgExpr::arg, NamedArgExpr::argnumber, generate_unaccent_rules::args, Assert, elog, ERROR, fetch_function_defaults(), FUNC_MAX_ARGS, GETSTRUCT, i, IsA, lappend(), lfirst, list_length(), NIL, and pronargs.

Referenced by expand_function_arguments().

◆ rowtype_field_matches()

static bool rowtype_field_matches ( Oid  rowtypeid,
int  fieldnum,
Oid  expectedtype,
int32  expectedtypmod,
Oid  expectedcollation 
)
static

Definition at line 2186 of file clauses.c.

2189{
2190 TupleDesc tupdesc;
2191 Form_pg_attribute attr;
2192
2193 /* No issue for RECORD, since there is no way to ALTER such a type */
2194 if (rowtypeid == RECORDOID)
2195 return true;
2196 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2197 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2198 {
2199 ReleaseTupleDesc(tupdesc);
2200 return false;
2201 }
2202 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2203 if (attr->attisdropped ||
2204 attr->atttypid != expectedtype ||
2205 attr->atttypmod != expectedtypmod ||
2206 attr->attcollation != expectedcollation)
2207 {
2208 ReleaseTupleDesc(tupdesc);
2209 return false;
2210 }
2211 ReleaseTupleDesc(tupdesc);
2212 return true;
2213}
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:212
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:153
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1976

References lookup_rowtype_tupdesc_domain(), TupleDescData::natts, ReleaseTupleDesc, and TupleDescAttr().

Referenced by eval_const_expressions_mutator().

◆ simplify_and_arguments()

static List * simplify_and_arguments ( List args,
eval_const_expressions_context context,
bool *  haveNull,
bool *  forceFalse 
)
static

Definition at line 3898 of file clauses.c.

3901{
3902 List *newargs = NIL;
3903 List *unprocessed_args;
3904
3905 /* See comments in simplify_or_arguments */
3906 unprocessed_args = list_copy(args);
3907 while (unprocessed_args)
3908 {
3909 Node *arg = (Node *) linitial(unprocessed_args);
3910
3911 unprocessed_args = list_delete_first(unprocessed_args);
3912
3913 /* flatten nested ANDs as per above comment */
3914 if (is_andclause(arg))
3915 {
3916 List *subargs = ((BoolExpr *) arg)->args;
3917 List *oldlist = unprocessed_args;
3918
3919 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3920 /* perhaps-overly-tense code to avoid leaking old lists */
3921 list_free(oldlist);
3922 continue;
3923 }
3924
3925 /* If it's not an AND, simplify it */
3927
3928 /*
3929 * It is unlikely but not impossible for simplification of a non-AND
3930 * clause to produce an AND. Recheck, but don't be too tense about it
3931 * since it's not a mainstream case. In particular we don't worry
3932 * about const-simplifying the input twice, nor about list leakage.
3933 */
3934 if (is_andclause(arg))
3935 {
3936 List *subargs = ((BoolExpr *) arg)->args;
3937
3938 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3939 continue;
3940 }
3941
3942 /*
3943 * OK, we have a const-simplified non-AND argument. Process it per
3944 * comments above.
3945 */
3946 if (IsA(arg, Const))
3947 {
3948 Const *const_input = (Const *) arg;
3949
3950 if (const_input->constisnull)
3951 *haveNull = true;
3952 else if (!DatumGetBool(const_input->constvalue))
3953 {
3954 *forceFalse = true;
3955
3956 /*
3957 * Once we detect a FALSE result we can just exit the loop
3958 * immediately. However, if we ever add a notion of
3959 * non-removable functions, we'd need to keep scanning.
3960 */
3961 return NIL;
3962 }
3963 /* otherwise, we can drop the constant-true input */
3964 continue;
3965 }
3966
3967 /* else emit the simplified arg into the result list */
3968 newargs = lappend(newargs, arg);
3969 }
3970
3971 return newargs;
3972}
List * list_delete_first(List *list)
Definition: list.c:943
List * list_copy(const List *oldlist)
Definition: list.c:1573
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:107

References arg, generate_unaccent_rules::args, DatumGetBool(), eval_const_expressions_mutator(), is_andclause(), IsA, lappend(), linitial, list_concat_copy(), list_copy(), list_delete_first(), list_free(), and NIL.

Referenced by eval_const_expressions_mutator().

◆ simplify_boolean_equality()

static Node * simplify_boolean_equality ( Oid  opno,
List args 
)
static

Definition at line 3992 of file clauses.c.

3993{
3994 Node *leftop;
3995 Node *rightop;
3996
3997 Assert(list_length(args) == 2);
3998 leftop = linitial(args);
3999 rightop = lsecond(args);
4000 if (leftop && IsA(leftop, Const))
4001 {
4002 Assert(!((Const *) leftop)->constisnull);
4003 if (opno == BooleanEqualOperator)
4004 {
4005 if (DatumGetBool(((Const *) leftop)->constvalue))
4006 return rightop; /* true = foo */
4007 else
4008 return negate_clause(rightop); /* false = foo */
4009 }
4010 else
4011 {
4012 if (DatumGetBool(((Const *) leftop)->constvalue))
4013 return negate_clause(rightop); /* true <> foo */
4014 else
4015 return rightop; /* false <> foo */
4016 }
4017 }
4018 if (rightop && IsA(rightop, Const))
4019 {
4020 Assert(!((Const *) rightop)->constisnull);
4021 if (opno == BooleanEqualOperator)
4022 {
4023 if (DatumGetBool(((Const *) rightop)->constvalue))
4024 return leftop; /* foo = true */
4025 else
4026 return negate_clause(leftop); /* foo = false */
4027 }
4028 else
4029 {
4030 if (DatumGetBool(((Const *) rightop)->constvalue))
4031 return negate_clause(leftop); /* foo <> true */
4032 else
4033 return leftop; /* foo <> false */
4034 }
4035 }
4036 return NULL;
4037}

References generate_unaccent_rules::args, Assert, DatumGetBool(), IsA, linitial, list_length(), lsecond, and negate_clause().

Referenced by eval_const_expressions_mutator().

◆ simplify_function()

static Expr * simplify_function ( Oid  funcid,
Oid  result_type,
int32  result_typmod,
Oid  result_collid,
Oid  input_collid,
List **  args_p,
bool  funcvariadic,
bool  process_args,
bool  allow_non_const,
eval_const_expressions_context context 
)
static

Definition at line 4061 of file clauses.c.

4065{
4066 List *args = *args_p;
4067 HeapTuple func_tuple;
4068 Form_pg_proc func_form;
4069 Expr *newexpr;
4070
4071 /*
4072 * We have three strategies for simplification: execute the function to
4073 * deliver a constant result, use a transform function to generate a
4074 * substitute node tree, or expand in-line the body of the function
4075 * definition (which only works for simple SQL-language functions, but
4076 * that is a common case). Each case needs access to the function's
4077 * pg_proc tuple, so fetch it just once.
4078 *
4079 * Note: the allow_non_const flag suppresses both the second and third
4080 * strategies; so if !allow_non_const, simplify_function can only return a
4081 * Const or NULL. Argument-list rewriting happens anyway, though.
4082 */
4083 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4084 if (!HeapTupleIsValid(func_tuple))
4085 elog(ERROR, "cache lookup failed for function %u", funcid);
4086 func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4087
4088 /*
4089 * Process the function arguments, unless the caller did it already.
4090 *
4091 * Here we must deal with named or defaulted arguments, and then
4092 * recursively apply eval_const_expressions to the whole argument list.
4093 */
4094 if (process_args)
4095 {
4096 args = expand_function_arguments(args, false, result_type, func_tuple);