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)
 
CreateStatsStmttransformStatsStmt (Oid relid, CreateStatsStmt *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)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const struct AttrMap *attmap, Oid *constraintOid)
 

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1187 of file parse_utilcmd.c.

1188 {
1189  List *result = NIL;
1190  List *atsubcmds = NIL;
1191  AttrNumber parent_attno;
1192  Relation relation;
1193  Relation childrel;
1194  TupleDesc tupleDesc;
1195  TupleConstr *constr;
1196  AttrMap *attmap;
1197  char *comment;
1198 
1199  /*
1200  * Open the relation referenced by the LIKE clause. We should still have
1201  * the table lock obtained by transformTableLikeClause (and this'll throw
1202  * an assertion failure if not). Hence, no need to recheck privileges
1203  * etc. We must open the rel by OID not name, to be sure we get the same
1204  * table.
1205  */
1206  if (!OidIsValid(table_like_clause->relationOid))
1207  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1208 
1209  relation = relation_open(table_like_clause->relationOid, NoLock);
1210 
1211  tupleDesc = RelationGetDescr(relation);
1212  constr = tupleDesc->constr;
1213 
1214  /*
1215  * Open the newly-created child relation; we have lock on that too.
1216  */
1217  childrel = relation_openrv(heapRel, NoLock);
1218 
1219  /*
1220  * Construct a map from the LIKE relation's attnos to the child rel's.
1221  * This re-checks type match etc, although it shouldn't be possible to
1222  * have a failure since both tables are locked.
1223  */
1224  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1225  tupleDesc);
1226 
1227  /*
1228  * Process defaults, if required.
1229  */
1230  if ((table_like_clause->options &
1232  constr != NULL)
1233  {
1234  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1235  parent_attno++)
1236  {
1237  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1238  parent_attno - 1);
1239 
1240  /*
1241  * Ignore dropped columns in the parent.
1242  */
1243  if (attribute->attisdropped)
1244  continue;
1245 
1246  /*
1247  * Copy default, if present and it should be copied. We have
1248  * separate options for plain default expressions and GENERATED
1249  * defaults.
1250  */
1251  if (attribute->atthasdef &&
1252  (attribute->attgenerated ?
1253  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1254  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1255  {
1256  Node *this_default = NULL;
1257  AttrDefault *attrdef = constr->defval;
1258  AlterTableCmd *atsubcmd;
1259  bool found_whole_row;
1260 
1261  /* Find default in constraint structure */
1262  for (int i = 0; i < constr->num_defval; i++)
1263  {
1264  if (attrdef[i].adnum == parent_attno)
1265  {
1266  this_default = stringToNode(attrdef[i].adbin);
1267  break;
1268  }
1269  }
1270  if (this_default == NULL)
1271  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1272  parent_attno, RelationGetRelationName(relation));
1273 
1274  atsubcmd = makeNode(AlterTableCmd);
1275  atsubcmd->subtype = AT_CookedColumnDefault;
1276  atsubcmd->num = attmap->attnums[parent_attno - 1];
1277  atsubcmd->def = map_variable_attnos(this_default,
1278  1, 0,
1279  attmap,
1280  InvalidOid,
1281  &found_whole_row);
1282 
1283  /*
1284  * Prevent this for the same reason as for constraints below.
1285  * Note that defaults cannot contain any vars, so it's OK that
1286  * the error message refers to generated columns.
1287  */
1288  if (found_whole_row)
1289  ereport(ERROR,
1290  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1291  errmsg("cannot convert whole-row table reference"),
1292  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1293  NameStr(attribute->attname),
1294  RelationGetRelationName(relation))));
1295 
1296  atsubcmds = lappend(atsubcmds, atsubcmd);
1297  }
1298  }
1299  }
1300 
1301  /*
1302  * Copy CHECK constraints if requested, being careful to adjust attribute
1303  * numbers so they match the child.
1304  */
1305  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1306  constr != NULL)
1307  {
1308  int ccnum;
1309 
1310  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1311  {
1312  char *ccname = constr->check[ccnum].ccname;
1313  char *ccbin = constr->check[ccnum].ccbin;
1314  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1315  Node *ccbin_node;
1316  bool found_whole_row;
1317  Constraint *n;
1318  AlterTableCmd *atsubcmd;
1319 
1320  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1321  1, 0,
1322  attmap,
1323  InvalidOid, &found_whole_row);
1324 
1325  /*
1326  * We reject whole-row variables because the whole point of LIKE
1327  * is that the new table's rowtype might later diverge from the
1328  * parent's. So, while translation might be possible right now,
1329  * it wouldn't be possible to guarantee it would work in future.
1330  */
1331  if (found_whole_row)
1332  ereport(ERROR,
1333  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1334  errmsg("cannot convert whole-row table reference"),
1335  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1336  ccname,
1337  RelationGetRelationName(relation))));
1338 
1339  n = makeNode(Constraint);
1340  n->contype = CONSTR_CHECK;
1341  n->conname = pstrdup(ccname);
1342  n->location = -1;
1343  n->is_no_inherit = ccnoinherit;
1344  n->raw_expr = NULL;
1345  n->cooked_expr = nodeToString(ccbin_node);
1346 
1347  /* We can skip validation, since the new table should be empty. */
1348  n->skip_validation = true;
1349  n->initially_valid = true;
1350 
1351  atsubcmd = makeNode(AlterTableCmd);
1352  atsubcmd->subtype = AT_AddConstraint;
1353  atsubcmd->def = (Node *) n;
1354  atsubcmds = lappend(atsubcmds, atsubcmd);
1355 
1356  /* Copy comment on constraint */
1357  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1359  n->conname, false),
1360  ConstraintRelationId,
1361  0)) != NULL)
1362  {
1363  CommentStmt *stmt = makeNode(CommentStmt);
1364 
1365  stmt->objtype = OBJECT_TABCONSTRAINT;
1366  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1367  makeString(heapRel->relname),
1368  makeString(n->conname));
1369  stmt->comment = comment;
1370 
1371  result = lappend(result, stmt);
1372  }
1373  }
1374  }
1375 
1376  /*
1377  * If we generated any ALTER TABLE actions above, wrap them into a single
1378  * ALTER TABLE command. Stick it at the front of the result, so it runs
1379  * before any CommentStmts we made above.
1380  */
1381  if (atsubcmds)
1382  {
1384 
1385  atcmd->relation = copyObject(heapRel);
1386  atcmd->cmds = atsubcmds;
1387  atcmd->objtype = OBJECT_TABLE;
1388  atcmd->missing_ok = false;
1389  result = lcons(atcmd, result);
1390  }
1391 
1392  /*
1393  * Process indexes if required.
1394  */
1395  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1396  relation->rd_rel->relhasindex)
1397  {
1398  List *parent_indexes;
1399  ListCell *l;
1400 
1401  parent_indexes = RelationGetIndexList(relation);
1402 
1403  foreach(l, parent_indexes)
1404  {
1405  Oid parent_index_oid = lfirst_oid(l);
1406  Relation parent_index;
1407  IndexStmt *index_stmt;
1408 
1409  parent_index = index_open(parent_index_oid, AccessShareLock);
1410 
1411  /* Build CREATE INDEX statement to recreate the parent_index */
1412  index_stmt = generateClonedIndexStmt(heapRel,
1413  parent_index,
1414  attmap,
1415  NULL);
1416 
1417  /* Copy comment on index, if requested */
1418  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1419  {
1420  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1421 
1422  /*
1423  * We make use of IndexStmt's idxcomment option, so as not to
1424  * need to know now what name the index will have.
1425  */
1426  index_stmt->idxcomment = comment;
1427  }
1428 
1429  result = lappend(result, index_stmt);
1430 
1431  index_close(parent_index, AccessShareLock);
1432  }
1433  }
1434 
1435  /* Done with child rel */
1436  table_close(childrel, NoLock);
1437 
1438  /*
1439  * Close the parent rel, but keep our AccessShareLock on it until xact
1440  * commit. That will prevent someone else from deleting or ALTERing the
1441  * parent before the child is committed.
1442  */
1443  table_close(relation, NoLock);
1444 
1445  return result;
1446 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:681
#define OidIsValid(objectId)
Definition: c.h:710
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lcons(void *datum, List *list)
Definition: list.c:474
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1305
#define copyObject(obj)
Definition: nodes.h:689
#define makeNode(_type_)
Definition: nodes.h:621
char * nodeToString(const void *obj)
Definition: outfuncs.c:4785
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2584
@ OBJECT_TABLE
Definition: parsenodes.h:2175
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2174
@ AT_AddConstraint
Definition: parsenodes.h:2244
@ AT_CookedColumnDefault
Definition: parsenodes.h:2230
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:711
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:715
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:717
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:714
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:713
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define NIL
Definition: pg_list.h:65
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:89
#define RelationGetRelid(relation)
Definition: rel.h:488
#define RelationGetDescr(relation)
Definition: rel.h:514
#define RelationGetRelationName(relation)
Definition: rel.h:522
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4675
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
AlterTableType subtype
Definition: parsenodes.h:2309
RangeVar * relation
Definition: parsenodes.h:2218
ObjectType objtype
Definition: parsenodes.h:2220
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * comment
Definition: parsenodes.h:3143
ObjectType objtype
Definition: parsenodes.h:3141
Node * object
Definition: parsenodes.h:3142
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ConstrType contype
Definition: parsenodes.h:2610
bool is_no_inherit
Definition: parsenodes.h:2619
char * cooked_expr
Definition: parsenodes.h:2621
bool initially_valid
Definition: parsenodes.h:2658
bool skip_validation
Definition: parsenodes.h:2657
Node * raw_expr
Definition: parsenodes.h:2620
char * conname
Definition: parsenodes.h:2613
char * idxcomment
Definition: parsenodes.h:3247
Definition: pg_list.h:51
Definition: nodes.h:574
char * relname
Definition: primnodes.h:68
char * schemaname
Definition: primnodes.h:67
Form_pg_class rd_rel
Definition: rel.h:109
AttrDefault * defval
Definition: tupdesc.h:39
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_defval
Definition: tupdesc.h:42
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, CommentStmt::comment, Constraint::conname, TupleDescData::constr, CONSTR_CHECK, Constraint::contype, Constraint::cooked_expr, copyObject, CREATE_TABLE_LIKE_COMMENTS, CREATE_TABLE_LIKE_CONSTRAINTS, CREATE_TABLE_LIKE_DEFAULTS, CREATE_TABLE_LIKE_GENERATED, CREATE_TABLE_LIKE_INDEXES, AlterTableCmd::def, TupleConstr::defval, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), i, IndexStmt::idxcomment, index_close(), index_open(), Constraint::initially_valid, InvalidOid, Constraint::is_no_inherit, lappend(), lcons(), lfirst_oid, list_make3, Constraint::location, makeNode, makeString(), map_variable_attnos(), AlterTableStmt::missing_ok, NameStr, TupleDescData::natts, NIL, nodeToString(), NoLock, AlterTableCmd::num, TupleConstr::num_check, TupleConstr::num_defval, CommentStmt::object, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, CommentStmt::objtype, OidIsValid, TableLikeClause::options, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, AlterTableStmt::relation, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stringToNode(), AlterTableCmd::subtype, table_close(), and TupleDescAttr.

Referenced by ProcessUtilitySlow().

◆ 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 3289 of file parse_utilcmd.c.

3292 {
3293  Relation rel;
3294  TupleDesc tupdesc;
3295  ParseState *pstate;
3296  CreateStmtContext cxt;
3297  List *save_alist;
3298  ListCell *lcmd,
3299  *l;
3300  List *newcmds = NIL;
3301  bool skipValidation = true;
3302  AlterTableCmd *newcmd;
3303  ParseNamespaceItem *nsitem;
3304 
3305  /* Caller is responsible for locking the relation */
3306  rel = relation_open(relid, NoLock);
3307  tupdesc = RelationGetDescr(rel);
3308 
3309  /* Set up pstate */
3310  pstate = make_parsestate(NULL);
3311  pstate->p_sourcetext = queryString;
3312  nsitem = addRangeTableEntryForRelation(pstate,
3313  rel,
3315  NULL,
3316  false,
3317  true);
3318  addNSItemToQuery(pstate, nsitem, false, true, true);
3319 
3320  /* Set up CreateStmtContext */
3321  cxt.pstate = pstate;
3322  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3323  {
3324  cxt.stmtType = "ALTER FOREIGN TABLE";
3325  cxt.isforeign = true;
3326  }
3327  else
3328  {
3329  cxt.stmtType = "ALTER TABLE";
3330  cxt.isforeign = false;
3331  }
3332  cxt.relation = stmt->relation;
3333  cxt.rel = rel;
3334  cxt.inhRelations = NIL;
3335  cxt.isalter = true;
3336  cxt.columns = NIL;
3337  cxt.ckconstraints = NIL;
3338  cxt.fkconstraints = NIL;
3339  cxt.ixconstraints = NIL;
3340  cxt.likeclauses = NIL;
3341  cxt.extstats = NIL;
3342  cxt.blist = NIL;
3343  cxt.alist = NIL;
3344  cxt.pkey = NULL;
3345  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3346  cxt.partbound = NULL;
3347  cxt.ofType = false;
3348 
3349  /*
3350  * Transform ALTER subcommands that need it (most don't). These largely
3351  * re-use code from CREATE TABLE.
3352  */
3353  foreach(lcmd, stmt->cmds)
3354  {
3355  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3356 
3357  switch (cmd->subtype)
3358  {
3359  case AT_AddColumn:
3360  case AT_AddColumnRecurse:
3361  {
3362  ColumnDef *def = castNode(ColumnDef, cmd->def);
3363 
3364  transformColumnDefinition(&cxt, def);
3365 
3366  /*
3367  * If the column has a non-null default, we can't skip
3368  * validation of foreign keys.
3369  */
3370  if (def->raw_default != NULL)
3371  skipValidation = false;
3372 
3373  /*
3374  * All constraints are processed in other ways. Remove the
3375  * original list
3376  */
3377  def->constraints = NIL;
3378 
3379  newcmds = lappend(newcmds, cmd);
3380  break;
3381  }
3382 
3383  case AT_AddConstraint:
3385 
3386  /*
3387  * The original AddConstraint cmd node doesn't go to newcmds
3388  */
3389  if (IsA(cmd->def, Constraint))
3390  {
3391  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3392  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3393  skipValidation = false;
3394  }
3395  else
3396  elog(ERROR, "unrecognized node type: %d",
3397  (int) nodeTag(cmd->def));
3398  break;
3399 
3400  case AT_AlterColumnType:
3401  {
3402  ColumnDef *def = castNode(ColumnDef, cmd->def);
3404 
3405  /*
3406  * For ALTER COLUMN TYPE, transform the USING clause if
3407  * one was specified.
3408  */
3409  if (def->raw_default)
3410  {
3411  def->cooked_default =
3412  transformExpr(pstate, def->raw_default,
3414  }
3415 
3416  /*
3417  * For identity column, create ALTER SEQUENCE command to
3418  * change the data type of the sequence.
3419  */
3420  attnum = get_attnum(relid, cmd->name);
3421  if (attnum == InvalidAttrNumber)
3422  ereport(ERROR,
3423  (errcode(ERRCODE_UNDEFINED_COLUMN),
3424  errmsg("column \"%s\" of relation \"%s\" does not exist",
3425  cmd->name, RelationGetRelationName(rel))));
3426 
3427  if (attnum > 0 &&
3428  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3429  {
3430  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3431  Oid typeOid = typenameTypeId(pstate, def->typeName);
3432  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3433 
3434  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3435  get_rel_name(seq_relid),
3436  -1);
3437  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3438  altseqstmt->for_identity = true;
3439  cxt.blist = lappend(cxt.blist, altseqstmt);
3440  }
3441 
3442  newcmds = lappend(newcmds, cmd);
3443  break;
3444  }
3445 
3446  case AT_AddIdentity:
3447  {
3448  Constraint *def = castNode(Constraint, cmd->def);
3449  ColumnDef *newdef = makeNode(ColumnDef);
3451 
3452  newdef->colname = cmd->name;
3453  newdef->identity = def->generated_when;
3454  cmd->def = (Node *) newdef;
3455 
3456  attnum = get_attnum(relid, cmd->name);
3457  if (attnum == InvalidAttrNumber)
3458  ereport(ERROR,
3459  (errcode(ERRCODE_UNDEFINED_COLUMN),
3460  errmsg("column \"%s\" of relation \"%s\" does not exist",
3461  cmd->name, RelationGetRelationName(rel))));
3462 
3463  generateSerialExtraStmts(&cxt, newdef,
3464  get_atttype(relid, attnum),
3465  def->options, true, true,
3466  NULL, NULL);
3467 
3468  newcmds = lappend(newcmds, cmd);
3469  break;
3470  }
3471 
3472  case AT_SetIdentity:
3473  {
3474  /*
3475  * Create an ALTER SEQUENCE statement for the internal
3476  * sequence of the identity column.
3477  */
3478  ListCell *lc;
3479  List *newseqopts = NIL;
3480  List *newdef = NIL;
3482  Oid seq_relid;
3483 
3484  /*
3485  * Split options into those handled by ALTER SEQUENCE and
3486  * those for ALTER TABLE proper.
3487  */
3488  foreach(lc, castNode(List, cmd->def))
3489  {
3490  DefElem *def = lfirst_node(DefElem, lc);
3491 
3492  if (strcmp(def->defname, "generated") == 0)
3493  newdef = lappend(newdef, def);
3494  else
3495  newseqopts = lappend(newseqopts, def);
3496  }
3497 
3498  attnum = get_attnum(relid, cmd->name);
3499  if (attnum == InvalidAttrNumber)
3500  ereport(ERROR,
3501  (errcode(ERRCODE_UNDEFINED_COLUMN),
3502  errmsg("column \"%s\" of relation \"%s\" does not exist",
3503  cmd->name, RelationGetRelationName(rel))));
3504 
3505  seq_relid = getIdentitySequence(relid, attnum, true);
3506 
3507  if (seq_relid)
3508  {
3509  AlterSeqStmt *seqstmt;
3510 
3511  seqstmt = makeNode(AlterSeqStmt);
3513  get_rel_name(seq_relid), -1);
3514  seqstmt->options = newseqopts;
3515  seqstmt->for_identity = true;
3516  seqstmt->missing_ok = false;
3517 
3518  cxt.blist = lappend(cxt.blist, seqstmt);
3519  }
3520 
3521  /*
3522  * If column was not an identity column, we just let the
3523  * ALTER TABLE command error out later. (There are cases
3524  * this fails to cover, but we'll need to restructure
3525  * where creation of the sequence dependency linkage
3526  * happens before we can fix it.)
3527  */
3528 
3529  cmd->def = (Node *) newdef;
3530  newcmds = lappend(newcmds, cmd);
3531  break;
3532  }
3533 
3534  case AT_AttachPartition:
3535  case AT_DetachPartition:
3536  {
3537  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3538 
3539  transformPartitionCmd(&cxt, partcmd);
3540  /* assign transformed value of the partition bound */
3541  partcmd->bound = cxt.partbound;
3542  }
3543 
3544  newcmds = lappend(newcmds, cmd);
3545  break;
3546 
3547  default:
3548 
3549  /*
3550  * Currently, we shouldn't actually get here for subcommand
3551  * types that don't require transformation; but if we do, just
3552  * emit them unchanged.
3553  */
3554  newcmds = lappend(newcmds, cmd);
3555  break;
3556  }
3557  }
3558 
3559  /*
3560  * Transfer anything we already have in cxt.alist into save_alist, to keep
3561  * it separate from the output of transformIndexConstraints.
3562  */
3563  save_alist = cxt.alist;
3564  cxt.alist = NIL;
3565 
3566  /* Postprocess constraints */
3568  transformFKConstraints(&cxt, skipValidation, true);
3569  transformCheckConstraints(&cxt, false);
3570 
3571  /*
3572  * Push any index-creation commands into the ALTER, so that they can be
3573  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3574  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3575  * subcommand has already been through transformIndexStmt.
3576  */
3577  foreach(l, cxt.alist)
3578  {
3579  Node *istmt = (Node *) lfirst(l);
3580 
3581  /*
3582  * We assume here that cxt.alist contains only IndexStmts and possibly
3583  * ALTER TABLE SET NOT NULL statements generated from primary key
3584  * constraints. We absorb the subcommands of the latter directly.
3585  */
3586  if (IsA(istmt, IndexStmt))
3587  {
3588  IndexStmt *idxstmt = (IndexStmt *) istmt;
3589 
3590  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3591  newcmd = makeNode(AlterTableCmd);
3593  newcmd->def = (Node *) idxstmt;
3594  newcmds = lappend(newcmds, newcmd);
3595  }
3596  else if (IsA(istmt, AlterTableStmt))
3597  {
3598  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3599 
3600  newcmds = list_concat(newcmds, alterstmt->cmds);
3601  }
3602  else
3603  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3604  }
3605  cxt.alist = NIL;
3606 
3607  /* Append any CHECK or FK constraints to the commands list */
3608  foreach(l, cxt.ckconstraints)
3609  {
3610  newcmd = makeNode(AlterTableCmd);
3611  newcmd->subtype = AT_AddConstraint;
3612  newcmd->def = (Node *) lfirst(l);
3613  newcmds = lappend(newcmds, newcmd);
3614  }
3615  foreach(l, cxt.fkconstraints)
3616  {
3617  newcmd = makeNode(AlterTableCmd);
3618  newcmd->subtype = AT_AddConstraint;
3619  newcmd->def = (Node *) lfirst(l);
3620  newcmds = lappend(newcmds, newcmd);
3621  }
3622 
3623  /* Append extended statistics objects */
3625 
3626  /* Close rel */
3627  relation_close(rel, NoLock);
3628 
3629  /*
3630  * Output results.
3631  */
3632  stmt->cmds = newcmds;
3633 
3634  *beforeStmts = cxt.blist;
3635  *afterStmts = list_concat(cxt.alist, save_alist);
3636 
3637  return stmt;
3638 }
#define InvalidAttrNumber
Definition: attnum.h:23
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1933
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:938
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:423
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:547
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:473
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
#define nodeTag(nodeptr)
Definition: nodes.h:578
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:112
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformExtendedStatistics(CreateStmtContext *cxt)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ CONSTR_FOREIGN
Definition: parsenodes.h:2588
@ AT_AddIndexConstraint
Definition: parsenodes.h:2251
@ AT_AddConstraintRecurse
Definition: parsenodes.h:2245
@ AT_SetIdentity
Definition: parsenodes.h:2294
@ AT_AddIndex
Definition: parsenodes.h:2242
@ AT_AddIdentity
Definition: parsenodes.h:2293
@ AT_AlterColumnType
Definition: parsenodes.h:2255
@ AT_AddColumnRecurse
Definition: parsenodes.h:2227
@ AT_DetachPartition
Definition: parsenodes.h:2291
@ AT_AttachPartition
Definition: parsenodes.h:2290
@ AT_AddColumn
Definition: parsenodes.h:2226
int16 attnum
Definition: pg_attribute.h:83
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:887
#define lfirst(lc)
Definition: pg_list.h:169
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define list_make1(x1)
Definition: pg_list.h:206
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
List * options
Definition: parsenodes.h:3017
RangeVar * sequence
Definition: parsenodes.h:3016
bool for_identity
Definition: parsenodes.h:3018
char identity
Definition: parsenodes.h:687
List * constraints
Definition: parsenodes.h:693
Node * cooked_default
Definition: parsenodes.h:686
char * colname
Definition: parsenodes.h:677
TypeName * typeName
Definition: parsenodes.h:678
Node * raw_default
Definition: parsenodes.h:685
List * options
Definition: parsenodes.h:2635
char generated_when
Definition: parsenodes.h:2622
IndexStmt * pkey
Definition: parse_utilcmd.c:92
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parse_utilcmd.c:77
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
char * defname
Definition: parsenodes.h:765
Oid indexOid
Definition: parsenodes.h:3248
const char * p_sourcetext
Definition: parse_node.h:182
PartitionBoundSpec * bound
Definition: parsenodes.h:895

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, 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::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, 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().

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3819 of file parse_utilcmd.c.

3820 {
3822  List *result;
3823  ListCell *elements;
3824 
3825  cxt.stmtType = "CREATE SCHEMA";
3826  cxt.schemaname = stmt->schemaname;
3827  cxt.authrole = (RoleSpec *) stmt->authrole;
3828  cxt.sequences = NIL;
3829  cxt.tables = NIL;
3830  cxt.views = NIL;
3831  cxt.indexes = NIL;
3832  cxt.triggers = NIL;
3833  cxt.grants = NIL;
3834 
3835  /*
3836  * Run through each schema element in the schema element list. Separate
3837  * statements by type, and do preliminary analysis.
3838  */
3839  foreach(elements, stmt->schemaElts)
3840  {
3841  Node *element = lfirst(elements);
3842 
3843  switch (nodeTag(element))
3844  {
3845  case T_CreateSeqStmt:
3846  {
3847  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3848 
3850  cxt.sequences = lappend(cxt.sequences, element);
3851  }
3852  break;
3853 
3854  case T_CreateStmt:
3855  {
3856  CreateStmt *elp = (CreateStmt *) element;
3857 
3859 
3860  /*
3861  * XXX todo: deal with constraints
3862  */
3863  cxt.tables = lappend(cxt.tables, element);
3864  }
3865  break;
3866 
3867  case T_ViewStmt:
3868  {
3869  ViewStmt *elp = (ViewStmt *) element;
3870 
3871  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3872 
3873  /*
3874  * XXX todo: deal with references between views
3875  */
3876  cxt.views = lappend(cxt.views, element);
3877  }
3878  break;
3879 
3880  case T_IndexStmt:
3881  {
3882  IndexStmt *elp = (IndexStmt *) element;
3883 
3885  cxt.indexes = lappend(cxt.indexes, element);
3886  }
3887  break;
3888 
3889  case T_CreateTrigStmt:
3890  {
3892 
3894  cxt.triggers = lappend(cxt.triggers, element);
3895  }
3896  break;
3897 
3898  case T_GrantStmt:
3899  cxt.grants = lappend(cxt.grants, element);
3900  break;
3901 
3902  default:
3903  elog(ERROR, "unrecognized node type: %d",
3904  (int) nodeTag(element));
3905  }
3906  }
3907 
3908  result = NIL;
3909  result = list_concat(result, cxt.sequences);
3910  result = list_concat(result, cxt.tables);
3911  result = list_concat(result, cxt.views);
3912  result = list_concat(result, cxt.indexes);
3913  result = list_concat(result, cxt.triggers);
3914  result = list_concat(result, cxt.grants);
3915 
3916  return result;
3917 }
@ T_CreateStmt
Definition: nodes.h:349
@ T_CreateTrigStmt
Definition: nodes.h:378
@ T_CreateSeqStmt
Definition: nodes.h:373
@ T_IndexStmt
Definition: nodes.h:355
@ T_GrantStmt
Definition: nodes.h:343
@ T_ViewStmt
Definition: nodes.h:365
static void setSchemaName(char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RoleSpec * authrole
Definition: parsenodes.h:2200
RangeVar * sequence
Definition: parsenodes.h:3006
RangeVar * relation
Definition: parsenodes.h:2530
RangeVar * relation
Definition: parsenodes.h:2893
RangeVar * relation
Definition: parsenodes.h:3238
RangeVar * view
Definition: parsenodes.h:3616

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, CreateSchemaStmtContext::schemaname, CreateSchemaStmt::schemaname, RangeVar::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().

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

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 
176  /* Set up pstate */
177  pstate = make_parsestate(NULL);
178  pstate->p_sourcetext = queryString;
179 
180  /*
181  * Look up the creation namespace. This also checks permissions on the
182  * target namespace, locks it against concurrent drops, checks for a
183  * preexisting relation in that namespace with the same name, and updates
184  * stmt->relation->relpersistence if the selected namespace is temporary.
185  */
186  setup_parser_errposition_callback(&pcbstate, pstate,
187  stmt->relation->location);
188  namespaceid =
190  &existing_relid);
192 
193  /*
194  * If the relation already exists and the user specified "IF NOT EXISTS",
195  * bail out with a NOTICE.
196  */
197  if (stmt->if_not_exists && OidIsValid(existing_relid))
198  {
199  ereport(NOTICE,
200  (errcode(ERRCODE_DUPLICATE_TABLE),
201  errmsg("relation \"%s\" already exists, skipping",
202  stmt->relation->relname)));
203  return NIL;
204  }
205 
206  /*
207  * If the target relation name isn't schema-qualified, make it so. This
208  * prevents some corner cases in which added-on rewritten commands might
209  * think they should apply to other relations that have the same name and
210  * are earlier in the search path. But a local temp table is effectively
211  * specified to be in pg_temp, so no need for anything extra in that case.
212  */
213  if (stmt->relation->schemaname == NULL
214  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
215  stmt->relation->schemaname = get_namespace_name(namespaceid);
216 
217  /* Set up CreateStmtContext */
218  cxt.pstate = pstate;
219  if (IsA(stmt, CreateForeignTableStmt))
220  {
221  cxt.stmtType = "CREATE FOREIGN TABLE";
222  cxt.isforeign = true;
223  }
224  else
225  {
226  cxt.stmtType = "CREATE TABLE";
227  cxt.isforeign = false;
228  }
229  cxt.relation = stmt->relation;
230  cxt.rel = NULL;
231  cxt.inhRelations = stmt->inhRelations;
232  cxt.isalter = false;
233  cxt.columns = NIL;
234  cxt.ckconstraints = NIL;
235  cxt.fkconstraints = NIL;
236  cxt.ixconstraints = NIL;
237  cxt.likeclauses = NIL;
238  cxt.extstats = NIL;
239  cxt.blist = NIL;
240  cxt.alist = NIL;
241  cxt.pkey = NULL;
242  cxt.ispartitioned = stmt->partspec != NULL;
243  cxt.partbound = stmt->partbound;
244  cxt.ofType = (stmt->ofTypename != NULL);
245 
246  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
247 
248  if (stmt->ofTypename)
249  transformOfType(&cxt, stmt->ofTypename);
250 
251  if (stmt->partspec)
252  {
253  if (stmt->inhRelations && !stmt->partbound)
254  ereport(ERROR,
255  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
256  errmsg("cannot create partitioned table as inheritance child")));
257  }
258 
259  /*
260  * Run through each primary element in the table creation clause. Separate
261  * column defs from constraints, and do preliminary analysis.
262  */
263  foreach(elements, stmt->tableElts)
264  {
265  Node *element = lfirst(elements);
266 
267  switch (nodeTag(element))
268  {
269  case T_ColumnDef:
271  break;
272 
273  case T_Constraint:
275  break;
276 
277  case T_TableLikeClause:
279  break;
280 
281  default:
282  elog(ERROR, "unrecognized node type: %d",
283  (int) nodeTag(element));
284  break;
285  }
286  }
287 
288  /*
289  * Transfer anything we already have in cxt.alist into save_alist, to keep
290  * it separate from the output of transformIndexConstraints. (This may
291  * not be necessary anymore, but we'll keep doing it to preserve the
292  * historical order of execution of the alist commands.)
293  */
294  save_alist = cxt.alist;
295  cxt.alist = NIL;
296 
297  Assert(stmt->constraints == NIL);
298 
299  /*
300  * Postprocess constraints that give rise to index definitions.
301  */
303 
304  /*
305  * Re-consideration of LIKE clauses should happen after creation of
306  * indexes, but before creation of foreign keys. This order is critical
307  * because a LIKE clause may attempt to create a primary key. If there's
308  * also a pkey in the main CREATE TABLE list, creation of that will not
309  * check for a duplicate at runtime (since index_check_primary_key()
310  * expects that we rejected dups here). Creation of the LIKE-generated
311  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
312  * only works if it happens second. On the other hand, we want to make
313  * pkeys before foreign key constraints, in case the user tries to make a
314  * self-referential FK.
315  */
316  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
317 
318  /*
319  * Postprocess foreign-key constraints.
320  */
321  transformFKConstraints(&cxt, true, false);
322 
323  /*
324  * Postprocess check constraints.
325  *
326  * For regular tables all constraints can be marked valid immediately,
327  * because the table is new therefore empty. Not so for foreign tables.
328  */
330 
331  /*
332  * Postprocess extended statistics.
333  */
335 
336  /*
337  * Output results.
338  */
339  stmt->tableElts = cxt.columns;
340  stmt->constraints = cxt.ckconstraints;
341 
342  result = lappend(cxt.blist, stmt);
343  result = list_concat(result, cxt.alist);
344  result = list_concat(result, save_alist);
345 
346  return result;
347 }
#define NOTICE
Definition: elog.h:29
Assert(fmt[strlen(fmt) - 1] !='\n')
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:536
@ T_Constraint
Definition: nodes.h:477
@ T_ColumnDef
Definition: nodes.h:474
@ T_TableLikeClause
Definition: nodes.h:489
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
List * tableElts
Definition: parsenodes.h:2531
TypeName * ofTypename
Definition: parsenodes.h:2536
bool if_not_exists
Definition: parsenodes.h:2542
List * inhRelations
Definition: parsenodes.h:2532
PartitionSpec * partspec
Definition: parsenodes.h:2535
PartitionBoundSpec * partbound
Definition: parsenodes.h:2534
List * constraints
Definition: parsenodes.h:2537
int location
Definition: primnodes.h:73
char relpersistence
Definition: primnodes.h:71

References CreateStmtContext::alist, Assert(), CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, CreateStmtContext::likeclauses, 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().

◆ transformIndexStmt()

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

Definition at line 2809 of file parse_utilcmd.c.

2810 {
2811  ParseState *pstate;
2812  ParseNamespaceItem *nsitem;
2813  ListCell *l;
2814  Relation rel;
2815 
2816  /* Nothing to do if statement already transformed. */
2817  if (stmt->transformed)
2818  return stmt;
2819 
2820  /* Set up pstate */
2821  pstate = make_parsestate(NULL);
2822  pstate->p_sourcetext = queryString;
2823 
2824  /*
2825  * Put the parent table into the rtable so that the expressions can refer
2826  * to its fields without qualification. Caller is responsible for locking
2827  * relation, but we still need to open it.
2828  */
2829  rel = relation_open(relid, NoLock);
2830  nsitem = addRangeTableEntryForRelation(pstate, rel,
2832  NULL, false, true);
2833 
2834  /* no to join list, yes to namespaces */
2835  addNSItemToQuery(pstate, nsitem, false, true, true);
2836 
2837  /* take care of the where clause */
2838  if (stmt->whereClause)
2839  {
2840  stmt->whereClause = transformWhereClause(pstate,
2841  stmt->whereClause,
2843  "WHERE");
2844  /* we have to fix its collations too */
2845  assign_expr_collations(pstate, stmt->whereClause);
2846  }
2847 
2848  /* take care of any index expressions */
2849  foreach(l, stmt->indexParams)
2850  {
2851  IndexElem *ielem = (IndexElem *) lfirst(l);
2852 
2853  if (ielem->expr)
2854  {
2855  /* Extract preliminary index col name before transforming expr */
2856  if (ielem->indexcolname == NULL)
2857  ielem->indexcolname = FigureIndexColname(ielem->expr);
2858 
2859  /* Now do parse transformation of the expression */
2860  ielem->expr = transformExpr(pstate, ielem->expr,
2862 
2863  /* We have to fix its collations too */
2864  assign_expr_collations(pstate, ielem->expr);
2865 
2866  /*
2867  * transformExpr() should have already rejected subqueries,
2868  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2869  * for an index expression.
2870  *
2871  * DefineIndex() will make more checks.
2872  */
2873  }
2874  }
2875 
2876  /*
2877  * Check that only the base rel is mentioned. (This should be dead code
2878  * now that add_missing_from is history.)
2879  */
2880  if (list_length(pstate->p_rtable) != 1)
2881  ereport(ERROR,
2882  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2883  errmsg("index expressions and predicates can refer only to the table being indexed")));
2884 
2885  free_parsestate(pstate);
2886 
2887  /* Close relation */
2888  table_close(rel, NoLock);
2889 
2890  /* Mark statement as successfully transformed */
2891  stmt->transformed = true;
2892 
2893  return stmt;
2894 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
char * FigureIndexColname(Node *node)
static int list_length(const List *l)
Definition: pg_list.h:149
Node * expr
Definition: parsenodes.h:734
char * indexcolname
Definition: parsenodes.h:735
List * indexParams
Definition: parsenodes.h:3241
bool transformed
Definition: parsenodes.h:3259
Node * whereClause
Definition: parsenodes.h:3245
List * p_rtable
Definition: parse_node.h:183

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), 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().

◆ transformPartitionBound()

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

Definition at line 3997 of file parse_utilcmd.c.

3999 {
4000  PartitionBoundSpec *result_spec;
4002  char strategy = get_partition_strategy(key);
4003  int partnatts = get_partition_natts(key);
4004  List *partexprs = get_partition_exprs(key);
4005 
4006  /* Avoid scribbling on input */
4007  result_spec = copyObject(spec);
4008 
4009  if (spec->is_default)
4010  {
4011  /*
4012  * Hash partitioning does not support a default partition; there's no
4013  * use case for it (since the set of partitions to create is perfectly
4014  * defined), and if users do get into it accidentally, it's hard to
4015  * back out from it afterwards.
4016  */
4017  if (strategy == PARTITION_STRATEGY_HASH)
4018  ereport(ERROR,
4019  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4020  errmsg("a hash-partitioned table may not have a default partition")));
4021 
4022  /*
4023  * In case of the default partition, parser had no way to identify the
4024  * partition strategy. Assign the parent's strategy to the default
4025  * partition bound spec.
4026  */
4027  result_spec->strategy = strategy;
4028 
4029  return result_spec;
4030  }
4031 
4032  if (strategy == PARTITION_STRATEGY_HASH)
4033  {
4034  if (spec->strategy != PARTITION_STRATEGY_HASH)
4035  ereport(ERROR,
4036  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4037  errmsg("invalid bound specification for a hash partition"),
4038  parser_errposition(pstate, exprLocation((Node *) spec))));
4039 
4040  if (spec->modulus <= 0)
4041  ereport(ERROR,
4042  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4043  errmsg("modulus for hash partition must be an integer value greater than zero")));
4044 
4045  Assert(spec->remainder >= 0);
4046 
4047  if (spec->remainder >= spec->modulus)
4048  ereport(ERROR,
4049  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4050  errmsg("remainder for hash partition must be less than modulus")));
4051  }
4052  else if (strategy == PARTITION_STRATEGY_LIST)
4053  {
4054  ListCell *cell;
4055  char *colname;
4056  Oid coltype;
4057  int32 coltypmod;
4058  Oid partcollation;
4059 
4060  if (spec->strategy != PARTITION_STRATEGY_LIST)
4061  ereport(ERROR,
4062  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4063  errmsg("invalid bound specification for a list partition"),
4064  parser_errposition(pstate, exprLocation((Node *) spec))));
4065 
4066  /* Get the only column's name in case we need to output an error */
4067  if (key->partattrs[0] != 0)
4068  colname = get_attname(RelationGetRelid(parent),
4069  key->partattrs[0], false);
4070  else
4071  colname = deparse_expression((Node *) linitial(partexprs),
4073  RelationGetRelid(parent)),
4074  false, false);
4075  /* Need its type data too */
4076  coltype = get_partition_col_typid(key, 0);
4077  coltypmod = get_partition_col_typmod(key, 0);
4078  partcollation = get_partition_col_collation(key, 0);
4079 
4080  result_spec->listdatums = NIL;
4081  foreach(cell, spec->listdatums)
4082  {
4083  Node *expr = lfirst(cell);
4084  Const *value;
4085  ListCell *cell2;
4086  bool duplicate;
4087 
4088  value = transformPartitionBoundValue(pstate, expr,
4089  colname, coltype, coltypmod,
4090  partcollation);
4091 
4092  /* Don't add to the result if the value is a duplicate */
4093  duplicate = false;
4094  foreach(cell2, result_spec->listdatums)
4095  {
4096  Const *value2 = lfirst_node(Const, cell2);
4097 
4098  if (equal(value, value2))
4099  {
4100  duplicate = true;
4101  break;
4102  }
4103  }
4104  if (duplicate)
4105  continue;
4106 
4107  result_spec->listdatums = lappend(result_spec->listdatums,
4108  value);
4109  }
4110  }
4111  else if (strategy == PARTITION_STRATEGY_RANGE)
4112  {
4113  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4114  ereport(ERROR,
4115  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4116  errmsg("invalid bound specification for a range partition"),
4117  parser_errposition(pstate, exprLocation((Node *) spec))));
4118 
4119  if (list_length(spec->lowerdatums) != partnatts)
4120  ereport(ERROR,
4121  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4122  errmsg("FROM must specify exactly one value per partitioning column")));
4123  if (list_length(spec->upperdatums) != partnatts)
4124  ereport(ERROR,
4125  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4126  errmsg("TO must specify exactly one value per partitioning column")));
4127 
4128  /*
4129  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4130  * any necessary validation.
4131  */
4132  result_spec->lowerdatums =
4134  parent);
4135  result_spec->upperdatums =
4137  parent);
4138  }
4139  else
4140  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4141 
4142  return result_spec;
4143 }
signed int int32
Definition: c.h:429
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3564
static struct @151 value
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1343
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
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)
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:835
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:836
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:834
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:174
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3610
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3670

References Assert(), 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, lfirst_node, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), 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().

◆ transformRuleStmt()

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

Definition at line 2979 of file parse_utilcmd.c.

2981 {
2982  Relation rel;
2983  ParseState *pstate;
2984  ParseNamespaceItem *oldnsitem;
2985  ParseNamespaceItem *newnsitem;
2986 
2987  /*
2988  * To avoid deadlock, make sure the first thing we do is grab
2989  * AccessExclusiveLock on the target relation. This will be needed by
2990  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2991  * beforehand.
2992  */
2994 
2995  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2996  ereport(ERROR,
2997  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2998  errmsg("rules on materialized views are not supported")));
2999 
3000  /* Set up pstate */
3001  pstate = make_parsestate(NULL);
3002  pstate->p_sourcetext = queryString;
3003 
3004  /*
3005  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3006  * Set up their ParseNamespaceItems in the main pstate for use in parsing
3007  * the rule qualification.
3008  */
3009  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3011  makeAlias("old", NIL),
3012  false, false);
3013  newnsitem = addRangeTableEntryForRelation(pstate, rel,
3015  makeAlias("new", NIL),
3016  false, false);
3017  /* Must override addRangeTableEntry's default access-check flags */
3018  oldnsitem->p_rte->requiredPerms = 0;
3019  newnsitem->p_rte->requiredPerms = 0;
3020 
3021  /*
3022  * They must be in the namespace too for lookup purposes, but only add the
3023  * one(s) that are relevant for the current kind of rule. In an UPDATE
3024  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3025  * there's no need to be so picky for INSERT & DELETE. We do not add them
3026  * to the joinlist.
3027  */
3028  switch (stmt->event)
3029  {
3030  case CMD_SELECT:
3031  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3032  break;
3033  case CMD_UPDATE:
3034  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3035  addNSItemToQuery(pstate, newnsitem, false, true, true);
3036  break;
3037  case CMD_INSERT:
3038  addNSItemToQuery(pstate, newnsitem, false, true, true);
3039  break;
3040  case CMD_DELETE:
3041  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3042  break;
3043  default:
3044  elog(ERROR, "unrecognized event type: %d",
3045  (int) stmt->event);
3046  break;
3047  }
3048 
3049  /* take care of the where clause */
3050  *whereClause = transformWhereClause(pstate,
3051  stmt->whereClause,
3053  "WHERE");
3054  /* we have to fix its collations too */
3055  assign_expr_collations(pstate, *whereClause);
3056 
3057  /* this is probably dead code without add_missing_from: */
3058  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3059  ereport(ERROR,
3060  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3061  errmsg("rule WHERE condition cannot contain references to other relations")));
3062 
3063  /*
3064  * 'instead nothing' rules with a qualification need a query rangetable so
3065  * the rewrite handler can add the negated rule qualification to the
3066  * original query. We create a query with the new command type CMD_NOTHING
3067  * here that is treated specially by the rewrite system.
3068  */
3069  if (stmt->actions == NIL)
3070  {
3071  Query *nothing_qry = makeNode(Query);
3072 
3073  nothing_qry->commandType = CMD_NOTHING;
3074  nothing_qry->rtable = pstate->p_rtable;
3075  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3076 
3077  *actions = list_make1(nothing_qry);
3078  }
3079  else
3080  {
3081  ListCell *l;
3082  List *newactions = NIL;
3083 
3084  /*
3085  * transform each statement, like parse_sub_analyze()
3086  */
3087  foreach(l, stmt->actions)
3088  {
3089  Node *action = (Node *) lfirst(l);
3090  ParseState *sub_pstate = make_parsestate(NULL);
3091  Query *sub_qry,
3092  *top_subqry;
3093  bool has_old,
3094  has_new;
3095 
3096  /*
3097  * Since outer ParseState isn't parent of inner, have to pass down
3098  * the query text by hand.
3099  */
3100  sub_pstate->p_sourcetext = queryString;
3101 
3102  /*
3103  * Set up OLD/NEW in the rtable for this statement. The entries
3104  * are added only to relnamespace, not varnamespace, because we
3105  * don't want them to be referred to by unqualified field names
3106  * nor "*" in the rule actions. We decide later whether to put
3107  * them in the joinlist.
3108  */
3109  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3111  makeAlias("old", NIL),
3112  false, false);
3113  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3115  makeAlias("new", NIL),
3116  false, false);
3117  oldnsitem->p_rte->requiredPerms = 0;
3118  newnsitem->p_rte->requiredPerms = 0;
3119  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3120  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3121 
3122  /* Transform the rule action statement */
3123  top_subqry = transformStmt(sub_pstate, action);
3124 
3125  /*
3126  * We cannot support utility-statement actions (eg NOTIFY) with
3127  * nonempty rule WHERE conditions, because there's no way to make
3128  * the utility action execute conditionally.
3129  */
3130  if (top_subqry->commandType == CMD_UTILITY &&
3131  *whereClause != NULL)
3132  ereport(ERROR,
3133  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3134  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3135 
3136  /*
3137  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3138  * into the SELECT, and that's what we need to look at. (Ugly
3139  * kluge ... try to fix this when we redesign querytrees.)
3140  */
3141  sub_qry = getInsertSelectQuery(top_subqry, NULL);
3142 
3143  /*
3144  * If the sub_qry is a setop, we cannot attach any qualifications
3145  * to it, because the planner won't notice them. This could
3146  * perhaps be relaxed someday, but for now, we may as well reject
3147  * such a rule immediately.
3148  */
3149  if (sub_qry->setOperations != NULL && *whereClause != NULL)
3150  ereport(ERROR,
3151  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3152  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3153 
3154  /*
3155  * Validate action's use of OLD/NEW, qual too
3156  */
3157  has_old =
3158  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3159  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3160  has_new =
3161  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3162  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3163 
3164  switch (stmt->event)
3165  {
3166  case CMD_SELECT:
3167  if (has_old)
3168  ereport(ERROR,
3169  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3170  errmsg("ON SELECT rule cannot use OLD")));
3171  if (has_new)
3172  ereport(ERROR,
3173  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3174  errmsg("ON SELECT rule cannot use NEW")));
3175  break;
3176  case CMD_UPDATE:
3177  /* both are OK */
3178  break;
3179  case CMD_INSERT:
3180  if (has_old)
3181  ereport(ERROR,
3182  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3183  errmsg("ON INSERT rule cannot use OLD")));
3184  break;
3185  case CMD_DELETE:
3186  if (has_new)
3187  ereport(ERROR,
3188  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3189  errmsg("ON DELETE rule cannot use NEW")));
3190  break;
3191  default:
3192  elog(ERROR, "unrecognized event type: %d",
3193  (int) stmt->event);
3194  break;
3195  }
3196 
3197  /*
3198  * OLD/NEW are not allowed in WITH queries, because they would
3199  * amount to outer references for the WITH, which we disallow.
3200  * However, they were already in the outer rangetable when we
3201  * analyzed the query, so we have to check.
3202  *
3203  * Note that in the INSERT...SELECT case, we need to examine the
3204  * CTE lists of both top_subqry and sub_qry.
3205  *
3206  * Note that we aren't digging into the body of the query looking
3207  * for WITHs in nested sub-SELECTs. A WITH down there can
3208  * legitimately refer to OLD/NEW, because it'd be an
3209  * indirect-correlated outer reference.
3210  */
3211  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3212  PRS2_OLD_VARNO, 0) ||
3213  rangeTableEntry_used((Node *) sub_qry->cteList,
3214  PRS2_OLD_VARNO, 0))
3215  ereport(ERROR,
3216  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3217  errmsg("cannot refer to OLD within WITH query")));
3218  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3219  PRS2_NEW_VARNO, 0) ||
3220  rangeTableEntry_used((Node *) sub_qry->cteList,
3221  PRS2_NEW_VARNO, 0))
3222  ereport(ERROR,
3223  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3224  errmsg("cannot refer to NEW within WITH query")));
3225 
3226  /*
3227  * For efficiency's sake, add OLD to the rule action's jointree
3228  * only if it was actually referenced in the statement or qual.
3229  *
3230  * For INSERT, NEW is not really a relation (only a reference to
3231  * the to-be-inserted tuple) and should never be added to the
3232  * jointree.
3233  *
3234  * For UPDATE, we treat NEW as being another kind of reference to
3235  * OLD, because it represents references to *transformed* tuples
3236  * of the existing relation. It would be wrong to enter NEW
3237  * separately in the jointree, since that would cause a double
3238  * join of the updated relation. It's also wrong to fail to make
3239  * a jointree entry if only NEW and not OLD is mentioned.
3240  */
3241  if (has_old || (has_new && stmt->event == CMD_UPDATE))
3242  {
3243  RangeTblRef *rtr;
3244 
3245  /*
3246  * If sub_qry is a setop, manipulating its jointree will do no
3247  * good at all, because the jointree is dummy. (This should be
3248  * a can't-happen case because of prior tests.)
3249  */
3250  if (sub_qry->setOperations != NULL)
3251  ereport(ERROR,
3252  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3253  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3254  /* hackishly add OLD to the already-built FROM clause */
3255  rtr = makeNode(RangeTblRef);
3256  rtr->rtindex = oldnsitem->p_rtindex;
3257  sub_qry->jointree->fromlist =
3258  lappend(sub_qry->jointree->fromlist, rtr);
3259  }
3260 
3261  newactions = lappend(newactions, top_subqry);
3262 
3263  free_parsestate(sub_pstate);
3264  }
3265 
3266  *actions = newactions;
3267  }
3268 
3269  free_parsestate(pstate);
3270 
3271  /* Close relation, but keep the exclusive lock */
3272  table_close(rel, NoLock);
3273 }
#define AccessExclusiveLock
Definition: lockdefs.h:43
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:388
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:286
@ CMD_UTILITY
Definition: nodes.h:726
@ CMD_INSERT
Definition: nodes.h:723
@ CMD_DELETE
Definition: nodes.h:724
@ CMD_UPDATE
Definition: nodes.h:722
@ CMD_SELECT
Definition: nodes.h:721
@ CMD_NOTHING
Definition: nodes.h:728
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:313
#define PRS2_OLD_VARNO
Definition: primnodes.h:192
#define PRS2_NEW_VARNO
Definition: primnodes.h:193
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:924
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:892
List * fromlist
Definition: primnodes.h:1825
RangeTblEntry * p_rte
Definition: parse_node.h:269
FromExpr * jointree
Definition: parsenodes.h:149
Node * setOperations
Definition: parsenodes.h:182
List * cteList
Definition: parsenodes.h:146
List * rtable
Definition: parsenodes.h:148
CmdType commandType
Definition: parsenodes.h:121
AclMode requiredPerms
Definition: parsenodes.h:1165
Node * whereClause
Definition: parsenodes.h:3488
RangeVar * relation
Definition: parsenodes.h:3486
CmdType event
Definition: parsenodes.h:3489
List * actions
Definition: parsenodes.h:3491
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102

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, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, 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().

◆ transformStatsStmt()

CreateStatsStmt* transformStatsStmt ( Oid  relid,
CreateStatsStmt stmt,
const char *  queryString 
)

Definition at line 2904 of file parse_utilcmd.c.

2905 {
2906  ParseState *pstate;
2907  ParseNamespaceItem *nsitem;
2908  ListCell *l;
2909  Relation rel;
2910 
2911  /* Nothing to do if statement already transformed. */
2912  if (stmt->transformed)
2913  return stmt;
2914 
2915  /* Set up pstate */
2916  pstate = make_parsestate(NULL);
2917  pstate->p_sourcetext = queryString;
2918 
2919  /*
2920  * Put the parent table into the rtable so that the expressions can refer
2921  * to its fields without qualification. Caller is responsible for locking
2922  * relation, but we still need to open it.
2923  */
2924  rel = relation_open(relid, NoLock);
2925  nsitem = addRangeTableEntryForRelation(pstate, rel,
2927  NULL, false, true);
2928 
2929  /* no to join list, yes to namespaces */
2930  addNSItemToQuery(pstate, nsitem, false, true, true);
2931 
2932  /* take care of any expressions */
2933  foreach(l, stmt->exprs)
2934  {
2935  StatsElem *selem = (StatsElem *) lfirst(l);
2936 
2937  if (selem->expr)
2938  {
2939  /* Now do parse transformation of the expression */
2940  selem->expr = transformExpr(pstate, selem->expr,
2942 
2943  /* We have to fix its collations too */
2944  assign_expr_collations(pstate, selem->expr);
2945  }
2946  }
2947 
2948  /*
2949  * Check that only the base rel is mentioned. (This should be dead code
2950  * now that add_missing_from is history.)
2951  */
2952  if (list_length(pstate->p_rtable) != 1)
2953  ereport(ERROR,
2954  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2955  errmsg("statistics expressions can refer only to the table being referenced")));
2956 
2957  free_parsestate(pstate);
2958 
2959  /* Close relation */
2960  table_close(rel, NoLock);
2961 
2962  /* Mark statement as successfully transformed */
2963  stmt->transformed = true;
2964 
2965  return stmt;
2966 }
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
Node * expr
Definition: parsenodes.h:3293

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, StatsElem::expr, EXPR_KIND_STATS_EXPRESSION, CreateStatsStmt::exprs, free_parsestate(), lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), table_close(), CreateStatsStmt::transformed, and transformExpr().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().