PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_utilcmd.h File Reference
Include dependency graph for parse_utilcmd.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
NodetransformPartitionBound (ParseState *pstate, Relation parent, Node *bound)
 

Function Documentation

List* transformAlterTableStmt ( Oid  relid,
AlterTableStmt stmt,
const char *  queryString 
)

Definition at line 2507 of file parse_utilcmd.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_ProcessedConstraint, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject(), AlterTableCmd::def, elog, ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::fkconstraints, CreateStmtContext::hasoids, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, list_concat(), make_parsestate(), makeNode, NIL, nodeTag, NoLock, NULL, OBJECT_FOREIGN_TABLE, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), relation_open(), AlterTableStmt::relkind, RELKIND_PARTITIONED_TABLE, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), and transformTableConstraint().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

2509 {
2510  Relation rel;
2511  ParseState *pstate;
2512  CreateStmtContext cxt;
2513  List *result;
2514  List *save_alist;
2515  ListCell *lcmd,
2516  *l;
2517  List *newcmds = NIL;
2518  bool skipValidation = true;
2519  AlterTableCmd *newcmd;
2520  RangeTblEntry *rte;
2521 
2522  /*
2523  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2524  * is overkill, but easy.)
2525  */
2526  stmt = (AlterTableStmt *) copyObject(stmt);
2527 
2528  /* Caller is responsible for locking the relation */
2529  rel = relation_open(relid, NoLock);
2530 
2531  /* Set up pstate */
2532  pstate = make_parsestate(NULL);
2533  pstate->p_sourcetext = queryString;
2534  rte = addRangeTableEntryForRelation(pstate,
2535  rel,
2536  NULL,
2537  false,
2538  true);
2539  addRTEtoQuery(pstate, rte, false, true, true);
2540 
2541  /* Set up CreateStmtContext */
2542  cxt.pstate = pstate;
2543  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2544  {
2545  cxt.stmtType = "ALTER FOREIGN TABLE";
2546  cxt.isforeign = true;
2547  }
2548  else
2549  {
2550  cxt.stmtType = "ALTER TABLE";
2551  cxt.isforeign = false;
2552  }
2553  cxt.relation = stmt->relation;
2554  cxt.rel = rel;
2555  cxt.inhRelations = NIL;
2556  cxt.isalter = true;
2557  cxt.hasoids = false; /* need not be right */
2558  cxt.columns = NIL;
2559  cxt.ckconstraints = NIL;
2560  cxt.fkconstraints = NIL;
2561  cxt.ixconstraints = NIL;
2562  cxt.inh_indexes = NIL;
2563  cxt.blist = NIL;
2564  cxt.alist = NIL;
2565  cxt.pkey = NULL;
2566  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
2567  cxt.partbound = NULL;
2568 
2569  /*
2570  * The only subtypes that currently require parse transformation handling
2571  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2572  * code from CREATE TABLE.
2573  */
2574  foreach(lcmd, stmt->cmds)
2575  {
2576  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2577 
2578  switch (cmd->subtype)
2579  {
2580  case AT_AddColumn:
2581  case AT_AddColumnToView:
2582  {
2583  ColumnDef *def = castNode(ColumnDef, cmd->def);
2584 
2585  transformColumnDefinition(&cxt, def);
2586 
2587  /*
2588  * If the column has a non-null default, we can't skip
2589  * validation of foreign keys.
2590  */
2591  if (def->raw_default != NULL)
2592  skipValidation = false;
2593 
2594  /*
2595  * All constraints are processed in other ways. Remove the
2596  * original list
2597  */
2598  def->constraints = NIL;
2599 
2600  newcmds = lappend(newcmds, cmd);
2601  break;
2602  }
2603 
2604  case AT_AddConstraint:
2605 
2606  /*
2607  * The original AddConstraint cmd node doesn't go to newcmds
2608  */
2609  if (IsA(cmd->def, Constraint))
2610  {
2611  transformTableConstraint(&cxt, (Constraint *) cmd->def);
2612  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2613  skipValidation = false;
2614  }
2615  else
2616  elog(ERROR, "unrecognized node type: %d",
2617  (int) nodeTag(cmd->def));
2618  break;
2619 
2621 
2622  /*
2623  * Already-transformed ADD CONSTRAINT, so just make it look
2624  * like the standard case.
2625  */
2626  cmd->subtype = AT_AddConstraint;
2627  newcmds = lappend(newcmds, cmd);
2628  break;
2629 
2630  case AT_AlterColumnType:
2631  {
2632  ColumnDef *def = (ColumnDef *) cmd->def;
2633 
2634  /*
2635  * For ALTER COLUMN TYPE, transform the USING clause if
2636  * one was specified.
2637  */
2638  if (def->raw_default)
2639  {
2640  def->cooked_default =
2641  transformExpr(pstate, def->raw_default,
2643  }
2644 
2645  newcmds = lappend(newcmds, cmd);
2646  break;
2647  }
2648 
2649  case AT_AttachPartition:
2650  case AT_DetachPartition:
2651  {
2652  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
2653 
2654  transformPartitionCmd(&cxt, partcmd);
2655  /* assign transformed value of the partition bound */
2656  partcmd->bound = cxt.partbound;
2657  }
2658 
2659  newcmds = lappend(newcmds, cmd);
2660  break;
2661 
2662  default:
2663  newcmds = lappend(newcmds, cmd);
2664  break;
2665  }
2666  }
2667 
2668  /*
2669  * transformIndexConstraints wants cxt.alist to contain only index
2670  * statements, so transfer anything we already have into save_alist
2671  * immediately.
2672  */
2673  save_alist = cxt.alist;
2674  cxt.alist = NIL;
2675 
2676  /* Postprocess constraints */
2678  transformFKConstraints(&cxt, skipValidation, true);
2679  transformCheckConstraints(&cxt, false);
2680 
2681  /*
2682  * Push any index-creation commands into the ALTER, so that they can be
2683  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2684  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2685  * subcommand has already been through transformIndexStmt.
2686  */
2687  foreach(l, cxt.alist)
2688  {
2689  IndexStmt *idxstmt = castNode(IndexStmt, lfirst(l));
2690 
2691  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2692  newcmd = makeNode(AlterTableCmd);
2694  newcmd->def = (Node *) idxstmt;
2695  newcmds = lappend(newcmds, newcmd);
2696  }
2697  cxt.alist = NIL;
2698 
2699  /* Append any CHECK or FK constraints to the commands list */
2700  foreach(l, cxt.ckconstraints)
2701  {
2702  newcmd = makeNode(AlterTableCmd);
2703  newcmd->subtype = AT_AddConstraint;
2704  newcmd->def = (Node *) lfirst(l);
2705  newcmds = lappend(newcmds, newcmd);
2706  }
2707  foreach(l, cxt.fkconstraints)
2708  {
2709  newcmd = makeNode(AlterTableCmd);
2710  newcmd->subtype = AT_AddConstraint;
2711  newcmd->def = (Node *) lfirst(l);
2712  newcmds = lappend(newcmds, newcmd);
2713  }
2714 
2715  /* Close rel */
2716  relation_close(rel, NoLock);
2717 
2718  /*
2719  * Output results.
2720  */
2721  stmt->cmds = newcmds;
2722 
2723  result = lappend(cxt.blist, stmt);
2724  result = list_concat(result, cxt.alist);
2725  result = list_concat(result, save_alist);
2726 
2727  return result;
2728 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Node * bound
Definition: parsenodes.h:781
List * constraints
Definition: parsenodes.h:609
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:508
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
AlterTableType subtype
Definition: parsenodes.h:1685
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Form_pg_class rd_rel
Definition: rel.h:113
#define OidIsValid(objectId)
Definition: c.h:533
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
ParseState * pstate
Definition: parse_utilcmd.c:74
Node * cooked_default
Definition: parsenodes.h:606
Oid indexOid
Definition: parsenodes.h:2597
RangeVar * relation
Definition: parse_utilcmd.c:76
IndexStmt * pkey
Definition: parse_utilcmd.c:91
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:167
ObjectType relkind
Definition: parsenodes.h:1603
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Node * raw_default
Definition: parsenodes.h:605
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:513
const char * stmtType
Definition: parse_utilcmd.c:75
RangeVar * relation
Definition: parsenodes.h:1601
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
#define elog
Definition: elog.h:219
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:45
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 2909 of file parse_utilcmd.c.

References CreateSchemaStmtContext::authrole, CreateSchemaStmt::authrole, element(), elog, ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmt::schemaElts, RangeVar::schemaname, CreateSchemaStmtContext::schemaname, CreateSchemaStmt::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::stmtType, T_CreateSeqStmt, T_CreateStmt, T_CreateTrigStmt, T_GrantStmt, T_IndexStmt, T_ViewStmt, CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

2910 {
2912  List *result;
2913  ListCell *elements;
2914 
2915  cxt.stmtType = "CREATE SCHEMA";
2916  cxt.schemaname = stmt->schemaname;
2917  cxt.authrole = (RoleSpec *) stmt->authrole;
2918  cxt.sequences = NIL;
2919  cxt.tables = NIL;
2920  cxt.views = NIL;
2921  cxt.indexes = NIL;
2922  cxt.triggers = NIL;
2923  cxt.grants = NIL;
2924 
2925  /*
2926  * Run through each schema element in the schema element list. Separate
2927  * statements by type, and do preliminary analysis.
2928  */
2929  foreach(elements, stmt->schemaElts)
2930  {
2931  Node *element = lfirst(elements);
2932 
2933  switch (nodeTag(element))
2934  {
2935  case T_CreateSeqStmt:
2936  {
2937  CreateSeqStmt *elp = (CreateSeqStmt *) element;
2938 
2940  cxt.sequences = lappend(cxt.sequences, element);
2941  }
2942  break;
2943 
2944  case T_CreateStmt:
2945  {
2946  CreateStmt *elp = (CreateStmt *) element;
2947 
2949 
2950  /*
2951  * XXX todo: deal with constraints
2952  */
2953  cxt.tables = lappend(cxt.tables, element);
2954  }
2955  break;
2956 
2957  case T_ViewStmt:
2958  {
2959  ViewStmt *elp = (ViewStmt *) element;
2960 
2961  setSchemaName(cxt.schemaname, &elp->view->schemaname);
2962 
2963  /*
2964  * XXX todo: deal with references between views
2965  */
2966  cxt.views = lappend(cxt.views, element);
2967  }
2968  break;
2969 
2970  case T_IndexStmt:
2971  {
2972  IndexStmt *elp = (IndexStmt *) element;
2973 
2975  cxt.indexes = lappend(cxt.indexes, element);
2976  }
2977  break;
2978 
2979  case T_CreateTrigStmt:
2980  {
2981  CreateTrigStmt *elp = (CreateTrigStmt *) element;
2982 
2984  cxt.triggers = lappend(cxt.triggers, element);
2985  }
2986  break;
2987 
2988  case T_GrantStmt:
2989  cxt.grants = lappend(cxt.grants, element);
2990  break;
2991 
2992  default:
2993  elog(ERROR, "unrecognized node type: %d",
2994  (int) nodeTag(element));
2995  }
2996  }
2997 
2998  result = NIL;
2999  result = list_concat(result, cxt.sequences);
3000  result = list_concat(result, cxt.tables);
3001  result = list_concat(result, cxt.views);
3002  result = list_concat(result, cxt.indexes);
3003  result = list_concat(result, cxt.triggers);
3004  result = list_concat(result, cxt.grants);
3005 
3006  return result;
3007 }
RangeVar * relation
Definition: parsenodes.h:1894
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:508
List * list_concat(List *list1, List *list2)
Definition: list.c:321
RangeVar * view
Definition: parsenodes.h:2881
char * schemaname
Definition: primnodes.h:66
RangeVar * relation
Definition: parsenodes.h:2589
RoleSpec * authrole
Definition: parsenodes.h:1583
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2357
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:513
RangeVar * relation
Definition: parsenodes.h:2242
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 154 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, copyObject(), element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmtContext::hasoids, CreateStmt::if_not_exists, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, CreateStmt::inhRelations, interpretOidsOption(), IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lcons(), lfirst, list_concat(), list_length(), RangeVar::location, make_parsestate(), makeDefElem(), makeInteger(), NIL, nodeTag, NoLock, NOTICE, NULL, CreateStmt::ofTypename, OidIsValid, CreateStmt::options, ParseState::p_sourcetext, CreateStmt::partbound, PARTITION_MAX_KEYS, PartitionSpec::partParams, CreateStmt::partspec, pg_strcasecmp(), CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RELPERSISTENCE_TEMP, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, PartitionSpec::strategy, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

155 {
156  ParseState *pstate;
157  CreateStmtContext cxt;
158  List *result;
159  List *save_alist;
160  ListCell *elements;
161  Oid namespaceid;
162  Oid existing_relid;
163  ParseCallbackState pcbstate;
164  bool like_found = false;
165 
166  /*
167  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
168  * overkill, but easy.)
169  */
170  stmt = (CreateStmt *) copyObject(stmt);
171 
172  /* Set up pstate */
173  pstate = make_parsestate(NULL);
174  pstate->p_sourcetext = queryString;
175 
176  /*
177  * Look up the creation namespace. This also checks permissions on the
178  * target namespace, locks it against concurrent drops, checks for a
179  * preexisting relation in that namespace with the same name, and updates
180  * stmt->relation->relpersistence if the selected namespace is temporary.
181  */
182  setup_parser_errposition_callback(&pcbstate, pstate,
183  stmt->relation->location);
184  namespaceid =
186  &existing_relid);
188 
189  /*
190  * If the relation already exists and the user specified "IF NOT EXISTS",
191  * bail out with a NOTICE.
192  */
193  if (stmt->if_not_exists && OidIsValid(existing_relid))
194  {
195  ereport(NOTICE,
196  (errcode(ERRCODE_DUPLICATE_TABLE),
197  errmsg("relation \"%s\" already exists, skipping",
198  stmt->relation->relname)));
199  return NIL;
200  }
201 
202  /*
203  * If the target relation name isn't schema-qualified, make it so. This
204  * prevents some corner cases in which added-on rewritten commands might
205  * think they should apply to other relations that have the same name and
206  * are earlier in the search path. But a local temp table is effectively
207  * specified to be in pg_temp, so no need for anything extra in that case.
208  */
209  if (stmt->relation->schemaname == NULL
211  stmt->relation->schemaname = get_namespace_name(namespaceid);
212 
213  /* Set up CreateStmtContext */
214  cxt.pstate = pstate;
215  if (IsA(stmt, CreateForeignTableStmt))
216  {
217  cxt.stmtType = "CREATE FOREIGN TABLE";
218  cxt.isforeign = true;
219  }
220  else
221  {
222  cxt.stmtType = "CREATE TABLE";
223  cxt.isforeign = false;
224  }
225  cxt.relation = stmt->relation;
226  cxt.rel = NULL;
227  cxt.inhRelations = stmt->inhRelations;
228  cxt.isalter = false;
229  cxt.columns = NIL;
230  cxt.ckconstraints = NIL;
231  cxt.fkconstraints = NIL;
232  cxt.ixconstraints = NIL;
233  cxt.inh_indexes = NIL;
234  cxt.blist = NIL;
235  cxt.alist = NIL;
236  cxt.pkey = NULL;
237  cxt.ispartitioned = stmt->partspec != NULL;
238 
239  /*
240  * Notice that we allow OIDs here only for plain tables, even though
241  * foreign tables also support them. This is necessary because the
242  * default_with_oids GUC must apply only to plain tables and not any other
243  * relkind; doing otherwise would break existing pg_dump files. We could
244  * allow explicit "WITH OIDS" while not allowing default_with_oids to
245  * affect other relkinds, but it would complicate interpretOidsOption(),
246  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
247  * anyway.
248  */
249  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
250 
251  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
252 
253  if (stmt->ofTypename)
254  transformOfType(&cxt, stmt->ofTypename);
255 
256  if (stmt->partspec)
257  {
258  int partnatts = list_length(stmt->partspec->partParams);
259 
260  if (stmt->inhRelations && !stmt->partbound)
261  ereport(ERROR,
262  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
263  errmsg("cannot create partitioned table as inheritance child")));
264 
265  if (partnatts > PARTITION_MAX_KEYS)
266  ereport(ERROR,
267  (errcode(ERRCODE_TOO_MANY_COLUMNS),
268  errmsg("cannot partition using more than %d columns",
270 
271  if (!pg_strcasecmp(stmt->partspec->strategy, "list") &&
272  partnatts > 1)
273  ereport(ERROR,
274  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
275  errmsg("cannot list partition using more than one column")));
276  }
277 
278  /*
279  * Run through each primary element in the table creation clause. Separate
280  * column defs from constraints, and do preliminary analysis.
281  */
282  foreach(elements, stmt->tableElts)
283  {
284  Node *element = lfirst(elements);
285 
286  switch (nodeTag(element))
287  {
288  case T_ColumnDef:
289  transformColumnDefinition(&cxt, (ColumnDef *) element);
290  break;
291 
292  case T_Constraint:
293  transformTableConstraint(&cxt, (Constraint *) element);
294  break;
295 
296  case T_TableLikeClause:
297  like_found = true;
298  transformTableLikeClause(&cxt, (TableLikeClause *) element);
299  break;
300 
301  default:
302  elog(ERROR, "unrecognized node type: %d",
303  (int) nodeTag(element));
304  break;
305  }
306  }
307 
308  /*
309  * If we had any LIKE tables, they may require creation of an OID column
310  * even though the command's own WITH clause didn't ask for one (or,
311  * perhaps, even specifically rejected having one). Insert a WITH option
312  * to ensure that happens. We prepend to the list because the first oid
313  * option will be honored, and we want to override anything already there.
314  * (But note that DefineRelation will override this again to add an OID
315  * column if one appears in an inheritance parent table.)
316  */
317  if (like_found && cxt.hasoids)
318  stmt->options = lcons(makeDefElem("oids",
319  (Node *) makeInteger(true), -1),
320  stmt->options);
321 
322  /*
323  * transformIndexConstraints wants cxt.alist to contain only index
324  * statements, so transfer anything we already have into save_alist.
325  */
326  save_alist = cxt.alist;
327  cxt.alist = NIL;
328 
329  Assert(stmt->constraints == NIL);
330 
331  /*
332  * Postprocess constraints that give rise to index definitions.
333  */
335 
336  /*
337  * Postprocess foreign-key constraints.
338  */
339  transformFKConstraints(&cxt, true, false);
340 
341  /*
342  * Postprocess check constraints.
343  */
344  transformCheckConstraints(&cxt, true);
345 
346  /*
347  * Output results.
348  */
349  stmt->tableElts = cxt.columns;
350  stmt->constraints = cxt.ckconstraints;
351 
352  result = lappend(cxt.blist, stmt);
353  result = list_concat(result, cxt.alist);
354  result = list_concat(result, save_alist);
355 
356  return result;
357 }
RangeVar * relation
Definition: parsenodes.h:1894
#define NIL
Definition: pg_list.h:69
List * inhRelations
Definition: parsenodes.h:1896
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * partParams
Definition: parsenodes.h:732
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PARTITION_MAX_KEYS
List * list_concat(List *list1, List *list2)
Definition: list.c:321
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:533
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:543
char * schemaname
Definition: primnodes.h:66
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
List * constraints
Definition: parsenodes.h:1901
bool if_not_exists
Definition: parsenodes.h:1905
int location
Definition: primnodes.h:72
ParseState * pstate
Definition: parse_utilcmd.c:74
char * relname
Definition: primnodes.h:67
Value * makeInteger(long i)
Definition: value.c:23
RangeVar * relation
Definition: parse_utilcmd.c:76
IndexStmt * pkey
Definition: parse_utilcmd.c:91
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define NoLock
Definition: lockdefs.h:34
List * options
Definition: parsenodes.h:1902
const char * p_sourcetext
Definition: parse_node.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:143
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:507
Node * partbound
Definition: parsenodes.h:1898
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:1895
List * lcons(void *datum, List *list)
Definition: list.c:259
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static int list_length(const List *l)
Definition: pg_list.h:89
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:513
const char * stmtType
Definition: parse_utilcmd.c:75
char relpersistence
Definition: primnodes.h:70
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:241
char * strategy
Definition: parsenodes.h:731
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:1899
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:1900
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
IndexStmt* transformIndexStmt ( Oid  relid,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 2097 of file parse_utilcmd.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), copyObject(), ereport, errcode(), errmsg(), ERROR, IndexElem::expr, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, FigureIndexColname(), free_parsestate(), heap_close, IndexElem::indexcolname, IndexStmt::indexParams, lfirst, list_length(), make_parsestate(), NoLock, NULL, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), IndexStmt::transformed, transformExpr(), transformWhereClause(), and IndexStmt::whereClause.

Referenced by ATPostAlterTypeParse(), ProcessUtilitySlow(), and transformAlterTableStmt().

2098 {
2099  ParseState *pstate;
2100  RangeTblEntry *rte;
2101  ListCell *l;
2102  Relation rel;
2103 
2104  /* Nothing to do if statement already transformed. */
2105  if (stmt->transformed)
2106  return stmt;
2107 
2108  /*
2109  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2110  * overkill, but easy.)
2111  */
2112  stmt = (IndexStmt *) copyObject(stmt);
2113 
2114  /* Set up pstate */
2115  pstate = make_parsestate(NULL);
2116  pstate->p_sourcetext = queryString;
2117 
2118  /*
2119  * Put the parent table into the rtable so that the expressions can refer
2120  * to its fields without qualification. Caller is responsible for locking
2121  * relation, but we still need to open it.
2122  */
2123  rel = relation_open(relid, NoLock);
2124  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2125 
2126  /* no to join list, yes to namespaces */
2127  addRTEtoQuery(pstate, rte, false, true, true);
2128 
2129  /* take care of the where clause */
2130  if (stmt->whereClause)
2131  {
2132  stmt->whereClause = transformWhereClause(pstate,
2133  stmt->whereClause,
2135  "WHERE");
2136  /* we have to fix its collations too */
2137  assign_expr_collations(pstate, stmt->whereClause);
2138  }
2139 
2140  /* take care of any index expressions */
2141  foreach(l, stmt->indexParams)
2142  {
2143  IndexElem *ielem = (IndexElem *) lfirst(l);
2144 
2145  if (ielem->expr)
2146  {
2147  /* Extract preliminary index col name before transforming expr */
2148  if (ielem->indexcolname == NULL)
2149  ielem->indexcolname = FigureIndexColname(ielem->expr);
2150 
2151  /* Now do parse transformation of the expression */
2152  ielem->expr = transformExpr(pstate, ielem->expr,
2154 
2155  /* We have to fix its collations too */
2156  assign_expr_collations(pstate, ielem->expr);
2157 
2158  /*
2159  * transformExpr() should have already rejected subqueries,
2160  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2161  * for an index expression.
2162  *
2163  * DefineIndex() will make more checks.
2164  */
2165  }
2166  }
2167 
2168  /*
2169  * Check that only the base rel is mentioned. (This should be dead code
2170  * now that add_missing_from is history.)
2171  */
2172  if (list_length(pstate->p_rtable) != 1)
2173  ereport(ERROR,
2174  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2175  errmsg("index expressions and predicates can refer only to the table being indexed")));
2176 
2177  free_parsestate(pstate);
2178 
2179  /* Close relation */
2180  heap_close(rel, NoLock);
2181 
2182  /* Mark statement as successfully transformed */
2183  stmt->transformed = true;
2184 
2185  return stmt;
2186 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Node * whereClause
Definition: parsenodes.h:2594
int errcode(int sqlerrcode)
Definition: elog.c:575
char * FigureIndexColname(Node *node)
#define heap_close(r, l)
Definition: heapam.h:97
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:645
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2604
char * indexcolname
Definition: parsenodes.h:646
const char * p_sourcetext
Definition: parse_node.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2592
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:75
List * p_rtable
Definition: parse_node.h:168
Node* transformPartitionBound ( ParseState pstate,
Relation  parent,
Node bound 
)

Definition at line 3058 of file parse_utilcmd.c.

References Assert, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, copyObject(), deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, expression_planner(), exprLocation(), exprType(), forboth, format_type_be(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), get_relid_attribute_name(), i, PartitionRangeDatum::infinite, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionBoundSpec::listdatums, A_Const::location, PartitionBoundSpec::lowerdatums, make_const(), NIL, NULL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, PartitionBoundSpec::upperdatums, A_Const::val, value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3059 {
3060  PartitionBoundSpec *spec = (PartitionBoundSpec *) bound,
3061  *result_spec;
3062  PartitionKey key = RelationGetPartitionKey(parent);
3063  char strategy = get_partition_strategy(key);
3064  int partnatts = get_partition_natts(key);
3065  List *partexprs = get_partition_exprs(key);
3066 
3067  result_spec = copyObject(spec);
3068 
3069  if (strategy == PARTITION_STRATEGY_LIST)
3070  {
3071  ListCell *cell;
3072  char *colname;
3073 
3074  /* Get the only column's name in case we need to output an error */
3075  if (key->partattrs[0] != 0)
3076  colname = get_relid_attribute_name(RelationGetRelid(parent),
3077  key->partattrs[0]);
3078  else
3079  colname = deparse_expression((Node *) linitial(partexprs),
3081  RelationGetRelid(parent)),
3082  false, false);
3083 
3084  if (spec->strategy != PARTITION_STRATEGY_LIST)
3085  ereport(ERROR,
3086  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3087  errmsg("invalid bound specification for a list partition"),
3088  parser_errposition(pstate, exprLocation(bound))));
3089 
3090  result_spec->listdatums = NIL;
3091  foreach(cell, spec->listdatums)
3092  {
3093  A_Const *con = (A_Const *) lfirst(cell);
3094  Node *value;
3095  ListCell *cell2;
3096  bool duplicate;
3097 
3098  value = (Node *) make_const(pstate, &con->val, con->location);
3099  value = coerce_to_target_type(pstate,
3100  value, exprType(value),
3101  get_partition_col_typid(key, 0),
3102  get_partition_col_typmod(key, 0),
3105  -1);
3106 
3107  if (value == NULL)
3108  ereport(ERROR,
3109  (errcode(ERRCODE_DATATYPE_MISMATCH),
3110  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3112  colname),
3113  parser_errposition(pstate,
3114  exprLocation((Node *) con))));
3115 
3116  /* Simplify the expression */
3117  value = (Node *) expression_planner((Expr *) value);
3118 
3119  /* Don't add to the result if the value is a duplicate */
3120  duplicate = false;
3121  foreach(cell2, result_spec->listdatums)
3122  {
3123  Const *value2 = (Const *) lfirst(cell2);
3124 
3125  if (equal(value, value2))
3126  {
3127  duplicate = true;
3128  break;
3129  }
3130  }
3131  if (duplicate)
3132  continue;
3133 
3134  result_spec->listdatums = lappend(result_spec->listdatums,
3135  value);
3136  }
3137  }
3138  else if (strategy == PARTITION_STRATEGY_RANGE)
3139  {
3140  ListCell *cell1,
3141  *cell2;
3142  int i,
3143  j;
3144  char *colname;
3145 
3146  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3147  ereport(ERROR,
3148  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3149  errmsg("invalid bound specification for a range partition"),
3150  parser_errposition(pstate, exprLocation(bound))));
3151 
3152  Assert(spec->lowerdatums != NIL && spec->upperdatums != NIL);
3153 
3154  if (list_length(spec->lowerdatums) != partnatts)
3155  ereport(ERROR,
3156  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3157  errmsg("FROM must specify exactly one value per partitioning column")));
3158  if (list_length(spec->upperdatums) != partnatts)
3159  ereport(ERROR,
3160  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3161  errmsg("TO must specify exactly one value per partitioning column")));
3162 
3163  i = j = 0;
3164  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3165  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3166  {
3167  PartitionRangeDatum *ldatum,
3168  *rdatum;
3169  Node *value;
3170  A_Const *lcon = NULL,
3171  *rcon = NULL;
3172 
3173  ldatum = (PartitionRangeDatum *) lfirst(cell1);
3174  rdatum = (PartitionRangeDatum *) lfirst(cell2);
3175  /* Get the column's name in case we need to output an error */
3176  if (key->partattrs[i] != 0)
3177  colname = get_relid_attribute_name(RelationGetRelid(parent),
3178  key->partattrs[i]);
3179  else
3180  {
3181  colname = deparse_expression((Node *) list_nth(partexprs, j),
3183  RelationGetRelid(parent)),
3184  false, false);
3185  ++j;
3186  }
3187 
3188  if (!ldatum->infinite)
3189  lcon = (A_Const *) ldatum->value;
3190  if (!rdatum->infinite)
3191  rcon = (A_Const *) rdatum->value;
3192 
3193  if (lcon)
3194  {
3195  value = (Node *) make_const(pstate, &lcon->val, lcon->location);
3196  if (((Const *) value)->constisnull)
3197  ereport(ERROR,
3198  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3199  errmsg("cannot specify NULL in range bound")));
3200  value = coerce_to_target_type(pstate,
3201  value, exprType(value),
3202  get_partition_col_typid(key, i),
3203  get_partition_col_typmod(key, i),
3206  -1);
3207  if (value == NULL)
3208  ereport(ERROR,
3209  (errcode(ERRCODE_DATATYPE_MISMATCH),
3210  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3212  colname),
3213  parser_errposition(pstate, exprLocation((Node *) ldatum))));
3214 
3215  /* Simplify the expression */
3216  value = (Node *) expression_planner((Expr *) value);
3217  ldatum->value = value;
3218  }
3219 
3220  if (rcon)
3221  {
3222  value = (Node *) make_const(pstate, &rcon->val, rcon->location);
3223  if (((Const *) value)->constisnull)
3224  ereport(ERROR,
3225  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3226  errmsg("cannot specify NULL in range bound")));
3227  value = coerce_to_target_type(pstate,
3228  value, exprType(value),
3229  get_partition_col_typid(key, i),
3230  get_partition_col_typmod(key, i),
3233  -1);
3234  if (value == NULL)
3235  ereport(ERROR,
3236  (errcode(ERRCODE_DATATYPE_MISMATCH),
3237  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3239  colname),
3240  parser_errposition(pstate, exprLocation((Node *) rdatum))));
3241 
3242  /* Simplify the expression */
3243  value = (Node *) expression_planner((Expr *) value);
3244  rdatum->value = value;
3245  }
3246 
3247  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3248  copyObject(ldatum));
3249  result_spec->upperdatums = lappend(result_spec->upperdatums,
3250  copyObject(rdatum));
3251 
3252  ++i;
3253  }
3254  }
3255  else
3256  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3257 
3258  return (Node *) result_spec;
3259 }
#define NIL
Definition: pg_list.h:69
static struct @76 value
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
Expr * expression_planner(Expr *expr)
Definition: planner.c:5211
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Const * make_const(ParseState *pstate, Value *value, int location)
Definition: parse_node.c:468
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
static int get_partition_natts(PartitionKey key)
Definition: rel.h:593
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
void * list_nth(const List *list, int n)
Definition: list.c:410
static List * get_partition_exprs(PartitionKey key)
Definition: rel.h:599
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:2854
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: rel.h:620
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
AttrNumber * partattrs
Definition: rel.h:56
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:614
static int get_partition_strategy(PartitionKey key)
Definition: rel.h:587
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
int location
Definition: parsenodes.h:280
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:2795
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:736
#define RelationGetPartitionKey(relation)
Definition: rel.h:581
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:737
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
Value val
Definition: parsenodes.h:279
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:413
void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 2202 of file parse_utilcmd.c.

References AccessExclusiveLock, RuleStmt::actions, addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, copyObject(), Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, getInsertSelectQuery(), heap_close, heap_openrv(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, NULL, ParseState::p_joinlist, ParseState::p_rtable, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RELKIND_MATVIEW, RangeTblEntry::requiredPerms, Query::rtable, Query::setOperations, transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2204 {
2205  Relation rel;
2206  ParseState *pstate;
2207  RangeTblEntry *oldrte;
2208  RangeTblEntry *newrte;
2209 
2210  /*
2211  * To avoid deadlock, make sure the first thing we do is grab
2212  * AccessExclusiveLock on the target relation. This will be needed by
2213  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2214  * beforehand.
2215  */
2217 
2218  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2219  ereport(ERROR,
2220  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2221  errmsg("rules on materialized views are not supported")));
2222 
2223  /* Set up pstate */
2224  pstate = make_parsestate(NULL);
2225  pstate->p_sourcetext = queryString;
2226 
2227  /*
2228  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2229  * Set up their RTEs in the main pstate for use in parsing the rule
2230  * qualification.
2231  */
2232  oldrte = addRangeTableEntryForRelation(pstate, rel,
2233  makeAlias("old", NIL),
2234  false, false);
2235  newrte = addRangeTableEntryForRelation(pstate, rel,
2236  makeAlias("new", NIL),
2237  false, false);
2238  /* Must override addRangeTableEntry's default access-check flags */
2239  oldrte->requiredPerms = 0;
2240  newrte->requiredPerms = 0;
2241 
2242  /*
2243  * They must be in the namespace too for lookup purposes, but only add the
2244  * one(s) that are relevant for the current kind of rule. In an UPDATE
2245  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2246  * there's no need to be so picky for INSERT & DELETE. We do not add them
2247  * to the joinlist.
2248  */
2249  switch (stmt->event)
2250  {
2251  case CMD_SELECT:
2252  addRTEtoQuery(pstate, oldrte, false, true, true);
2253  break;
2254  case CMD_UPDATE:
2255  addRTEtoQuery(pstate, oldrte, false, true, true);
2256  addRTEtoQuery(pstate, newrte, false, true, true);
2257  break;
2258  case CMD_INSERT:
2259  addRTEtoQuery(pstate, newrte, false, true, true);
2260  break;
2261  case CMD_DELETE:
2262  addRTEtoQuery(pstate, oldrte, false, true, true);
2263  break;
2264  default:
2265  elog(ERROR, "unrecognized event type: %d",
2266  (int) stmt->event);
2267  break;
2268  }
2269 
2270  /* take care of the where clause */
2271  *whereClause = transformWhereClause(pstate,
2272  (Node *) copyObject(stmt->whereClause),
2274  "WHERE");
2275  /* we have to fix its collations too */
2276  assign_expr_collations(pstate, *whereClause);
2277 
2278  /* this is probably dead code without add_missing_from: */
2279  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2280  ereport(ERROR,
2281  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2282  errmsg("rule WHERE condition cannot contain references to other relations")));
2283 
2284  /*
2285  * 'instead nothing' rules with a qualification need a query rangetable so
2286  * the rewrite handler can add the negated rule qualification to the
2287  * original query. We create a query with the new command type CMD_NOTHING
2288  * here that is treated specially by the rewrite system.
2289  */
2290  if (stmt->actions == NIL)
2291  {
2292  Query *nothing_qry = makeNode(Query);
2293 
2294  nothing_qry->commandType = CMD_NOTHING;
2295  nothing_qry->rtable = pstate->p_rtable;
2296  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2297 
2298  *actions = list_make1(nothing_qry);
2299  }
2300  else
2301  {
2302  ListCell *l;
2303  List *newactions = NIL;
2304 
2305  /*
2306  * transform each statement, like parse_sub_analyze()
2307  */
2308  foreach(l, stmt->actions)
2309  {
2310  Node *action = (Node *) lfirst(l);
2311  ParseState *sub_pstate = make_parsestate(NULL);
2312  Query *sub_qry,
2313  *top_subqry;
2314  bool has_old,
2315  has_new;
2316 
2317  /*
2318  * Since outer ParseState isn't parent of inner, have to pass down
2319  * the query text by hand.
2320  */
2321  sub_pstate->p_sourcetext = queryString;
2322 
2323  /*
2324  * Set up OLD/NEW in the rtable for this statement. The entries
2325  * are added only to relnamespace, not varnamespace, because we
2326  * don't want them to be referred to by unqualified field names
2327  * nor "*" in the rule actions. We decide later whether to put
2328  * them in the joinlist.
2329  */
2330  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2331  makeAlias("old", NIL),
2332  false, false);
2333  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2334  makeAlias("new", NIL),
2335  false, false);
2336  oldrte->requiredPerms = 0;
2337  newrte->requiredPerms = 0;
2338  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2339  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2340 
2341  /* Transform the rule action statement */
2342  top_subqry = transformStmt(sub_pstate,
2343  (Node *) copyObject(action));
2344 
2345  /*
2346  * We cannot support utility-statement actions (eg NOTIFY) with
2347  * nonempty rule WHERE conditions, because there's no way to make
2348  * the utility action execute conditionally.
2349  */
2350  if (top_subqry->commandType == CMD_UTILITY &&
2351  *whereClause != NULL)
2352  ereport(ERROR,
2353  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2354  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2355 
2356  /*
2357  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2358  * into the SELECT, and that's what we need to look at. (Ugly
2359  * kluge ... try to fix this when we redesign querytrees.)
2360  */
2361  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2362 
2363  /*
2364  * If the sub_qry is a setop, we cannot attach any qualifications
2365  * to it, because the planner won't notice them. This could
2366  * perhaps be relaxed someday, but for now, we may as well reject
2367  * such a rule immediately.
2368  */
2369  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2370  ereport(ERROR,
2371  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2372  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2373 
2374  /*
2375  * Validate action's use of OLD/NEW, qual too
2376  */
2377  has_old =
2378  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2379  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2380  has_new =
2381  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2382  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2383 
2384  switch (stmt->event)
2385  {
2386  case CMD_SELECT:
2387  if (has_old)
2388  ereport(ERROR,
2389  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2390  errmsg("ON SELECT rule cannot use OLD")));
2391  if (has_new)
2392  ereport(ERROR,
2393  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2394  errmsg("ON SELECT rule cannot use NEW")));
2395  break;
2396  case CMD_UPDATE:
2397  /* both are OK */
2398  break;
2399  case CMD_INSERT:
2400  if (has_old)
2401  ereport(ERROR,
2402  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2403  errmsg("ON INSERT rule cannot use OLD")));
2404  break;
2405  case CMD_DELETE:
2406  if (has_new)
2407  ereport(ERROR,
2408  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2409  errmsg("ON DELETE rule cannot use NEW")));
2410  break;
2411  default:
2412  elog(ERROR, "unrecognized event type: %d",
2413  (int) stmt->event);
2414  break;
2415  }
2416 
2417  /*
2418  * OLD/NEW are not allowed in WITH queries, because they would
2419  * amount to outer references for the WITH, which we disallow.
2420  * However, they were already in the outer rangetable when we
2421  * analyzed the query, so we have to check.
2422  *
2423  * Note that in the INSERT...SELECT case, we need to examine the
2424  * CTE lists of both top_subqry and sub_qry.
2425  *
2426  * Note that we aren't digging into the body of the query looking
2427  * for WITHs in nested sub-SELECTs. A WITH down there can
2428  * legitimately refer to OLD/NEW, because it'd be an
2429  * indirect-correlated outer reference.
2430  */
2431  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2432  PRS2_OLD_VARNO, 0) ||
2433  rangeTableEntry_used((Node *) sub_qry->cteList,
2434  PRS2_OLD_VARNO, 0))
2435  ereport(ERROR,
2436  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2437  errmsg("cannot refer to OLD within WITH query")));
2438  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2439  PRS2_NEW_VARNO, 0) ||
2440  rangeTableEntry_used((Node *) sub_qry->cteList,
2441  PRS2_NEW_VARNO, 0))
2442  ereport(ERROR,
2443  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2444  errmsg("cannot refer to NEW within WITH query")));
2445 
2446  /*
2447  * For efficiency's sake, add OLD to the rule action's jointree
2448  * only if it was actually referenced in the statement or qual.
2449  *
2450  * For INSERT, NEW is not really a relation (only a reference to
2451  * the to-be-inserted tuple) and should never be added to the
2452  * jointree.
2453  *
2454  * For UPDATE, we treat NEW as being another kind of reference to
2455  * OLD, because it represents references to *transformed* tuples
2456  * of the existing relation. It would be wrong to enter NEW
2457  * separately in the jointree, since that would cause a double
2458  * join of the updated relation. It's also wrong to fail to make
2459  * a jointree entry if only NEW and not OLD is mentioned.
2460  */
2461  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2462  {
2463  /*
2464  * If sub_qry is a setop, manipulating its jointree will do no
2465  * good at all, because the jointree is dummy. (This should be
2466  * a can't-happen case because of prior tests.)
2467  */
2468  if (sub_qry->setOperations != NULL)
2469  ereport(ERROR,
2470  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2471  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2472  /* hack so we can use addRTEtoQuery() */
2473  sub_pstate->p_rtable = sub_qry->rtable;
2474  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2475  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2476  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2477  }
2478 
2479  newactions = lappend(newactions, top_subqry);
2480 
2481  free_parsestate(sub_pstate);
2482  }
2483 
2484  *actions = newactions;
2485  }
2486 
2487  free_parsestate(pstate);
2488 
2489  /* Close relation, but keep the exclusive lock */
2490  heap_close(rel, NoLock);
2491 }
#define NIL
Definition: pg_list.h:69
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:282
FromExpr * jointree
Definition: parsenodes.h:129
#define RELKIND_MATVIEW
Definition: pg_class.h:167
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
List * actions
Definition: parsenodes.h:2758
AclMode requiredPerms
Definition: parsenodes.h:965
List * fromlist
Definition: primnodes.h:1433
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define list_make1(x1)
Definition: pg_list.h:133
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
List * rtable
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:247
List * lappend(List *list, void *datum)
Definition: list.c:128
#define PRS2_OLD_VARNO
Definition: primnodes.h:138
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1315
CmdType commandType
Definition: parsenodes.h:103
#define makeNode(_type_)
Definition: nodes.h:556
CmdType event
Definition: parsenodes.h:2756
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2755
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
#define AccessExclusiveLock
Definition: lockdefs.h:46
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * p_joinlist
Definition: parse_node.h:170
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
#define elog
Definition: elog.h:219
RangeVar * relation
Definition: parsenodes.h:2753
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:75
Definition: pg_list.h:45
#define PRS2_NEW_VARNO
Definition: primnodes.h:139
List * p_rtable
Definition: parse_node.h:168