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

1193 {
1194  List *result = NIL;
1195  List *atsubcmds = NIL;
1196  AttrNumber parent_attno;
1197  Relation relation;
1198  Relation childrel;
1199  TupleDesc tupleDesc;
1200  TupleConstr *constr;
1201  AttrMap *attmap;
1202  char *comment;
1203 
1204  /*
1205  * Open the relation referenced by the LIKE clause. We should still have
1206  * the table lock obtained by transformTableLikeClause (and this'll throw
1207  * an assertion failure if not). Hence, no need to recheck privileges
1208  * etc. We must open the rel by OID not name, to be sure we get the same
1209  * table.
1210  */
1211  if (!OidIsValid(table_like_clause->relationOid))
1212  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1213 
1214  relation = relation_open(table_like_clause->relationOid, NoLock);
1215 
1216  tupleDesc = RelationGetDescr(relation);
1217  constr = tupleDesc->constr;
1218 
1219  /*
1220  * Open the newly-created child relation; we have lock on that too.
1221  */
1222  childrel = relation_openrv(heapRel, NoLock);
1223 
1224  /*
1225  * Construct a map from the LIKE relation's attnos to the child rel's.
1226  * This re-checks type match etc, although it shouldn't be possible to
1227  * have a failure since both tables are locked.
1228  */
1229  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1230  tupleDesc,
1231  false);
1232 
1233  /*
1234  * Process defaults, if required.
1235  */
1236  if ((table_like_clause->options &
1238  constr != NULL)
1239  {
1240  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1241  parent_attno++)
1242  {
1243  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1244  parent_attno - 1);
1245 
1246  /*
1247  * Ignore dropped columns in the parent.
1248  */
1249  if (attribute->attisdropped)
1250  continue;
1251 
1252  /*
1253  * Copy default, if present and it should be copied. We have
1254  * separate options for plain default expressions and GENERATED
1255  * defaults.
1256  */
1257  if (attribute->atthasdef &&
1258  (attribute->attgenerated ?
1259  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1260  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1261  {
1262  Node *this_default = NULL;
1263  AttrDefault *attrdef = constr->defval;
1264  AlterTableCmd *atsubcmd;
1265  bool found_whole_row;
1266 
1267  /* Find default in constraint structure */
1268  for (int i = 0; i < constr->num_defval; i++)
1269  {
1270  if (attrdef[i].adnum == parent_attno)
1271  {
1272  this_default = stringToNode(attrdef[i].adbin);
1273  break;
1274  }
1275  }
1276  if (this_default == NULL)
1277  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1278  parent_attno, RelationGetRelationName(relation));
1279 
1280  atsubcmd = makeNode(AlterTableCmd);
1281  atsubcmd->subtype = AT_CookedColumnDefault;
1282  atsubcmd->num = attmap->attnums[parent_attno - 1];
1283  atsubcmd->def = map_variable_attnos(this_default,
1284  1, 0,
1285  attmap,
1286  InvalidOid,
1287  &found_whole_row);
1288 
1289  /*
1290  * Prevent this for the same reason as for constraints below.
1291  * Note that defaults cannot contain any vars, so it's OK that
1292  * the error message refers to generated columns.
1293  */
1294  if (found_whole_row)
1295  ereport(ERROR,
1296  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1297  errmsg("cannot convert whole-row table reference"),
1298  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1299  NameStr(attribute->attname),
1300  RelationGetRelationName(relation))));
1301 
1302  atsubcmds = lappend(atsubcmds, atsubcmd);
1303  }
1304  }
1305  }
1306 
1307  /*
1308  * Copy CHECK constraints if requested, being careful to adjust attribute
1309  * numbers so they match the child.
1310  */
1311  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1312  constr != NULL)
1313  {
1314  int ccnum;
1315 
1316  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1317  {
1318  char *ccname = constr->check[ccnum].ccname;
1319  char *ccbin = constr->check[ccnum].ccbin;
1320  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1321  Node *ccbin_node;
1322  bool found_whole_row;
1323  Constraint *n;
1324  AlterTableCmd *atsubcmd;
1325 
1326  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1327  1, 0,
1328  attmap,
1329  InvalidOid, &found_whole_row);
1330 
1331  /*
1332  * We reject whole-row variables because the whole point of LIKE
1333  * is that the new table's rowtype might later diverge from the
1334  * parent's. So, while translation might be possible right now,
1335  * it wouldn't be possible to guarantee it would work in future.
1336  */
1337  if (found_whole_row)
1338  ereport(ERROR,
1339  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1340  errmsg("cannot convert whole-row table reference"),
1341  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1342  ccname,
1343  RelationGetRelationName(relation))));
1344 
1345  n = makeNode(Constraint);
1346  n->contype = CONSTR_CHECK;
1347  n->conname = pstrdup(ccname);
1348  n->location = -1;
1349  n->is_no_inherit = ccnoinherit;
1350  n->raw_expr = NULL;
1351  n->cooked_expr = nodeToString(ccbin_node);
1352 
1353  /* We can skip validation, since the new table should be empty. */
1354  n->skip_validation = true;
1355  n->initially_valid = true;
1356 
1357  atsubcmd = makeNode(AlterTableCmd);
1358  atsubcmd->subtype = AT_AddConstraint;
1359  atsubcmd->def = (Node *) n;
1360  atsubcmds = lappend(atsubcmds, atsubcmd);
1361 
1362  /* Copy comment on constraint */
1363  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1365  n->conname, false),
1366  ConstraintRelationId,
1367  0)) != NULL)
1368  {
1369  CommentStmt *stmt = makeNode(CommentStmt);
1370 
1371  stmt->objtype = OBJECT_TABCONSTRAINT;
1372  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1373  makeString(heapRel->relname),
1374  makeString(n->conname));
1375  stmt->comment = comment;
1376 
1377  result = lappend(result, stmt);
1378  }
1379  }
1380  }
1381 
1382  /*
1383  * If we generated any ALTER TABLE actions above, wrap them into a single
1384  * ALTER TABLE command. Stick it at the front of the result, so it runs
1385  * before any CommentStmts we made above.
1386  */
1387  if (atsubcmds)
1388  {
1390 
1391  atcmd->relation = copyObject(heapRel);
1392  atcmd->cmds = atsubcmds;
1393  atcmd->objtype = OBJECT_TABLE;
1394  atcmd->missing_ok = false;
1395  result = lcons(atcmd, result);
1396  }
1397 
1398  /*
1399  * Process indexes if required.
1400  */
1401  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1402  relation->rd_rel->relhasindex)
1403  {
1404  List *parent_indexes;
1405  ListCell *l;
1406 
1407  parent_indexes = RelationGetIndexList(relation);
1408 
1409  foreach(l, parent_indexes)
1410  {
1411  Oid parent_index_oid = lfirst_oid(l);
1412  Relation parent_index;
1413  IndexStmt *index_stmt;
1414 
1415  parent_index = index_open(parent_index_oid, AccessShareLock);
1416 
1417  /* Build CREATE INDEX statement to recreate the parent_index */
1418  index_stmt = generateClonedIndexStmt(heapRel,
1419  parent_index,
1420  attmap,
1421  NULL);
1422 
1423  /* Copy comment on index, if requested */
1424  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1425  {
1426  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1427 
1428  /*
1429  * We make use of IndexStmt's idxcomment option, so as not to
1430  * need to know now what name the index will have.
1431  */
1432  index_stmt->idxcomment = comment;
1433  }
1434 
1435  result = lappend(result, index_stmt);
1436 
1437  index_close(parent_index, AccessShareLock);
1438  }
1439  }
1440 
1441  /* Done with child rel */
1442  table_close(childrel, NoLock);
1443 
1444  /*
1445  * Close the parent rel, but keep our AccessShareLock on it until xact
1446  * commit. That will prevent someone else from deleting or ALTERing the
1447  * parent before the child is committed.
1448  */
1449  table_close(relation, NoLock);
1450 
1451  return result;
1452 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:178
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:730
#define OidIsValid(objectId)
Definition: c.h:759
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
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:338
List * lcons(void *datum, List *list)
Definition: list.c:494
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1624
#define copyObject(obj)
Definition: nodes.h:233
#define makeNode(_type_)
Definition: nodes.h:165
char * nodeToString(const void *obj)
Definition: outfuncs.c:878
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2390
@ OBJECT_TABLE
Definition: parsenodes.h:1984
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:1983
@ AT_AddConstraint
Definition: parsenodes.h:2051
@ AT_CookedColumnDefault
Definition: parsenodes.h:2038
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:749
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:753
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:755
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:752
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:751
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:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetDescr(relation)
Definition: rel.h:527
#define RelationGetRelationName(relation)
Definition: rel.h:535
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4738
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:2113
RangeVar * relation
Definition: parsenodes.h:2027
ObjectType objtype
Definition: parsenodes.h:2029
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * comment
Definition: parsenodes.h:2951
ObjectType objtype
Definition: parsenodes.h:2949
Node * object
Definition: parsenodes.h:2950
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ConstrType contype
Definition: parsenodes.h:2418
bool is_no_inherit
Definition: parsenodes.h:2427
char * cooked_expr
Definition: parsenodes.h:2429
bool initially_valid
Definition: parsenodes.h:2466
bool skip_validation
Definition: parsenodes.h:2465
Node * raw_expr
Definition: parsenodes.h:2428
char * conname
Definition: parsenodes.h:2421
char * idxcomment
Definition: parsenodes.h:3055
Definition: pg_list.h:54
Definition: nodes.h:118
char * relname
Definition: primnodes.h:74
char * schemaname
Definition: primnodes.h:71
Form_pg_class rd_rel
Definition: rel.h:110
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:126
#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  {
3361  ColumnDef *def = castNode(ColumnDef, cmd->def);
3362 
3363  transformColumnDefinition(&cxt, def);
3364 
3365  /*
3366  * If the column has a non-null default, we can't skip
3367  * validation of foreign keys.
3368  */
3369  if (def->raw_default != NULL)
3370  skipValidation = false;
3371 
3372  /*
3373  * All constraints are processed in other ways. Remove the
3374  * original list
3375  */
3376  def->constraints = NIL;
3377 
3378  newcmds = lappend(newcmds, cmd);
3379  break;
3380  }
3381 
3382  case AT_AddConstraint:
3383 
3384  /*
3385  * The original AddConstraint cmd node doesn't go to newcmds
3386  */
3387  if (IsA(cmd->def, Constraint))
3388  {
3389  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3390  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3391  skipValidation = false;
3392  }
3393  else
3394  elog(ERROR, "unrecognized node type: %d",
3395  (int) nodeTag(cmd->def));
3396  break;
3397 
3398  case AT_AlterColumnType:
3399  {
3400  ColumnDef *def = castNode(ColumnDef, cmd->def);
3402 
3403  /*
3404  * For ALTER COLUMN TYPE, transform the USING clause if
3405  * one was specified.
3406  */
3407  if (def->raw_default)
3408  {
3409  def->cooked_default =
3410  transformExpr(pstate, def->raw_default,
3412  }
3413 
3414  /*
3415  * For identity column, create ALTER SEQUENCE command to
3416  * change the data type of the sequence.
3417  */
3418  attnum = get_attnum(relid, cmd->name);
3419  if (attnum == InvalidAttrNumber)
3420  ereport(ERROR,
3421  (errcode(ERRCODE_UNDEFINED_COLUMN),
3422  errmsg("column \"%s\" of relation \"%s\" does not exist",
3423  cmd->name, RelationGetRelationName(rel))));
3424 
3425  if (attnum > 0 &&
3426  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3427  {
3428  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3429  Oid typeOid = typenameTypeId(pstate, def->typeName);
3430  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3431 
3432  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3433  get_rel_name(seq_relid),
3434  -1);
3435  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3436  altseqstmt->for_identity = true;
3437  cxt.blist = lappend(cxt.blist, altseqstmt);
3438  }
3439 
3440  newcmds = lappend(newcmds, cmd);
3441  break;
3442  }
3443 
3444  case AT_AddIdentity:
3445  {
3446  Constraint *def = castNode(Constraint, cmd->def);
3447  ColumnDef *newdef = makeNode(ColumnDef);
3449 
3450  newdef->colname = cmd->name;
3451  newdef->identity = def->generated_when;
3452  cmd->def = (Node *) newdef;
3453 
3454  attnum = get_attnum(relid, cmd->name);
3455  if (attnum == InvalidAttrNumber)
3456  ereport(ERROR,
3457  (errcode(ERRCODE_UNDEFINED_COLUMN),
3458  errmsg("column \"%s\" of relation \"%s\" does not exist",
3459  cmd->name, RelationGetRelationName(rel))));
3460 
3461  generateSerialExtraStmts(&cxt, newdef,
3462  get_atttype(relid, attnum),
3463  def->options, true, true,
3464  NULL, NULL);
3465 
3466  newcmds = lappend(newcmds, cmd);
3467  break;
3468  }
3469 
3470  case AT_SetIdentity:
3471  {
3472  /*
3473  * Create an ALTER SEQUENCE statement for the internal
3474  * sequence of the identity column.
3475  */
3476  ListCell *lc;
3477  List *newseqopts = NIL;
3478  List *newdef = NIL;
3480  Oid seq_relid;
3481 
3482  /*
3483  * Split options into those handled by ALTER SEQUENCE and
3484  * those for ALTER TABLE proper.
3485  */
3486  foreach(lc, castNode(List, cmd->def))
3487  {
3488  DefElem *def = lfirst_node(DefElem, lc);
3489 
3490  if (strcmp(def->defname, "generated") == 0)
3491  newdef = lappend(newdef, def);
3492  else
3493  newseqopts = lappend(newseqopts, def);
3494  }
3495 
3496  attnum = get_attnum(relid, cmd->name);
3497  if (attnum == InvalidAttrNumber)
3498  ereport(ERROR,
3499  (errcode(ERRCODE_UNDEFINED_COLUMN),
3500  errmsg("column \"%s\" of relation \"%s\" does not exist",
3501  cmd->name, RelationGetRelationName(rel))));
3502 
3503  seq_relid = getIdentitySequence(relid, attnum, true);
3504 
3505  if (seq_relid)
3506  {
3507  AlterSeqStmt *seqstmt;
3508 
3509  seqstmt = makeNode(AlterSeqStmt);
3511  get_rel_name(seq_relid), -1);
3512  seqstmt->options = newseqopts;
3513  seqstmt->for_identity = true;
3514  seqstmt->missing_ok = false;
3515 
3516  cxt.blist = lappend(cxt.blist, seqstmt);
3517  }
3518 
3519  /*
3520  * If column was not an identity column, we just let the
3521  * ALTER TABLE command error out later. (There are cases
3522  * this fails to cover, but we'll need to restructure
3523  * where creation of the sequence dependency linkage
3524  * happens before we can fix it.)
3525  */
3526 
3527  cmd->def = (Node *) newdef;
3528  newcmds = lappend(newcmds, cmd);
3529  break;
3530  }
3531 
3532  case AT_AttachPartition:
3533  case AT_DetachPartition:
3534  {
3535  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3536 
3537  transformPartitionCmd(&cxt, partcmd);
3538  /* assign transformed value of the partition bound */
3539  partcmd->bound = cxt.partbound;
3540  }
3541 
3542  newcmds = lappend(newcmds, cmd);
3543  break;
3544 
3545  default:
3546 
3547  /*
3548  * Currently, we shouldn't actually get here for subcommand
3549  * types that don't require transformation; but if we do, just
3550  * emit them unchanged.
3551  */
3552  newcmds = lappend(newcmds, cmd);
3553  break;
3554  }
3555  }
3556 
3557  /*
3558  * Transfer anything we already have in cxt.alist into save_alist, to keep
3559  * it separate from the output of transformIndexConstraints.
3560  */
3561  save_alist = cxt.alist;
3562  cxt.alist = NIL;
3563 
3564  /* Postprocess constraints */
3566  transformFKConstraints(&cxt, skipValidation, true);
3567  transformCheckConstraints(&cxt, false);
3568 
3569  /*
3570  * Push any index-creation commands into the ALTER, so that they can be
3571  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3572  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3573  * subcommand has already been through transformIndexStmt.
3574  */
3575  foreach(l, cxt.alist)
3576  {
3577  Node *istmt = (Node *) lfirst(l);
3578 
3579  /*
3580  * We assume here that cxt.alist contains only IndexStmts and possibly
3581  * ALTER TABLE SET NOT NULL statements generated from primary key
3582  * constraints. We absorb the subcommands of the latter directly.
3583  */
3584  if (IsA(istmt, IndexStmt))
3585  {
3586  IndexStmt *idxstmt = (IndexStmt *) istmt;
3587 
3588  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3589  newcmd = makeNode(AlterTableCmd);
3591  newcmd->def = (Node *) idxstmt;
3592  newcmds = lappend(newcmds, newcmd);
3593  }
3594  else if (IsA(istmt, AlterTableStmt))
3595  {
3596  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3597 
3598  newcmds = list_concat(newcmds, alterstmt->cmds);
3599  }
3600  else
3601  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3602  }
3603  cxt.alist = NIL;
3604 
3605  /* Append any CHECK or FK constraints to the commands list */
3606  foreach(l, cxt.ckconstraints)
3607  {
3608  newcmd = makeNode(AlterTableCmd);
3609  newcmd->subtype = AT_AddConstraint;
3610  newcmd->def = (Node *) lfirst(l);
3611  newcmds = lappend(newcmds, newcmd);
3612  }
3613  foreach(l, cxt.fkconstraints)
3614  {
3615  newcmd = makeNode(AlterTableCmd);
3616  newcmd->subtype = AT_AddConstraint;
3617  newcmd->def = (Node *) lfirst(l);
3618  newcmds = lappend(newcmds, newcmd);
3619  }
3620 
3621  /* Append extended statistics objects */
3623 
3624  /* Close rel */
3625  relation_close(rel, NoLock);
3626 
3627  /*
3628  * Output results.
3629  */
3630  stmt->cmds = newcmds;
3631 
3632  *beforeStmts = cxt.blist;
3633  *afterStmts = list_concat(cxt.alist, save_alist);
3634 
3635  return stmt;
3636 }
#define InvalidAttrNumber
Definition: attnum.h:23
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:857
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:939
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define nodeTag(nodeptr)
Definition: nodes.h:122
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92
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:2394
@ AT_AddIndexConstraint
Definition: parsenodes.h:2056
@ AT_SetIdentity
Definition: parsenodes.h:2098
@ AT_AddIndex
Definition: parsenodes.h:2049
@ AT_AddIdentity
Definition: parsenodes.h:2097
@ AT_AlterColumnType
Definition: parsenodes.h:2059
@ AT_DetachPartition
Definition: parsenodes.h:2095
@ AT_AttachPartition
Definition: parsenodes.h:2094
@ AT_AddColumn
Definition: parsenodes.h:2035
int16 attnum
Definition: pg_attribute.h:83
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:944
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define list_make1(x1)
Definition: pg_list.h:212
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
List * options
Definition: parsenodes.h:2825
RangeVar * sequence
Definition: parsenodes.h:2824
bool for_identity
Definition: parsenodes.h:2826
char identity
Definition: parsenodes.h:725
List * constraints
Definition: parsenodes.h:731
Node * cooked_default
Definition: parsenodes.h:724
char * colname
Definition: parsenodes.h:714
TypeName * typeName
Definition: parsenodes.h:715
Node * raw_default
Definition: parsenodes.h:723
List * options
Definition: parsenodes.h:2443
char generated_when
Definition: parsenodes.h:2430
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:803
Oid indexOid
Definition: parsenodes.h:3056
const char * p_sourcetext
Definition: parse_node.h:185
PartitionBoundSpec * bound
Definition: parsenodes.h:934

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, 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 3817 of file parse_utilcmd.c.

3818 {
3820  List *result;
3821  ListCell *elements;
3822 
3823  cxt.stmtType = "CREATE SCHEMA";
3824  cxt.schemaname = stmt->schemaname;
3825  cxt.authrole = (RoleSpec *) stmt->authrole;
3826  cxt.sequences = NIL;
3827  cxt.tables = NIL;
3828  cxt.views = NIL;
3829  cxt.indexes = NIL;
3830  cxt.triggers = NIL;
3831  cxt.grants = NIL;
3832 
3833  /*
3834  * Run through each schema element in the schema element list. Separate
3835  * statements by type, and do preliminary analysis.
3836  */
3837  foreach(elements, stmt->schemaElts)
3838  {
3839  Node *element = lfirst(elements);
3840 
3841  switch (nodeTag(element))
3842  {
3843  case T_CreateSeqStmt:
3844  {
3845  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3846 
3848  cxt.sequences = lappend(cxt.sequences, element);
3849  }
3850  break;
3851 
3852  case T_CreateStmt:
3853  {
3854  CreateStmt *elp = (CreateStmt *) element;
3855 
3857 
3858  /*
3859  * XXX todo: deal with constraints
3860  */
3861  cxt.tables = lappend(cxt.tables, element);
3862  }
3863  break;
3864 
3865  case T_ViewStmt:
3866  {
3867  ViewStmt *elp = (ViewStmt *) element;
3868 
3869  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3870 
3871  /*
3872  * XXX todo: deal with references between views
3873  */
3874  cxt.views = lappend(cxt.views, element);
3875  }
3876  break;
3877 
3878  case T_IndexStmt:
3879  {
3880  IndexStmt *elp = (IndexStmt *) element;
3881 
3883  cxt.indexes = lappend(cxt.indexes, element);
3884  }
3885  break;
3886 
3887  case T_CreateTrigStmt:
3888  {
3890 
3892  cxt.triggers = lappend(cxt.triggers, element);
3893  }
3894  break;
3895 
3896  case T_GrantStmt:
3897  cxt.grants = lappend(cxt.grants, element);
3898  break;
3899 
3900  default:
3901  elog(ERROR, "unrecognized node type: %d",
3902  (int) nodeTag(element));
3903  }
3904  }
3905 
3906  result = NIL;
3907  result = list_concat(result, cxt.sequences);
3908  result = list_concat(result, cxt.tables);
3909  result = list_concat(result, cxt.views);
3910  result = list_concat(result, cxt.indexes);
3911  result = list_concat(result, cxt.triggers);
3912  result = list_concat(result, cxt.grants);
3913 
3914  return result;
3915 }
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:2009
RangeVar * sequence
Definition: parsenodes.h:2814
RangeVar * relation
Definition: parsenodes.h:2336
RangeVar * relation
Definition: parsenodes.h:2701
RangeVar * relation
Definition: parsenodes.h:3046
RangeVar * view
Definition: parsenodes.h:3428

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, 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  /*
200  * If we are in an extension script, insist that the pre-existing
201  * object be a member of the extension, to avoid security risks.
202  */
203  ObjectAddress address;
204 
205  ObjectAddressSet(address, RelationRelationId, existing_relid);
207 
208  /* OK to skip */
209  ereport(NOTICE,
210  (errcode(ERRCODE_DUPLICATE_TABLE),
211  errmsg("relation \"%s\" already exists, skipping",
212  stmt->relation->relname)));
213  return NIL;
214  }
215 
216  /*
217  * If the target relation name isn't schema-qualified, make it so. This
218  * prevents some corner cases in which added-on rewritten commands might
219  * think they should apply to other relations that have the same name and
220  * are earlier in the search path. But a local temp table is effectively
221  * specified to be in pg_temp, so no need for anything extra in that case.
222  */
223  if (stmt->relation->schemaname == NULL
224  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
225  stmt->relation->schemaname = get_namespace_name(namespaceid);
226 
227  /* Set up CreateStmtContext */
228  cxt.pstate = pstate;
229  if (IsA(stmt, CreateForeignTableStmt))
230  {
231  cxt.stmtType = "CREATE FOREIGN TABLE";
232  cxt.isforeign = true;
233  }
234  else
235  {
236  cxt.stmtType = "CREATE TABLE";
237  cxt.isforeign = false;
238  }
239  cxt.relation = stmt->relation;
240  cxt.rel = NULL;
241  cxt.inhRelations = stmt->inhRelations;
242  cxt.isalter = false;
243  cxt.columns = NIL;
244  cxt.ckconstraints = NIL;
245  cxt.fkconstraints = NIL;
246  cxt.ixconstraints = NIL;
247  cxt.likeclauses = NIL;
248  cxt.extstats = NIL;
249  cxt.blist = NIL;
250  cxt.alist = NIL;
251  cxt.pkey = NULL;
252  cxt.ispartitioned = stmt->partspec != NULL;
253  cxt.partbound = stmt->partbound;
254  cxt.ofType = (stmt->ofTypename != NULL);
255 
256  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
257 
258  if (stmt->ofTypename)
259  transformOfType(&cxt, stmt->ofTypename);
260 
261  if (stmt->partspec)
262  {
263  if (stmt->inhRelations && !stmt->partbound)
264  ereport(ERROR,
265  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
266  errmsg("cannot create partitioned table as inheritance child")));
267  }
268 
269  /*
270  * Run through each primary element in the table creation clause. Separate
271  * column defs from constraints, and do preliminary analysis.
272  */
273  foreach(elements, stmt->tableElts)
274  {
275  Node *element = lfirst(elements);
276 
277  switch (nodeTag(element))
278  {
279  case T_ColumnDef:
281  break;
282 
283  case T_Constraint:
285  break;
286 
287  case T_TableLikeClause:
289  break;
290 
291  default:
292  elog(ERROR, "unrecognized node type: %d",
293  (int) nodeTag(element));
294  break;
295  }
296  }
297 
298  /*
299  * Transfer anything we already have in cxt.alist into save_alist, to keep
300  * it separate from the output of transformIndexConstraints. (This may
301  * not be necessary anymore, but we'll keep doing it to preserve the
302  * historical order of execution of the alist commands.)
303  */
304  save_alist = cxt.alist;
305  cxt.alist = NIL;
306 
307  Assert(stmt->constraints == NIL);
308 
309  /*
310  * Postprocess constraints that give rise to index definitions.
311  */
313 
314  /*
315  * Re-consideration of LIKE clauses should happen after creation of
316  * indexes, but before creation of foreign keys. This order is critical
317  * because a LIKE clause may attempt to create a primary key. If there's
318  * also a pkey in the main CREATE TABLE list, creation of that will not
319  * check for a duplicate at runtime (since index_check_primary_key()
320  * expects that we rejected dups here). Creation of the LIKE-generated
321  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
322  * only works if it happens second. On the other hand, we want to make
323  * pkeys before foreign key constraints, in case the user tries to make a
324  * self-referential FK.
325  */
326  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
327 
328  /*
329  * Postprocess foreign-key constraints.
330  */
331  transformFKConstraints(&cxt, true, false);
332 
333  /*
334  * Postprocess check constraints.
335  *
336  * For regular tables all constraints can be marked valid immediately,
337  * because the table is new therefore empty. Not so for foreign tables.
338  */
340 
341  /*
342  * Postprocess extended statistics.
343  */
345 
346  /*
347  * Output results.
348  */
349  stmt->tableElts = cxt.columns;
350  stmt->constraints = cxt.ckconstraints;
351 
352  result = lappend(cxt.blist, stmt);
353  result = list_concat(result, cxt.alist);
354  result = list_concat(result, save_alist);
355 
356  return result;
357 }
#define NOTICE
Definition: elog.h:35
Assert(fmt[strlen(fmt) - 1] !='\n')
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:537
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
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)
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition: pg_depend.c:257
List * tableElts
Definition: parsenodes.h:2337
TypeName * ofTypename
Definition: parsenodes.h:2342
bool if_not_exists
Definition: parsenodes.h:2348
List * inhRelations
Definition: parsenodes.h:2338
PartitionSpec * partspec
Definition: parsenodes.h:2341
PartitionBoundSpec * partbound
Definition: parsenodes.h:2340
List * constraints
Definition: parsenodes.h:2343
int location
Definition: primnodes.h:86
char relpersistence
Definition: primnodes.h:80

References CreateStmtContext::alist, Assert(), CreateStmtContext::blist, cancel_parser_errposition_callback(), checkMembershipInCurrentExtension(), 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, ObjectAddressSet, 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, 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 2813 of file parse_utilcmd.c.

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

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

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

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

2985 {
2986  Relation rel;
2987  ParseState *pstate;
2988  ParseNamespaceItem *oldnsitem;
2989  ParseNamespaceItem *newnsitem;
2990 
2991  /*
2992  * To avoid deadlock, make sure the first thing we do is grab
2993  * AccessExclusiveLock on the target relation. This will be needed by
2994  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2995  * beforehand.
2996  */
2998 
2999  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3000  ereport(ERROR,
3001  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3002  errmsg("rules on materialized views are not supported")));
3003 
3004  /* Set up pstate */
3005  pstate = make_parsestate(NULL);
3006  pstate->p_sourcetext = queryString;
3007 
3008  /*
3009  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3010  * Set up their ParseNamespaceItems in the main pstate for use in parsing
3011  * the rule qualification.
3012  */
3013  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3015  makeAlias("old", NIL),
3016  false, false);
3017  newnsitem = addRangeTableEntryForRelation(pstate, rel,
3019  makeAlias("new", NIL),
3020  false, false);
3021 
3022  /*
3023  * They must be in the namespace too for lookup purposes, but only add the
3024  * one(s) that are relevant for the current kind of rule. In an UPDATE
3025  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3026  * there's no need to be so picky for INSERT & DELETE. We do not add them
3027  * to the joinlist.
3028  */
3029  switch (stmt->event)
3030  {
3031  case CMD_SELECT:
3032  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3033  break;
3034  case CMD_UPDATE:
3035  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3036  addNSItemToQuery(pstate, newnsitem, false, true, true);
3037  break;
3038  case CMD_INSERT:
3039  addNSItemToQuery(pstate, newnsitem, false, true, true);
3040  break;
3041  case CMD_DELETE:
3042  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3043  break;
3044  default:
3045  elog(ERROR, "unrecognized event type: %d",
3046  (int) stmt->event);
3047  break;
3048  }
3049 
3050  /* take care of the where clause */
3051  *whereClause = transformWhereClause(pstate,
3052  stmt->whereClause,
3054  "WHERE");
3055  /* we have to fix its collations too */
3056  assign_expr_collations(pstate, *whereClause);
3057 
3058  /* this is probably dead code without add_missing_from: */
3059  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3060  ereport(ERROR,
3061  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3062  errmsg("rule WHERE condition cannot contain references to other relations")));
3063 
3064  /*
3065  * 'instead nothing' rules with a qualification need a query rangetable so
3066  * the rewrite handler can add the negated rule qualification to the
3067  * original query. We create a query with the new command type CMD_NOTHING
3068  * here that is treated specially by the rewrite system.
3069  */
3070  if (stmt->actions == NIL)
3071  {
3072  Query *nothing_qry = makeNode(Query);
3073 
3074  nothing_qry->commandType = CMD_NOTHING;
3075  nothing_qry->rtable = pstate->p_rtable;
3076  nothing_qry->rteperminfos = pstate->p_rteperminfos;
3077  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3078 
3079  *actions = list_make1(nothing_qry);
3080  }
3081  else
3082  {
3083  ListCell *l;
3084  List *newactions = NIL;
3085 
3086  /*
3087  * transform each statement, like parse_sub_analyze()
3088  */
3089  foreach(l, stmt->actions)
3090  {
3091  Node *action = (Node *) lfirst(l);
3092  ParseState *sub_pstate = make_parsestate(NULL);
3093  Query *sub_qry,
3094  *top_subqry;
3095  bool has_old,
3096  has_new;
3097 
3098  /*
3099  * Since outer ParseState isn't parent of inner, have to pass down
3100  * the query text by hand.
3101  */
3102  sub_pstate->p_sourcetext = queryString;
3103 
3104  /*
3105  * Set up OLD/NEW in the rtable for this statement. The entries
3106  * are added only to relnamespace, not varnamespace, because we
3107  * don't want them to be referred to by unqualified field names
3108  * nor "*" in the rule actions. We decide later whether to put
3109  * them in the joinlist.
3110  */
3111  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3113  makeAlias("old", NIL),
3114  false, false);
3115  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3117  makeAlias("new", NIL),
3118  false, false);
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:387
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:285
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
@ CMD_NOTHING
Definition: nodes.h:272
@ 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:211
#define PRS2_NEW_VARNO
Definition: primnodes.h:212
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:957
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:925
List * fromlist
Definition: primnodes.h:1799
List * p_rteperminfos
Definition: parse_node.h:187
FromExpr * jointree
Definition: parsenodes.h:175
List * rteperminfos
Definition: parsenodes.h:174
Node * setOperations
Definition: parsenodes.h:210
List * cteList
Definition: parsenodes.h:166
List * rtable
Definition: parsenodes.h:168
CmdType commandType
Definition: parsenodes.h:123
Node * whereClause
Definition: parsenodes.h:3300
RangeVar * relation
Definition: parsenodes.h:3298
CmdType event
Definition: parsenodes.h:3301
List * actions
Definition: parsenodes.h:3303
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

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, ParseState::p_rteperminfos, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, Query::rtable, Query::rteperminfos, 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 2908 of file parse_utilcmd.c.

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

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