PostgreSQL Source Code git master
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_parameters_in_from_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 Nodesimplify_aggref (Aggref *aggref, 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 Queryinline_sql_function_in_from (PlannerInfo *root, RangeTblFunction *rtfunc, FuncExpr *fexpr, HeapTuple func_tuple, Form_pg_proc funcform, const char *src)
 
static Querysubstitute_actual_parameters_in_from (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_parameters_in_from_mutator (Node *node, substitute_actual_parameters_in_from_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)
 
bool expr_is_nonnullable (PlannerInfo *root, Expr *expr, 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_function_in_from (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 1200 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 2442 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:5157
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Definition: nodes.h:135

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

Definition at line 2433 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4512{
4513 int nargsprovided = list_length(args);
4514 List *defaults;
4515 int ndelete;
4516
4517 /* Get all the default expressions from the pg_proc tuple */
4518 defaults = fetch_function_defaults(func_tuple);
4519
4520 /* Delete any unused defaults from the list */
4521 ndelete = nargsprovided + list_length(defaults) - pronargs;
4522 if (ndelete < 0)
4523 elog(ERROR, "not enough default arguments");
4524 if (ndelete > 0)
4525 defaults = list_delete_first_n(defaults, ndelete);
4526
4527 /* And form the combined argument list, not modifying the input list */
4528 return list_concat_copy(args, defaults);
4529}
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4535
#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 2162 of file clauses.c.

2163{
2164 Oid opoid;
2165 Node *temp;
2166
2167 /* Sanity checks: caller is at fault if these fail */
2168 if (!is_opclause(clause) ||
2169 list_length(clause->args) != 2)
2170 elog(ERROR, "cannot commute non-binary-operator clause");
2171
2172 opoid = get_commutator(clause->opno);
2173
2174 if (!OidIsValid(opoid))
2175 elog(ERROR, "could not find commutator for operator %u",
2176 clause->opno);
2177
2178 /*
2179 * modify the clause in-place!
2180 */
2181 clause->opno = opoid;
2182 clause->opfuncid = InvalidOid;
2183 /* opresulttype, opretset, opcollid, inputcollid need not change */
2184
2185 temp = linitial(clause->args);
2186 linitial(clause->args) = lsecond(clause->args);
2187 lsecond(clause->args) = temp;
2188}
#define OidIsValid(objectId)
Definition: c.h:777
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 190 of file clauses.c.

191{
192 return contain_agg_clause_walker(clause, NULL);
193}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:196

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

197{
198 if (node == NULL)
199 return false;
200 if (IsA(node, Aggref))
201 {
202 Assert(((Aggref *) node)->agglevelsup == 0);
203 return true; /* abort the tree traversal and return true */
204 }
205 if (IsA(node, GroupingFunc))
206 {
207 Assert(((GroupingFunc *) node)->agglevelsup == 0);
208 return true; /* abort the tree traversal and return true */
209 }
210 Assert(!IsA(node, SubLink));
212}
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 1193 of file clauses.c.

1194{
1195 int flags = 0;
1196
1197 return contain_context_dependent_node_walker(clause, &flags);
1198}
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1203

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

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

1152{
1153 return contain_exec_param_walker(clause, param_ids);
1154}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1157

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

1158{
1159 if (node == NULL)
1160 return false;
1161 if (IsA(node, Param))
1162 {
1163 Param *p = (Param *) node;
1164
1165 if (p->paramkind == PARAM_EXEC &&
1166 list_member_int(param_ids, p->paramid))
1167 return true;
1168 }
1169 return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1170}
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 1277 of file clauses.c.

1278{
1279 return contain_leaked_vars_walker(clause, NULL);
1280}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1289

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

1284{
1285 return !get_func_leakproof(func_id);
1286}
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 1289 of file clauses.c.

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

503{
504 /* We assume here that expression_planner() won't scribble on its input */
505 expr = expression_planner(expr);
506
507 /* Now we can search for non-immutable functions */
508 return contain_mutable_functions((Node *) expr);
509}
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:382
Expr * expression_planner(Expr *expr)
Definition: planner.c:6763

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

389{
390 return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
391}
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 394 of file clauses.c.

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

3793{
3794 if (node == NULL)
3795 return false;
3796 if (IsA(node, Const))
3797 return false;
3798 if (IsA(node, List))
3799 return expression_tree_walker(node, contain_non_const_walker, context);
3800 /* Otherwise, abort the tree traversal and return true */
3801 return true;
3802}
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3792

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

1006{
1007 return contain_nonstrict_functions_walker(clause, NULL);
1008}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1017

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

1012{
1013 return !func_strict(func_id);
1014}
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 1017 of file clauses.c.

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

349{
350 if (node == NULL)
351 return false;
352 if (IsA(node, SubPlan) ||
353 IsA(node, AlternativeSubPlan) ||
354 IsA(node, SubLink))
355 return true; /* abort the tree traversal and return true */
356 return expression_tree_walker(node, contain_subplans_walker, context);
357}

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

551{
552 return contain_volatile_functions_walker(clause, NULL);
553}
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:562

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_function_in_from(), 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 671 of file clauses.c.

672{
673 /* We assume here that expression_planner() won't scribble on its input */
674 expr = expression_planner(expr);
675
676 /* Now we can search for volatile functions */
677 return contain_volatile_functions((Node *) expr);
678}
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:550

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

557{
558 return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
559}

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

686{
688}
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:698

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

692{
693 return (func_id != F_NEXTVAL &&
694 func_volatile(func_id) == PROVOLATILE_VOLATILE);
695}

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

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

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

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

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

228{
229 return contain_windowfuncs(clause);
230}
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 2303 of file clauses.c.

2304{
2305 (void) convert_saop_to_hashed_saop_walker(node, NULL);
2306}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2309

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

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

3809{
3810 char provolatile = func_volatile(funcid);
3811
3812 /*
3813 * Ordinarily we are only allowed to simplify immutable functions. But for
3814 * purposes of estimation, we consider it okay to simplify functions that
3815 * are merely stable; the risk that the result might change from planning
3816 * time to execution time is worth taking in preference to not being able
3817 * to estimate the value at all.
3818 */
3819 if (provolatile == PROVOLATILE_IMMUTABLE)
3820 return true;
3821 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3822 return true;
3823 return false;
3824}

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

2412{
2414
2415 context.boundParams = root->glob->boundParams; /* bound Params */
2416 /* we do not need to mark the plan as depending on inlined functions */
2417 context.root = NULL;
2418 context.active_fns = NIL; /* nothing being recursively simplified */
2419 context.case_val = NULL; /* no CASE being examined */
2420 context.estimate = true; /* unsafe transformations OK */
2421 return eval_const_expressions_mutator(node, &context);
2422}
#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 2456 of file clauses.c.

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

5159{
5160 EState *estate;
5161 ExprState *exprstate;
5162 MemoryContext oldcontext;
5163 Datum const_val;
5164 bool const_is_null;
5165 int16 resultTypLen;
5166 bool resultTypByVal;
5167
5168 /*
5169 * To use the executor, we need an EState.
5170 */
5171 estate = CreateExecutorState();
5172
5173 /* We can use the estate's working context to avoid memory leaks. */
5174 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5175
5176 /* Make sure any opfuncids are filled in. */
5177 fix_opfuncids((Node *) expr);
5178
5179 /*
5180 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5181 * because it'd result in recursively invoking eval_const_expressions.)
5182 */
5183 exprstate = ExecInitExpr(expr, NULL);
5184
5185 /*
5186 * And evaluate it.
5187 *
5188 * It is OK to use a default econtext because none of the ExecEvalExpr()
5189 * code used in this situation will use econtext. That might seem
5190 * fortuitous, but it's not so unreasonable --- a constant expression does
5191 * not depend on context, by definition, n'est ce pas?
5192 */
5193 const_val = ExecEvalExprSwitchContext(exprstate,
5194 GetPerTupleExprContext(estate),
5195 &const_is_null);
5196
5197 /* Get info needed about result datatype */
5198 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
5199
5200 /* Get back to outer memory context */
5201 MemoryContextSwitchTo(oldcontext);
5202
5203 /*
5204 * Must copy result out of sub-context used by expression eval.
5205 *
5206 * Also, if it's varlena, forcibly detoast it. This protects us against
5207 * storing TOAST pointers into plans that might outlive the referenced
5208 * data. (makeConst would handle detoasting anyway, but it's worth a few
5209 * extra lines here so that we can do the copy and detoast in one step.)
5210 */
5211 if (!const_is_null)
5212 {
5213 if (resultTypLen == -1)
5214 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
5215 else
5216 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
5217 }
5218
5219 /* Release all the junk we just created */
5220 FreeExecutorState(estate);
5221
5222 /*
5223 * Make the constant result node.
5224 */
5225 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5226 resultTypLen,
5227 const_val, const_is_null,
5228 resultTypByVal);
5229}
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:656
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:436
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1837
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 4610 of file clauses.c.

4615{
4616 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4617 bool has_nonconst_input = false;
4618 bool has_null_input = false;
4619 ListCell *arg;
4620 FuncExpr *newexpr;
4621
4622 /*
4623 * Can't simplify if it returns a set.
4624 */
4625 if (funcform->proretset)
4626 return NULL;
4627
4628 /*
4629 * Can't simplify if it returns RECORD. The immediate problem is that it
4630 * will be needing an expected tupdesc which we can't supply here.
4631 *
4632 * In the case where it has OUT parameters, we could build an expected
4633 * tupdesc from those, but there may be other gotchas lurking. In
4634 * particular, if the function were to return NULL, we would produce a
4635 * null constant with no remaining indication of which concrete record
4636 * type it is. For now, seems best to leave the function call unreduced.
4637 */
4638 if (funcform->prorettype == RECORDOID)
4639 return NULL;
4640
4641 /*
4642 * Check for constant inputs and especially constant-NULL inputs.
4643 */
4644 foreach(arg, args)
4645 {
4646 if (IsA(lfirst(arg), Const))
4647 has_null_input |= ((Const *) lfirst(arg))->constisnull;
4648 else
4649 has_nonconst_input = true;
4650 }
4651
4652 /*
4653 * If the function is strict and has a constant-NULL input, it will never
4654 * be called at all, so we can replace the call by a NULL constant, even
4655 * if there are other inputs that aren't constant, and even if the
4656 * function is not otherwise immutable.
4657 */
4658 if (funcform->proisstrict && has_null_input)
4659 return (Expr *) makeNullConst(result_type, result_typmod,
4660 result_collid);
4661
4662 /*
4663 * Otherwise, can simplify only if all inputs are constants. (For a
4664 * non-strict function, constant NULL inputs are treated the same as
4665 * constant non-NULL inputs.)
4666 */
4667 if (has_nonconst_input)
4668 return NULL;
4669
4670 /*
4671 * Ordinarily we are only allowed to simplify immutable functions. But for
4672 * purposes of estimation, we consider it okay to simplify functions that
4673 * are merely stable; the risk that the result might change from planning
4674 * time to execution time is worth taking in preference to not being able
4675 * to estimate the value at all.
4676 */
4677 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4678 /* okay */ ;
4679 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4680 /* okay */ ;
4681 else
4682 return NULL;
4683
4684 /*
4685 * OK, looks like we can simplify this operator/function.
4686 *
4687 * Build a new FuncExpr node containing the already-simplified arguments.
4688 */
4689 newexpr = makeNode(FuncExpr);
4690 newexpr->funcid = funcid;
4691 newexpr->funcresulttype = result_type;
4692 newexpr->funcretset = false;
4693 newexpr->funcvariadic = funcvariadic;
4694 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4695 newexpr->funccollid = result_collid; /* doesn't matter */
4696 newexpr->inputcollid = input_collid;
4697 newexpr->args = args;
4698 newexpr->location = -1;
4699
4700 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4701 result_collid);
4702}
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 4360 of file clauses.c.

4362{
4363 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4364 Oid *proargtypes = funcform->proargtypes.values;
4365 int pronargs = funcform->pronargs;
4366 bool has_named_args = false;
4367 ListCell *lc;
4368
4369 /*
4370 * If we are asked to match to OUT arguments, then use the proallargtypes
4371 * array (which includes those); otherwise use proargtypes (which
4372 * doesn't). Of course, if proallargtypes is null, we always use
4373 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4374 * considering that we may have nothing to do here, but fortunately the
4375 * common case is include_out_arguments == false.)
4376 */
4377 if (include_out_arguments)
4378 {
4379 Datum proallargtypes;
4380 bool isNull;
4381
4382 proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4383 Anum_pg_proc_proallargtypes,
4384 &isNull);
4385 if (!isNull)
4386 {
4387 ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4388
4389 pronargs = ARR_DIMS(arr)[0];
4390 if (ARR_NDIM(arr) != 1 ||
4391 pronargs < 0 ||
4392 ARR_HASNULL(arr) ||
4393 ARR_ELEMTYPE(arr) != OIDOID)
4394 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4395 Assert(pronargs >= funcform->pronargs);
4396 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4397 }
4398 }
4399
4400 /* Do we have any named arguments? */
4401 foreach(lc, args)
4402 {
4403 Node *arg = (Node *) lfirst(lc);
4404
4405 if (IsA(arg, NamedArgExpr))
4406 {
4407 has_named_args = true;
4408 break;
4409 }
4410 }
4411
4412 /* If so, we must apply reorder_function_arguments */
4413 if (has_named_args)
4414 {
4416 /* Recheck argument types and add casts if needed */
4417 recheck_cast_function_args(args, result_type,
4418 proargtypes, pronargs,
4419 func_tuple);
4420 }
4421 else if (list_length(args) < pronargs)
4422 {
4423 /* No named args, but we seem to be short some defaults */
4424 args = add_function_defaults(args, pronargs, func_tuple);
4425 /* Recheck argument types and add casts if needed */
4426 recheck_cast_function_args(args, result_type,
4427 proargtypes, pronargs,
4428 func_tuple);
4429 }
4430
4431 return args;
4432}
#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:4511
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4441
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4565
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().

◆ expr_is_nonnullable()

bool expr_is_nonnullable ( PlannerInfo root,
Expr expr,
bool  use_rel_info 
)

Definition at line 4329 of file clauses.c.

4330{
4331 if (IsA(expr, Var))
4332 return var_is_nonnullable(root, (Var *) expr, use_rel_info);
4333 if (IsA(expr, Const))
4334 return !castNode(Const, expr)->constisnull;
4335
4336 return false;
4337}

References castNode, IsA, root, and var_is_nonnullable().

Referenced by int8inc_support(), restriction_is_always_false(), and restriction_is_always_true().

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 301 of file clauses.c.

302{
303 if (clause == NULL)
304 return 1.0;
305 if (IsA(clause, FuncExpr))
306 {
307 FuncExpr *expr = (FuncExpr *) clause;
308
309 if (expr->funcretset)
310 return clamp_row_est(get_function_rows(root, expr->funcid, clause));
311 }
312 if (IsA(clause, OpExpr))
313 {
314 OpExpr *expr = (OpExpr *) clause;
315
316 if (expr->opretset)
317 {
318 set_opfuncid(expr);
319 return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
320 }
321 }
322 return 1.0;
323}
double clamp_row_est(double nrows)
Definition: costsize.c:213
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:2377

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

4536{
4537 List *defaults;
4538 Datum proargdefaults;
4539 char *str;
4540
4541 proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4542 Anum_pg_proc_proargdefaults);
4543 str = TextDatumGetCString(proargdefaults);
4544 defaults = castNode(List, stringToNode(str));
4545 pfree(str);
4546 return defaults;
4547}
#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 1992 of file clauses.c.

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

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

1472{
1473 return find_nonnullable_rels_walker(clause, true);
1474}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1477

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

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

1723{
1724 return find_nonnullable_vars_walker(clause, true);
1725}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1728

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

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

241{
242 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
243
244 lists->numWindowFuncs = 0;
245 lists->maxWinRef = maxWinRef;
246 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
247 (void) find_window_functions_walker(clause, lists);
248 return lists;
249}
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:252
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 252 of file clauses.c.

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

4741{
4742 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4743 char *src;
4744 Datum tmp;
4745 bool isNull;
4746 MemoryContext oldcxt;
4747 MemoryContext mycxt;
4748 inline_error_callback_arg callback_arg;
4749 ErrorContextCallback sqlerrcontext;
4750 FuncExpr *fexpr;
4752 TupleDesc rettupdesc;
4753 ParseState *pstate;
4754 List *raw_parsetree_list;
4755 List *querytree_list;
4757 Node *newexpr;
4758 int *usecounts;
4759 ListCell *arg;
4760 int i;
4761
4762 /*
4763 * Forget it if the function is not SQL-language or has other showstopper
4764 * properties. (The prokind and nargs checks are just paranoia.)
4765 */
4766 if (funcform->prolang != SQLlanguageId ||
4767 funcform->prokind != PROKIND_FUNCTION ||
4768 funcform->prosecdef ||
4769 funcform->proretset ||
4770 funcform->prorettype == RECORDOID ||
4771 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4772 funcform->pronargs != list_length(args))
4773 return NULL;
4774
4775 /* Check for recursive function, and give up trying to expand if so */
4776 if (list_member_oid(context->active_fns, funcid))
4777 return NULL;
4778
4779 /* Check permission to call function (fail later, if not) */
4780 if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4781 return NULL;
4782
4783 /* Check whether a plugin wants to hook function entry/exit */
4784 if (FmgrHookIsNeeded(funcid))
4785 return NULL;
4786
4787 /*
4788 * Make a temporary memory context, so that we don't leak all the stuff
4789 * that parsing might create.
4790 */
4792 "inline_function",
4794 oldcxt = MemoryContextSwitchTo(mycxt);
4795
4796 /*
4797 * We need a dummy FuncExpr node containing the already-simplified
4798 * arguments. (In some cases we don't really need it, but building it is
4799 * cheap enough that it's not worth contortions to avoid.)
4800 */
4801 fexpr = makeNode(FuncExpr);
4802 fexpr->funcid = funcid;
4803 fexpr->funcresulttype = result_type;
4804 fexpr->funcretset = false;
4805 fexpr->funcvariadic = funcvariadic;
4806 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4807 fexpr->funccollid = result_collid; /* doesn't matter */
4808 fexpr->inputcollid = input_collid;
4809 fexpr->args = args;
4810 fexpr->location = -1;
4811
4812 /* Fetch the function body */
4813 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4814 src = TextDatumGetCString(tmp);
4815
4816 /*
4817 * Setup error traceback support for ereport(). This is so that we can
4818 * finger the function that bad information came from.
4819 */
4820 callback_arg.proname = NameStr(funcform->proname);
4821 callback_arg.prosrc = src;
4822
4823 sqlerrcontext.callback = sql_inline_error_callback;
4824 sqlerrcontext.arg = &callback_arg;
4825 sqlerrcontext.previous = error_context_stack;
4826 error_context_stack = &sqlerrcontext;
4827
4828 /* If we have prosqlbody, pay attention to that not prosrc */
4829 tmp = SysCacheGetAttr(PROCOID,
4830 func_tuple,
4831 Anum_pg_proc_prosqlbody,
4832 &isNull);
4833 if (!isNull)
4834 {
4835 Node *n;
4836 List *query_list;
4837
4839 if (IsA(n, List))
4840 query_list = linitial_node(List, castNode(List, n));
4841 else
4842 query_list = list_make1(n);
4843 if (list_length(query_list) != 1)
4844 goto fail;
4845 querytree = linitial(query_list);
4846
4847 /*
4848 * Because we'll insist below that the querytree have an empty rtable
4849 * and no sublinks, it cannot have any relation references that need
4850 * to be locked or rewritten. So we can omit those steps.
4851 */
4852 }
4853 else
4854 {
4855 /* Set up to handle parameters while parsing the function body. */
4856 pinfo = prepare_sql_fn_parse_info(func_tuple,
4857 (Node *) fexpr,
4858 input_collid);
4859
4860 /*
4861 * We just do parsing and parse analysis, not rewriting, because
4862 * rewriting will not affect table-free-SELECT-only queries, which is
4863 * all that we care about. Also, we can punt as soon as we detect
4864 * more than one command in the function body.
4865 */
4866 raw_parsetree_list = pg_parse_query(src);
4867 if (list_length(raw_parsetree_list) != 1)
4868 goto fail;
4869
4870 pstate = make_parsestate(NULL);
4871 pstate->p_sourcetext = src;
4872 sql_fn_parser_setup(pstate, pinfo);
4873
4874 querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4875
4876 free_parsestate(pstate);
4877 }
4878
4879 /*
4880 * The single command must be a simple "SELECT expression".
4881 *
4882 * Note: if you change the tests involved in this, see also plpgsql's
4883 * exec_simple_check_plan(). That generally needs to have the same idea
4884 * of what's a "simple expression", so that inlining a function that
4885 * previously wasn't inlined won't change plpgsql's conclusion.
4886 */
4887 if (!IsA(querytree, Query) ||
4888 querytree->commandType != CMD_SELECT ||
4889 querytree->hasAggs ||
4890 querytree->hasWindowFuncs ||
4891 querytree->hasTargetSRFs ||
4892 querytree->hasSubLinks ||
4893 querytree->cteList ||
4894 querytree->rtable ||
4895 querytree->jointree->fromlist ||
4896 querytree->jointree->quals ||
4897 querytree->groupClause ||
4898 querytree->groupingSets ||
4899 querytree->havingQual ||
4900 querytree->windowClause ||
4901 querytree->distinctClause ||
4902 querytree->sortClause ||
4903 querytree->limitOffset ||
4904 querytree->limitCount ||
4905 querytree->setOperations ||
4906 list_length(querytree->targetList) != 1)
4907 goto fail;
4908
4909 /* If the function result is composite, resolve it */
4910 (void) get_expr_result_type((Node *) fexpr,
4911 NULL,
4912 &rettupdesc);
4913
4914 /*
4915 * Make sure the function (still) returns what it's declared to. This
4916 * will raise an error if wrong, but that's okay since the function would
4917 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4918 * a coercion if needed to make the tlist expression match the declared
4919 * type of the function.
4920 *
4921 * Note: we do not try this until we have verified that no rewriting was
4922 * needed; that's probably not important, but let's be careful.
4923 */
4924 querytree_list = list_make1(querytree);
4925 if (check_sql_fn_retval(list_make1(querytree_list),
4926 result_type, rettupdesc,
4927 funcform->prokind,
4928 false))
4929 goto fail; /* reject whole-tuple-result cases */
4930
4931 /*
4932 * Given the tests above, check_sql_fn_retval shouldn't have decided to
4933 * inject a projection step, but let's just make sure.
4934 */
4935 if (querytree != linitial(querytree_list))
4936 goto fail;
4937
4938 /* Now we can grab the tlist expression */
4939 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4940
4941 /*
4942 * If the SQL function returns VOID, we can only inline it if it is a
4943 * SELECT of an expression returning VOID (ie, it's just a redirection to
4944 * another VOID-returning function). In all non-VOID-returning cases,
4945 * check_sql_fn_retval should ensure that newexpr returns the function's
4946 * declared result type, so this test shouldn't fail otherwise; but we may
4947 * as well cope gracefully if it does.
4948 */
4949 if (exprType(newexpr) != result_type)
4950 goto fail;
4951
4952 /*
4953 * Additional validity checks on the expression. It mustn't be more
4954 * volatile than the surrounding function (this is to avoid breaking hacks
4955 * that involve pretending a function is immutable when it really ain't).
4956 * If the surrounding function is declared strict, then the expression
4957 * must contain only strict constructs and must use all of the function
4958 * parameters (this is overkill, but an exact analysis is hard).
4959 */
4960 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4962 goto fail;
4963 else if (funcform->provolatile == PROVOLATILE_STABLE &&
4965 goto fail;
4966
4967 if (funcform->proisstrict &&
4969 goto fail;
4970
4971 /*
4972 * If any parameter expression contains a context-dependent node, we can't
4973 * inline, for fear of putting such a node into the wrong context.
4974 */
4976 goto fail;
4977
4978 /*
4979 * We may be able to do it; there are still checks on parameter usage to
4980 * make, but those are most easily done in combination with the actual
4981 * substitution of the inputs. So start building expression with inputs
4982 * substituted.
4983 */
4984 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4985 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4986 args, usecounts);
4987
4988 /* Now check for parameter usage */
4989 i = 0;
4990 foreach(arg, args)
4991 {
4992 Node *param = lfirst(arg);
4993
4994 if (usecounts[i] == 0)
4995 {
4996 /* Param not used at all: uncool if func is strict */
4997 if (funcform->proisstrict)
4998 goto fail;
4999 }
5000 else if (usecounts[i] != 1)
5001 {
5002 /* Param used multiple times: uncool if expensive or volatile */
5003 QualCost eval_cost;
5004
5005 /*
5006 * We define "expensive" as "contains any subplan or more than 10
5007 * operators". Note that the subplan search has to be done
5008 * explicitly, since cost_qual_eval() will barf on unplanned
5009 * subselects.
5010 */
5011 if (contain_subplans(param))
5012 goto fail;
5013 cost_qual_eval(&eval_cost, list_make1(param), NULL);
5014 if (eval_cost.startup + eval_cost.per_tuple >
5015 10 * cpu_operator_cost)
5016 goto fail;
5017
5018 /*
5019 * Check volatility last since this is more expensive than the
5020 * above tests
5021 */
5022 if (contain_volatile_functions(param))
5023 goto fail;
5024 }
5025 i++;
5026 }
5027
5028 /*
5029 * Whew --- we can make the substitution. Copy the modified expression
5030 * out of the temporary memory context, and clean up.
5031 */
5032 MemoryContextSwitchTo(oldcxt);
5033
5034 newexpr = copyObject(newexpr);
5035
5036 MemoryContextDelete(mycxt);
5037
5038 /*
5039 * If the result is of a collatable type, force the result to expose the
5040 * correct collation. In most cases this does not matter, but it's
5041 * possible that the function result is used directly as a sort key or in
5042 * other places where we expect exprCollation() to tell the truth.
5043 */
5044 if (OidIsValid(result_collid))
5045 {
5046 Oid exprcoll = exprCollation(newexpr);
5047
5048 if (OidIsValid(exprcoll) && exprcoll != result_collid)
5049 {
5050 CollateExpr *newnode = makeNode(CollateExpr);
5051
5052 newnode->arg = (Expr *) newexpr;
5053 newnode->collOid = result_collid;
5054 newnode->location = -1;
5055
5056 newexpr = (Node *) newnode;
5057 }
5058 }
5059
5060 /*
5061 * Since there is now no trace of the function in the plan tree, we must
5062 * explicitly record the plan's dependency on the function.
5063 */
5064 if (context->root)
5065 record_plan_function_dependency(context->root, funcid);
5066
5067 /*
5068 * Recursively try to simplify the modified expression. Here we must add
5069 * the current function to the context list of active functions.
5070 */
5071 context->active_fns = lappend_oid(context->active_fns, funcid);
5072 newexpr = eval_const_expressions_mutator(newexpr, context);
5073 context->active_fns = list_delete_last(context->active_fns);
5074
5075 error_context_stack = sqlerrcontext.previous;
5076
5077 return (Expr *) newexpr;
5078
5079 /* Here if func is not inlinable: release temp memory and return NULL */
5080fail:
5081 MemoryContextSwitchTo(oldcxt);
5082 MemoryContextDelete(mycxt);
5083 error_context_stack = sqlerrcontext.previous;
5084
5085 return NULL;
5086}
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:754
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:5092
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:5133
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1193
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:1005
bool contain_subplans(Node *clause)
Definition: clauses.c:342
double cpu_operator_cost
Definition: costsize.c:134
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4781
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:261
#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_function_in_from()

Query * inline_function_in_from ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 5249 of file clauses.c.

5250{
5251 RangeTblFunction *rtfunc;
5252 FuncExpr *fexpr;
5253 Oid func_oid;
5254 HeapTuple func_tuple;
5255 Form_pg_proc funcform;
5256 MemoryContext oldcxt;
5257 MemoryContext mycxt;
5258 Datum tmp;
5259 char *src;
5260 inline_error_callback_arg callback_arg;
5261 ErrorContextCallback sqlerrcontext;
5262 Query *querytree = NULL;
5263
5264 Assert(rte->rtekind == RTE_FUNCTION);
5265
5266 /*
5267 * Guard against infinite recursion during expansion by checking for stack
5268 * overflow. (There's no need to do more.)
5269 */
5271
5272 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5273 if (rte->funcordinality)
5274 return NULL;
5275
5276 /* Fail if RTE isn't a single, simple FuncExpr */
5277 if (list_length(rte->functions) != 1)
5278 return NULL;
5279 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5280
5281 if (!IsA(rtfunc->funcexpr, FuncExpr))
5282 return NULL;
5283 fexpr = (FuncExpr *) rtfunc->funcexpr;
5284
5285 func_oid = fexpr->funcid;
5286
5287 /*
5288 * Refuse to inline if the arguments contain any volatile functions or
5289 * sub-selects. Volatile functions are rejected because inlining may
5290 * result in the arguments being evaluated multiple times, risking a
5291 * change in behavior. Sub-selects are rejected partly for implementation
5292 * reasons (pushing them down another level might change their behavior)
5293 * and partly because they're likely to be expensive and so multiple
5294 * evaluation would be bad.
5295 */
5296 if (contain_volatile_functions((Node *) fexpr->args) ||
5297 contain_subplans((Node *) fexpr->args))
5298 return NULL;
5299
5300 /* Check permission to call function (fail later, if not) */
5301 if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5302 return NULL;
5303
5304 /* Check whether a plugin wants to hook function entry/exit */
5305 if (FmgrHookIsNeeded(func_oid))
5306 return NULL;
5307
5308 /*
5309 * OK, let's take a look at the function's pg_proc entry.
5310 */
5311 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5312 if (!HeapTupleIsValid(func_tuple))
5313 elog(ERROR, "cache lookup failed for function %u", func_oid);
5314 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5315
5316 /*
5317 * If the function SETs any configuration parameters, inlining would cause
5318 * us to miss making those changes.
5319 */
5320 if (!heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5321 {
5322 ReleaseSysCache(func_tuple);
5323 return NULL;
5324 }
5325
5326 /*
5327 * Make a temporary memory context, so that we don't leak all the stuff
5328 * that parsing and rewriting might create. If we succeed, we'll copy
5329 * just the finished query tree back up to the caller's context.
5330 */
5332 "inline_function_in_from",
5334 oldcxt = MemoryContextSwitchTo(mycxt);
5335
5336 /* Fetch the function body */
5337 tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5338 src = TextDatumGetCString(tmp);
5339
5340 /*
5341 * If the function has an attached support function that can handle
5342 * SupportRequestInlineInFrom, then attempt to inline with that.
5343 */
5344 if (funcform->prosupport)
5345 {
5347
5348 req.type = T_SupportRequestInlineInFrom;
5349 req.root = root;
5350 req.rtfunc = rtfunc;
5351 req.proc = func_tuple;
5352
5353 querytree = (Query *)
5354 DatumGetPointer(OidFunctionCall1(funcform->prosupport,
5355 PointerGetDatum(&req)));
5356 }
5357
5358 /*
5359 * Setup error traceback support for ereport(). This is so that we can
5360 * finger the function that bad information came from. We don't install
5361 * this while running the support function, since it'd be likely to do the
5362 * wrong thing: any parse errors reported during that are very likely not
5363 * against the raw function source text.
5364 */
5365 callback_arg.proname = NameStr(funcform->proname);
5366 callback_arg.prosrc = src;
5367
5368 sqlerrcontext.callback = sql_inline_error_callback;
5369 sqlerrcontext.arg = &callback_arg;
5370 sqlerrcontext.previous = error_context_stack;
5371 error_context_stack = &sqlerrcontext;
5372
5373 /*
5374 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5375 * mechanism.
5376 */
5377 if (!querytree)
5379 func_tuple, funcform, src);
5380
5381 if (!querytree)
5382 goto fail; /* no luck there either, fail */
5383
5384 /*
5385 * The result had better be a SELECT Query.
5386 */
5388 Assert(querytree->commandType == CMD_SELECT);
5389
5390 /*
5391 * Looks good --- substitute parameters into the query.
5392 */
5394 funcform->pronargs,
5395 fexpr->args);
5396
5397 /*
5398 * Copy the modified query out of the temporary memory context, and clean
5399 * up.
5400 */
5401 MemoryContextSwitchTo(oldcxt);
5402
5404
5405 MemoryContextDelete(mycxt);
5406 error_context_stack = sqlerrcontext.previous;
5407 ReleaseSysCache(func_tuple);
5408
5409 /*
5410 * We don't have to fix collations here because the upper query is already
5411 * parsed, ie, the collations in the RTE are what count.
5412 */
5413
5414 /*
5415 * Since there is now no trace of the function in the plan tree, we must
5416 * explicitly record the plan's dependency on the function.
5417 */
5419
5420 /*
5421 * We must also notice if the inserted query adds a dependency on the
5422 * calling role due to RLS quals.
5423 */
5424 if (querytree->hasRowSecurity)
5425 root->glob->dependsOnRole = true;
5426
5427 return querytree;
5428
5429 /* Here if func is not inlinable: release temp memory and return NULL */
5430fail:
5431 MemoryContextSwitchTo(oldcxt);
5432 MemoryContextDelete(mycxt);
5433 error_context_stack = sqlerrcontext.previous;
5434 ReleaseSysCache(func_tuple);
5435
5436 return NULL;
5437}
static Query * substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
Definition: clauses.c:5613
static Query * inline_sql_function_in_from(PlannerInfo *root, RangeTblFunction *rtfunc, FuncExpr *fexpr, HeapTuple func_tuple, Form_pg_proc funcform, const char *src)
Definition: clauses.c:5453
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
@ RTE_FUNCTION
Definition: parsenodes.h:1046
bool funcordinality
Definition: parsenodes.h:1210
List * functions
Definition: parsenodes.h:1208
RTEKind rtekind
Definition: parsenodes.h:1078
RangeTblFunction * rtfunc
Definition: supportnodes.h:123

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert(), ErrorContextCallback::callback, check_stack_depth(), CMD_SELECT, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, DatumGetPointer(), elog, ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, RangeTblEntry::functions, GETSTRUCT(), GetUserId(), heap_attisnull(), HeapTupleIsValid, if(), inline_sql_function_in_from(), IsA, linitial, list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), ObjectIdGetDatum(), OidFunctionCall1, PointerGetDatum(), ErrorContextCallback::previous, SupportRequestInlineInFrom::proc, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), root, SupportRequestInlineInFrom::root, RTE_FUNCTION, RangeTblEntry::rtekind, SupportRequestInlineInFrom::rtfunc, SearchSysCache1(), sql_inline_error_callback(), substitute_actual_parameters_in_from(), SysCacheGetAttrNotNull(), TextDatumGetCString, and SupportRequestInlineInFrom::type.

Referenced by preprocess_function_rtes().

◆ inline_sql_function_in_from()

static Query * inline_sql_function_in_from ( PlannerInfo root,
RangeTblFunction rtfunc,
FuncExpr fexpr,
HeapTuple  func_tuple,
Form_pg_proc  funcform,
const char *  src 
)
static

Definition at line 5453 of file clauses.c.

5459{
5460 Datum sqlbody;
5461 bool isNull;
5462 List *querytree_list;
5464 TypeFuncClass functypclass;
5465 TupleDesc rettupdesc;
5466
5467 /*
5468 * The function must be declared to return a set, else inlining would
5469 * change the results if the contained SELECT didn't return exactly one
5470 * row.
5471 */
5472 if (!fexpr->funcretset)
5473 return NULL;
5474
5475 /*
5476 * Forget it if the function is not SQL-language or has other showstopper
5477 * properties. In particular it mustn't be declared STRICT, since we
5478 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5479 * supposed to cause it to be executed with its own snapshot, rather than
5480 * sharing the snapshot of the calling query. We also disallow returning
5481 * SETOF VOID, because inlining would result in exposing the actual result
5482 * of the function's last SELECT, which should not happen in that case.
5483 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5484 */
5485 if (funcform->prolang != SQLlanguageId ||
5486 funcform->prokind != PROKIND_FUNCTION ||
5487 funcform->proisstrict ||
5488 funcform->provolatile == PROVOLATILE_VOLATILE ||
5489 funcform->prorettype == VOIDOID ||
5490 funcform->prosecdef ||
5491 !funcform->proretset ||
5492 list_length(fexpr->args) != funcform->pronargs)
5493 return NULL;
5494
5495 /* If we have prosqlbody, pay attention to that not prosrc */
5496 sqlbody = SysCacheGetAttr(PROCOID,
5497 func_tuple,
5498 Anum_pg_proc_prosqlbody,
5499 &isNull);
5500 if (!isNull)
5501 {
5502 Node *n;
5503
5504 n = stringToNode(TextDatumGetCString(sqlbody));
5505 if (IsA(n, List))
5506 querytree_list = linitial_node(List, castNode(List, n));
5507 else
5508 querytree_list = list_make1(n);
5509 if (list_length(querytree_list) != 1)
5510 return NULL;
5511 querytree = linitial(querytree_list);
5512
5513 /* Acquire necessary locks, then apply rewriter. */
5514 AcquireRewriteLocks(querytree, true, false);
5515 querytree_list = pg_rewrite_query(querytree);
5516 if (list_length(querytree_list) != 1)
5517 return NULL;
5518 querytree = linitial(querytree_list);
5519 }
5520 else
5521 {
5523 List *raw_parsetree_list;
5524
5525 /*
5526 * Set up to handle parameters while parsing the function body. We
5527 * can use the FuncExpr just created as the input for
5528 * prepare_sql_fn_parse_info.
5529 */
5530 pinfo = prepare_sql_fn_parse_info(func_tuple,
5531 (Node *) fexpr,
5532 fexpr->inputcollid);
5533
5534 /*
5535 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5536 * skip rewriting here). We can fail as soon as we find more than one
5537 * query, though.
5538 */
5539 raw_parsetree_list = pg_parse_query(src);
5540 if (list_length(raw_parsetree_list) != 1)
5541 return NULL;
5542
5543 querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5544 src,
5546 pinfo, NULL);
5547 if (list_length(querytree_list) != 1)
5548 return NULL;
5549 querytree = linitial(querytree_list);
5550 }
5551
5552 /*
5553 * Also resolve the actual function result tupdesc, if composite. If we
5554 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5555 * (This logic should match ExecInitFunctionScan.)
5556 */
5557 if (rtfunc->funccolnames != NIL)
5558 {
5559 functypclass = TYPEFUNC_RECORD;
5560 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5561 rtfunc->funccoltypes,
5562 rtfunc->funccoltypmods,
5563 rtfunc->funccolcollations);
5564 }
5565 else
5566 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5567
5568 /*
5569 * The single command must be a plain SELECT.
5570 */
5571 if (!IsA(querytree, Query) ||
5572 querytree->commandType != CMD_SELECT)
5573 return NULL;
5574
5575 /*
5576 * Make sure the function (still) returns what it's declared to. This
5577 * will raise an error if wrong, but that's okay since the function would
5578 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5579 * coercions if needed to make the tlist expression(s) match the declared
5580 * type of the function. We also ask it to insert dummy NULL columns for
5581 * any dropped columns in rettupdesc, so that the elements of the modified
5582 * tlist match up to the attribute numbers.
5583 *
5584 * If the function returns a composite type, don't inline unless the check
5585 * shows it's returning a whole tuple result; otherwise what it's
5586 * returning is a single composite column which is not what we need.
5587 */
5588 if (!check_sql_fn_retval(list_make1(querytree_list),
5589 fexpr->funcresulttype, rettupdesc,
5590 funcform->prokind,
5591 true) &&
5592 (functypclass == TYPEFUNC_COMPOSITE ||
5593 functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5594 functypclass == TYPEFUNC_RECORD))
5595 return NULL; /* reject not-whole-tuple-result cases */
5596
5597 /*
5598 * check_sql_fn_retval might've inserted a projection step, but that's
5599 * fine; just make sure we use the upper Query.
5600 */
5601 querytree = linitial_node(Query, querytree_list);
5602
5603 return querytree;
5604}
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
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)
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition: tupdesc.c:1051

References AcquireRewriteLocks(), FuncExpr::args, BuildDescFromLists(), castNode, check_sql_fn_retval(), CMD_SELECT, get_expr_result_type(), IsA, linitial, linitial_node, list_length(), list_make1, NIL, pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), querytree(), sql_fn_parser_setup(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by inline_function_in_from().

◆ is_parallel_safe()

bool is_parallel_safe ( PlannerInfo root,
Node node 
)

Definition at line 765 of file clauses.c.

766{
768 PlannerInfo *proot;
769 ListCell *l;
770
771 /*
772 * Even if the original querytree contained nothing unsafe, we need to
773 * search the expression if we have generated any PARAM_EXEC Params while
774 * planning, because those are parallel-restricted and there might be one
775 * in this expression. But otherwise we don't need to look.
776 */
777 if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
778 root->glob->paramExecTypes == NIL)
779 return true;
780 /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
781 context.max_hazard = PROPARALLEL_SAFE;
782 context.max_interesting = PROPARALLEL_RESTRICTED;
783 context.safe_param_ids = NIL;
784
785 /*
786 * The params that refer to the same or parent query level are considered
787 * parallel-safe. The idea is that we compute such params at Gather or
788 * Gather Merge node and pass their value to workers.
789 */
790 for (proot = root; proot != NULL; proot = proot->parent_root)
791 {
792 foreach(l, proot->init_plans)
793 {
794 SubPlan *initsubplan = (SubPlan *) lfirst(l);
795
796 context.safe_param_ids = list_concat(context.safe_param_ids,
797 initsubplan->setParam);
798 }
799 }
800
801 return !max_parallel_hazard_walker(node, &context);
802}
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition: clauses.c:841
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 2103 of file clauses.c.

2104{
2105 /*
2106 * We could implement this check in one recursive scan. But since the
2107 * check for volatile functions is both moderately expensive and unlikely
2108 * to fail, it seems better to look for Vars first and only check for
2109 * volatile functions if we find no Vars.
2110 */
2111 if (!contain_var_clause(clause) &&
2113 return true;
2114 return false;
2115}

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

2124{
2125 if (bms_is_empty(relids) &&
2127 return true;
2128 return false;
2129}

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

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

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

5707{
5708 Node *arrayNode = NULL;
5709 ScalarArrayOpExpr *saopexpr = NULL;
5710 Oid arraytype = get_array_type(coltype);
5711
5712 if (!OidIsValid(arraytype))
5713 return NULL;
5714
5715 /*
5716 * Assemble an array from the list of constants. It seems more profitable
5717 * to build a const array. But in the presence of other nodes, we don't
5718 * have a specific value here and must employ an ArrayExpr instead.
5719 */
5720 if (haveNonConst)
5721 {
5722 ArrayExpr *arrayExpr = makeNode(ArrayExpr);
5723
5724 /* array_collid will be set by parse_collate.c */
5725 arrayExpr->element_typeid = coltype;
5726 arrayExpr->array_typeid = arraytype;
5727 arrayExpr->multidims = false;
5728 arrayExpr->elements = exprs;
5729 arrayExpr->location = -1;
5730
5731 arrayNode = (Node *) arrayExpr;
5732 }
5733 else
5734 {
5735 int16 typlen;
5736 bool typbyval;
5737 char typalign;
5738 Datum *elems;
5739 bool *nulls;
5740 int i = 0;
5741 ArrayType *arrayConst;
5742 int dims[1] = {list_length(exprs)};
5743 int lbs[1] = {1};
5744
5745 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5746
5747 elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
5748 nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
5749 foreach_node(Const, value, exprs)
5750 {
5751 elems[i] = value->constvalue;
5752 nulls[i++] = value->constisnull;
5753 }
5754
5755 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5756 coltype, typlen, typbyval, typalign);
5757 arrayNode = (Node *) makeConst(arraytype, -1, arraycollid,
5758 -1, PointerGetDatum(arrayConst),
5759 false, false);
5760
5761 pfree(elems);
5762 pfree(nulls);
5763 list_free(exprs);
5764 }
5765
5766 /* Build the SAOP expression node */
5767 saopexpr = makeNode(ScalarArrayOpExpr);
5768 saopexpr->opno = oper;
5769 saopexpr->opfuncid = get_opcode(oper);
5770 saopexpr->hashfuncid = InvalidOid;
5771 saopexpr->negfuncid = InvalidOid;
5772 saopexpr->useOr = true;
5773 saopexpr->inputcollid = inputcollid;
5774 saopexpr->args = list_make2(leftexpr, arrayNode);
5775 saopexpr->location = -1;
5776
5777 return saopexpr;
5778}
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 @171 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 746 of file clauses.c.

747{
749
750 context.max_hazard = PROPARALLEL_SAFE;
751 context.max_interesting = PROPARALLEL_UNSAFE;
752 context.safe_param_ids = NIL;
753 (void) max_parallel_hazard_walker((Node *) parse, &context);
754 return context.max_hazard;
755}
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 834 of file clauses.c.

835{
837 (max_parallel_hazard_context *) context);
838}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:806
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 806 of file clauses.c.

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

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

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

2146{
2147 int result;
2148 Relids varnos = pull_varnos(root, clause);
2149
2150 varnos = bms_del_members(varnos, root->outer_join_rels);
2151 result = bms_num_members(varnos);
2152 bms_free(varnos);
2153 return result;
2154}
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1160
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:750
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 5673 of file clauses.c.

5674{
5675 Bitmapset *result = NULL;
5676
5677 (void) pull_paramids_walker((Node *) expr, &result);
5678
5679 return result;
5680}
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition: clauses.c:5683

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

5684{
5685 if (node == NULL)
5686 return false;
5687 if (IsA(node, Param))
5688 {
5689 Param *param = (Param *) node;
5690
5691 *context = bms_add_member(*context, param->paramid);
5692 return false;
5693 }
5694 return expression_tree_walker(node, pull_paramids_walker, context);
5695}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814

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

4568{
4569 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4570 int nargs;
4571 Oid actual_arg_types[FUNC_MAX_ARGS];
4572 Oid declared_arg_types[FUNC_MAX_ARGS];
4573 Oid rettype;
4574 ListCell *lc;
4575
4577 elog(ERROR, "too many function arguments");
4578 nargs = 0;
4579 foreach(lc, args)
4580 {
4581 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4582 }
4583 Assert(nargs == pronargs);
4584 memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4585 rettype = enforce_generic_type_consistency(actual_arg_types,
4586 declared_arg_types,
4587 nargs,
4588 funcform->prorettype,
4589 false);
4590 /* let's just check we got the same answer as the parser did ... */
4591 if (rettype != result_type)
4592 elog(ERROR, "function's resolved result type changed during planning");
4593
4594 /* perform any necessary typecasting of arguments */
4595 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4596}
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 4441 of file clauses.c.

4442{
4443 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4444 int nargsprovided = list_length(args);
4445 Node *argarray[FUNC_MAX_ARGS];
4446 ListCell *lc;
4447 int i;
4448
4449 Assert(nargsprovided <= pronargs);
4450 if (pronargs < 0 || pronargs > FUNC_MAX_ARGS)
4451 elog(ERROR, "too many function arguments");
4452 memset(argarray, 0, pronargs * sizeof(Node *));
4453
4454 /* Deconstruct the argument list into an array indexed by argnumber */
4455 i = 0;
4456 foreach(lc, args)
4457 {
4458 Node *arg = (Node *) lfirst(lc);
4459
4460 if (!IsA(arg, NamedArgExpr))
4461 {
4462 /* positional argument, assumed to precede all named args */
4463 Assert(argarray[i] == NULL);
4464 argarray[i++] = arg;
4465 }
4466 else
4467 {
4468 NamedArgExpr *na = (NamedArgExpr *) arg;
4469
4470 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4471 Assert(argarray[na->argnumber] == NULL);
4472 argarray[na->argnumber] = (Node *) na->arg;
4473 }
4474 }
4475
4476 /*
4477 * Fetch default expressions, if needed, and insert into array at proper
4478 * locations (they aren't necessarily consecutive or all used)
4479 */
4480 if (nargsprovided < pronargs)
4481 {
4482 List *defaults = fetch_function_defaults(func_tuple);
4483
4484 i = pronargs - funcform->pronargdefaults;
4485 foreach(lc, defaults)
4486 {
4487 if (argarray[i] == NULL)
4488 argarray[i] = (Node *) lfirst(lc);
4489 i++;
4490 }
4491 }
4492
4493 /* Now reconstruct the args list in proper order */
4494 args = NIL;
4495 for (i = 0; i < pronargs; i++)
4496 {
4497 Assert(argarray[i] != NULL);
4498 args = lappend(args, argarray[i]);
4499 }
4500
4501 return args;
4502}
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 2201 of file clauses.c.

2204{
2205 TupleDesc tupdesc;
2206 Form_pg_attribute attr;
2207
2208 /* No issue for RECORD, since there is no way to ALTER such a type */
2209 if (rowtypeid == RECORDOID)
2210 return true;
2211 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2212 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2213 {
2214 ReleaseTupleDesc(tupdesc);
2215 return false;
2216 }
2217 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2218 if (attr->attisdropped ||
2219 attr->atttypid != expectedtype ||
2220 attr->atttypmod != expectedtypmod ||
2221 attr->attcollation != expectedcollation)
2222 {
2223 ReleaseTupleDesc(tupdesc);
2224 return false;
2225 }
2226 ReleaseTupleDesc(tupdesc);
2227 return true;
2228}
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_aggref()

static Node * simplify_aggref ( Aggref aggref,
eval_const_expressions_context context 
)
static

Definition at line 4221 of file clauses.c.

4222{
4223 Oid prosupport = get_func_support(aggref->aggfnoid);
4224
4225 if (OidIsValid(prosupport))
4226 {
4228 Node *newnode;
4229
4230 /*
4231 * Build a SupportRequestSimplifyAggref node to pass to the support
4232 * function.
4233 */
4234 req.type = T_SupportRequestSimplifyAggref;
4235 req.root = context->root;
4236 req.aggref = aggref;
4237
4238 newnode = (Node *) DatumGetPointer(OidFunctionCall1(prosupport,
4239 PointerGetDatum(&req)));
4240
4241 /*
4242 * We expect the support function to return either a new Node or NULL
4243 * (when simplification isn't possible).
4244 */
4245 Assert(newnode != (Node *) aggref || newnode == NULL);
4246
4247 if (newnode != NULL)
4248 return newnode;
4249 }
4250
4251 return (Node *) aggref;
4252}
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:2025
Oid aggfnoid
Definition: primnodes.h:463

References Aggref::aggfnoid, SupportRequestSimplifyAggref::aggref, Assert(), DatumGetPointer(), get_func_support(), OidFunctionCall1, OidIsValid, PointerGetDatum(), eval_const_expressions_context::root, SupportRequestSimplifyAggref::root, and SupportRequestSimplifyAggref::type.

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

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

4047{
4048 Node *leftop;
4049 Node *rightop;
4050
4051 Assert(list_length(args) == 2);
4052 leftop = linitial(args);
4053 rightop = lsecond(args);
4054 if (leftop && IsA(leftop, Const))
4055 {
4056 Assert(!((Const *) leftop)->constisnull);
4057 if (opno == BooleanEqualOperator)
4058 {
4059 if (DatumGetBool(((Const *) leftop)->constvalue))
4060 return rightop; /* true = foo */
4061 else
4062 return negate_clause(rightop); /* false = foo */
4063 }
4064 else
4065 {
4066 if (DatumGetBool(((Const *) leftop)->constvalue))
4067 return negate_clause(rightop); /* true <> foo */
4068 else
4069 return rightop; /* false <> foo */
4070 }
4071 }
4072 if (rightop && IsA(rightop, Const))
4073 {
4074 Assert(!((Const *) rightop)->constisnull);
4075 if (opno == BooleanEqualOperator)
4076 {
4077 if (DatumGetBool(((Const *) rightop)->constvalue))
4078 return leftop; /* foo = true */
4079 else
4080 return negate_clause(leftop); /* foo = false */
4081 }
4082 else
4083 {
4084 if (DatumGetBool(((Const *) rightop)->constvalue))
4085 return negate_clause(leftop); /* foo <> true */
4086 else
4087 return leftop; /* foo <> false */
4088 }
4089 }
4090 return NULL;
4091}

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

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

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

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

5134{
5136 int syntaxerrposition;
5137
5138 /* If it's a syntax error, convert to internal syntax error report */
5139 syntaxerrposition = geterrposition();
5140 if (syntaxerrposition > 0)
5141 {
5142 errposition(0);
5143 internalerrposition(syntaxerrposition);
5144 internalerrquery(callback_arg->prosrc);
5145 }
5146
5147 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5148}
int internalerrquery(const char *query)
Definition: elog.c:1516
int internalerrposition(int cursorpos)
Definition: elog.c:1496
int geterrposition(void)
Definition: elog.c:1612
int errposition(int cursorpos)
Definition: elog.c:1480
#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_function_in_from().

◆ substitute_actual_parameters()

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

Definition at line 5092 of file clauses.c.

5094{
5096
5097 context.nargs = nargs;
5098 context.args = args;
5099 context.usecounts = usecounts;
5100
5101 return substitute_actual_parameters_mutator(expr, &context);
5102}
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition: clauses.c:5105

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

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

◆ substitute_actual_parameters_in_from_mutator()

static Node * substitute_actual_parameters_in_from_mutator ( Node node,
substitute_actual_parameters_in_from_context context 
)
static

Definition at line 5628 of file clauses.c.

5630{
5631 Node *result;
5632
5633 if (node == NULL)
5634 return NULL;
5635 if (IsA(node, Query))
5636 {
5637 context->sublevels_up++;
5638 result = (Node *) query_tree_mutator((Query *) node,
5640 context,
5641 0);
5642 context->sublevels_up--;
5643 return result;
5644 }
5645 if (IsA(node, Param))
5646 {
5647 Param *param = (Param *) node;
5648
5649 if (param->paramkind == PARAM_EXTERN)
5650 {
5651 if (param->paramid <= 0 || param->paramid > context->nargs)
5652 elog(ERROR, "invalid paramid: %d", param->paramid);
5653
5654 /*
5655 * Since the parameter is being inserted into a subquery, we must
5656 * adjust levels.
5657 */
5658 result = copyObject(list_nth(context->args, param->paramid - 1));
5659 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5660 return result;
5661 }
5662 }
5663 return expression_tree_mutator(node,
5665 context);
5666}
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:881

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

Referenced by substitute_actual_parameters_in_from(), and substitute_actual_parameters_in_from_mutator().

◆ substitute_actual_parameters_mutator()

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

Definition at line 5105 of file clauses.c.

5107{
5108 if (node == NULL)
5109 return NULL;
5110 if (IsA(node, Param))
5111 {
5112 Param *param = (Param *) node;
5113
5114 if (param->paramkind != PARAM_EXTERN)
5115 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5116 if (param->paramid <= 0 || param->paramid > context->nargs)
5117 elog(ERROR, "invalid paramid: %d", param->paramid);
5118
5119 /* Count usage of parameter */
5120 context->usecounts[param->paramid - 1]++;
5121
5122 /* Select the appropriate actual arg and replace the Param with it */
5123 /* We don't need to copy at this time (it'll get done later) */
5124 return list_nth(context->args, param->paramid - 1);
5125 }
5127}

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

◆ var_is_nonnullable()

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

Definition at line 4264 of file clauses.c.

4265{
4266 Bitmapset *notnullattnums = NULL;
4267
4268 Assert(IsA(var, Var));
4269
4270 /* skip upper-level Vars */
4271 if (var->varlevelsup != 0)
4272 return false;
4273
4274 /* could the Var be nulled by any outer joins or grouping sets? */
4275 if (!bms_is_empty(var->varnullingrels))
4276 return false;
4277
4278 /* system columns cannot be NULL */
4279 if (var->varattno < 0)
4280 return true;
4281
4282 /*
4283 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4284 * NULL constraint information from the corresponding RelOptInfo if it is
4285 * available; otherwise, we search the hash table for this information.
4286 */
4287 if (use_rel_info)
4288 {
4289 RelOptInfo *rel = find_base_rel(root, var->varno);
4290
4291 notnullattnums = rel->notnullattnums;
4292 }
4293 else
4294 {
4296
4297 /*
4298 * We must skip inheritance parent tables, as some child tables may
4299 * have a NOT NULL constraint for a column while others may not. This
4300 * cannot happen with partitioned tables, though.
4301 */
4302 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4303 return false;
4304
4305 notnullattnums = find_relation_notnullatts(root, rte->relid);
4306 }
4307
4308 if (var->varattno > 0 &&
4309 bms_is_member(var->varattno, notnullattnums))
4310 return true;
4311
4312 return false;
4313}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:610
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:987

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