PostgreSQL Source Code  git master
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)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const struct AttrMap *attmap, Oid *constraintOid)
 

Function Documentation

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const struct AttrMap attmap,
Oid constraintOid 
)

◆ transformAlterTableStmt()

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

Definition at line 3027 of file parse_utilcmd.c.

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, 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(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

3030 {
3031  Relation rel;
3032  TupleDesc tupdesc;
3033  ParseState *pstate;
3034  CreateStmtContext cxt;
3035  List *save_alist;
3036  ListCell *lcmd,
3037  *l;
3038  List *newcmds = NIL;
3039  bool skipValidation = true;
3040  AlterTableCmd *newcmd;
3041  ParseNamespaceItem *nsitem;
3042 
3043  /*
3044  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3045  * is overkill, but easy.)
3046  */
3047  stmt = copyObject(stmt);
3048 
3049  /* Caller is responsible for locking the relation */
3050  rel = relation_open(relid, NoLock);
3051  tupdesc = RelationGetDescr(rel);
3052 
3053  /* Set up pstate */
3054  pstate = make_parsestate(NULL);
3055  pstate->p_sourcetext = queryString;
3056  nsitem = addRangeTableEntryForRelation(pstate,
3057  rel,
3059  NULL,
3060  false,
3061  true);
3062  addNSItemToQuery(pstate, nsitem, false, true, true);
3063 
3064  /* Set up CreateStmtContext */
3065  cxt.pstate = pstate;
3066  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3067  {
3068  cxt.stmtType = "ALTER FOREIGN TABLE";
3069  cxt.isforeign = true;
3070  }
3071  else
3072  {
3073  cxt.stmtType = "ALTER TABLE";
3074  cxt.isforeign = false;
3075  }
3076  cxt.relation = stmt->relation;
3077  cxt.rel = rel;
3078  cxt.inhRelations = NIL;
3079  cxt.isalter = true;
3080  cxt.columns = NIL;
3081  cxt.ckconstraints = NIL;
3082  cxt.fkconstraints = NIL;
3083  cxt.ixconstraints = NIL;
3084  cxt.inh_indexes = NIL;
3085  cxt.extstats = NIL;
3086  cxt.blist = NIL;
3087  cxt.alist = NIL;
3088  cxt.pkey = NULL;
3089  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3090  cxt.partbound = NULL;
3091  cxt.ofType = false;
3092 
3093  /*
3094  * Transform ALTER subcommands that need it (most don't). These largely
3095  * re-use code from CREATE TABLE.
3096  */
3097  foreach(lcmd, stmt->cmds)
3098  {
3099  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3100 
3101  switch (cmd->subtype)
3102  {
3103  case AT_AddColumn:
3104  case AT_AddColumnRecurse:
3105  {
3106  ColumnDef *def = castNode(ColumnDef, cmd->def);
3107 
3108  transformColumnDefinition(&cxt, def);
3109 
3110  /*
3111  * If the column has a non-null default, we can't skip
3112  * validation of foreign keys.
3113  */
3114  if (def->raw_default != NULL)
3115  skipValidation = false;
3116 
3117  /*
3118  * All constraints are processed in other ways. Remove the
3119  * original list
3120  */
3121  def->constraints = NIL;
3122 
3123  newcmds = lappend(newcmds, cmd);
3124  break;
3125  }
3126 
3127  case AT_AddConstraint:
3129 
3130  /*
3131  * The original AddConstraint cmd node doesn't go to newcmds
3132  */
3133  if (IsA(cmd->def, Constraint))
3134  {
3135  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3136  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3137  skipValidation = false;
3138  }
3139  else
3140  elog(ERROR, "unrecognized node type: %d",
3141  (int) nodeTag(cmd->def));
3142  break;
3143 
3144  case AT_AlterColumnType:
3145  {
3146  ColumnDef *def = castNode(ColumnDef, cmd->def);
3148 
3149  /*
3150  * For ALTER COLUMN TYPE, transform the USING clause if
3151  * one was specified.
3152  */
3153  if (def->raw_default)
3154  {
3155  def->cooked_default =
3156  transformExpr(pstate, def->raw_default,
3158  }
3159 
3160  /*
3161  * For identity column, create ALTER SEQUENCE command to
3162  * change the data type of the sequence.
3163  */
3164  attnum = get_attnum(relid, cmd->name);
3165  if (attnum == InvalidAttrNumber)
3166  ereport(ERROR,
3167  (errcode(ERRCODE_UNDEFINED_COLUMN),
3168  errmsg("column \"%s\" of relation \"%s\" does not exist",
3169  cmd->name, RelationGetRelationName(rel))));
3170 
3171  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3172  {
3173  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3174  Oid typeOid = typenameTypeId(pstate, def->typeName);
3175  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3176 
3177  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3178  get_rel_name(seq_relid),
3179  -1);
3180  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3181  altseqstmt->for_identity = true;
3182  cxt.blist = lappend(cxt.blist, altseqstmt);
3183  }
3184 
3185  newcmds = lappend(newcmds, cmd);
3186  break;
3187  }
3188 
3189  case AT_AddIdentity:
3190  {
3191  Constraint *def = castNode(Constraint, cmd->def);
3192  ColumnDef *newdef = makeNode(ColumnDef);
3194 
3195  newdef->colname = cmd->name;
3196  newdef->identity = def->generated_when;
3197  cmd->def = (Node *) newdef;
3198 
3199  attnum = get_attnum(relid, cmd->name);
3200  if (attnum == InvalidAttrNumber)
3201  ereport(ERROR,
3202  (errcode(ERRCODE_UNDEFINED_COLUMN),
3203  errmsg("column \"%s\" of relation \"%s\" does not exist",
3204  cmd->name, RelationGetRelationName(rel))));
3205 
3206  generateSerialExtraStmts(&cxt, newdef,
3207  get_atttype(relid, attnum),
3208  def->options, true, true,
3209  NULL, NULL);
3210 
3211  newcmds = lappend(newcmds, cmd);
3212  break;
3213  }
3214 
3215  case AT_SetIdentity:
3216  {
3217  /*
3218  * Create an ALTER SEQUENCE statement for the internal
3219  * sequence of the identity column.
3220  */
3221  ListCell *lc;
3222  List *newseqopts = NIL;
3223  List *newdef = NIL;
3225  Oid seq_relid;
3226 
3227  /*
3228  * Split options into those handled by ALTER SEQUENCE and
3229  * those for ALTER TABLE proper.
3230  */
3231  foreach(lc, castNode(List, cmd->def))
3232  {
3233  DefElem *def = lfirst_node(DefElem, lc);
3234 
3235  if (strcmp(def->defname, "generated") == 0)
3236  newdef = lappend(newdef, def);
3237  else
3238  newseqopts = lappend(newseqopts, def);
3239  }
3240 
3241  attnum = get_attnum(relid, cmd->name);
3242  if (attnum == InvalidAttrNumber)
3243  ereport(ERROR,
3244  (errcode(ERRCODE_UNDEFINED_COLUMN),
3245  errmsg("column \"%s\" of relation \"%s\" does not exist",
3246  cmd->name, RelationGetRelationName(rel))));
3247 
3248  seq_relid = getIdentitySequence(relid, attnum, true);
3249 
3250  if (seq_relid)
3251  {
3252  AlterSeqStmt *seqstmt;
3253 
3254  seqstmt = makeNode(AlterSeqStmt);
3256  get_rel_name(seq_relid), -1);
3257  seqstmt->options = newseqopts;
3258  seqstmt->for_identity = true;
3259  seqstmt->missing_ok = false;
3260 
3261  cxt.blist = lappend(cxt.blist, seqstmt);
3262  }
3263 
3264  /*
3265  * If column was not an identity column, we just let the
3266  * ALTER TABLE command error out later. (There are cases
3267  * this fails to cover, but we'll need to restructure
3268  * where creation of the sequence dependency linkage
3269  * happens before we can fix it.)
3270  */
3271 
3272  cmd->def = (Node *) newdef;
3273  newcmds = lappend(newcmds, cmd);
3274  break;
3275  }
3276 
3277  case AT_AttachPartition:
3278  case AT_DetachPartition:
3279  {
3280  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3281 
3282  transformPartitionCmd(&cxt, partcmd);
3283  /* assign transformed value of the partition bound */
3284  partcmd->bound = cxt.partbound;
3285  }
3286 
3287  newcmds = lappend(newcmds, cmd);
3288  break;
3289 
3290  default:
3291 
3292  /*
3293  * Currently, we shouldn't actually get here for subcommand
3294  * types that don't require transformation; but if we do, just
3295  * emit them unchanged.
3296  */
3297  newcmds = lappend(newcmds, cmd);
3298  break;
3299  }
3300  }
3301 
3302  /*
3303  * Transfer anything we already have in cxt.alist into save_alist, to keep
3304  * it separate from the output of transformIndexConstraints.
3305  */
3306  save_alist = cxt.alist;
3307  cxt.alist = NIL;
3308 
3309  /* Postprocess constraints */
3311  transformFKConstraints(&cxt, skipValidation, true);
3312  transformCheckConstraints(&cxt, false);
3313 
3314  /*
3315  * Push any index-creation commands into the ALTER, so that they can be
3316  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3317  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3318  * subcommand has already been through transformIndexStmt.
3319  */
3320  foreach(l, cxt.alist)
3321  {
3322  Node *istmt = (Node *) lfirst(l);
3323 
3324  /*
3325  * We assume here that cxt.alist contains only IndexStmts and possibly
3326  * ALTER TABLE SET NOT NULL statements generated from primary key
3327  * constraints. We absorb the subcommands of the latter directly.
3328  */
3329  if (IsA(istmt, IndexStmt))
3330  {
3331  IndexStmt *idxstmt = (IndexStmt *) istmt;
3332 
3333  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3334  newcmd = makeNode(AlterTableCmd);
3336  newcmd->def = (Node *) idxstmt;
3337  newcmds = lappend(newcmds, newcmd);
3338  }
3339  else if (IsA(istmt, AlterTableStmt))
3340  {
3341  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3342 
3343  newcmds = list_concat(newcmds, alterstmt->cmds);
3344  }
3345  else
3346  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3347  }
3348  cxt.alist = NIL;
3349 
3350  /* Append any CHECK or FK constraints to the commands list */
3351  foreach(l, cxt.ckconstraints)
3352  {
3353  newcmd = makeNode(AlterTableCmd);
3354  newcmd->subtype = AT_AddConstraint;
3355  newcmd->def = (Node *) lfirst(l);
3356  newcmds = lappend(newcmds, newcmd);
3357  }
3358  foreach(l, cxt.fkconstraints)
3359  {
3360  newcmd = makeNode(AlterTableCmd);
3361  newcmd->subtype = AT_AddConstraint;
3362  newcmd->def = (Node *) lfirst(l);
3363  newcmds = lappend(newcmds, newcmd);
3364  }
3365 
3366  /* Append extended statistic objects */
3368 
3369  /* Close rel */
3370  relation_close(rel, NoLock);
3371 
3372  /*
3373  * Output results.
3374  */
3375  stmt->cmds = newcmds;
3376 
3377  *beforeStmts = cxt.blist;
3378  *afterStmts = list_concat(cxt.alist, save_alist);
3379 
3380  return stmt;
3381 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
char generated_when
Definition: parsenodes.h:2161
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:454
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char identity
Definition: parsenodes.h:655
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:661
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
AlterTableType subtype
Definition: parsenodes.h:1860
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:780
#define OidIsValid(objectId)
Definition: c.h:644
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
List * options
Definition: parsenodes.h:2553
List * options
Definition: parsenodes.h:2173
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
ParseState * pstate
Definition: parse_utilcmd.c:78
Node * cooked_default
Definition: parsenodes.h:654
Oid indexOid
Definition: parsenodes.h:2783
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
#define RelationGetRelationName(relation)
Definition: rel.h:462
const char * p_sourcetext
Definition: parse_node.h:179
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
#define ereport(elevel, rest)
Definition: elog.h:141
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
RangeVar * sequence
Definition: parsenodes.h:2552
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:573
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:859
TypeName * typeName
Definition: parsenodes.h:647
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:822
RangeVar * relation
Definition: parsenodes.h:1774
#define elog(elevel,...)
Definition: elog.h:228
bool for_identity
Definition: parsenodes.h:2554
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:641
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:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3562 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().

3563 {
3565  List *result;
3566  ListCell *elements;
3567 
3568  cxt.stmtType = "CREATE SCHEMA";
3569  cxt.schemaname = stmt->schemaname;
3570  cxt.authrole = (RoleSpec *) stmt->authrole;
3571  cxt.sequences = NIL;
3572  cxt.tables = NIL;
3573  cxt.views = NIL;
3574  cxt.indexes = NIL;
3575  cxt.triggers = NIL;
3576  cxt.grants = NIL;
3577 
3578  /*
3579  * Run through each schema element in the schema element list. Separate
3580  * statements by type, and do preliminary analysis.
3581  */
3582  foreach(elements, stmt->schemaElts)
3583  {
3584  Node *element = lfirst(elements);
3585 
3586  switch (nodeTag(element))
3587  {
3588  case T_CreateSeqStmt:
3589  {
3590  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3591 
3593  cxt.sequences = lappend(cxt.sequences, element);
3594  }
3595  break;
3596 
3597  case T_CreateStmt:
3598  {
3599  CreateStmt *elp = (CreateStmt *) element;
3600 
3602 
3603  /*
3604  * XXX todo: deal with constraints
3605  */
3606  cxt.tables = lappend(cxt.tables, element);
3607  }
3608  break;
3609 
3610  case T_ViewStmt:
3611  {
3612  ViewStmt *elp = (ViewStmt *) element;
3613 
3614  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3615 
3616  /*
3617  * XXX todo: deal with references between views
3618  */
3619  cxt.views = lappend(cxt.views, element);
3620  }
3621  break;
3622 
3623  case T_IndexStmt:
3624  {
3625  IndexStmt *elp = (IndexStmt *) element;
3626 
3628  cxt.indexes = lappend(cxt.indexes, element);
3629  }
3630  break;
3631 
3632  case T_CreateTrigStmt:
3633  {
3634  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3635 
3637  cxt.triggers = lappend(cxt.triggers, element);
3638  }
3639  break;
3640 
3641  case T_GrantStmt:
3642  cxt.grants = lappend(cxt.grants, element);
3643  break;
3644 
3645  default:
3646  elog(ERROR, "unrecognized node type: %d",
3647  (int) nodeTag(element));
3648  }
3649  }
3650 
3651  result = NIL;
3652  result = list_concat(result, cxt.sequences);
3653  result = list_concat(result, cxt.tables);
3654  result = list_concat(result, cxt.views);
3655  result = list_concat(result, cxt.indexes);
3656  result = list_concat(result, cxt.triggers);
3657  result = list_concat(result, cxt.grants);
3658 
3659  return result;
3660 }
RangeVar * relation
Definition: parsenodes.h:2069
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
RangeVar * view
Definition: parsenodes.h:3112
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2773
RoleSpec * authrole
Definition: parsenodes.h:1756
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:322
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2542
#define lfirst(lc)
Definition: pg_list.h:190
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228
RangeVar * relation
Definition: parsenodes.h:2428
Definition: pg_list.h:50

◆ transformCreateStmt()

List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 165 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::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, list_concat(), RangeVar::location, make_parsestate(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

166 {
167  ParseState *pstate;
168  CreateStmtContext cxt;
169  List *result;
170  List *save_alist;
171  ListCell *elements;
172  Oid namespaceid;
173  Oid existing_relid;
174  ParseCallbackState pcbstate;
175  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
176 
177  /*
178  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
179  * overkill, but easy.)
180  */
181  stmt = copyObject(stmt);
182 
183  /* Set up pstate */
184  pstate = make_parsestate(NULL);
185  pstate->p_sourcetext = queryString;
186 
187  /*
188  * Look up the creation namespace. This also checks permissions on the
189  * target namespace, locks it against concurrent drops, checks for a
190  * preexisting relation in that namespace with the same name, and updates
191  * stmt->relation->relpersistence if the selected namespace is temporary.
192  */
193  setup_parser_errposition_callback(&pcbstate, pstate,
194  stmt->relation->location);
195  namespaceid =
197  &existing_relid);
199 
200  /*
201  * If the relation already exists and the user specified "IF NOT EXISTS",
202  * bail out with a NOTICE.
203  */
204  if (stmt->if_not_exists && OidIsValid(existing_relid))
205  {
206  ereport(NOTICE,
207  (errcode(ERRCODE_DUPLICATE_TABLE),
208  errmsg("relation \"%s\" already exists, skipping",
209  stmt->relation->relname)));
210  return NIL;
211  }
212 
213  /*
214  * If the target relation name isn't schema-qualified, make it so. This
215  * prevents some corner cases in which added-on rewritten commands might
216  * think they should apply to other relations that have the same name and
217  * are earlier in the search path. But a local temp table is effectively
218  * specified to be in pg_temp, so no need for anything extra in that case.
219  */
220  if (stmt->relation->schemaname == NULL
221  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
222  stmt->relation->schemaname = get_namespace_name(namespaceid);
223 
224  /* Set up CreateStmtContext */
225  cxt.pstate = pstate;
226  if (IsA(stmt, CreateForeignTableStmt))
227  {
228  cxt.stmtType = "CREATE FOREIGN TABLE";
229  cxt.isforeign = true;
230  }
231  else
232  {
233  cxt.stmtType = "CREATE TABLE";
234  cxt.isforeign = false;
235  }
236  cxt.relation = stmt->relation;
237  cxt.rel = NULL;
238  cxt.inhRelations = stmt->inhRelations;
239  cxt.isalter = false;
240  cxt.columns = NIL;
241  cxt.ckconstraints = NIL;
242  cxt.fkconstraints = NIL;
243  cxt.ixconstraints = NIL;
244  cxt.inh_indexes = NIL;
245  cxt.extstats = NIL;
246  cxt.blist = NIL;
247  cxt.alist = NIL;
248  cxt.pkey = NULL;
249  cxt.ispartitioned = stmt->partspec != NULL;
250  cxt.partbound = stmt->partbound;
251  cxt.ofType = (stmt->ofTypename != NULL);
252 
253  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
254 
255  if (stmt->ofTypename)
256  transformOfType(&cxt, stmt->ofTypename);
257 
258  if (stmt->partspec)
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 
266  /*
267  * Run through each primary element in the table creation clause. Separate
268  * column defs from constraints, and do preliminary analysis.
269  */
270  foreach(elements, stmt->tableElts)
271  {
272  Node *element = lfirst(elements);
273 
274  switch (nodeTag(element))
275  {
276  case T_ColumnDef:
277  transformColumnDefinition(&cxt, (ColumnDef *) element);
278  break;
279 
280  case T_Constraint:
281  transformTableConstraint(&cxt, (Constraint *) element);
282  break;
283 
284  case T_TableLikeClause:
285  transformTableLikeClause(&cxt, (TableLikeClause *) element);
286  break;
287 
288  default:
289  elog(ERROR, "unrecognized node type: %d",
290  (int) nodeTag(element));
291  break;
292  }
293  }
294 
295  /*
296  * Transfer anything we already have in cxt.alist into save_alist, to keep
297  * it separate from the output of transformIndexConstraints. (This may
298  * not be necessary anymore, but we'll keep doing it to preserve the
299  * historical order of execution of the alist commands.)
300  */
301  save_alist = cxt.alist;
302  cxt.alist = NIL;
303 
304  Assert(stmt->constraints == NIL);
305 
306  /*
307  * Postprocess constraints that give rise to index definitions.
308  */
310 
311  /*
312  * Postprocess foreign-key constraints.
313  */
314  transformFKConstraints(&cxt, true, false);
315 
316  /*
317  * Postprocess check constraints.
318  */
319  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
320 
321  /*
322  * Postprocess extended statistics.
323  */
325 
326  /*
327  * Output results.
328  */
329  stmt->tableElts = cxt.columns;
330  stmt->constraints = cxt.ckconstraints;
331 
332  result = lappend(cxt.blist, stmt);
333  result = list_concat(result, cxt.alist);
334  result = list_concat(result, save_alist);
335 
336  return result;
337 }
RangeVar * relation
Definition: parsenodes.h:2069
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2071
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
List * constraints
Definition: parsenodes.h:2076
bool if_not_exists
Definition: parsenodes.h:2081
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2073
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
List * lappend(List *list, void *datum)
Definition: list.c:322
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:526
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2070
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define copyObject(obj)
Definition: nodes.h:641
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2074
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2075
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

IndexStmt* transformIndexStmt ( Oid  relid,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 2609 of file parse_utilcmd.c.

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

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

2610 {
2611  ParseState *pstate;
2612  ParseNamespaceItem *nsitem;
2613  ListCell *l;
2614  Relation rel;
2615 
2616  /* Nothing to do if statement already transformed. */
2617  if (stmt->transformed)
2618  return stmt;
2619 
2620  /*
2621  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2622  * overkill, but easy.)
2623  */
2624  stmt = copyObject(stmt);
2625 
2626  /* Set up pstate */
2627  pstate = make_parsestate(NULL);
2628  pstate->p_sourcetext = queryString;
2629 
2630  /*
2631  * Put the parent table into the rtable so that the expressions can refer
2632  * to its fields without qualification. Caller is responsible for locking
2633  * relation, but we still need to open it.
2634  */
2635  rel = relation_open(relid, NoLock);
2636  nsitem = addRangeTableEntryForRelation(pstate, rel,
2638  NULL, false, true);
2639 
2640  /* no to join list, yes to namespaces */
2641  addNSItemToQuery(pstate, nsitem, false, true, true);
2642 
2643  /* take care of the where clause */
2644  if (stmt->whereClause)
2645  {
2646  stmt->whereClause = transformWhereClause(pstate,
2647  stmt->whereClause,
2649  "WHERE");
2650  /* we have to fix its collations too */
2651  assign_expr_collations(pstate, stmt->whereClause);
2652  }
2653 
2654  /* take care of any index expressions */
2655  foreach(l, stmt->indexParams)
2656  {
2657  IndexElem *ielem = (IndexElem *) lfirst(l);
2658 
2659  if (ielem->expr)
2660  {
2661  /* Extract preliminary index col name before transforming expr */
2662  if (ielem->indexcolname == NULL)
2663  ielem->indexcolname = FigureIndexColname(ielem->expr);
2664 
2665  /* Now do parse transformation of the expression */
2666  ielem->expr = transformExpr(pstate, ielem->expr,
2668 
2669  /* We have to fix its collations too */
2670  assign_expr_collations(pstate, ielem->expr);
2671 
2672  /*
2673  * transformExpr() should have already rejected subqueries,
2674  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2675  * for an index expression.
2676  *
2677  * DefineIndex() will make more checks.
2678  */
2679  }
2680  }
2681 
2682  /*
2683  * Check that only the base rel is mentioned. (This should be dead code
2684  * now that add_missing_from is history.)
2685  */
2686  if (list_length(pstate->p_rtable) != 1)
2687  ereport(ERROR,
2688  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2689  errmsg("index expressions and predicates can refer only to the table being indexed")));
2690 
2691  free_parsestate(pstate);
2692 
2693  /* Close relation */
2694  table_close(rel, NoLock);
2695 
2696  /* Mark statement as successfully transformed */
2697  stmt->transformed = true;
2698 
2699  return stmt;
2700 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Node * whereClause
Definition: parsenodes.h:2780
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:608
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:700
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2790
char * indexcolname
Definition: parsenodes.h:701
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel, rest)
Definition: elog.h:141
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2776
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
List * p_rtable
Definition: parse_node.h:180

◆ transformPartitionBound()

PartitionBoundSpec* transformPartitionBound ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 3732 of file parse_utilcmd.c.

References Assert, castNode, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend(), lfirst, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), transformPartitionRangeBounds(), PartitionBoundSpec::upperdatums, and value.

Referenced by DefineRelation(), and transformPartitionCmd().

3734 {
3735  PartitionBoundSpec *result_spec;
3737  char strategy = get_partition_strategy(key);
3738  int partnatts = get_partition_natts(key);
3739  List *partexprs = get_partition_exprs(key);
3740 
3741  /* Avoid scribbling on input */
3742  result_spec = copyObject(spec);
3743 
3744  if (spec->is_default)
3745  {
3746  /*
3747  * Hash partitioning does not support a default partition; there's no
3748  * use case for it (since the set of partitions to create is perfectly
3749  * defined), and if users do get into it accidentally, it's hard to
3750  * back out from it afterwards.
3751  */
3752  if (strategy == PARTITION_STRATEGY_HASH)
3753  ereport(ERROR,
3754  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3755  errmsg("a hash-partitioned table may not have a default partition")));
3756 
3757  /*
3758  * In case of the default partition, parser had no way to identify the
3759  * partition strategy. Assign the parent's strategy to the default
3760  * partition bound spec.
3761  */
3762  result_spec->strategy = strategy;
3763 
3764  return result_spec;
3765  }
3766 
3767  if (strategy == PARTITION_STRATEGY_HASH)
3768  {
3769  if (spec->strategy != PARTITION_STRATEGY_HASH)
3770  ereport(ERROR,
3771  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3772  errmsg("invalid bound specification for a hash partition"),
3773  parser_errposition(pstate, exprLocation((Node *) spec))));
3774 
3775  if (spec->modulus <= 0)
3776  ereport(ERROR,
3777  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3778  errmsg("modulus for hash partition must be a positive integer")));
3779 
3780  Assert(spec->remainder >= 0);
3781 
3782  if (spec->remainder >= spec->modulus)
3783  ereport(ERROR,
3784  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3785  errmsg("remainder for hash partition must be less than modulus")));
3786  }
3787  else if (strategy == PARTITION_STRATEGY_LIST)
3788  {
3789  ListCell *cell;
3790  char *colname;
3791  Oid coltype;
3792  int32 coltypmod;
3793  Oid partcollation;
3794 
3795  if (spec->strategy != PARTITION_STRATEGY_LIST)
3796  ereport(ERROR,
3797  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3798  errmsg("invalid bound specification for a list partition"),
3799  parser_errposition(pstate, exprLocation((Node *) spec))));
3800 
3801  /* Get the only column's name in case we need to output an error */
3802  if (key->partattrs[0] != 0)
3803  colname = get_attname(RelationGetRelid(parent),
3804  key->partattrs[0], false);
3805  else
3806  colname = deparse_expression((Node *) linitial(partexprs),
3808  RelationGetRelid(parent)),
3809  false, false);
3810  /* Need its type data too */
3811  coltype = get_partition_col_typid(key, 0);
3812  coltypmod = get_partition_col_typmod(key, 0);
3813  partcollation = get_partition_col_collation(key, 0);
3814 
3815  result_spec->listdatums = NIL;
3816  foreach(cell, spec->listdatums)
3817  {
3818  Node *expr = lfirst(cell);
3819  Const *value;
3820  ListCell *cell2;
3821  bool duplicate;
3822 
3823  value = transformPartitionBoundValue(pstate, expr,
3824  colname, coltype, coltypmod,
3825  partcollation);
3826 
3827  /* Don't add to the result if the value is a duplicate */
3828  duplicate = false;
3829  foreach(cell2, result_spec->listdatums)
3830  {
3831  Const *value2 = castNode(Const, lfirst(cell2));
3832 
3833  if (equal(value, value2))
3834  {
3835  duplicate = true;
3836  break;
3837  }
3838  }
3839  if (duplicate)
3840  continue;
3841 
3842  result_spec->listdatums = lappend(result_spec->listdatums,
3843  value);
3844  }
3845  }
3846  else if (strategy == PARTITION_STRATEGY_RANGE)
3847  {
3848  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3849  ereport(ERROR,
3850  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3851  errmsg("invalid bound specification for a range partition"),
3852  parser_errposition(pstate, exprLocation((Node *) spec))));
3853 
3854  if (list_length(spec->lowerdatums) != partnatts)
3855  ereport(ERROR,
3856  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3857  errmsg("FROM must specify exactly one value per partitioning column")));
3858  if (list_length(spec->upperdatums) != partnatts)
3859  ereport(ERROR,
3860  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3861  errmsg("TO must specify exactly one value per partitioning column")));
3862 
3863  /*
3864  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3865  * any necessary validation.
3866  */
3867  result_spec->lowerdatums =
3869  parent);
3870  result_spec->upperdatums =
3872  parent);
3873  }
3874  else
3875  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3876 
3877  return result_spec;
3878 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3018
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
static struct @145 value
Definition: nodes.h:525
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:608
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:355
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static Const * transformPartitionBoundValue(ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3272
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:798
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3212
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:799
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:800
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define copyObject(obj)
Definition: nodes.h:641
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:428

◆ transformRuleStmt()

void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 2716 of file parse_utilcmd.c.

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, RuleStmt::actions, addNSItemToQuery(), addRangeTableEntryForRelation(), 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(), getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RangeTblEntry::requiredPerms, Query::rtable, RangeTblRef::rtindex, Query::setOperations, table_close(), table_openrv(), transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2718 {
2719  Relation rel;
2720  ParseState *pstate;
2721  ParseNamespaceItem *oldnsitem;
2722  ParseNamespaceItem *newnsitem;
2723 
2724  /*
2725  * To avoid deadlock, make sure the first thing we do is grab
2726  * AccessExclusiveLock on the target relation. This will be needed by
2727  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2728  * beforehand.
2729  */
2731 
2732  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2733  ereport(ERROR,
2734  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2735  errmsg("rules on materialized views are not supported")));
2736 
2737  /* Set up pstate */
2738  pstate = make_parsestate(NULL);
2739  pstate->p_sourcetext = queryString;
2740 
2741  /*
2742  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2743  * Set up their ParseNamespaceItems in the main pstate for use in parsing
2744  * the rule qualification.
2745  */
2746  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
2748  makeAlias("old", NIL),
2749  false, false);
2750  newnsitem = addRangeTableEntryForRelation(pstate, rel,
2752  makeAlias("new", NIL),
2753  false, false);
2754  /* Must override addRangeTableEntry's default access-check flags */
2755  oldnsitem->p_rte->requiredPerms = 0;
2756  newnsitem->p_rte->requiredPerms = 0;
2757 
2758  /*
2759  * They must be in the namespace too for lookup purposes, but only add the
2760  * one(s) that are relevant for the current kind of rule. In an UPDATE
2761  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2762  * there's no need to be so picky for INSERT & DELETE. We do not add them
2763  * to the joinlist.
2764  */
2765  switch (stmt->event)
2766  {
2767  case CMD_SELECT:
2768  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2769  break;
2770  case CMD_UPDATE:
2771  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2772  addNSItemToQuery(pstate, newnsitem, false, true, true);
2773  break;
2774  case CMD_INSERT:
2775  addNSItemToQuery(pstate, newnsitem, false, true, true);
2776  break;
2777  case CMD_DELETE:
2778  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2779  break;
2780  default:
2781  elog(ERROR, "unrecognized event type: %d",
2782  (int) stmt->event);
2783  break;
2784  }
2785 
2786  /* take care of the where clause */
2787  *whereClause = transformWhereClause(pstate,
2788  (Node *) copyObject(stmt->whereClause),
2790  "WHERE");
2791  /* we have to fix its collations too */
2792  assign_expr_collations(pstate, *whereClause);
2793 
2794  /* this is probably dead code without add_missing_from: */
2795  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2796  ereport(ERROR,
2797  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2798  errmsg("rule WHERE condition cannot contain references to other relations")));
2799 
2800  /*
2801  * 'instead nothing' rules with a qualification need a query rangetable so
2802  * the rewrite handler can add the negated rule qualification to the
2803  * original query. We create a query with the new command type CMD_NOTHING
2804  * here that is treated specially by the rewrite system.
2805  */
2806  if (stmt->actions == NIL)
2807  {
2808  Query *nothing_qry = makeNode(Query);
2809 
2810  nothing_qry->commandType = CMD_NOTHING;
2811  nothing_qry->rtable = pstate->p_rtable;
2812  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2813 
2814  *actions = list_make1(nothing_qry);
2815  }
2816  else
2817  {
2818  ListCell *l;
2819  List *newactions = NIL;
2820 
2821  /*
2822  * transform each statement, like parse_sub_analyze()
2823  */
2824  foreach(l, stmt->actions)
2825  {
2826  Node *action = (Node *) lfirst(l);
2827  ParseState *sub_pstate = make_parsestate(NULL);
2828  Query *sub_qry,
2829  *top_subqry;
2830  bool has_old,
2831  has_new;
2832 
2833  /*
2834  * Since outer ParseState isn't parent of inner, have to pass down
2835  * the query text by hand.
2836  */
2837  sub_pstate->p_sourcetext = queryString;
2838 
2839  /*
2840  * Set up OLD/NEW in the rtable for this statement. The entries
2841  * are added only to relnamespace, not varnamespace, because we
2842  * don't want them to be referred to by unqualified field names
2843  * nor "*" in the rule actions. We decide later whether to put
2844  * them in the joinlist.
2845  */
2846  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
2848  makeAlias("old", NIL),
2849  false, false);
2850  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
2852  makeAlias("new", NIL),
2853  false, false);
2854  oldnsitem->p_rte->requiredPerms = 0;
2855  newnsitem->p_rte->requiredPerms = 0;
2856  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
2857  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
2858 
2859  /* Transform the rule action statement */
2860  top_subqry = transformStmt(sub_pstate,
2861  (Node *) copyObject(action));
2862 
2863  /*
2864  * We cannot support utility-statement actions (eg NOTIFY) with
2865  * nonempty rule WHERE conditions, because there's no way to make
2866  * the utility action execute conditionally.
2867  */
2868  if (top_subqry->commandType == CMD_UTILITY &&
2869  *whereClause != NULL)
2870  ereport(ERROR,
2871  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2872  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2873 
2874  /*
2875  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2876  * into the SELECT, and that's what we need to look at. (Ugly
2877  * kluge ... try to fix this when we redesign querytrees.)
2878  */
2879  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2880 
2881  /*
2882  * If the sub_qry is a setop, we cannot attach any qualifications
2883  * to it, because the planner won't notice them. This could
2884  * perhaps be relaxed someday, but for now, we may as well reject
2885  * such a rule immediately.
2886  */
2887  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2888  ereport(ERROR,
2889  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2890  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2891 
2892  /*
2893  * Validate action's use of OLD/NEW, qual too
2894  */
2895  has_old =
2896  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2897  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2898  has_new =
2899  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2900  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2901 
2902  switch (stmt->event)
2903  {
2904  case CMD_SELECT:
2905  if (has_old)
2906  ereport(ERROR,
2907  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2908  errmsg("ON SELECT rule cannot use OLD")));
2909  if (has_new)
2910  ereport(ERROR,
2911  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2912  errmsg("ON SELECT rule cannot use NEW")));
2913  break;
2914  case CMD_UPDATE:
2915  /* both are OK */
2916  break;
2917  case CMD_INSERT:
2918  if (has_old)
2919  ereport(ERROR,
2920  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2921  errmsg("ON INSERT rule cannot use OLD")));
2922  break;
2923  case CMD_DELETE:
2924  if (has_new)
2925  ereport(ERROR,
2926  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2927  errmsg("ON DELETE rule cannot use NEW")));
2928  break;
2929  default:
2930  elog(ERROR, "unrecognized event type: %d",
2931  (int) stmt->event);
2932  break;
2933  }
2934 
2935  /*
2936  * OLD/NEW are not allowed in WITH queries, because they would
2937  * amount to outer references for the WITH, which we disallow.
2938  * However, they were already in the outer rangetable when we
2939  * analyzed the query, so we have to check.
2940  *
2941  * Note that in the INSERT...SELECT case, we need to examine the
2942  * CTE lists of both top_subqry and sub_qry.
2943  *
2944  * Note that we aren't digging into the body of the query looking
2945  * for WITHs in nested sub-SELECTs. A WITH down there can
2946  * legitimately refer to OLD/NEW, because it'd be an
2947  * indirect-correlated outer reference.
2948  */
2949  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2950  PRS2_OLD_VARNO, 0) ||
2951  rangeTableEntry_used((Node *) sub_qry->cteList,
2952  PRS2_OLD_VARNO, 0))
2953  ereport(ERROR,
2954  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2955  errmsg("cannot refer to OLD within WITH query")));
2956  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2957  PRS2_NEW_VARNO, 0) ||
2958  rangeTableEntry_used((Node *) sub_qry->cteList,
2959  PRS2_NEW_VARNO, 0))
2960  ereport(ERROR,
2961  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2962  errmsg("cannot refer to NEW within WITH query")));
2963 
2964  /*
2965  * For efficiency's sake, add OLD to the rule action's jointree
2966  * only if it was actually referenced in the statement or qual.
2967  *
2968  * For INSERT, NEW is not really a relation (only a reference to
2969  * the to-be-inserted tuple) and should never be added to the
2970  * jointree.
2971  *
2972  * For UPDATE, we treat NEW as being another kind of reference to
2973  * OLD, because it represents references to *transformed* tuples
2974  * of the existing relation. It would be wrong to enter NEW
2975  * separately in the jointree, since that would cause a double
2976  * join of the updated relation. It's also wrong to fail to make
2977  * a jointree entry if only NEW and not OLD is mentioned.
2978  */
2979  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2980  {
2981  RangeTblRef *rtr;
2982 
2983  /*
2984  * If sub_qry is a setop, manipulating its jointree will do no
2985  * good at all, because the jointree is dummy. (This should be
2986  * a can't-happen case because of prior tests.)
2987  */
2988  if (sub_qry->setOperations != NULL)
2989  ereport(ERROR,
2990  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2991  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2992  /* hackishly add OLD to the already-built FROM clause */
2993  rtr = makeNode(RangeTblRef);
2994  rtr->rtindex = oldnsitem->p_rtindex;
2995  sub_qry->jointree->fromlist =
2996  lappend(sub_qry->jointree->fromlist, rtr);
2997  }
2998 
2999  newactions = lappend(newactions, top_subqry);
3000 
3001  free_parsestate(sub_pstate);
3002  }
3003 
3004  *actions = newactions;
3005  }
3006 
3007  free_parsestate(pstate);
3008 
3009  /* Close relation, but keep the exclusive lock */
3010  table_close(rel, NoLock);
3011 }
#define NIL
Definition: pg_list.h:65
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:924
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:283
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
FromExpr * jointree
Definition: parsenodes.h:138
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
List * actions
Definition: parsenodes.h:2987
AclMode requiredPerms
Definition: parsenodes.h:1117
List * fromlist
Definition: primnodes.h:1510
Form_pg_class rd_rel
Definition: rel.h:84
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:385
RangeTblEntry * p_rte
Definition: parse_node.h:257
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel, rest)
Definition: elog.h:141
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:254
List * lappend(List *list, void *datum)
Definition: list.c:322
#define PRS2_OLD_VARNO
Definition: primnodes.h:178
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:573
CmdType event
Definition: parsenodes.h:2985
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2984
static int list_length(const List *l)
Definition: pg_list.h:169
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:892
#define copyObject(obj)
Definition: nodes.h:641
RangeVar * relation
Definition: parsenodes.h:2982
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
Definition: pg_list.h:50
#define PRS2_NEW_VARNO
Definition: primnodes.h:179
List * p_rtable
Definition: parse_node.h:180