PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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_collate.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.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)
 
ScalarArrayOpExprmake_SAOP_expr (Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

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

Definition at line 1187 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 2428 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:4976
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Definition: nodes.h:135

Definition at line 2432 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:2442
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155

Definition at line 2419 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

Definition at line 2271 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 4330 of file clauses.c.

4331{
4332 int nargsprovided = list_length(args);
4333 List *defaults;
4334 int ndelete;
4335
4336 /* Get all the default expressions from the pg_proc tuple */
4337 defaults = fetch_function_defaults(func_tuple);
4338
4339 /* Delete any unused defaults from the list */
4340 ndelete = nargsprovided + list_length(defaults) - pronargs;
4341 if (ndelete < 0)
4342 elog(ERROR, "not enough default arguments");
4343 if (ndelete > 0)
4344 defaults = list_delete_first_n(defaults, ndelete);
4345
4346 /* And form the combined argument list, not modifying the input list */
4347 return list_concat_copy(args, defaults);
4348}
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4354
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
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 2149 of file clauses.c.

2150{
2151 Oid opoid;
2152 Node *temp;
2153
2154 /* Sanity checks: caller is at fault if these fail */
2155 if (!is_opclause(clause) ||
2156 list_length(clause->args) != 2)
2157 elog(ERROR, "cannot commute non-binary-operator clause");
2158
2159 opoid = get_commutator(clause->opno);
2160
2161 if (!OidIsValid(opoid))
2162 elog(ERROR, "could not find commutator for operator %u",
2163 clause->opno);
2164
2165 /*
2166 * modify the clause in-place!
2167 */
2168 clause->opno = opoid;
2169 clause->opfuncid = InvalidOid;
2170 /* opresulttype, opretset, opcollid, inputcollid need not change */
2171
2172 temp = linitial(clause->args);
2173 linitial(clause->args) = lsecond(clause->args);
2174 lsecond(clause->args) = temp;
2175}
#define OidIsValid(objectId)
Definition: c.h:746
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1649
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:35
unsigned int Oid
Definition: postgres_ext.h:30
Oid opno
Definition: primnodes.h:835
List * args
Definition: primnodes.h:853

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 179 of file clauses.c.

180{
181 return contain_agg_clause_walker(clause, NULL);
182}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:185

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 185 of file clauses.c.

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

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 1180 of file clauses.c.

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

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 1190 of file clauses.c.

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

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

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 1138 of file clauses.c.

1139{
1140 return contain_exec_param_walker(clause, param_ids);
1141}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1144

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 1144 of file clauses.c.

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

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 1264 of file clauses.c.

1265{
1266 return contain_leaked_vars_walker(clause, NULL);
1267}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1276

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 1270 of file clauses.c.

1271{
1272 return !get_func_leakproof(func_id);
1273}
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1977

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 1276 of file clauses.c.

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

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

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 377 of file clauses.c.

378{
379 return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
380}
char func_volatile(Oid funcid)
Definition: lsyscache.c:1920

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 383 of file clauses.c.

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

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 3740 of file clauses.c.

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

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 994 of file clauses.c.

995{
996 return contain_nonstrict_functions_walker(clause, NULL);
997}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1006

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 1000 of file clauses.c.

1001{
1002 return !func_strict(func_id);
1003}
bool func_strict(Oid funcid)
Definition: lsyscache.c:1901

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 1006 of file clauses.c.

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

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 337 of file clauses.c.

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

References contain_subplans_walker(), expression_tree_walker, and IsA.

Referenced by contain_subplans(), and contain_subplans_walker().

◆ contain_volatile_functions()

bool contain_volatile_functions ( Node clause)

Definition at line 539 of file clauses.c.

540{
541 return contain_volatile_functions_walker(clause, NULL);
542}
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:551

References contain_volatile_functions_walker().

Referenced by apply_child_basequals(), ATExecAddColumn(), check_hashjoinable(), check_mergejoinable(), check_output_expressions(), compute_semijoin_info(), contain_volatile_functions_after_planning(), convert_ANY_sublink_to_join(), convert_EXISTS_sublink_to_join(), convert_EXISTS_to_ANY(), convert_VALUES_to_ANY(), CopyFrom(), distribute_qual_to_rels(), estimate_num_groups(), ExecInitWindowAgg(), expand_indexqual_rowcompare(), find_compatible_agg(), find_simplified_clause(), get_eclass_for_sort_expr(), get_memoize_path(), group_similar_or_args(), initialize_peragg(), inline_function(), inline_set_returning_function(), is_pseudo_constant_clause(), is_pseudo_constant_clause_relids(), is_pseudo_constant_for_index(), is_safe_restriction_clause_for(), is_simple_subquery(), is_simple_values(), IsBinaryTidClause(), IsTidEqualAnyClause(), make_sort_input_target(), mark_nullable_by_grouping(), match_clause_to_ordering_op(), match_clause_to_partition_key(), match_opclause_to_indexcol(), match_orclause_to_indexcol(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), paraminfo_get_equal_hashops(), qual_is_pushdown_safe(), remove_unused_subquery_outputs(), SS_process_ctes(), and subquery_planner().

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 660 of file clauses.c.

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

References contain_volatile_functions(), and expression_planner().

◆ contain_volatile_functions_checker()

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

Definition at line 545 of file clauses.c.

546{
547 return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
548}

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 674 of file clauses.c.

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

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 680 of file clauses.c.

681{
682 return (func_id != F_NEXTVAL &&
683 func_volatile(func_id) == PROVOLATILE_VOLATILE);
684}

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 687 of file clauses.c.

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

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 551 of file clauses.c.

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

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 216 of file clauses.c.

217{
218 return contain_windowfuncs(clause);
219}
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 2289 of file clauses.c.

2290{
2291 (void) convert_saop_to_hashed_saop_walker(node, NULL);
2292}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2295

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 2295 of file clauses.c.

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

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

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

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

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 2442 of file clauses.c.

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

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 4976 of file clauses.c.

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

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 4429 of file clauses.c.

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

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 4179 of file clauses.c.

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

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

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 4354 of file clauses.c.

4355{
4356 List *defaults;
4357 Datum proargdefaults;
4358 char *str;
4359
4360 proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4361 Anum_pg_proc_proargdefaults);
4362 str = TextDatumGetCString(proargdefaults);
4363 defaults = castNode(List, stringToNode(str));
4364 pfree(str);
4365 return defaults;
4366}
#define TextDatumGetCString(d)
Definition: builtins.h:98
const char * str
void pfree(void *pointer)
Definition: mcxt.c:2147
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 1979 of file clauses.c.

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

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 1918 of file clauses.c.

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

1459{
1460 return find_nonnullable_rels_walker(clause, true);
1461}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1464

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 1464 of file clauses.c.

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

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(), SubPlan::subLinkType, SubPlan::testexpr, 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 1709 of file clauses.c.

1710{
1711 return find_nonnullable_vars_walker(clause, true);
1712}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1715

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 1715 of file clauses.c.

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

230{
231 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
232
233 lists->numWindowFuncs = 0;
234 lists->maxWinRef = maxWinRef;
235 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
236 (void) find_window_functions_walker(clause, lists);
237 return lists;
238}
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:241
void * palloc0(Size size)
Definition: mcxt.c:1970
void * palloc(Size size)
Definition: mcxt.c:1940
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 241 of file clauses.c.

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

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

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

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 754 of file clauses.c.

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

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 2090 of file clauses.c.

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

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 2110 of file clauses.c.

2111{
2112 if (bms_is_empty(relids) &&
2114 return true;
2115 return false;
2116}

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 2028 of file clauses.c.

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

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), Assert(), DatumGetArrayTypeP, 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().

◆ make_SAOP_expr()

ScalarArrayOpExpr * make_SAOP_expr ( Oid  oper,
Node leftexpr,
Oid  coltype,
Oid  arraycollid,
Oid  inputcollid,
List exprs,
bool  haveNonConst 
)

Definition at line 5453 of file clauses.c.

5455{
5456 Node *arrayNode = NULL;
5457 ScalarArrayOpExpr *saopexpr = NULL;
5458 Oid arraytype = get_array_type(coltype);
5459
5460 if (!OidIsValid(arraytype))
5461 return NULL;
5462
5463 /*
5464 * Assemble an array from the list of constants. It seems more profitable
5465 * to build a const array. But in the presence of other nodes, we don't
5466 * have a specific value here and must employ an ArrayExpr instead.
5467 */
5468 if (haveNonConst)
5469 {
5470 ArrayExpr *arrayExpr = makeNode(ArrayExpr);
5471
5472 /* array_collid will be set by parse_collate.c */
5473 arrayExpr->element_typeid = coltype;
5474 arrayExpr->array_typeid = arraytype;
5475 arrayExpr->multidims = false;
5476 arrayExpr->elements = exprs;
5477 arrayExpr->location = -1;
5478
5479 arrayNode = (Node *) arrayExpr;
5480 }
5481 else
5482 {
5483 int16 typlen;
5484 bool typbyval;
5485 char typalign;
5486 Datum *elems;
5487 bool *nulls;
5488 int i = 0;
5489 ArrayType *arrayConst;
5490 int dims[1] = {list_length(exprs)};
5491 int lbs[1] = {1};
5492
5493 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5494
5495 elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
5496 nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
5497 foreach_node(Const, value, exprs)
5498 {
5499 elems[i] = value->constvalue;
5500 nulls[i++] = value->constisnull;
5501 }
5502
5503 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5504 coltype, typlen, typbyval, typalign);
5505 arrayNode = (Node *) makeConst(arraytype, -1, arraycollid,
5506 -1, PointerGetDatum(arrayConst),
5507 false, false);
5508
5509 pfree(elems);
5510 pfree(nulls);
5511 list_free(exprs);
5512 }
5513
5514 /* Build the SAOP expression node */
5515 saopexpr = makeNode(ScalarArrayOpExpr);
5516 saopexpr->opno = oper;
5517 saopexpr->opfuncid = get_opcode(oper);
5518 saopexpr->hashfuncid = InvalidOid;
5519 saopexpr->negfuncid = InvalidOid;
5520 saopexpr->useOr = true;
5521 saopexpr->inputcollid = inputcollid;
5522 saopexpr->args = list_make2(leftexpr, arrayNode);
5523 saopexpr->location = -1;
5524
5525 return saopexpr;
5526}
ArrayType * construct_md_array(Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3494
static struct @165 value
void list_free(List *list)
Definition: list.c:1546
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2411
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2927
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:370
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
#define list_make2(x1, x2)
Definition: pg_list.h:214
char typalign
Definition: pg_type.h:176
ParseLoc location
Definition: primnodes.h:1401
ParseLoc location
Definition: primnodes.h:936

References ScalarArrayOpExpr::args, construct_md_array(), foreach_node, get_array_type(), get_opcode(), get_typlenbyvalalign(), i, InvalidOid, list_free(), list_length(), list_make2, ScalarArrayOpExpr::location, ArrayExpr::location, makeConst(), makeNode, OidIsValid, oper(), ScalarArrayOpExpr::opno, palloc(), pfree(), PointerGetDatum(), typalign, ScalarArrayOpExpr::useOr, and value.

Referenced by convert_VALUES_to_ANY(), and match_orclause_to_indexcol().

◆ max_parallel_hazard()

char max_parallel_hazard ( Query parse)

Definition at line 735 of file clauses.c.

736{
738
739 context.max_hazard = PROPARALLEL_SAFE;
740 context.max_interesting = PROPARALLEL_UNSAFE;
741 context.safe_param_ids = NIL;
742 (void) max_parallel_hazard_walker((Node *) parse, &context);
743 return context.max_hazard;
744}
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 823 of file clauses.c.

824{
826 (max_parallel_hazard_context *) context);
827}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:795
char func_parallel(Oid funcid)
Definition: lsyscache.c:1939

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 795 of file clauses.c.

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

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 830 of file clauses.c.

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

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 2132 of file clauses.c.

2133{
2134 int result;
2135 Relids varnos = pull_varnos(root, clause);
2136
2137 varnos = bms_del_members(varnos, root->outer_join_rels);
2138 result = bms_num_members(varnos);
2139 bms_free(varnos);
2140 return result;
2141}
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 5421 of file clauses.c.

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

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 5431 of file clauses.c.

5432{
5433 if (node == NULL)
5434 return false;
5435 if (IsA(node, Param))
5436 {
5437 Param *param = (Param *) node;
5438
5439 *context = bms_add_member(*context, param->paramid);
5440 return false;
5441 }
5442 return expression_tree_walker(node, pull_paramids_walker, context);
5443}
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 4384 of file clauses.c.

4387{
4388 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4389 int nargs;
4390 Oid actual_arg_types[FUNC_MAX_ARGS];
4391 Oid declared_arg_types[FUNC_MAX_ARGS];
4392 Oid rettype;
4393 ListCell *lc;
4394
4396 elog(ERROR, "too many function arguments");
4397 nargs = 0;
4398 foreach(lc, args)
4399 {
4400 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4401 }
4402 Assert(nargs == pronargs);
4403 memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4404 rettype = enforce_generic_type_consistency(actual_arg_types,
4405 declared_arg_types,
4406 nargs,
4407 funcform->prorettype,
4408 false);
4409 /* let's just check we got the same answer as the parser did ... */
4410 if (rettype != result_type)
4411 elog(ERROR, "function's resolved result type changed during planning");
4412
4413 /* perform any necessary typecasting of arguments */
4414 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4415}
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 4260 of file clauses.c.

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

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 2188 of file clauses.c.

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

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 3900 of file clauses.c.

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

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

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 4063 of file clauses.c.

4067{
4068 List *args = *args_p;
4069 HeapTuple func_tuple;
4070 Form_pg_proc func_form;
4071 Expr *newexpr;
4072
4073 /*
4074 * We have three strategies for simplification: execute the function to
4075 * deliver a constant result, use a transform function to generate a
4076 * substitute node tree, or expand in-line the body of the function
4077 * definition (which only works for simple SQL-language functions, but
4078 * that is a common case). Each case needs access to the function's
4079 * pg_proc tuple, so fetch it just once.
4080 *
4081 * Note: the allow_non_const flag suppresses both the second and third
4082 * strategies; so if !allow_non_const, simplify_function can only return a
4083 * Const or NULL. Argument-list rewriting happens anyway, though.
4084 */
4085 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4086 if (!HeapTupleIsValid(func_tuple))
4087 elog(ERROR, "cache lookup failed for function %u", funcid);
4088 func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4089
4090 /*
4091 * Process the function arguments, unless the caller did it already.
4092 *
4093 * Here we must deal with named or defaulted arguments, and then
4094 * recursively apply eval_const_expressions to the whole argument list.
4095 */
4096 if (process_args)
4097 {
4098 args = expand_function_arguments(args, false, result_type, func_tuple);
4101 context);
4102 /* Argument processing done, give it back to the caller */
4103 *args_p = args;
4104 }
4105
4106 /* Now attempt simplification of the function call proper. */
4107
4108 newexpr = evaluate_function(funcid, result_type, result_typmod,
4109 result_collid, input_collid,
4110 args, funcvariadic,
4111 func_tuple, context);
4112
4113 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4114 {
4115 /*
4116 * Build a SupportRequestSimplify node to pass to the support
4117 * function, pointing to a dummy FuncExpr node containing the
4118 * simplified arg list. We use this approach to present a uniform
4119 * interface to the support function regardless of how the target
4120 * function is actually being invoked.
4121 */
4123 FuncExpr fexpr;
4124
4125 fexpr.xpr.type = T_FuncExpr;
4126 fexpr.funcid = funcid;
4127 fexpr.funcresulttype = result_type;
4128 fexpr.funcretset = func_form->proretset;
4129 fexpr.funcvariadic = funcvariadic;
4130 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4131 fexpr.funccollid = result_collid;
4132 fexpr.inputcollid = input_collid;
4133 fexpr.args = args;
4134 fexpr.location = -1;
4135
4136 req.type = T_SupportRequestSimplify;
4137 req.root = context->root;
4138 req.fcall = &fexpr;
4139
4140 newexpr = (Expr *)
4141 DatumGetPointer(OidFunctionCall1(func_form->prosupport,
4142 PointerGetDatum(&req)));
4143
4144 /* catch a possible API misunderstanding */
4145 Assert(newexpr != (Expr *) &fexpr);
4146 }
4147
4148 if (!newexpr && allow_non_const)
4149 newexpr = inline_function(funcid, result_type, result_collid,
4150 input_collid, args, funcvariadic,
4151 func_tuple, context);
4152
4153 ReleaseSysCache(func_tuple);
4154
4155 return newexpr;
4156}
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)
Definition: clauses.c:4429
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)
Definition: clauses.c:4555
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
Expr xpr
Definition: primnodes.h:765
struct PlannerInfo * root
Definition: supportnodes.h:68

References generate_unaccent_rules::args, FuncExpr::args, Assert(), COERCE_EXPLICIT_CALL, DatumGetPointer(), elog, ERROR, eval_const_expressions_mutator(), evaluate_function(), expand_function_arguments(), expression_tree_mutator, SupportRequestSimplify::fcall, FuncExpr::funcid, GETSTRUCT(), HeapTupleIsValid, inline_function(), FuncExpr::location, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PointerGetDatum(), ReleaseSysCache(), eval_const_expressions_context::root, SupportRequestSimplify::root, SearchSysCache1(), SupportRequestSimplify::type, and FuncExpr::xpr.

Referenced by eval_const_expressions_mutator().

◆ simplify_or_arguments()

static List * simplify_or_arguments ( List args,
eval_const_expressions_context context,
bool *  haveNull,
bool *  forceTrue 
)
static

Definition at line 3794 of file clauses.c.

3797{
3798 List *newargs = NIL;
3799 List *unprocessed_args;
3800
3801 /*
3802 * We want to ensure that any OR immediately beneath another OR gets
3803 * flattened into a single OR-list, so as to simplify later reasoning.
3804 *
3805 * To avoid stack overflow from recursion of eval_const_expressions, we
3806 * resort to some tenseness here: we keep a list of not-yet-processed
3807 * inputs, and handle flattening of nested ORs by prepending to the to-do
3808 * list instead of recursing. Now that the parser generates N-argument
3809 * ORs from simple lists, this complexity is probably less necessary than
3810 * it once was, but we might as well keep the logic.
3811 */
3812 unprocessed_args = list_copy(args);
3813 while (unprocessed_args)
3814 {
3815 Node *arg = (Node *) linitial(unprocessed_args);
3816
3817 unprocessed_args = list_delete_first(unprocessed_args);
3818
3819 /* flatten nested ORs as per above comment */
3820 if (is_orclause(arg))
3821 {
3822 List *subargs = ((BoolExpr *) arg)->args;
3823 List *oldlist = unprocessed_args;
3824
3825 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3826 /* perhaps-overly-tense code to avoid leaking old lists */
3827 list_free(oldlist);
3828 continue;
3829 }
3830
3831 /* If it's not an OR, simplify it */
3833
3834 /*
3835 * It is unlikely but not impossible for simplification of a non-OR
3836 * clause to produce an OR. Recheck, but don't be too tense about it
3837 * since it's not a mainstream case. In particular we don't worry
3838 * about const-simplifying the input twice, nor about list leakage.
3839 */
3840 if (is_orclause(arg))
3841 {
3842 List *subargs = ((BoolExpr *) arg)->args;
3843
3844 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3845 continue;
3846 }
3847
3848 /*
3849 * OK, we have a const-simplified non-OR argument. Process it per
3850 * comments above.
3851 */
3852 if (IsA(arg, Const))
3853 {
3854 Const *const_input = (Const *) arg;
3855
3856 if (const_input->constisnull)
3857 *haveNull = true;
3858 else if (DatumGetBool(const_input->constvalue))
3859 {
3860 *forceTrue = true;
3861
3862 /*
3863 * Once we detect a TRUE result we can just exit the loop
3864 * immediately. However, if we ever add a notion of
3865 * non-removable functions, we'd need to keep scanning.
3866 */
3867 return NIL;
3868 }
3869 /* otherwise, we can drop the constant-false input */
3870 continue;
3871 }
3872
3873 /* else emit the simplified arg into the result list */
3874 newargs = lappend(newargs, arg);
3875 }
3876
3877 return newargs;
3878}
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:116

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

Referenced by eval_const_expressions_mutator().

◆ sql_inline_error_callback()

static void sql_inline_error_callback ( void *  arg)
static

Definition at line 4952 of file clauses.c.

4953{
4955 int syntaxerrposition;
4956
4957 /* If it's a syntax error, convert to internal syntax error report */
4958 syntaxerrposition = geterrposition();
4959 if (syntaxerrposition > 0)
4960 {
4961 errposition(0);
4962 internalerrposition(syntaxerrposition);
4963 internalerrquery(callback_arg->prosrc);
4964 }
4965
4966 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4967}
int internalerrquery(const char *query)
Definition: elog.c:1504
int internalerrposition(int cursorpos)
Definition: elog.c:1484
int geterrposition(void)
Definition: elog.c:1617
int errposition(int cursorpos)
Definition: elog.c:1468
#define errcontext
Definition: elog.h:197

References arg, errcontext, errposition(), geterrposition(), internalerrposition(), internalerrquery(), inline_error_callback_arg::proname, and inline_error_callback_arg::prosrc.

Referenced by inline_function(), and inline_set_returning_function().

◆ substitute_actual_parameters()

static Node * substitute_actual_parameters ( Node expr,
int  nargs,
List args,
int *  usecounts 
)
static

Definition at line 4911 of file clauses.c.

4913{
4915
4916 context.nargs = nargs;
4917 context.args = args;
4918 context.usecounts = usecounts;
4919
4920 return substitute_actual_parameters_mutator(expr, &context);
4921}
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition: clauses.c:4924

References generate_unaccent_rules::args, substitute_actual_parameters_context::args, substitute_actual_parameters_context::nargs, substitute_actual_parameters_mutator(), and substitute_actual_parameters_context::usecounts.

Referenced by inline_function().

◆ substitute_actual_parameters_mutator()

static Node * substitute_actual_parameters_mutator ( Node node,
substitute_actual_parameters_context context 
)
static

Definition at line 4924 of file clauses.c.

4926{
4927 if (node == NULL)
4928 return NULL;
4929 if (IsA(node, Param))
4930 {
4931 Param *param = (Param *) node;
4932
4933 if (param->paramkind != PARAM_EXTERN)
4934 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4935 if (param->paramid <= 0 || param->paramid > context->nargs)
4936 elog(ERROR, "invalid paramid: %d", param->paramid);
4937
4938 /* Count usage of parameter */
4939 context->usecounts[param->paramid - 1]++;
4940
4941 /* Select the appropriate actual arg and replace the Param with it */
4942 /* We don't need to copy at this time (it'll get done later) */
4943 return list_nth(context->args, param->paramid - 1);
4944 }
4946}

References substitute_actual_parameters_context::args, elog, ERROR, expression_tree_mutator, IsA, list_nth(), substitute_actual_parameters_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, substitute_actual_parameters_mutator(), and substitute_actual_parameters_context::usecounts.

Referenced by substitute_actual_parameters(), and substitute_actual_parameters_mutator().

◆ substitute_actual_srf_parameters()

static Query * substitute_actual_srf_parameters ( Query expr,
int  nargs,
List args 
)
static

Definition at line 5361 of file clauses.c.

5362{
5364
5365 context.nargs = nargs;
5366 context.args = args;
5367 context.sublevels_up = 1;
5368
5369 return query_tree_mutator(expr,
5371 &context,
5372 0);
5373}
static Node * substitute_actual_srf_parameters_mutator(Node *node, substitute_actual_srf_parameters_context *context)
Definition: clauses.c:5376
#define query_tree_mutator(q, m, c, f)
Definition: nodeFuncs.h:160

References generate_unaccent_rules::args, substitute_actual_srf_parameters_context::args, substitute_actual_srf_parameters_context::nargs, query_tree_mutator, substitute_actual_srf_parameters_context::sublevels_up, and substitute_actual_srf_parameters_mutator().

Referenced by inline_set_returning_function().

◆ substitute_actual_srf_parameters_mutator()

static Node * substitute_actual_srf_parameters_mutator ( Node node,
substitute_actual_srf_parameters_context context 
)
static

Definition at line 5376 of file clauses.c.

5378{
5379 Node *result;
5380
5381 if (node == NULL)
5382 return NULL;
5383 if (IsA(node, Query))
5384 {
5385 context->sublevels_up++;
5386 result = (Node *) query_tree_mutator((Query *) node,
5388 context,
5389 0);
5390 context->sublevels_up--;
5391 return result;
5392 }
5393 if (IsA(node, Param))
5394 {
5395 Param *param = (Param *) node;
5396
5397 if (param->paramkind == PARAM_EXTERN)
5398 {
5399 if (param->paramid <= 0 || param->paramid > context->nargs)
5400 elog(ERROR, "invalid paramid: %d", param->paramid);
5401
5402 /*
5403 * Since the parameter is being inserted into a subquery, we must
5404 * adjust levels.
5405 */
5406 result = copyObject(list_nth(context->args, param->paramid - 1));
5407 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5408 return result;
5409 }
5410 }
5411 return expression_tree_mutator(node,
5413 context);
5414}
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:928

References substitute_actual_srf_parameters_context::args, copyObject, elog, ERROR, expression_tree_mutator, IncrementVarSublevelsUp(), IsA, list_nth(), substitute_actual_srf_parameters_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, query_tree_mutator, substitute_actual_srf_parameters_context::sublevels_up, and substitute_actual_srf_parameters_mutator().

Referenced by substitute_actual_srf_parameters(), and substitute_actual_srf_parameters_mutator().