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_class.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/pathnode.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 "parser/parsetree.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)
 
bool var_is_nonnullable (PlannerInfo *root, Var *var, bool use_rel_info)
 
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 1192 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 2434 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:5076
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Definition: nodes.h:135

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

Definition at line 2425 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4431{
4432 int nargsprovided = list_length(args);
4433 List *defaults;
4434 int ndelete;
4435
4436 /* Get all the default expressions from the pg_proc tuple */
4437 defaults = fetch_function_defaults(func_tuple);
4438
4439 /* Delete any unused defaults from the list */
4440 ndelete = nargsprovided + list_length(defaults) - pronargs;
4441 if (ndelete < 0)
4442 elog(ERROR, "not enough default arguments");
4443 if (ndelete > 0)
4444 defaults = list_delete_first_n(defaults, ndelete);
4445
4446 /* And form the combined argument list, not modifying the input list */
4447 return list_concat_copy(args, defaults);
4448}
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4454
#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 2154 of file clauses.c.

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

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

183{
184 return contain_agg_clause_walker(clause, NULL);
185}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:188

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

189{
190 if (node == NULL)
191 return false;
192 if (IsA(node, Aggref))
193 {
194 Assert(((Aggref *) node)->agglevelsup == 0);
195 return true; /* abort the tree traversal and return true */
196 }
197 if (IsA(node, GroupingFunc))
198 {
199 Assert(((GroupingFunc *) node)->agglevelsup == 0);
200 return true; /* abort the tree traversal and return true */
201 }
202 Assert(!IsA(node, SubLink));
204}
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 1185 of file clauses.c.

1186{
1187 int flags = 0;
1188
1189 return contain_context_dependent_node_walker(clause, &flags);
1190}
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1195

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

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

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

1144{
1145 return contain_exec_param_walker(clause, param_ids);
1146}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1149

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

1150{
1151 if (node == NULL)
1152 return false;
1153 if (IsA(node, Param))
1154 {
1155 Param *p = (Param *) node;
1156
1157 if (p->paramkind == PARAM_EXEC &&
1158 list_member_int(param_ids, p->paramid))
1159 return true;
1160 }
1161 return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1162}
bool list_member_int(const List *list, int datum)
Definition: list.c:702
@ PARAM_EXEC
Definition: primnodes.h:385
int paramid
Definition: primnodes.h:396
ParamKind paramkind
Definition: primnodes.h:395

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

1270{
1271 return contain_leaked_vars_walker(clause, NULL);
1272}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1281

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

1276{
1277 return !get_func_leakproof(func_id);
1278}
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:2004

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

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

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

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

381{
382 return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
383}
char func_volatile(Oid funcid)
Definition: lsyscache.c:1947

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

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

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

3780{
3781 if (node == NULL)
3782 return false;
3783 if (IsA(node, Const))
3784 return false;
3785 if (IsA(node, List))
3786 return expression_tree_walker(node, contain_non_const_walker, context);
3787 /* Otherwise, abort the tree traversal and return true */
3788 return true;
3789}
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3779

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

998{
999 return contain_nonstrict_functions_walker(clause, NULL);
1000}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1009

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

1004{
1005 return !func_strict(func_id);
1006}
bool func_strict(Oid funcid)
Definition: lsyscache.c:1928

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

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

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

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

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

543{
544 return contain_volatile_functions_walker(clause, NULL);
545}
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:554

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

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

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

549{
550 return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
551}

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

678{
680}
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:690

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

684{
685 return (func_id != F_NEXTVAL &&
686 func_volatile(func_id) == PROVOLATILE_VOLATILE);
687}

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

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

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

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

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

220{
221 return contain_windowfuncs(clause);
222}
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 2295 of file clauses.c.

2296{
2297 (void) convert_saop_to_hashed_saop_walker(node, NULL);
2298}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2301

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

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

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

3796{
3797 char provolatile = func_volatile(funcid);
3798
3799 /*
3800 * Ordinarily we are only allowed to simplify immutable functions. But for
3801 * purposes of estimation, we consider it okay to simplify functions that
3802 * are merely stable; the risk that the result might change from planning
3803 * time to execution time is worth taking in preference to not being able
3804 * to estimate the value at all.
3805 */
3806 if (provolatile == PROVOLATILE_IMMUTABLE)
3807 return true;
3808 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3809 return true;
3810 return false;
3811}

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

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

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

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

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(), WindowFunc::ignore_nulls, 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, Param::paramcollid, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, 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_is_nonnullable(), 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 5076 of file clauses.c.

5078{
5079 EState *estate;
5080 ExprState *exprstate;
5081 MemoryContext oldcontext;
5082 Datum const_val;
5083 bool const_is_null;
5084 int16 resultTypLen;
5085 bool resultTypByVal;
5086
5087 /*
5088 * To use the executor, we need an EState.
5089 */
5090 estate = CreateExecutorState();
5091
5092 /* We can use the estate's working context to avoid memory leaks. */
5093 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5094
5095 /* Make sure any opfuncids are filled in. */
5096 fix_opfuncids((Node *) expr);
5097
5098 /*
5099 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5100 * because it'd result in recursively invoking eval_const_expressions.)
5101 */
5102 exprstate = ExecInitExpr(expr, NULL);
5103
5104 /*
5105 * And evaluate it.
5106 *
5107 * It is OK to use a default econtext because none of the ExecEvalExpr()
5108 * code used in this situation will use econtext. That might seem
5109 * fortuitous, but it's not so unreasonable --- a constant expression does
5110 * not depend on context, by definition, n'est ce pas?
5111 */
5112 const_val = ExecEvalExprSwitchContext(exprstate,
5113 GetPerTupleExprContext(estate),
5114 &const_is_null);
5115
5116 /* Get info needed about result datatype */
5117 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
5118
5119 /* Get back to outer memory context */
5120 MemoryContextSwitchTo(oldcontext);
5121
5122 /*
5123 * Must copy result out of sub-context used by expression eval.
5124 *
5125 * Also, if it's varlena, forcibly detoast it. This protects us against
5126 * storing TOAST pointers into plans that might outlive the referenced
5127 * data. (makeConst would handle detoasting anyway, but it's worth a few
5128 * extra lines here so that we can do the copy and detoast in one step.)
5129 */
5130 if (!const_is_null)
5131 {
5132 if (resultTypLen == -1)
5133 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
5134 else
5135 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
5136 }
5137
5138 /* Release all the junk we just created */
5139 FreeExecutorState(estate);
5140
5141 /*
5142 * Make the constant result node.
5143 */
5144 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5145 resultTypLen,
5146 const_val, const_is_null,
5147 resultTypByVal);
5148}
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:143
void FreeExecutorState(EState *estate)
Definition: execUtils.c:192
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:653
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:433
#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:332
MemoryContext es_query_cxt
Definition: execnodes.h:710

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

4534{
4535 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4536 bool has_nonconst_input = false;
4537 bool has_null_input = false;
4538 ListCell *arg;
4539 FuncExpr *newexpr;
4540
4541 /*
4542 * Can't simplify if it returns a set.
4543 */
4544 if (funcform->proretset)
4545 return NULL;
4546
4547 /*
4548 * Can't simplify if it returns RECORD. The immediate problem is that it
4549 * will be needing an expected tupdesc which we can't supply here.
4550 *
4551 * In the case where it has OUT parameters, we could build an expected
4552 * tupdesc from those, but there may be other gotchas lurking. In
4553 * particular, if the function were to return NULL, we would produce a
4554 * null constant with no remaining indication of which concrete record
4555 * type it is. For now, seems best to leave the function call unreduced.
4556 */
4557 if (funcform->prorettype == RECORDOID)
4558 return NULL;
4559
4560 /*
4561 * Check for constant inputs and especially constant-NULL inputs.
4562 */
4563 foreach(arg, args)
4564 {
4565 if (IsA(lfirst(arg), Const))
4566 has_null_input |= ((Const *) lfirst(arg))->constisnull;
4567 else
4568 has_nonconst_input = true;
4569 }
4570
4571 /*
4572 * If the function is strict and has a constant-NULL input, it will never
4573 * be called at all, so we can replace the call by a NULL constant, even
4574 * if there are other inputs that aren't constant, and even if the
4575 * function is not otherwise immutable.
4576 */
4577 if (funcform->proisstrict && has_null_input)
4578 return (Expr *) makeNullConst(result_type, result_typmod,
4579 result_collid);
4580
4581 /*
4582 * Otherwise, can simplify only if all inputs are constants. (For a
4583 * non-strict function, constant NULL inputs are treated the same as
4584 * constant non-NULL inputs.)
4585 */
4586 if (has_nonconst_input)
4587 return NULL;
4588
4589 /*
4590 * Ordinarily we are only allowed to simplify immutable functions. But for
4591 * purposes of estimation, we consider it okay to simplify functions that
4592 * are merely stable; the risk that the result might change from planning
4593 * time to execution time is worth taking in preference to not being able
4594 * to estimate the value at all.
4595 */
4596 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4597 /* okay */ ;
4598 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4599 /* okay */ ;
4600 else
4601 return NULL;
4602
4603 /*
4604 * OK, looks like we can simplify this operator/function.
4605 *
4606 * Build a new FuncExpr node containing the already-simplified arguments.
4607 */
4608 newexpr = makeNode(FuncExpr);
4609 newexpr->funcid = funcid;
4610 newexpr->funcresulttype = result_type;
4611 newexpr->funcretset = false;
4612 newexpr->funcvariadic = funcvariadic;
4613 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4614 newexpr->funccollid = result_collid; /* doesn't matter */
4615 newexpr->inputcollid = input_collid;
4616 newexpr->args = args;
4617 newexpr->location = -1;
4618
4619 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4620 result_collid);
4621}
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:766

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

4281{
4282 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4283 Oid *proargtypes = funcform->proargtypes.values;
4284 int pronargs = funcform->pronargs;
4285 bool has_named_args = false;
4286 ListCell *lc;
4287
4288 /*
4289 * If we are asked to match to OUT arguments, then use the proallargtypes
4290 * array (which includes those); otherwise use proargtypes (which
4291 * doesn't). Of course, if proallargtypes is null, we always use
4292 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4293 * considering that we may have nothing to do here, but fortunately the
4294 * common case is include_out_arguments == false.)
4295 */
4296 if (include_out_arguments)
4297 {
4298 Datum proallargtypes;
4299 bool isNull;
4300
4301 proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4302 Anum_pg_proc_proallargtypes,
4303 &isNull);
4304 if (!isNull)
4305 {
4306 ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4307
4308 pronargs = ARR_DIMS(arr)[0];
4309 if (ARR_NDIM(arr) != 1 ||
4310 pronargs < 0 ||
4311 ARR_HASNULL(arr) ||
4312 ARR_ELEMTYPE(arr) != OIDOID)
4313 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4314 Assert(pronargs >= funcform->pronargs);
4315 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4316 }
4317 }
4318
4319 /* Do we have any named arguments? */
4320 foreach(lc, args)
4321 {
4322 Node *arg = (Node *) lfirst(lc);
4323
4324 if (IsA(arg, NamedArgExpr))
4325 {
4326 has_named_args = true;
4327 break;
4328 }
4329 }
4330
4331 /* If so, we must apply reorder_function_arguments */
4332 if (has_named_args)
4333 {
4335 /* Recheck argument types and add casts if needed */
4336 recheck_cast_function_args(args, result_type,
4337 proargtypes, pronargs,
4338 func_tuple);
4339 }
4340 else if (list_length(args) < pronargs)
4341 {
4342 /* No named args, but we seem to be short some defaults */
4343 args = add_function_defaults(args, pronargs, func_tuple);
4344 /* Recheck argument types and add casts if needed */
4345 recheck_cast_function_args(args, result_type,
4346 proargtypes, pronargs,
4347 func_tuple);
4348 }
4349
4350 return args;
4351}
#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:4430
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4360
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4484
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595

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

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

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

4455{
4456 List *defaults;
4457 Datum proargdefaults;
4458 char *str;
4459
4460 proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4461 Anum_pg_proc_proargdefaults);
4462 str = TextDatumGetCString(proargdefaults);
4463 defaults = castNode(List, stringToNode(str));
4464 pfree(str);
4465 return defaults;
4466}
#define TextDatumGetCString(d)
Definition: builtins.h:98
const char * str
void pfree(void *pointer)
Definition: mcxt.c:1594
void * stringToNode(const char *str)
Definition: read.c:90
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:625

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

1985{
1986 if (node == NULL)
1987 return NULL;
1988 if (IsA(node, NullTest))
1989 {
1990 /* check for var IS NULL */
1991 NullTest *expr = (NullTest *) node;
1992
1993 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1994 {
1995 Var *var = (Var *) expr->arg;
1996
1997 if (var && IsA(var, Var) &&
1998 var->varlevelsup == 0)
1999 return var;
2000 }
2001 }
2002 else if (IsA(node, BooleanTest))
2003 {
2004 /* var IS UNKNOWN is equivalent to var IS NULL */
2005 BooleanTest *expr = (BooleanTest *) node;
2006
2007 if (expr->booltesttype == IS_UNKNOWN)
2008 {
2009 Var *var = (Var *) expr->arg;
2010
2011 if (var && IsA(var, Var) &&
2012 var->varlevelsup == 0)
2013 return var;
2014 }
2015 }
2016 return NULL;
2017}
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 1923 of file clauses.c.

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

1464{
1465 return find_nonnullable_rels_walker(clause, true);
1466}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1469

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

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

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

1715{
1716 return find_nonnullable_vars_walker(clause, true);
1717}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1720

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

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

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

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

4660{
4661 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4662 char *src;
4663 Datum tmp;
4664 bool isNull;
4665 MemoryContext oldcxt;
4666 MemoryContext mycxt;
4667 inline_error_callback_arg callback_arg;
4668 ErrorContextCallback sqlerrcontext;
4669 FuncExpr *fexpr;
4671 TupleDesc rettupdesc;
4672 ParseState *pstate;
4673 List *raw_parsetree_list;
4674 List *querytree_list;
4676 Node *newexpr;
4677 int *usecounts;
4678 ListCell *arg;
4679 int i;
4680
4681 /*
4682 * Forget it if the function is not SQL-language or has other showstopper
4683 * properties. (The prokind and nargs checks are just paranoia.)
4684 */
4685 if (funcform->prolang != SQLlanguageId ||
4686 funcform->prokind != PROKIND_FUNCTION ||
4687 funcform->prosecdef ||
4688 funcform->proretset ||
4689 funcform->prorettype == RECORDOID ||
4690 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4691 funcform->pronargs != list_length(args))
4692 return NULL;
4693
4694 /* Check for recursive function, and give up trying to expand if so */
4695 if (list_member_oid(context->active_fns, funcid))
4696 return NULL;
4697
4698 /* Check permission to call function (fail later, if not) */
4699 if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4700 return NULL;
4701
4702 /* Check whether a plugin wants to hook function entry/exit */
4703 if (FmgrHookIsNeeded(funcid))
4704 return NULL;
4705
4706 /*
4707 * Make a temporary memory context, so that we don't leak all the stuff
4708 * that parsing might create.
4709 */
4711 "inline_function",
4713 oldcxt = MemoryContextSwitchTo(mycxt);
4714
4715 /*
4716 * We need a dummy FuncExpr node containing the already-simplified
4717 * arguments. (In some cases we don't really need it, but building it is
4718 * cheap enough that it's not worth contortions to avoid.)
4719 */
4720 fexpr = makeNode(FuncExpr);
4721 fexpr->funcid = funcid;
4722 fexpr->funcresulttype = result_type;
4723 fexpr->funcretset = false;
4724 fexpr->funcvariadic = funcvariadic;
4725 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4726 fexpr->funccollid = result_collid; /* doesn't matter */
4727 fexpr->inputcollid = input_collid;
4728 fexpr->args = args;
4729 fexpr->location = -1;
4730
4731 /* Fetch the function body */
4732 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4733 src = TextDatumGetCString(tmp);
4734
4735 /*
4736 * Setup error traceback support for ereport(). This is so that we can
4737 * finger the function that bad information came from.
4738 */
4739 callback_arg.proname = NameStr(funcform->proname);
4740 callback_arg.prosrc = src;
4741
4742 sqlerrcontext.callback = sql_inline_error_callback;
4743 sqlerrcontext.arg = &callback_arg;
4744 sqlerrcontext.previous = error_context_stack;
4745 error_context_stack = &sqlerrcontext;
4746
4747 /* If we have prosqlbody, pay attention to that not prosrc */
4748 tmp = SysCacheGetAttr(PROCOID,
4749 func_tuple,
4750 Anum_pg_proc_prosqlbody,
4751 &isNull);
4752 if (!isNull)
4753 {
4754 Node *n;
4755 List *query_list;
4756
4758 if (IsA(n, List))
4759 query_list = linitial_node(List, castNode(List, n));
4760 else
4761 query_list = list_make1(n);
4762 if (list_length(query_list) != 1)
4763 goto fail;
4764 querytree = linitial(query_list);
4765
4766 /*
4767 * Because we'll insist below that the querytree have an empty rtable
4768 * and no sublinks, it cannot have any relation references that need
4769 * to be locked or rewritten. So we can omit those steps.
4770 */
4771 }
4772 else
4773 {
4774 /* Set up to handle parameters while parsing the function body. */
4775 pinfo = prepare_sql_fn_parse_info(func_tuple,
4776 (Node *) fexpr,
4777 input_collid);
4778
4779 /*
4780 * We just do parsing and parse analysis, not rewriting, because
4781 * rewriting will not affect table-free-SELECT-only queries, which is
4782 * all that we care about. Also, we can punt as soon as we detect
4783 * more than one command in the function body.
4784 */
4785 raw_parsetree_list = pg_parse_query(src);
4786 if (list_length(raw_parsetree_list) != 1)
4787 goto fail;
4788
4789 pstate = make_parsestate(NULL);
4790 pstate->p_sourcetext = src;
4791 sql_fn_parser_setup(pstate, pinfo);
4792
4793 querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4794
4795 free_parsestate(pstate);
4796 }
4797
4798 /*
4799 * The single command must be a simple "SELECT expression".
4800 *
4801 * Note: if you change the tests involved in this, see also plpgsql's
4802 * exec_simple_check_plan(). That generally needs to have the same idea
4803 * of what's a "simple expression", so that inlining a function that
4804 * previously wasn't inlined won't change plpgsql's conclusion.
4805 */
4806 if (!IsA(querytree, Query) ||
4807 querytree->commandType != CMD_SELECT ||
4808 querytree->hasAggs ||
4809 querytree->hasWindowFuncs ||
4810 querytree->hasTargetSRFs ||
4811 querytree->hasSubLinks ||
4812 querytree->cteList ||
4813 querytree->rtable ||
4814 querytree->jointree->fromlist ||
4815 querytree->jointree->quals ||
4816 querytree->groupClause ||
4817 querytree->groupingSets ||
4818 querytree->havingQual ||
4819 querytree->windowClause ||
4820 querytree->distinctClause ||
4821 querytree->sortClause ||
4822 querytree->limitOffset ||
4823 querytree->limitCount ||
4824 querytree->setOperations ||
4825 list_length(querytree->targetList) != 1)
4826 goto fail;
4827
4828 /* If the function result is composite, resolve it */
4829 (void) get_expr_result_type((Node *) fexpr,
4830 NULL,
4831 &rettupdesc);
4832
4833 /*
4834 * Make sure the function (still) returns what it's declared to. This
4835 * will raise an error if wrong, but that's okay since the function would
4836 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4837 * a coercion if needed to make the tlist expression match the declared
4838 * type of the function.
4839 *
4840 * Note: we do not try this until we have verified that no rewriting was
4841 * needed; that's probably not important, but let's be careful.
4842 */
4843 querytree_list = list_make1(querytree);
4844 if (check_sql_fn_retval(list_make1(querytree_list),
4845 result_type, rettupdesc,
4846 funcform->prokind,
4847 false))
4848 goto fail; /* reject whole-tuple-result cases */
4849
4850 /*
4851 * Given the tests above, check_sql_fn_retval shouldn't have decided to
4852 * inject a projection step, but let's just make sure.
4853 */
4854 if (querytree != linitial(querytree_list))
4855 goto fail;
4856
4857 /* Now we can grab the tlist expression */
4858 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4859
4860 /*
4861 * If the SQL function returns VOID, we can only inline it if it is a
4862 * SELECT of an expression returning VOID (ie, it's just a redirection to
4863 * another VOID-returning function). In all non-VOID-returning cases,
4864 * check_sql_fn_retval should ensure that newexpr returns the function's
4865 * declared result type, so this test shouldn't fail otherwise; but we may
4866 * as well cope gracefully if it does.
4867 */
4868 if (exprType(newexpr) != result_type)
4869 goto fail;
4870
4871 /*
4872 * Additional validity checks on the expression. It mustn't be more
4873 * volatile than the surrounding function (this is to avoid breaking hacks
4874 * that involve pretending a function is immutable when it really ain't).
4875 * If the surrounding function is declared strict, then the expression
4876 * must contain only strict constructs and must use all of the function
4877 * parameters (this is overkill, but an exact analysis is hard).
4878 */
4879 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4881 goto fail;
4882 else if (funcform->provolatile == PROVOLATILE_STABLE &&
4884 goto fail;
4885
4886 if (funcform->proisstrict &&
4888 goto fail;
4889
4890 /*
4891 * If any parameter expression contains a context-dependent node, we can't
4892 * inline, for fear of putting such a node into the wrong context.
4893 */
4895 goto fail;
4896
4897 /*
4898 * We may be able to do it; there are still checks on parameter usage to
4899 * make, but those are most easily done in combination with the actual
4900 * substitution of the inputs. So start building expression with inputs
4901 * substituted.
4902 */
4903 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4904 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4905 args, usecounts);
4906
4907 /* Now check for parameter usage */
4908 i = 0;
4909 foreach(arg, args)
4910 {
4911 Node *param = lfirst(arg);
4912
4913 if (usecounts[i] == 0)
4914 {
4915 /* Param not used at all: uncool if func is strict */
4916 if (funcform->proisstrict)
4917 goto fail;
4918 }
4919 else if (usecounts[i] != 1)
4920 {
4921 /* Param used multiple times: uncool if expensive or volatile */
4922 QualCost eval_cost;
4923
4924 /*
4925 * We define "expensive" as "contains any subplan or more than 10
4926 * operators". Note that the subplan search has to be done
4927 * explicitly, since cost_qual_eval() will barf on unplanned
4928 * subselects.
4929 */
4930 if (contain_subplans(param))
4931 goto fail;
4932 cost_qual_eval(&eval_cost, list_make1(param), NULL);
4933 if (eval_cost.startup + eval_cost.per_tuple >
4934 10 * cpu_operator_cost)
4935 goto fail;
4936
4937 /*
4938 * Check volatility last since this is more expensive than the
4939 * above tests
4940 */
4941 if (contain_volatile_functions(param))
4942 goto fail;
4943 }
4944 i++;
4945 }
4946
4947 /*
4948 * Whew --- we can make the substitution. Copy the modified expression
4949 * out of the temporary memory context, and clean up.
4950 */
4951 MemoryContextSwitchTo(oldcxt);
4952
4953 newexpr = copyObject(newexpr);
4954
4955 MemoryContextDelete(mycxt);
4956
4957 /*
4958 * If the result is of a collatable type, force the result to expose the
4959 * correct collation. In most cases this does not matter, but it's
4960 * possible that the function result is used directly as a sort key or in
4961 * other places where we expect exprCollation() to tell the truth.
4962 */
4963 if (OidIsValid(result_collid))
4964 {
4965 Oid exprcoll = exprCollation(newexpr);
4966
4967 if (OidIsValid(exprcoll) && exprcoll != result_collid)
4968 {
4969 CollateExpr *newnode = makeNode(CollateExpr);
4970
4971 newnode->arg = (Expr *) newexpr;
4972 newnode->collOid = result_collid;
4973 newnode->location = -1;
4974
4975 newexpr = (Node *) newnode;
4976 }
4977 }
4978
4979 /*
4980 * Since there is now no trace of the function in the plan tree, we must
4981 * explicitly record the plan's dependency on the function.
4982 */
4983 if (context->root)
4984 record_plan_function_dependency(context->root, funcid);
4985
4986 /*
4987 * Recursively try to simplify the modified expression. Here we must add
4988 * the current function to the context list of active functions.
4989 */
4990 context->active_fns = lappend_oid(context->active_fns, funcid);
4991 newexpr = eval_const_expressions_mutator(newexpr, context);
4992 context->active_fns = list_delete_last(context->active_fns);
4993
4994 error_context_stack = sqlerrcontext.previous;
4995
4996 return (Expr *) newexpr;
4997
4998 /* Here if func is not inlinable: release temp memory and return NULL */
4999fail:
5000 MemoryContextSwitchTo(oldcxt);
5001 MemoryContextDelete(mycxt);
5002 error_context_stack = sqlerrcontext.previous;
5003
5004 return NULL;
5005}
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:3834
#define NameStr(name)
Definition: c.h:751
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:5011
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:5052
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1185
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:997
bool contain_subplans(Node *clause)
Definition: clauses.c:334
double cpu_operator_cost
Definition: costsize.c:134
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4791
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:2116
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:340
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:251
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:160
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
Oid GetUserId(void)
Definition: miscinit.c:469
@ CMD_SELECT
Definition: nodes.h:275
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:260
#define linitial_node(type, l)
Definition: pg_list.h:181
List * pg_parse_query(const char *query_string)
Definition: postgres.c:604
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3575
struct ErrorContextCallback * previous
Definition: elog.h:297
void(* callback)(void *arg)
Definition: elog.h:298
const char * p_sourcetext
Definition: parse_node.h:195
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 5168 of file clauses.c.

5169{
5170 RangeTblFunction *rtfunc;
5171 FuncExpr *fexpr;
5172 Oid func_oid;
5173 HeapTuple func_tuple;
5174 Form_pg_proc funcform;
5175 char *src;
5176 Datum tmp;
5177 bool isNull;
5178 MemoryContext oldcxt;
5179 MemoryContext mycxt;
5180 inline_error_callback_arg callback_arg;
5181 ErrorContextCallback sqlerrcontext;
5183 TypeFuncClass functypclass;
5184 TupleDesc rettupdesc;
5185 List *raw_parsetree_list;
5186 List *querytree_list;
5188
5189 Assert(rte->rtekind == RTE_FUNCTION);
5190
5191 /*
5192 * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
5193 * own FROM clause, since that must cause infinite recursion at runtime.
5194 * It will cause this code to recurse too, so check for stack overflow.
5195 * (There's no need to do more.)
5196 */
5198
5199 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5200 if (rte->funcordinality)
5201 return NULL;
5202
5203 /* Fail if RTE isn't a single, simple FuncExpr */
5204 if (list_length(rte->functions) != 1)
5205 return NULL;
5206 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5207
5208 if (!IsA(rtfunc->funcexpr, FuncExpr))
5209 return NULL;
5210 fexpr = (FuncExpr *) rtfunc->funcexpr;
5211
5212 func_oid = fexpr->funcid;
5213
5214 /*
5215 * The function must be declared to return a set, else inlining would
5216 * change the results if the contained SELECT didn't return exactly one
5217 * row.
5218 */
5219 if (!fexpr->funcretset)
5220 return NULL;
5221
5222 /*
5223 * Refuse to inline if the arguments contain any volatile functions or
5224 * sub-selects. Volatile functions are rejected because inlining may
5225 * result in the arguments being evaluated multiple times, risking a
5226 * change in behavior. Sub-selects are rejected partly for implementation
5227 * reasons (pushing them down another level might change their behavior)
5228 * and partly because they're likely to be expensive and so multiple
5229 * evaluation would be bad.
5230 */
5231 if (contain_volatile_functions((Node *) fexpr->args) ||
5232 contain_subplans((Node *) fexpr->args))
5233 return NULL;
5234
5235 /* Check permission to call function (fail later, if not) */
5236 if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5237 return NULL;
5238
5239 /* Check whether a plugin wants to hook function entry/exit */
5240 if (FmgrHookIsNeeded(func_oid))
5241 return NULL;
5242
5243 /*
5244 * OK, let's take a look at the function's pg_proc entry.
5245 */
5246 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5247 if (!HeapTupleIsValid(func_tuple))
5248 elog(ERROR, "cache lookup failed for function %u", func_oid);
5249 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5250
5251 /*
5252 * Forget it if the function is not SQL-language or has other showstopper
5253 * properties. In particular it mustn't be declared STRICT, since we
5254 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5255 * supposed to cause it to be executed with its own snapshot, rather than
5256 * sharing the snapshot of the calling query. We also disallow returning
5257 * SETOF VOID, because inlining would result in exposing the actual result
5258 * of the function's last SELECT, which should not happen in that case.
5259 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5260 */
5261 if (funcform->prolang != SQLlanguageId ||
5262 funcform->prokind != PROKIND_FUNCTION ||
5263 funcform->proisstrict ||
5264 funcform->provolatile == PROVOLATILE_VOLATILE ||
5265 funcform->prorettype == VOIDOID ||
5266 funcform->prosecdef ||
5267 !funcform->proretset ||
5268 list_length(fexpr->args) != funcform->pronargs ||
5269 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5270 {
5271 ReleaseSysCache(func_tuple);
5272 return NULL;
5273 }
5274
5275 /*
5276 * Make a temporary memory context, so that we don't leak all the stuff
5277 * that parsing might create.
5278 */
5280 "inline_set_returning_function",
5282 oldcxt = MemoryContextSwitchTo(mycxt);
5283
5284 /* Fetch the function body */
5285 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5286 src = TextDatumGetCString(tmp);
5287
5288 /*
5289 * Setup error traceback support for ereport(). This is so that we can
5290 * finger the function that bad information came from.
5291 */
5292 callback_arg.proname = NameStr(funcform->proname);
5293 callback_arg.prosrc = src;
5294
5295 sqlerrcontext.callback = sql_inline_error_callback;
5296 sqlerrcontext.arg = &callback_arg;
5297 sqlerrcontext.previous = error_context_stack;
5298 error_context_stack = &sqlerrcontext;
5299
5300 /* If we have prosqlbody, pay attention to that not prosrc */
5301 tmp = SysCacheGetAttr(PROCOID,
5302 func_tuple,
5303 Anum_pg_proc_prosqlbody,
5304 &isNull);
5305 if (!isNull)
5306 {
5307 Node *n;
5308
5310 if (IsA(n, List))
5311 querytree_list = linitial_node(List, castNode(List, n));
5312 else
5313 querytree_list = list_make1(n);
5314 if (list_length(querytree_list) != 1)
5315 goto fail;
5316 querytree = linitial(querytree_list);
5317
5318 /* Acquire necessary locks, then apply rewriter. */
5319 AcquireRewriteLocks(querytree, true, false);
5320 querytree_list = pg_rewrite_query(querytree);
5321 if (list_length(querytree_list) != 1)
5322 goto fail;
5323 querytree = linitial(querytree_list);
5324 }
5325 else
5326 {
5327 /*
5328 * Set up to handle parameters while parsing the function body. We
5329 * can use the FuncExpr just created as the input for
5330 * prepare_sql_fn_parse_info.
5331 */
5332 pinfo = prepare_sql_fn_parse_info(func_tuple,
5333 (Node *) fexpr,
5334 fexpr->inputcollid);
5335
5336 /*
5337 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5338 * skip rewriting here). We can fail as soon as we find more than one
5339 * query, though.
5340 */
5341 raw_parsetree_list = pg_parse_query(src);
5342 if (list_length(raw_parsetree_list) != 1)
5343 goto fail;
5344
5345 querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5346 src,
5348 pinfo, NULL);
5349 if (list_length(querytree_list) != 1)
5350 goto fail;
5351 querytree = linitial(querytree_list);
5352 }
5353
5354 /*
5355 * Also resolve the actual function result tupdesc, if composite. If we
5356 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5357 * (This logic should match ExecInitFunctionScan.)
5358 */
5359 if (rtfunc->funccolnames != NIL)
5360 {
5361 functypclass = TYPEFUNC_RECORD;
5362 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5363 rtfunc->funccoltypes,
5364 rtfunc->funccoltypmods,
5365 rtfunc->funccolcollations);
5366 }
5367 else
5368 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5369
5370 /*
5371 * The single command must be a plain SELECT.
5372 */
5373 if (!IsA(querytree, Query) ||
5374 querytree->commandType != CMD_SELECT)
5375 goto fail;
5376
5377 /*
5378 * Make sure the function (still) returns what it's declared to. This
5379 * will raise an error if wrong, but that's okay since the function would
5380 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5381 * coercions if needed to make the tlist expression(s) match the declared
5382 * type of the function. We also ask it to insert dummy NULL columns for
5383 * any dropped columns in rettupdesc, so that the elements of the modified
5384 * tlist match up to the attribute numbers.
5385 *
5386 * If the function returns a composite type, don't inline unless the check
5387 * shows it's returning a whole tuple result; otherwise what it's
5388 * returning is a single composite column which is not what we need.
5389 */
5390 if (!check_sql_fn_retval(list_make1(querytree_list),
5391 fexpr->funcresulttype, rettupdesc,
5392 funcform->prokind,
5393 true) &&
5394 (functypclass == TYPEFUNC_COMPOSITE ||
5395 functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5396 functypclass == TYPEFUNC_RECORD))
5397 goto fail; /* reject not-whole-tuple-result cases */
5398
5399 /*
5400 * check_sql_fn_retval might've inserted a projection step, but that's
5401 * fine; just make sure we use the upper Query.
5402 */
5403 querytree = linitial_node(Query, querytree_list);
5404
5405 /*
5406 * Looks good --- substitute parameters into the query.
5407 */
5409 funcform->pronargs,
5410 fexpr->args);
5411
5412 /*
5413 * Copy the modified query out of the temporary memory context, and clean
5414 * up.
5415 */
5416 MemoryContextSwitchTo(oldcxt);
5417
5419
5420 MemoryContextDelete(mycxt);
5421 error_context_stack = sqlerrcontext.previous;
5422 ReleaseSysCache(func_tuple);
5423
5424 /*
5425 * We don't have to fix collations here because the upper query is already
5426 * parsed, ie, the collations in the RTE are what count.
5427 */
5428
5429 /*
5430 * Since there is now no trace of the function in the plan tree, we must
5431 * explicitly record the plan's dependency on the function.
5432 */
5434
5435 /*
5436 * We must also notice if the inserted query adds a dependency on the
5437 * calling role due to RLS quals.
5438 */
5439 if (querytree->hasRowSecurity)
5440 root->glob->dependsOnRole = true;
5441
5442 return querytree;
5443
5444 /* Here if func is not inlinable: release temp memory and return NULL */
5445fail:
5446 MemoryContextSwitchTo(oldcxt);
5447 MemoryContextDelete(mycxt);
5448 error_context_stack = sqlerrcontext.previous;
5449 ReleaseSysCache(func_tuple);
5450
5451 return NULL;
5452}
static Query * substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
Definition: clauses.c:5461
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)(ParseState *pstate, void *arg)
Definition: params.h:107
@ RTE_FUNCTION
Definition: parsenodes.h:1046
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:763
List * pg_rewrite_query(Query *query)
Definition: postgres.c:803
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
bool funcordinality
Definition: parsenodes.h:1210
List * functions
Definition: parsenodes.h:1208
RTEKind rtekind
Definition: parsenodes.h:1078
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition: tupdesc.c:1051

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

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

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_nestloop_plan(), create_partial_unique_paths(), 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 2095 of file clauses.c.

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

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

2116{
2117 if (bms_is_empty(relids) &&
2119 return true;
2120 return false;
2121}

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

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

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

5555{
5556 Node *arrayNode = NULL;
5557 ScalarArrayOpExpr *saopexpr = NULL;
5558 Oid arraytype = get_array_type(coltype);
5559
5560 if (!OidIsValid(arraytype))
5561 return NULL;
5562
5563 /*
5564 * Assemble an array from the list of constants. It seems more profitable
5565 * to build a const array. But in the presence of other nodes, we don't
5566 * have a specific value here and must employ an ArrayExpr instead.
5567 */
5568 if (haveNonConst)
5569 {
5570 ArrayExpr *arrayExpr = makeNode(ArrayExpr);
5571
5572 /* array_collid will be set by parse_collate.c */
5573 arrayExpr->element_typeid = coltype;
5574 arrayExpr->array_typeid = arraytype;
5575 arrayExpr->multidims = false;
5576 arrayExpr->elements = exprs;
5577 arrayExpr->location = -1;
5578
5579 arrayNode = (Node *) arrayExpr;
5580 }
5581 else
5582 {
5583 int16 typlen;
5584 bool typbyval;
5585 char typalign;
5586 Datum *elems;
5587 bool *nulls;
5588 int i = 0;
5589 ArrayType *arrayConst;
5590 int dims[1] = {list_length(exprs)};
5591 int lbs[1] = {1};
5592
5593 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5594
5595 elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
5596 nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
5597 foreach_node(Const, value, exprs)
5598 {
5599 elems[i] = value->constvalue;
5600 nulls[i++] = value->constisnull;
5601 }
5602
5603 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5604 coltype, typlen, typbyval, typalign);
5605 arrayNode = (Node *) makeConst(arraytype, -1, arraycollid,
5606 -1, PointerGetDatum(arrayConst),
5607 false, false);
5608
5609 pfree(elems);
5610 pfree(nulls);
5611 list_free(exprs);
5612 }
5613
5614 /* Build the SAOP expression node */
5615 saopexpr = makeNode(ScalarArrayOpExpr);
5616 saopexpr->opno = oper;
5617 saopexpr->opfuncid = get_opcode(oper);
5618 saopexpr->hashfuncid = InvalidOid;
5619 saopexpr->negfuncid = InvalidOid;
5620 saopexpr->useOr = true;
5621 saopexpr->inputcollid = inputcollid;
5622 saopexpr->args = list_make2(leftexpr, arrayNode);
5623 saopexpr->location = -1;
5624
5625 return saopexpr;
5626}
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:3495
static struct @169 value
void list_free(List *list)
Definition: list.c:1546
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2438
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2954
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:371
#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:1421
ParseLoc location
Definition: primnodes.h:951

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

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

827{
829 (max_parallel_hazard_context *) context);
830}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:798
char func_parallel(Oid funcid)
Definition: lsyscache.c:1966

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

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

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

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

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

2138{
2139 int result;
2140 Relids varnos = pull_varnos(root, clause);
2141
2142 varnos = bms_del_members(varnos, root->outer_join_rels);
2143 result = bms_num_members(varnos);
2144 bms_free(varnos);
2145 return result;
2146}
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 5521 of file clauses.c.

5522{
5523 Bitmapset *result = NULL;
5524
5525 (void) pull_paramids_walker((Node *) expr, &result);
5526
5527 return result;
5528}
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition: clauses.c:5531

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

5532{
5533 if (node == NULL)
5534 return false;
5535 if (IsA(node, Param))
5536 {
5537 Param *param = (Param *) node;
5538
5539 *context = bms_add_member(*context, param->paramid);
5540 return false;
5541 }
5542 return expression_tree_walker(node, pull_paramids_walker, context);
5543}
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 4484 of file clauses.c.

4487{
4488 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4489 int nargs;
4490 Oid actual_arg_types[FUNC_MAX_ARGS];
4491 Oid declared_arg_types[FUNC_MAX_ARGS];
4492 Oid rettype;
4493 ListCell *lc;
4494
4496 elog(ERROR, "too many function arguments");
4497 nargs = 0;
4498 foreach(lc, args)
4499 {
4500 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4501 }
4502 Assert(nargs == pronargs);
4503 memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4504 rettype = enforce_generic_type_consistency(actual_arg_types,
4505 declared_arg_types,
4506 nargs,
4507 funcform->prorettype,
4508 false);
4509 /* let's just check we got the same answer as the parser did ... */
4510 if (rettype != result_type)
4511 elog(ERROR, "function's resolved result type changed during planning");
4512
4513 /* perform any necessary typecasting of arguments */
4514 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4515}
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:1948
#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 4360 of file clauses.c.

4361{
4362 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4363 int nargsprovided = list_length(args);
4364 Node *argarray[FUNC_MAX_ARGS];
4365 ListCell *lc;
4366 int i;
4367
4368 Assert(nargsprovided <= pronargs);
4369 if (pronargs < 0 || pronargs > FUNC_MAX_ARGS)
4370 elog(ERROR, "too many function arguments");
4371 memset(argarray, 0, pronargs * sizeof(Node *));
4372
4373 /* Deconstruct the argument list into an array indexed by argnumber */
4374 i = 0;
4375 foreach(lc, args)
4376 {
4377 Node *arg = (Node *) lfirst(lc);
4378
4379 if (!IsA(arg, NamedArgExpr))
4380 {
4381 /* positional argument, assumed to precede all named args */
4382 Assert(argarray[i] == NULL);
4383 argarray[i++] = arg;
4384 }
4385 else
4386 {
4387 NamedArgExpr *na = (NamedArgExpr *) arg;
4388
4389 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4390 Assert(argarray[na->argnumber] == NULL);
4391 argarray[na->argnumber] = (Node *) na->arg;
4392 }
4393 }
4394
4395 /*
4396 * Fetch default expressions, if needed, and insert into array at proper
4397 * locations (they aren't necessarily consecutive or all used)
4398 */
4399 if (nargsprovided < pronargs)
4400 {
4401 List *defaults = fetch_function_defaults(func_tuple);
4402
4403 i = pronargs - funcform->pronargdefaults;
4404 foreach(lc, defaults)
4405 {
4406 if (argarray[i] == NULL)
4407 argarray[i] = (Node *) lfirst(lc);
4408 i++;
4409 }
4410 }
4411
4412 /* Now reconstruct the args list in proper order */
4413 args = NIL;
4414 for (i = 0; i < pronargs; i++)
4415 {
4416 Assert(argarray[i] != NULL);
4417 args = lappend(args, argarray[i]);
4418 }
4419
4420 return args;
4421}
Expr * arg
Definition: primnodes.h:823

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

2196{
2197 TupleDesc tupdesc;
2198 Form_pg_attribute attr;
2199
2200 /* No issue for RECORD, since there is no way to ALTER such a type */
2201 if (rowtypeid == RECORDOID)
2202 return true;
2203 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2204 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2205 {
2206 ReleaseTupleDesc(tupdesc);
2207 return false;
2208 }
2209 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2210 if (attr->attisdropped ||
2211 attr->atttypid != expectedtype ||
2212 attr->atttypmod != expectedtypmod ||
2213 attr->attcollation != expectedcollation)
2214 {
2215 ReleaseTupleDesc(tupdesc);
2216 return false;
2217 }
2218 ReleaseTupleDesc(tupdesc);
2219 return true;
2220}
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:1977

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

3942{
3943 List *newargs = NIL;
3944 List *unprocessed_args;
3945
3946 /* See comments in simplify_or_arguments */
3947 unprocessed_args = list_copy(args);
3948 while (unprocessed_args)
3949 {
3950 Node *arg = (Node *) linitial(unprocessed_args);
3951
3952 unprocessed_args = list_delete_first(unprocessed_args);
3953
3954 /* flatten nested ANDs as per above comment */
3955 if (is_andclause(arg))
3956 {
3957 List *subargs = ((BoolExpr *) arg)->args;
3958 List *oldlist = unprocessed_args;
3959
3960 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3961 /* perhaps-overly-tense code to avoid leaking old lists */
3962 list_free(oldlist);
3963 continue;
3964 }
3965
3966 /* If it's not an AND, simplify it */
3968
3969 /*
3970 * It is unlikely but not impossible for simplification of a non-AND
3971 * clause to produce an AND. Recheck, but don't be too tense about it
3972 * since it's not a mainstream case. In particular we don't worry
3973 * about const-simplifying the input twice, nor about list leakage.
3974 */
3975 if (is_andclause(arg))
3976 {
3977 List *subargs = ((BoolExpr *) arg)->args;
3978
3979 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3980 continue;
3981 }
3982
3983 /*
3984 * OK, we have a const-simplified non-AND argument. Process it per
3985 * comments above.
3986 */
3987 if (IsA(arg, Const))
3988 {
3989 Const *const_input = (Const *) arg;
3990
3991 if (const_input->constisnull)
3992 *haveNull = true;
3993 else if (!DatumGetBool(const_input->constvalue))
3994 {
3995 *forceFalse = true;
3996
3997 /*
3998 * Once we detect a FALSE result we can just exit the loop
3999 * immediately. However, if we ever add a notion of
4000 * non-removable functions, we'd need to keep scanning.
4001 */
4002 return NIL;
4003 }
4004 /* otherwise, we can drop the constant-true input */
4005 continue;
4006 }
4007
4008 /* else emit the simplified arg into the result list */
4009 newargs = lappend(newargs, arg);
4010 }
4011
4012 return newargs;
4013}
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 4033 of file clauses.c.

4034{
4035 Node *leftop;
4036 Node *rightop;
4037
4038 Assert(list_length(args) == 2);
4039 leftop = linitial(args);
4040 rightop = lsecond(args);
4041 if (leftop && IsA(leftop, Const))
4042 {
4043 Assert(!((Const *) leftop)->constisnull);
4044 if (opno == BooleanEqualOperator)
4045 {
4046 if (DatumGetBool(((Const *) leftop)->constvalue))
4047 return rightop; /* true = foo */
4048 else
4049 return negate_clause(rightop); /* false = foo */
4050 }
4051 else
4052 {
4053 if (DatumGetBool(((Const *) leftop)->constvalue))
4054 return negate_clause(rightop); /* true <> foo */
4055 else
4056 return rightop; /* false <> foo */
4057 }
4058 }
4059 if (rightop && IsA(rightop, Const))
4060 {
4061 Assert(!((Const *) rightop)->constisnull);
4062 if (opno == BooleanEqualOperator)
4063 {
4064 if (DatumGetBool(((Const *) rightop)->constvalue))
4065 return leftop; /* foo = true */
4066 else
4067 return negate_clause(leftop); /* foo = false */
4068 }
4069 else
4070 {
4071 if (DatumGetBool(((Const *) rightop)->constvalue))
4072 return negate_clause(leftop); /* foo <> true */
4073 else
4074 return leftop; /* foo <> false */
4075 }
4076 }
4077 return NULL;
4078}

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

4106{
4107 List *args = *args_p;
4108 HeapTuple func_tuple;
4109 Form_pg_proc func_form;
4110 Expr *newexpr;
4111
4112 /*
4113 * We have three strategies for simplification: execute the function to
4114 * deliver a constant result, use a transform function to generate a
4115 * substitute node tree, or expand in-line the body of the function
4116 * definition (which only works for simple SQL-language functions, but
4117 * that is a common case). Each case needs access to the function's
4118 * pg_proc tuple, so fetch it just once.
4119 *
4120 * Note: the allow_non_const flag suppresses both the second and third
4121 * strategies; so if !allow_non_const, simplify_function can only return a
4122 * Const or NULL. Argument-list rewriting happens anyway, though.
4123 */
4124 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4125 if (!HeapTupleIsValid(func_tuple))
4126 elog(ERROR, "cache lookup failed for function %u", funcid);
4127 func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4128
4129 /*
4130 * Process the function arguments, unless the caller did it already.
4131 *
4132 * Here we must deal with named or defaulted arguments, and then
4133 * recursively apply eval_const_expressions to the whole argument list.
4134 */
4135 if (process_args)
4136 {
4137 args = expand_function_arguments(args, false, result_type, func_tuple);
4140 context);
4141 /* Argument processing done, give it back to the caller */
4142 *args_p = args;
4143 }
4144
4145 /* Now attempt simplification of the function call proper. */
4146
4147 newexpr = evaluate_function(funcid, result_type, result_typmod,
4148 result_collid, input_collid,
4149 args, funcvariadic,
4150 func_tuple, context);
4151
4152 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4153 {
4154 /*
4155 * Build a SupportRequestSimplify node to pass to the support
4156 * function, pointing to a dummy FuncExpr node containing the
4157 * simplified arg list. We use this approach to present a uniform
4158 * interface to the support function regardless of how the target
4159 * function is actually being invoked.
4160 */
4162 FuncExpr fexpr;
4163
4164 fexpr.xpr.type = T_FuncExpr;
4165 fexpr.funcid = funcid;
4166 fexpr.funcresulttype = result_type;
4167 fexpr.funcretset = func_form->proretset;
4168 fexpr.funcvariadic = funcvariadic;
4169 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4170 fexpr.funccollid = result_collid;
4171 fexpr.inputcollid = input_collid;
4172 fexpr.args = args;
4173 fexpr.location = -1;
4174
4175 req.type = T_SupportRequestSimplify;
4176 req.root = context->root;
4177 req.fcall = &fexpr;
4178
4179 newexpr = (Expr *)
4180 DatumGetPointer(OidFunctionCall1(func_form->prosupport,
4181 PointerGetDatum(&req)));
4182
4183 /* catch a possible API misunderstanding */
4184 Assert(newexpr != (Expr *) &fexpr);
4185 }
4186
4187 if (!newexpr && allow_non_const)
4188 newexpr = inline_function(funcid, result_type, result_collid,
4189 input_collid, args, funcvariadic,
4190 func_tuple, context);
4191
4192 ReleaseSysCache(func_tuple);
4193
4194 return newexpr;
4195}
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:4529
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:4655
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
Expr xpr
Definition: primnodes.h:780
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 3833 of file clauses.c.

3836{
3837 List *newargs = NIL;
3838 List *unprocessed_args;
3839
3840 /*
3841 * We want to ensure that any OR immediately beneath another OR gets
3842 * flattened into a single OR-list, so as to simplify later reasoning.
3843 *
3844 * To avoid stack overflow from recursion of eval_const_expressions, we
3845 * resort to some tenseness here: we keep a list of not-yet-processed
3846 * inputs, and handle flattening of nested ORs by prepending to the to-do
3847 * list instead of recursing. Now that the parser generates N-argument
3848 * ORs from simple lists, this complexity is probably less necessary than
3849 * it once was, but we might as well keep the logic.
3850 */
3851 unprocessed_args = list_copy(args);
3852 while (unprocessed_args)
3853 {
3854 Node *arg = (Node *) linitial(unprocessed_args);
3855
3856 unprocessed_args = list_delete_first(unprocessed_args);
3857
3858 /* flatten nested ORs as per above comment */
3859 if (is_orclause(arg))
3860 {
3861 List *subargs = ((BoolExpr *) arg)->args;
3862 List *oldlist = unprocessed_args;
3863
3864 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3865 /* perhaps-overly-tense code to avoid leaking old lists */
3866 list_free(oldlist);
3867 continue;
3868 }
3869
3870 /* If it's not an OR, simplify it */
3872
3873 /*
3874 * It is unlikely but not impossible for simplification of a non-OR
3875 * clause to produce an OR. Recheck, but don't be too tense about it
3876 * since it's not a mainstream case. In particular we don't worry
3877 * about const-simplifying the input twice, nor about list leakage.
3878 */
3879 if (is_orclause(arg))
3880 {
3881 List *subargs = ((BoolExpr *) arg)->args;
3882
3883 unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3884 continue;
3885 }
3886
3887 /*
3888 * OK, we have a const-simplified non-OR argument. Process it per
3889 * comments above.
3890 */
3891 if (IsA(arg, Const))
3892 {
3893 Const *const_input = (Const *) arg;
3894
3895 if (const_input->constisnull)
3896 *haveNull = true;
3897 else if (DatumGetBool(const_input->constvalue))
3898 {
3899 *forceTrue = true;
3900
3901 /*
3902 * Once we detect a TRUE result we can just exit the loop
3903 * immediately. However, if we ever add a notion of
3904 * non-removable functions, we'd need to keep scanning.
3905 */
3906 return NIL;
3907 }
3908 /* otherwise, we can drop the constant-false input */
3909 continue;
3910 }
3911
3912 /* else emit the simplified arg into the result list */
3913 newargs = lappend(newargs, arg);
3914 }
3915
3916 return newargs;
3917}
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 5052 of file clauses.c.

5053{
5055 int syntaxerrposition;
5056
5057 /* If it's a syntax error, convert to internal syntax error report */
5058 syntaxerrposition = geterrposition();
5059 if (syntaxerrposition > 0)
5060 {
5061 errposition(0);
5062 internalerrposition(syntaxerrposition);
5063 internalerrquery(callback_arg->prosrc);
5064 }
5065
5066 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5067}
int internalerrquery(const char *query)
Definition: elog.c:1507
int internalerrposition(int cursorpos)
Definition: elog.c:1487
int geterrposition(void)
Definition: elog.c:1603
int errposition(int cursorpos)
Definition: elog.c:1471
#define errcontext
Definition: elog.h:198

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

5013{
5015
5016 context.nargs = nargs;
5017 context.args = args;
5018 context.usecounts = usecounts;
5019
5020 return substitute_actual_parameters_mutator(expr, &context);
5021}
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition: clauses.c:5024

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

5026{
5027 if (node == NULL)
5028 return NULL;
5029 if (IsA(node, Param))
5030 {
5031 Param *param = (Param *) node;
5032
5033 if (param->paramkind != PARAM_EXTERN)
5034 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5035 if (param->paramid <= 0 || param->paramid > context->nargs)
5036 elog(ERROR, "invalid paramid: %d", param->paramid);
5037
5038 /* Count usage of parameter */
5039 context->usecounts[param->paramid - 1]++;
5040
5041 /* Select the appropriate actual arg and replace the Param with it */
5042 /* We don't need to copy at this time (it'll get done later) */
5043 return list_nth(context->args, param->paramid - 1);
5044 }
5046}

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

5462{
5464
5465 context.nargs = nargs;
5466 context.args = args;
5467 context.sublevels_up = 1;
5468
5469 return query_tree_mutator(expr,
5471 &context,
5472 0);
5473}
static Node * substitute_actual_srf_parameters_mutator(Node *node, substitute_actual_srf_parameters_context *context)
Definition: clauses.c:5476
#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 5476 of file clauses.c.

5478{
5479 Node *result;
5480
5481 if (node == NULL)
5482 return NULL;
5483 if (IsA(node, Query))
5484 {
5485 context->sublevels_up++;
5486 result = (Node *) query_tree_mutator((Query *) node,
5488 context,
5489 0);
5490 context->sublevels_up--;
5491 return result;
5492 }
5493 if (IsA(node, Param))
5494 {
5495 Param *param = (Param *) node;
5496
5497 if (param->paramkind == PARAM_EXTERN)
5498 {
5499 if (param->paramid <= 0 || param->paramid > context->nargs)
5500 elog(ERROR, "invalid paramid: %d", param->paramid);
5501
5502 /*
5503 * Since the parameter is being inserted into a subquery, we must
5504 * adjust levels.
5505 */
5506 result = copyObject(list_nth(context->args, param->paramid - 1));
5507 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5508 return result;
5509 }
5510 }
5511 return expression_tree_mutator(node,
5513 context);
5514}
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:884

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().

◆ var_is_nonnullable()

bool var_is_nonnullable ( PlannerInfo root,
Var var,
bool  use_rel_info 
)

Definition at line 4207 of file clauses.c.

4208{
4209 Bitmapset *notnullattnums = NULL;
4210
4211 Assert(IsA(var, Var));
4212
4213 /* skip upper-level Vars */
4214 if (var->varlevelsup != 0)
4215 return false;
4216
4217 /* could the Var be nulled by any outer joins or grouping sets? */
4218 if (!bms_is_empty(var->varnullingrels))
4219 return false;
4220
4221 /* system columns cannot be NULL */
4222 if (var->varattno < 0)
4223 return true;
4224
4225 /*
4226 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4227 * NULL constraint information from the corresponding RelOptInfo if it is
4228 * available; otherwise, we search the hash table for this information.
4229 */
4230 if (use_rel_info)
4231 {
4232 RelOptInfo *rel = find_base_rel(root, var->varno);
4233
4234 notnullattnums = rel->notnullattnums;
4235 }
4236 else
4237 {
4239
4240 /*
4241 * We must skip inheritance parent tables, as some child tables may
4242 * have a NOT NULL constraint for a column while others may not. This
4243 * cannot happen with partitioned tables, though.
4244 */
4245 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4246 return false;
4247
4248 notnullattnums = find_relation_notnullatts(root, rte->relid);
4249 }
4250
4251 if (var->varattno > 0 &&
4252 bms_is_member(var->varattno, notnullattnums))
4253 return true;
4254
4255 return false;
4256}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:613
Bitmapset * find_relation_notnullatts(PlannerInfo *root, Oid relid)
Definition: plancat.c:755
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:529
Bitmapset * notnullattnums
Definition: pathnodes.h:990

References Assert(), bms_is_empty, bms_is_member(), find_base_rel(), find_relation_notnullatts(), RangeTblEntry::inh, IsA, RelOptInfo::notnullattnums, planner_rt_fetch, root, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by eval_const_expressions_mutator(), and expr_is_nonnullable().