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

3064 {
3065  Relation rel;
3066  TupleDesc tupdesc;
3067  ParseState *pstate;
3068  CreateStmtContext cxt;
3069  List *save_alist;
3070  ListCell *lcmd,
3071  *l;
3072  List *newcmds = NIL;
3073  bool skipValidation = true;
3074  AlterTableCmd *newcmd;
3075  ParseNamespaceItem *nsitem;
3076 
3077  /*
3078  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3079  * is overkill, but easy.)
3080  */
3081  stmt = copyObject(stmt);
3082 
3083  /* Caller is responsible for locking the relation */
3084  rel = relation_open(relid, NoLock);
3085  tupdesc = RelationGetDescr(rel);
3086 
3087  /* Set up pstate */
3088  pstate = make_parsestate(NULL);
3089  pstate->p_sourcetext = queryString;
3090  nsitem = addRangeTableEntryForRelation(pstate,
3091  rel,
3093  NULL,
3094  false,
3095  true);
3096  addNSItemToQuery(pstate, nsitem, false, true, true);
3097 
3098  /* Set up CreateStmtContext */
3099  cxt.pstate = pstate;
3100  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3101  {
3102  cxt.stmtType = "ALTER FOREIGN TABLE";
3103  cxt.isforeign = true;
3104  }
3105  else
3106  {
3107  cxt.stmtType = "ALTER TABLE";
3108  cxt.isforeign = false;
3109  }
3110  cxt.relation = stmt->relation;
3111  cxt.rel = rel;
3112  cxt.inhRelations = NIL;
3113  cxt.isalter = true;
3114  cxt.columns = NIL;
3115  cxt.ckconstraints = NIL;
3116  cxt.fkconstraints = NIL;
3117  cxt.ixconstraints = NIL;
3118  cxt.inh_indexes = NIL;
3119  cxt.extstats = NIL;
3120  cxt.blist = NIL;
3121  cxt.alist = NIL;
3122  cxt.pkey = NULL;
3123  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3124  cxt.partbound = NULL;
3125  cxt.ofType = false;
3126 
3127  /*
3128  * Transform ALTER subcommands that need it (most don't). These largely
3129  * re-use code from CREATE TABLE.
3130  */
3131  foreach(lcmd, stmt->cmds)
3132  {
3133  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3134 
3135  switch (cmd->subtype)
3136  {
3137  case AT_AddColumn:
3138  case AT_AddColumnRecurse:
3139  {
3140  ColumnDef *def = castNode(ColumnDef, cmd->def);
3141 
3142  transformColumnDefinition(&cxt, def);
3143 
3144  /*
3145  * If the column has a non-null default, we can't skip
3146  * validation of foreign keys.
3147  */
3148  if (def->raw_default != NULL)
3149  skipValidation = false;
3150 
3151  /*
3152  * All constraints are processed in other ways. Remove the
3153  * original list
3154  */
3155  def->constraints = NIL;
3156 
3157  newcmds = lappend(newcmds, cmd);
3158  break;
3159  }
3160 
3161  case AT_AddConstraint:
3163 
3164  /*
3165  * The original AddConstraint cmd node doesn't go to newcmds
3166  */
3167  if (IsA(cmd->def, Constraint))
3168  {
3169  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3170  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3171  skipValidation = false;
3172  }
3173  else
3174  elog(ERROR, "unrecognized node type: %d",
3175  (int) nodeTag(cmd->def));
3176  break;
3177 
3178  case AT_AlterColumnType:
3179  {
3180  ColumnDef *def = castNode(ColumnDef, cmd->def);
3182 
3183  /*
3184  * For ALTER COLUMN TYPE, transform the USING clause if
3185  * one was specified.
3186  */
3187  if (def->raw_default)
3188  {
3189  def->cooked_default =
3190  transformExpr(pstate, def->raw_default,
3192  }
3193 
3194  /*
3195  * For identity column, create ALTER SEQUENCE command to
3196  * change the data type of the sequence.
3197  */
3198  attnum = get_attnum(relid, cmd->name);
3199  if (attnum == InvalidAttrNumber)
3200  ereport(ERROR,
3201  (errcode(ERRCODE_UNDEFINED_COLUMN),
3202  errmsg("column \"%s\" of relation \"%s\" does not exist",
3203  cmd->name, RelationGetRelationName(rel))));
3204 
3205  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3206  {
3207  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3208  Oid typeOid = typenameTypeId(pstate, def->typeName);
3209  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3210 
3211  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3212  get_rel_name(seq_relid),
3213  -1);
3214  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3215  altseqstmt->for_identity = true;
3216  cxt.blist = lappend(cxt.blist, altseqstmt);
3217  }
3218 
3219  newcmds = lappend(newcmds, cmd);
3220  break;
3221  }
3222 
3223  case AT_AddIdentity:
3224  {
3225  Constraint *def = castNode(Constraint, cmd->def);
3226  ColumnDef *newdef = makeNode(ColumnDef);
3228 
3229  newdef->colname = cmd->name;
3230  newdef->identity = def->generated_when;
3231  cmd->def = (Node *) newdef;
3232 
3233  attnum = get_attnum(relid, cmd->name);
3234  if (attnum == InvalidAttrNumber)
3235  ereport(ERROR,
3236  (errcode(ERRCODE_UNDEFINED_COLUMN),
3237  errmsg("column \"%s\" of relation \"%s\" does not exist",
3238  cmd->name, RelationGetRelationName(rel))));
3239 
3240  generateSerialExtraStmts(&cxt, newdef,
3241  get_atttype(relid, attnum),
3242  def->options, true, true,
3243  NULL, NULL);
3244 
3245  newcmds = lappend(newcmds, cmd);
3246  break;
3247  }
3248 
3249  case AT_SetIdentity:
3250  {
3251  /*
3252  * Create an ALTER SEQUENCE statement for the internal
3253  * sequence of the identity column.
3254  */
3255  ListCell *lc;
3256  List *newseqopts = NIL;
3257  List *newdef = NIL;
3259  Oid seq_relid;
3260 
3261  /*
3262  * Split options into those handled by ALTER SEQUENCE and
3263  * those for ALTER TABLE proper.
3264  */
3265  foreach(lc, castNode(List, cmd->def))
3266  {
3267  DefElem *def = lfirst_node(DefElem, lc);
3268 
3269  if (strcmp(def->defname, "generated") == 0)
3270  newdef = lappend(newdef, def);
3271  else
3272  newseqopts = lappend(newseqopts, def);
3273  }
3274 
3275  attnum = get_attnum(relid, cmd->name);
3276  if (attnum == InvalidAttrNumber)
3277  ereport(ERROR,
3278  (errcode(ERRCODE_UNDEFINED_COLUMN),
3279  errmsg("column \"%s\" of relation \"%s\" does not exist",
3280  cmd->name, RelationGetRelationName(rel))));
3281 
3282  seq_relid = getIdentitySequence(relid, attnum, true);
3283 
3284  if (seq_relid)
3285  {
3286  AlterSeqStmt *seqstmt;
3287 
3288  seqstmt = makeNode(AlterSeqStmt);
3290  get_rel_name(seq_relid), -1);
3291  seqstmt->options = newseqopts;
3292  seqstmt->for_identity = true;
3293  seqstmt->missing_ok = false;
3294 
3295  cxt.blist = lappend(cxt.blist, seqstmt);
3296  }
3297 
3298  /*
3299  * If column was not an identity column, we just let the
3300  * ALTER TABLE command error out later. (There are cases
3301  * this fails to cover, but we'll need to restructure
3302  * where creation of the sequence dependency linkage
3303  * happens before we can fix it.)
3304  */
3305 
3306  cmd->def = (Node *) newdef;
3307  newcmds = lappend(newcmds, cmd);
3308  break;
3309  }
3310 
3311  case AT_AttachPartition:
3312  case AT_DetachPartition:
3313  {
3314  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3315 
3316  transformPartitionCmd(&cxt, partcmd);
3317  /* assign transformed value of the partition bound */
3318  partcmd->bound = cxt.partbound;
3319  }
3320 
3321  newcmds = lappend(newcmds, cmd);
3322  break;
3323 
3324  default:
3325 
3326  /*
3327  * Currently, we shouldn't actually get here for subcommand
3328  * types that don't require transformation; but if we do, just
3329  * emit them unchanged.
3330  */
3331  newcmds = lappend(newcmds, cmd);
3332  break;
3333  }
3334  }
3335 
3336  /*
3337  * Transfer anything we already have in cxt.alist into save_alist, to keep
3338  * it separate from the output of transformIndexConstraints.
3339  */
3340  save_alist = cxt.alist;
3341  cxt.alist = NIL;
3342 
3343  /* Postprocess constraints */
3345  transformFKConstraints(&cxt, skipValidation, true);
3346  transformCheckConstraints(&cxt, false);
3347 
3348  /*
3349  * Push any index-creation commands into the ALTER, so that they can be
3350  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3351  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3352  * subcommand has already been through transformIndexStmt.
3353  */
3354  foreach(l, cxt.alist)
3355  {
3356  Node *istmt = (Node *) lfirst(l);
3357 
3358  /*
3359  * We assume here that cxt.alist contains only IndexStmts and possibly
3360  * ALTER TABLE SET NOT NULL statements generated from primary key
3361  * constraints. We absorb the subcommands of the latter directly.
3362  */
3363  if (IsA(istmt, IndexStmt))
3364  {
3365  IndexStmt *idxstmt = (IndexStmt *) istmt;
3366 
3367  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3368  newcmd = makeNode(AlterTableCmd);
3370  newcmd->def = (Node *) idxstmt;
3371  newcmds = lappend(newcmds, newcmd);
3372  }
3373  else if (IsA(istmt, AlterTableStmt))
3374  {
3375  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3376 
3377  newcmds = list_concat(newcmds, alterstmt->cmds);
3378  }
3379  else
3380  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3381  }
3382  cxt.alist = NIL;
3383 
3384  /* Append any CHECK or FK constraints to the commands list */
3385  foreach(l, cxt.ckconstraints)
3386  {
3387  newcmd = makeNode(AlterTableCmd);
3388  newcmd->subtype = AT_AddConstraint;
3389  newcmd->def = (Node *) lfirst(l);
3390  newcmds = lappend(newcmds, newcmd);
3391  }
3392  foreach(l, cxt.fkconstraints)
3393  {
3394  newcmd = makeNode(AlterTableCmd);
3395  newcmd->subtype = AT_AddConstraint;
3396  newcmd->def = (Node *) lfirst(l);
3397  newcmds = lappend(newcmds, newcmd);
3398  }
3399 
3400  /* Append extended statistic objects */
3402 
3403  /* Close rel */
3404  relation_close(rel, NoLock);
3405 
3406  /*
3407  * Output results.
3408  */
3409  stmt->cmds = newcmds;
3410 
3411  *beforeStmts = cxt.blist;
3412  *afterStmts = list_concat(cxt.alist, save_alist);
3413 
3414  return stmt;
3415 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
char generated_when
Definition: parsenodes.h:2164
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:482
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char identity
Definition: parsenodes.h:656
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:662
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1815
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:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1863
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:872
#define OidIsValid(objectId)
Definition: c.h:644
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
List * options
Definition: parsenodes.h:2556
List * options
Definition: parsenodes.h:2176
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:655
Oid indexOid
Definition: parsenodes.h:2786
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:3155
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:807
#define RelationGetRelationName(relation)
Definition: rel.h:490
const char * p_sourcetext
Definition: parse_node.h:179
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:862
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:654
List * lappend(List *list, void *datum)
Definition: list.c:321
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
RangeVar * sequence
Definition: parsenodes.h:2555
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:577
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:861
TypeName * typeName
Definition: parsenodes.h:648
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:534
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:824
RangeVar * relation
Definition: parsenodes.h:1777
#define elog(elevel,...)
Definition: elog.h:214
bool for_identity
Definition: parsenodes.h:2557
char * defname
Definition: parsenodes.h:732
char * colname
Definition: parsenodes.h:647
#define copyObject(obj)
Definition: nodes.h:645
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:1791
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 3596 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().

3597 {
3599  List *result;
3600  ListCell *elements;
3601 
3602  cxt.stmtType = "CREATE SCHEMA";
3603  cxt.schemaname = stmt->schemaname;
3604  cxt.authrole = (RoleSpec *) stmt->authrole;
3605  cxt.sequences = NIL;
3606  cxt.tables = NIL;
3607  cxt.views = NIL;
3608  cxt.indexes = NIL;
3609  cxt.triggers = NIL;
3610  cxt.grants = NIL;
3611 
3612  /*
3613  * Run through each schema element in the schema element list. Separate
3614  * statements by type, and do preliminary analysis.
3615  */
3616  foreach(elements, stmt->schemaElts)
3617  {
3618  Node *element = lfirst(elements);
3619 
3620  switch (nodeTag(element))
3621  {
3622  case T_CreateSeqStmt:
3623  {
3624  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3625 
3627  cxt.sequences = lappend(cxt.sequences, element);
3628  }
3629  break;
3630 
3631  case T_CreateStmt:
3632  {
3633  CreateStmt *elp = (CreateStmt *) element;
3634 
3636 
3637  /*
3638  * XXX todo: deal with constraints
3639  */
3640  cxt.tables = lappend(cxt.tables, element);
3641  }
3642  break;
3643 
3644  case T_ViewStmt:
3645  {
3646  ViewStmt *elp = (ViewStmt *) element;
3647 
3648  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3649 
3650  /*
3651  * XXX todo: deal with references between views
3652  */
3653  cxt.views = lappend(cxt.views, element);
3654  }
3655  break;
3656 
3657  case T_IndexStmt:
3658  {
3659  IndexStmt *elp = (IndexStmt *) element;
3660 
3662  cxt.indexes = lappend(cxt.indexes, element);
3663  }
3664  break;
3665 
3666  case T_CreateTrigStmt:
3667  {
3668  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3669 
3671  cxt.triggers = lappend(cxt.triggers, element);
3672  }
3673  break;
3674 
3675  case T_GrantStmt:
3676  cxt.grants = lappend(cxt.grants, element);
3677  break;
3678 
3679  default:
3680  elog(ERROR, "unrecognized node type: %d",
3681  (int) nodeTag(element));
3682  }
3683  }
3684 
3685  result = NIL;
3686  result = list_concat(result, cxt.sequences);
3687  result = list_concat(result, cxt.tables);
3688  result = list_concat(result, cxt.views);
3689  result = list_concat(result, cxt.indexes);
3690  result = list_concat(result, cxt.triggers);
3691  result = list_concat(result, cxt.grants);
3692 
3693  return result;
3694 }
RangeVar * relation
Definition: parsenodes.h:2072
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
RangeVar * view
Definition: parsenodes.h:3128
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2776
RoleSpec * authrole
Definition: parsenodes.h:1759
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:321
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2545
#define lfirst(lc)
Definition: pg_list.h:190
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:534
#define elog(elevel,...)
Definition: elog.h:214
RangeVar * relation
Definition: parsenodes.h:2431
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:2072
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2074
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Definition: nodes.h:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
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:2079
bool if_not_exists
Definition: parsenodes.h:2084
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2076
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:3155
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:179
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:321
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:534
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2073
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:534
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:824
#define elog(elevel,...)
Definition: elog.h:214
#define copyObject(obj)
Definition: nodes.h:645
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2077
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2078
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

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

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

2644 {
2645  ParseState *pstate;
2646  ParseNamespaceItem *nsitem;
2647  ListCell *l;
2648  Relation rel;
2649 
2650  /* Nothing to do if statement already transformed. */
2651  if (stmt->transformed)
2652  return stmt;
2653 
2654  /*
2655  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2656  * overkill, but easy.)
2657  */
2658  stmt = copyObject(stmt);
2659 
2660  /* Set up pstate */
2661  pstate = make_parsestate(NULL);
2662  pstate->p_sourcetext = queryString;
2663 
2664  /*
2665  * Put the parent table into the rtable so that the expressions can refer
2666  * to its fields without qualification. Caller is responsible for locking
2667  * relation, but we still need to open it.
2668  */
2669  rel = relation_open(relid, NoLock);
2670  nsitem = addRangeTableEntryForRelation(pstate, rel,
2672  NULL, false, true);
2673 
2674  /* no to join list, yes to namespaces */
2675  addNSItemToQuery(pstate, nsitem, false, true, true);
2676 
2677  /* take care of the where clause */
2678  if (stmt->whereClause)
2679  {
2680  stmt->whereClause = transformWhereClause(pstate,
2681  stmt->whereClause,
2683  "WHERE");
2684  /* we have to fix its collations too */
2685  assign_expr_collations(pstate, stmt->whereClause);
2686  }
2687 
2688  /* take care of any index expressions */
2689  foreach(l, stmt->indexParams)
2690  {
2691  IndexElem *ielem = (IndexElem *) lfirst(l);
2692 
2693  if (ielem->expr)
2694  {
2695  /* Extract preliminary index col name before transforming expr */
2696  if (ielem->indexcolname == NULL)
2697  ielem->indexcolname = FigureIndexColname(ielem->expr);
2698 
2699  /* Now do parse transformation of the expression */
2700  ielem->expr = transformExpr(pstate, ielem->expr,
2702 
2703  /* We have to fix its collations too */
2704  assign_expr_collations(pstate, ielem->expr);
2705 
2706  /*
2707  * transformExpr() should have already rejected subqueries,
2708  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2709  * for an index expression.
2710  *
2711  * DefineIndex() will make more checks.
2712  */
2713  }
2714  }
2715 
2716  /*
2717  * Check that only the base rel is mentioned. (This should be dead code
2718  * now that add_missing_from is history.)
2719  */
2720  if (list_length(pstate->p_rtable) != 1)
2721  ereport(ERROR,
2722  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2723  errmsg("index expressions and predicates can refer only to the table being indexed")));
2724 
2725  free_parsestate(pstate);
2726 
2727  /* Close relation */
2728  table_close(rel, NoLock);
2729 
2730  /* Mark statement as successfully transformed */
2731  stmt->transformed = true;
2732 
2733  return stmt;
2734 }
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:2783
#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:610
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:701
#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:2796
char * indexcolname
Definition: parsenodes.h:702
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2779
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define copyObject(obj)
Definition: nodes.h:645
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 3774 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().

3776 {
3777  PartitionBoundSpec *result_spec;
3779  char strategy = get_partition_strategy(key);
3780  int partnatts = get_partition_natts(key);
3781  List *partexprs = get_partition_exprs(key);
3782 
3783  /* Avoid scribbling on input */
3784  result_spec = copyObject(spec);
3785 
3786  if (spec->is_default)
3787  {
3788  /*
3789  * Hash partitioning does not support a default partition; there's no
3790  * use case for it (since the set of partitions to create is perfectly
3791  * defined), and if users do get into it accidentally, it's hard to
3792  * back out from it afterwards.
3793  */
3794  if (strategy == PARTITION_STRATEGY_HASH)
3795  ereport(ERROR,
3796  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3797  errmsg("a hash-partitioned table may not have a default partition")));
3798 
3799  /*
3800  * In case of the default partition, parser had no way to identify the
3801  * partition strategy. Assign the parent's strategy to the default
3802  * partition bound spec.
3803  */
3804  result_spec->strategy = strategy;
3805 
3806  return result_spec;
3807  }
3808 
3809  if (strategy == PARTITION_STRATEGY_HASH)
3810  {
3811  if (spec->strategy != PARTITION_STRATEGY_HASH)
3812  ereport(ERROR,
3813  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3814  errmsg("invalid bound specification for a hash partition"),
3815  parser_errposition(pstate, exprLocation((Node *) spec))));
3816 
3817  if (spec->modulus <= 0)
3818  ereport(ERROR,
3819  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3820  errmsg("modulus for hash partition must be a positive integer")));
3821 
3822  Assert(spec->remainder >= 0);
3823 
3824  if (spec->remainder >= spec->modulus)
3825  ereport(ERROR,
3826  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3827  errmsg("remainder for hash partition must be less than modulus")));
3828  }
3829  else if (strategy == PARTITION_STRATEGY_LIST)
3830  {
3831  ListCell *cell;
3832  char *colname;
3833  Oid coltype;
3834  int32 coltypmod;
3835  Oid partcollation;
3836 
3837  if (spec->strategy != PARTITION_STRATEGY_LIST)
3838  ereport(ERROR,
3839  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3840  errmsg("invalid bound specification for a list partition"),
3841  parser_errposition(pstate, exprLocation((Node *) spec))));
3842 
3843  /* Get the only column's name in case we need to output an error */
3844  if (key->partattrs[0] != 0)
3845  colname = get_attname(RelationGetRelid(parent),
3846  key->partattrs[0], false);
3847  else
3848  colname = deparse_expression((Node *) linitial(partexprs),
3850  RelationGetRelid(parent)),
3851  false, false);
3852  /* Need its type data too */
3853  coltype = get_partition_col_typid(key, 0);
3854  coltypmod = get_partition_col_typmod(key, 0);
3855  partcollation = get_partition_col_collation(key, 0);
3856 
3857  result_spec->listdatums = NIL;
3858  foreach(cell, spec->listdatums)
3859  {
3860  Node *expr = lfirst(cell);
3861  Const *value;
3862  ListCell *cell2;
3863  bool duplicate;
3864 
3865  value = transformPartitionBoundValue(pstate, expr,
3866  colname, coltype, coltypmod,
3867  partcollation);
3868 
3869  /* Don't add to the result if the value is a duplicate */
3870  duplicate = false;
3871  foreach(cell2, result_spec->listdatums)
3872  {
3873  Const *value2 = castNode(Const, lfirst(cell2));
3874 
3875  if (equal(value, value2))
3876  {
3877  duplicate = true;
3878  break;
3879  }
3880  }
3881  if (duplicate)
3882  continue;
3883 
3884  result_spec->listdatums = lappend(result_spec->listdatums,
3885  value);
3886  }
3887  }
3888  else if (strategy == PARTITION_STRATEGY_RANGE)
3889  {
3890  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3891  ereport(ERROR,
3892  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3893  errmsg("invalid bound specification for a range partition"),
3894  parser_errposition(pstate, exprLocation((Node *) spec))));
3895 
3896  if (list_length(spec->lowerdatums) != partnatts)
3897  ereport(ERROR,
3898  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3899  errmsg("FROM must specify exactly one value per partitioning column")));
3900  if (list_length(spec->upperdatums) != partnatts)
3901  ereport(ERROR,
3902  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3903  errmsg("TO must specify exactly one value per partitioning column")));
3904 
3905  /*
3906  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3907  * any necessary validation.
3908  */
3909  result_spec->lowerdatums =
3911  parent);
3912  result_spec->upperdatums =
3914  parent);
3915  }
3916  else
3917  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3918 
3919  return result_spec;
3920 }
#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:3033
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
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
Definition: nodes.h:529
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:610
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:3283
#define RelationGetRelationName(relation)
Definition: rel.h:490
List * lappend(List *list, void *datum)
Definition: list.c:321
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:800
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#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:3223
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:801
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:802
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:776
#define copyObject(obj)
Definition: nodes.h:645
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ transformRuleStmt()

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

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

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