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

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

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

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

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::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().

3315 {
3316  Relation rel;
3317  TupleDesc tupdesc;
3318  ParseState *pstate;
3319  CreateStmtContext cxt;
3320  List *save_alist;
3321  ListCell *lcmd,
3322  *l;
3323  List *newcmds = NIL;
3324  bool skipValidation = true;
3325  AlterTableCmd *newcmd;
3326  ParseNamespaceItem *nsitem;
3327 
3328  /*
3329  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3330  * is overkill, but easy.)
3331  */
3332  stmt = copyObject(stmt);
3333 
3334  /* Caller is responsible for locking the relation */
3335  rel = relation_open(relid, NoLock);
3336  tupdesc = RelationGetDescr(rel);
3337 
3338  /* Set up pstate */
3339  pstate = make_parsestate(NULL);
3340  pstate->p_sourcetext = queryString;
3341  nsitem = addRangeTableEntryForRelation(pstate,
3342  rel,
3344  NULL,
3345  false,
3346  true);
3347  addNSItemToQuery(pstate, nsitem, false, true, true);
3348 
3349  /* Set up CreateStmtContext */
3350  cxt.pstate = pstate;
3351  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3352  {
3353  cxt.stmtType = "ALTER FOREIGN TABLE";
3354  cxt.isforeign = true;
3355  }
3356  else
3357  {
3358  cxt.stmtType = "ALTER TABLE";
3359  cxt.isforeign = false;
3360  }
3361  cxt.relation = stmt->relation;
3362  cxt.rel = rel;
3363  cxt.inhRelations = NIL;
3364  cxt.isalter = true;
3365  cxt.columns = NIL;
3366  cxt.ckconstraints = NIL;
3367  cxt.fkconstraints = NIL;
3368  cxt.ixconstraints = NIL;
3369  cxt.likeclauses = NIL;
3370  cxt.extstats = NIL;
3371  cxt.blist = NIL;
3372  cxt.alist = NIL;
3373  cxt.pkey = NULL;
3374  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3375  cxt.partbound = NULL;
3376  cxt.ofType = false;
3377 
3378  /*
3379  * Transform ALTER subcommands that need it (most don't). These largely
3380  * re-use code from CREATE TABLE.
3381  */
3382  foreach(lcmd, stmt->cmds)
3383  {
3384  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3385 
3386  switch (cmd->subtype)
3387  {
3388  case AT_AddColumn:
3389  case AT_AddColumnRecurse:
3390  {
3391  ColumnDef *def = castNode(ColumnDef, cmd->def);
3392 
3393  transformColumnDefinition(&cxt, def);
3394 
3395  /*
3396  * If the column has a non-null default, we can't skip
3397  * validation of foreign keys.
3398  */
3399  if (def->raw_default != NULL)
3400  skipValidation = false;
3401 
3402  /*
3403  * All constraints are processed in other ways. Remove the
3404  * original list
3405  */
3406  def->constraints = NIL;
3407 
3408  newcmds = lappend(newcmds, cmd);
3409  break;
3410  }
3411 
3412  case AT_AddConstraint:
3414 
3415  /*
3416  * The original AddConstraint cmd node doesn't go to newcmds
3417  */
3418  if (IsA(cmd->def, Constraint))
3419  {
3420  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3421  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3422  skipValidation = false;
3423  }
3424  else
3425  elog(ERROR, "unrecognized node type: %d",
3426  (int) nodeTag(cmd->def));
3427  break;
3428 
3429  case AT_AlterColumnType:
3430  {
3431  ColumnDef *def = castNode(ColumnDef, cmd->def);
3433 
3434  /*
3435  * For ALTER COLUMN TYPE, transform the USING clause if
3436  * one was specified.
3437  */
3438  if (def->raw_default)
3439  {
3440  def->cooked_default =
3441  transformExpr(pstate, def->raw_default,
3443  }
3444 
3445  /*
3446  * For identity column, create ALTER SEQUENCE command to
3447  * change the data type of the sequence.
3448  */
3449  attnum = get_attnum(relid, cmd->name);
3450  if (attnum == InvalidAttrNumber)
3451  ereport(ERROR,
3452  (errcode(ERRCODE_UNDEFINED_COLUMN),
3453  errmsg("column \"%s\" of relation \"%s\" does not exist",
3454  cmd->name, RelationGetRelationName(rel))));
3455 
3456  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3457  {
3458  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3459  Oid typeOid = typenameTypeId(pstate, def->typeName);
3460  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3461 
3462  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3463  get_rel_name(seq_relid),
3464  -1);
3465  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3466  altseqstmt->for_identity = true;
3467  cxt.blist = lappend(cxt.blist, altseqstmt);
3468  }
3469 
3470  newcmds = lappend(newcmds, cmd);
3471  break;
3472  }
3473 
3474  case AT_AddIdentity:
3475  {
3476  Constraint *def = castNode(Constraint, cmd->def);
3477  ColumnDef *newdef = makeNode(ColumnDef);
3479 
3480  newdef->colname = cmd->name;
3481  newdef->identity = def->generated_when;
3482  cmd->def = (Node *) newdef;
3483 
3484  attnum = get_attnum(relid, cmd->name);
3485  if (attnum == InvalidAttrNumber)
3486  ereport(ERROR,
3487  (errcode(ERRCODE_UNDEFINED_COLUMN),
3488  errmsg("column \"%s\" of relation \"%s\" does not exist",
3489  cmd->name, RelationGetRelationName(rel))));
3490 
3491  generateSerialExtraStmts(&cxt, newdef,
3492  get_atttype(relid, attnum),
3493  def->options, true, true,
3494  NULL, NULL);
3495 
3496  newcmds = lappend(newcmds, cmd);
3497  break;
3498  }
3499 
3500  case AT_SetIdentity:
3501  {
3502  /*
3503  * Create an ALTER SEQUENCE statement for the internal
3504  * sequence of the identity column.
3505  */
3506  ListCell *lc;
3507  List *newseqopts = NIL;
3508  List *newdef = NIL;
3510  Oid seq_relid;
3511 
3512  /*
3513  * Split options into those handled by ALTER SEQUENCE and
3514  * those for ALTER TABLE proper.
3515  */
3516  foreach(lc, castNode(List, cmd->def))
3517  {
3518  DefElem *def = lfirst_node(DefElem, lc);
3519 
3520  if (strcmp(def->defname, "generated") == 0)
3521  newdef = lappend(newdef, def);
3522  else
3523  newseqopts = lappend(newseqopts, def);
3524  }
3525 
3526  attnum = get_attnum(relid, cmd->name);
3527  if (attnum == InvalidAttrNumber)
3528  ereport(ERROR,
3529  (errcode(ERRCODE_UNDEFINED_COLUMN),
3530  errmsg("column \"%s\" of relation \"%s\" does not exist",
3531  cmd->name, RelationGetRelationName(rel))));
3532 
3533  seq_relid = getIdentitySequence(relid, attnum, true);
3534 
3535  if (seq_relid)
3536  {
3537  AlterSeqStmt *seqstmt;
3538 
3539  seqstmt = makeNode(AlterSeqStmt);
3541  get_rel_name(seq_relid), -1);
3542  seqstmt->options = newseqopts;
3543  seqstmt->for_identity = true;
3544  seqstmt->missing_ok = false;
3545 
3546  cxt.blist = lappend(cxt.blist, seqstmt);
3547  }
3548 
3549  /*
3550  * If column was not an identity column, we just let the
3551  * ALTER TABLE command error out later. (There are cases
3552  * this fails to cover, but we'll need to restructure
3553  * where creation of the sequence dependency linkage
3554  * happens before we can fix it.)
3555  */
3556 
3557  cmd->def = (Node *) newdef;
3558  newcmds = lappend(newcmds, cmd);
3559  break;
3560  }
3561 
3562  case AT_AttachPartition:
3563  case AT_DetachPartition:
3564  {
3565  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3566 
3567  transformPartitionCmd(&cxt, partcmd);
3568  /* assign transformed value of the partition bound */
3569  partcmd->bound = cxt.partbound;
3570  }
3571 
3572  newcmds = lappend(newcmds, cmd);
3573  break;
3574 
3575  default:
3576 
3577  /*
3578  * Currently, we shouldn't actually get here for subcommand
3579  * types that don't require transformation; but if we do, just
3580  * emit them unchanged.
3581  */
3582  newcmds = lappend(newcmds, cmd);
3583  break;
3584  }
3585  }
3586 
3587  /*
3588  * Transfer anything we already have in cxt.alist into save_alist, to keep
3589  * it separate from the output of transformIndexConstraints.
3590  */
3591  save_alist = cxt.alist;
3592  cxt.alist = NIL;
3593 
3594  /* Postprocess constraints */
3596  transformFKConstraints(&cxt, skipValidation, true);
3597  transformCheckConstraints(&cxt, false);
3598 
3599  /*
3600  * Push any index-creation commands into the ALTER, so that they can be
3601  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3602  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3603  * subcommand has already been through transformIndexStmt.
3604  */
3605  foreach(l, cxt.alist)
3606  {
3607  Node *istmt = (Node *) lfirst(l);
3608 
3609  /*
3610  * We assume here that cxt.alist contains only IndexStmts and possibly
3611  * ALTER TABLE SET NOT NULL statements generated from primary key
3612  * constraints. We absorb the subcommands of the latter directly.
3613  */
3614  if (IsA(istmt, IndexStmt))
3615  {
3616  IndexStmt *idxstmt = (IndexStmt *) istmt;
3617 
3618  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3619  newcmd = makeNode(AlterTableCmd);
3621  newcmd->def = (Node *) idxstmt;
3622  newcmds = lappend(newcmds, newcmd);
3623  }
3624  else if (IsA(istmt, AlterTableStmt))
3625  {
3626  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3627 
3628  newcmds = list_concat(newcmds, alterstmt->cmds);
3629  }
3630  else
3631  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3632  }
3633  cxt.alist = NIL;
3634 
3635  /* Append any CHECK or FK constraints to the commands list */
3636  foreach(l, cxt.ckconstraints)
3637  {
3638  newcmd = makeNode(AlterTableCmd);
3639  newcmd->subtype = AT_AddConstraint;
3640  newcmd->def = (Node *) lfirst(l);
3641  newcmds = lappend(newcmds, newcmd);
3642  }
3643  foreach(l, cxt.fkconstraints)
3644  {
3645  newcmd = makeNode(AlterTableCmd);
3646  newcmd->subtype = AT_AddConstraint;
3647  newcmd->def = (Node *) lfirst(l);
3648  newcmds = lappend(newcmds, newcmd);
3649  }
3650 
3651  /* Append extended statistic objects */
3653 
3654  /* Close rel */
3655  relation_close(rel, NoLock);
3656 
3657  /*
3658  * Output results.
3659  */
3660  stmt->cmds = newcmds;
3661 
3662  *beforeStmts = cxt.blist;
3663  *afterStmts = list_concat(cxt.alist, save_alist);
3664 
3665  return stmt;
3666 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
char generated_when
Definition: parsenodes.h:2251
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:495
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
char identity
Definition: parsenodes.h:668
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:674
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:698
AlterTableType subtype
Definition: parsenodes.h:1949
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:914
#define OidIsValid(objectId)
Definition: c.h:710
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2644
List * options
Definition: parsenodes.h:2263
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:206
ParseState * pstate
Definition: parse_utilcmd.c:79
Node * cooked_default
Definition: parsenodes.h:667
Oid indexOid
Definition: parsenodes.h:2875
RangeVar * relation
Definition: parse_utilcmd.c:81
IndexStmt * pkey
Definition: parse_utilcmd.c:96
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
#define RelationGetRelationName(relation)
Definition: rel.h:503
const char * p_sourcetext
Definition: parse_node.h:181
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:938
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:98
Node * raw_default
Definition: parsenodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:336
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
RangeVar * sequence
Definition: parsenodes.h:2643
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:587
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:875
TypeName * typeName
Definition: parsenodes.h:659
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:544
const char * stmtType
Definition: parse_utilcmd.c:80
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:909
RangeVar * relation
Definition: parsenodes.h:1859
#define elog(elevel,...)
Definition: elog.h:232
bool for_identity
Definition: parsenodes.h:2645
char * defname
Definition: parsenodes.h:746
char * colname
Definition: parsenodes.h:658
#define copyObject(obj)
Definition: nodes.h:655
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3847 of file parse_utilcmd.c.

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

Referenced by CreateSchemaCommand().

3848 {
3850  List *result;
3851  ListCell *elements;
3852 
3853  cxt.stmtType = "CREATE SCHEMA";
3854  cxt.schemaname = stmt->schemaname;
3855  cxt.authrole = (RoleSpec *) stmt->authrole;
3856  cxt.sequences = NIL;
3857  cxt.tables = NIL;
3858  cxt.views = NIL;
3859  cxt.indexes = NIL;
3860  cxt.triggers = NIL;
3861  cxt.grants = NIL;
3862 
3863  /*
3864  * Run through each schema element in the schema element list. Separate
3865  * statements by type, and do preliminary analysis.
3866  */
3867  foreach(elements, stmt->schemaElts)
3868  {
3869  Node *element = lfirst(elements);
3870 
3871  switch (nodeTag(element))
3872  {
3873  case T_CreateSeqStmt:
3874  {
3875  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3876 
3878  cxt.sequences = lappend(cxt.sequences, element);
3879  }
3880  break;
3881 
3882  case T_CreateStmt:
3883  {
3884  CreateStmt *elp = (CreateStmt *) element;
3885 
3887 
3888  /*
3889  * XXX todo: deal with constraints
3890  */
3891  cxt.tables = lappend(cxt.tables, element);
3892  }
3893  break;
3894 
3895  case T_ViewStmt:
3896  {
3897  ViewStmt *elp = (ViewStmt *) element;
3898 
3899  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3900 
3901  /*
3902  * XXX todo: deal with references between views
3903  */
3904  cxt.views = lappend(cxt.views, element);
3905  }
3906  break;
3907 
3908  case T_IndexStmt:
3909  {
3910  IndexStmt *elp = (IndexStmt *) element;
3911 
3913  cxt.indexes = lappend(cxt.indexes, element);
3914  }
3915  break;
3916 
3917  case T_CreateTrigStmt:
3918  {
3919  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3920 
3922  cxt.triggers = lappend(cxt.triggers, element);
3923  }
3924  break;
3925 
3926  case T_GrantStmt:
3927  cxt.grants = lappend(cxt.grants, element);
3928  break;
3929 
3930  default:
3931  elog(ERROR, "unrecognized node type: %d",
3932  (int) nodeTag(element));
3933  }
3934  }
3935 
3936  result = NIL;
3937  result = list_concat(result, cxt.sequences);
3938  result = list_concat(result, cxt.tables);
3939  result = list_concat(result, cxt.views);
3940  result = list_concat(result, cxt.indexes);
3941  result = list_concat(result, cxt.triggers);
3942  result = list_concat(result, cxt.grants);
3943 
3944  return result;
3945 }
RangeVar * relation
Definition: parsenodes.h:2159
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
RangeVar * view
Definition: parsenodes.h:3234
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2865
RoleSpec * authrole
Definition: parsenodes.h:1841
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * sequence
Definition: parsenodes.h:2633
#define lfirst(lc)
Definition: pg_list.h:169
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define elog(elevel,...)
Definition: elog.h:232
RangeVar * relation
Definition: parsenodes.h:2520
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 169 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, copyObject, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::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().

170 {
171  ParseState *pstate;
172  CreateStmtContext cxt;
173  List *result;
174  List *save_alist;
175  ListCell *elements;
176  Oid namespaceid;
177  Oid existing_relid;
178  ParseCallbackState pcbstate;
179 
180  /*
181  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
182  * overkill, but easy.)
183  */
184  stmt = copyObject(stmt);
185 
186  /* Set up pstate */
187  pstate = make_parsestate(NULL);
188  pstate->p_sourcetext = queryString;
189 
190  /*
191  * Look up the creation namespace. This also checks permissions on the
192  * target namespace, locks it against concurrent drops, checks for a
193  * preexisting relation in that namespace with the same name, and updates
194  * stmt->relation->relpersistence if the selected namespace is temporary.
195  */
196  setup_parser_errposition_callback(&pcbstate, pstate,
197  stmt->relation->location);
198  namespaceid =
200  &existing_relid);
202 
203  /*
204  * If the relation already exists and the user specified "IF NOT EXISTS",
205  * bail out with a NOTICE.
206  */
207  if (stmt->if_not_exists && OidIsValid(existing_relid))
208  {
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:
280  transformColumnDefinition(&cxt, (ColumnDef *) element);
281  break;
282 
283  case T_Constraint:
284  transformTableConstraint(&cxt, (Constraint *) element);
285  break;
286 
287  case T_TableLikeClause:
288  transformTableLikeClause(&cxt, (TableLikeClause *) element);
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 }
RangeVar * relation
Definition: parsenodes.h:2159
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2161
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2166
bool if_not_exists
Definition: parsenodes.h:2171
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:79
PartitionBoundSpec * partbound
Definition: parsenodes.h:2163
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:81
IndexStmt * pkey
Definition: parse_utilcmd.c:96
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
#define ERROR
Definition: elog.h:46
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:181
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:98
List * lappend(List *list, void *datum)
Definition: list.c:336
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:534
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2160
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:544
const char * stmtType
Definition: parse_utilcmd.c:80
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define copyObject(obj)
Definition: nodes.h:655
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2164
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2165
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

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

Definition at line 2816 of file parse_utilcmd.c.

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

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

2817 {
2818  ParseState *pstate;
2819  ParseNamespaceItem *nsitem;
2820  ListCell *l;
2821  Relation rel;
2822 
2823  /* Nothing to do if statement already transformed. */
2824  if (stmt->transformed)
2825  return stmt;
2826 
2827  /*
2828  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2829  * overkill, but easy.)
2830  */
2831  stmt = copyObject(stmt);
2832 
2833  /* Set up pstate */
2834  pstate = make_parsestate(NULL);
2835  pstate->p_sourcetext = queryString;
2836 
2837  /*
2838  * Put the parent table into the rtable so that the expressions can refer
2839  * to its fields without qualification. Caller is responsible for locking
2840  * relation, but we still need to open it.
2841  */
2842  rel = relation_open(relid, NoLock);
2843  nsitem = addRangeTableEntryForRelation(pstate, rel,
2845  NULL, false, true);
2846 
2847  /* no to join list, yes to namespaces */
2848  addNSItemToQuery(pstate, nsitem, false, true, true);
2849 
2850  /* take care of the where clause */
2851  if (stmt->whereClause)
2852  {
2853  stmt->whereClause = transformWhereClause(pstate,
2854  stmt->whereClause,
2856  "WHERE");
2857  /* we have to fix its collations too */
2858  assign_expr_collations(pstate, stmt->whereClause);
2859  }
2860 
2861  /* take care of any index expressions */
2862  foreach(l, stmt->indexParams)
2863  {
2864  IndexElem *ielem = (IndexElem *) lfirst(l);
2865 
2866  if (ielem->expr)
2867  {
2868  /* Extract preliminary index col name before transforming expr */
2869  if (ielem->indexcolname == NULL)
2870  ielem->indexcolname = FigureIndexColname(ielem->expr);
2871 
2872  /* Now do parse transformation of the expression */
2873  ielem->expr = transformExpr(pstate, ielem->expr,
2875 
2876  /* We have to fix its collations too */
2877  assign_expr_collations(pstate, ielem->expr);
2878 
2879  /*
2880  * transformExpr() should have already rejected subqueries,
2881  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2882  * for an index expression.
2883  *
2884  * DefineIndex() will make more checks.
2885  */
2886  }
2887  }
2888 
2889  /*
2890  * Check that only the base rel is mentioned. (This should be dead code
2891  * now that add_missing_from is history.)
2892  */
2893  if (list_length(pstate->p_rtable) != 1)
2894  ereport(ERROR,
2895  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2896  errmsg("index expressions and predicates can refer only to the table being indexed")));
2897 
2898  free_parsestate(pstate);
2899 
2900  /* Close relation */
2901  table_close(rel, NoLock);
2902 
2903  /* Mark statement as successfully transformed */
2904  stmt->transformed = true;
2905 
2906  return stmt;
2907 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Node * whereClause
Definition: parsenodes.h:2872
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:698
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:715
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2885
char * indexcolname
Definition: parsenodes.h:716
const char * p_sourcetext
Definition: parse_node.h:181
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2868
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define copyObject(obj)
Definition: nodes.h:655
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:182

◆ transformPartitionBound()

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

Definition at line 4025 of file parse_utilcmd.c.

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

Referenced by DefineRelation(), and transformPartitionCmd().

4027 {
4028  PartitionBoundSpec *result_spec;
4030  char strategy = get_partition_strategy(key);
4031  int partnatts = get_partition_natts(key);
4032  List *partexprs = get_partition_exprs(key);
4033 
4034  /* Avoid scribbling on input */
4035  result_spec = copyObject(spec);
4036 
4037  if (spec->is_default)
4038  {
4039  /*
4040  * Hash partitioning does not support a default partition; there's no
4041  * use case for it (since the set of partitions to create is perfectly
4042  * defined), and if users do get into it accidentally, it's hard to
4043  * back out from it afterwards.
4044  */
4045  if (strategy == PARTITION_STRATEGY_HASH)
4046  ereport(ERROR,
4047  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4048  errmsg("a hash-partitioned table may not have a default partition")));
4049 
4050  /*
4051  * In case of the default partition, parser had no way to identify the
4052  * partition strategy. Assign the parent's strategy to the default
4053  * partition bound spec.
4054  */
4055  result_spec->strategy = strategy;
4056 
4057  return result_spec;
4058  }
4059 
4060  if (strategy == PARTITION_STRATEGY_HASH)
4061  {
4062  if (spec->strategy != PARTITION_STRATEGY_HASH)
4063  ereport(ERROR,
4064  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4065  errmsg("invalid bound specification for a hash partition"),
4066  parser_errposition(pstate, exprLocation((Node *) spec))));
4067 
4068  if (spec->modulus <= 0)
4069  ereport(ERROR,
4070  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4071  errmsg("modulus for hash partition must be a positive integer")));
4072 
4073  Assert(spec->remainder >= 0);
4074 
4075  if (spec->remainder >= spec->modulus)
4076  ereport(ERROR,
4077  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4078  errmsg("remainder for hash partition must be less than modulus")));
4079  }
4080  else if (strategy == PARTITION_STRATEGY_LIST)
4081  {
4082  ListCell *cell;
4083  char *colname;
4084  Oid coltype;
4085  int32 coltypmod;
4086  Oid partcollation;
4087 
4088  if (spec->strategy != PARTITION_STRATEGY_LIST)
4089  ereport(ERROR,
4090  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4091  errmsg("invalid bound specification for a list partition"),
4092  parser_errposition(pstate, exprLocation((Node *) spec))));
4093 
4094  /* Get the only column's name in case we need to output an error */
4095  if (key->partattrs[0] != 0)
4096  colname = get_attname(RelationGetRelid(parent),
4097  key->partattrs[0], false);
4098  else
4099  colname = deparse_expression((Node *) linitial(partexprs),
4101  RelationGetRelid(parent)),
4102  false, false);
4103  /* Need its type data too */
4104  coltype = get_partition_col_typid(key, 0);
4105  coltypmod = get_partition_col_typmod(key, 0);
4106  partcollation = get_partition_col_collation(key, 0);
4107 
4108  result_spec->listdatums = NIL;
4109  foreach(cell, spec->listdatums)
4110  {
4111  Node *expr = lfirst(cell);
4112  Const *value;
4113  ListCell *cell2;
4114  bool duplicate;
4115 
4116  value = transformPartitionBoundValue(pstate, expr,
4117  colname, coltype, coltypmod,
4118  partcollation);
4119 
4120  /* Don't add to the result if the value is a duplicate */
4121  duplicate = false;
4122  foreach(cell2, result_spec->listdatums)
4123  {
4124  Const *value2 = castNode(Const, lfirst(cell2));
4125 
4126  if (equal(value, value2))
4127  {
4128  duplicate = true;
4129  break;
4130  }
4131  }
4132  if (duplicate)
4133  continue;
4134 
4135  result_spec->listdatums = lappend(result_spec->listdatums,
4136  value);
4137  }
4138  }
4139  else if (strategy == PARTITION_STRATEGY_RANGE)
4140  {
4141  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4142  ereport(ERROR,
4143  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4144  errmsg("invalid bound specification for a range partition"),
4145  parser_errposition(pstate, exprLocation((Node *) spec))));
4146 
4147  if (list_length(spec->lowerdatums) != partnatts)
4148  ereport(ERROR,
4149  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4150  errmsg("FROM must specify exactly one value per partitioning column")));
4151  if (list_length(spec->upperdatums) != partnatts)
4152  ereport(ERROR,
4153  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4154  errmsg("TO must specify exactly one value per partitioning column")));
4155 
4156  /*
4157  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4158  * any necessary validation.
4159  */
4160  result_spec->lowerdatums =
4162  parent);
4163  result_spec->upperdatums =
4165  parent);
4166  }
4167  else
4168  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4169 
4170  return result_spec;
4171 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
static struct @142 value
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3113
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
Definition: nodes.h:539
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:698
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:429
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
static Const * transformPartitionBoundValue(ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3543
#define RelationGetRelationName(relation)
Definition: rel.h:503
List * lappend(List *list, void *datum)
Definition: list.c:336
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:814
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3483
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:815
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:816
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
#define copyObject(obj)
Definition: nodes.h:655
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:469

◆ transformRuleStmt()

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

Definition at line 3001 of file parse_utilcmd.c.

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, RuleStmt::actions, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, copyObject, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RangeTblEntry::requiredPerms, Query::rtable, RangeTblRef::rtindex, Query::setOperations, table_close(), table_openrv(), transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

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

◆ transformStatsStmt()

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

Definition at line 2917 of file parse_utilcmd.c.

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

2918 {
2919  ParseState *pstate;
2920  ParseNamespaceItem *nsitem;
2921  ListCell *l;
2922  Relation rel;
2923 
2924  /* Nothing to do if statement already transformed. */
2925  if (stmt->transformed)
2926  return stmt;
2927 
2928  /*
2929  * We must not scribble on the passed-in CreateStatsStmt, so copy it.
2930  * (This is overkill, but easy.)
2931  */
2932  stmt = copyObject(stmt);
2933 
2934  /* Set up pstate */
2935  pstate = make_parsestate(NULL);
2936  pstate->p_sourcetext = queryString;
2937 
2938  /*
2939  * Put the parent table into the rtable so that the expressions can refer
2940  * to its fields without qualification. Caller is responsible for locking
2941  * relation, but we still need to open it.
2942  */
2943  rel = relation_open(relid, NoLock);
2944  nsitem = addRangeTableEntryForRelation(pstate, rel,
2946  NULL, false, true);
2947 
2948  /* no to join list, yes to namespaces */
2949  addNSItemToQuery(pstate, nsitem, false, true, true);
2950 
2951  /* take care of any expressions */
2952  foreach(l, stmt->exprs)
2953  {
2954  StatsElem *selem = (StatsElem *) lfirst(l);
2955 
2956  if (selem->expr)
2957  {
2958  /* Now do parse transformation of the expression */
2959  selem->expr = transformExpr(pstate, selem->expr,
2961 
2962  /* We have to fix its collations too */
2963  assign_expr_collations(pstate, selem->expr);
2964  }
2965  }
2966 
2967  /*
2968  * Check that only the base rel is mentioned. (This should be dead code
2969  * now that add_missing_from is history.)
2970  */
2971  if (list_length(pstate->p_rtable) != 1)
2972  ereport(ERROR,
2973  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2974  errmsg("statistics expressions can refer only to the table being indexed")));
2975 
2976  free_parsestate(pstate);
2977 
2978  /* Close relation */
2979  table_close(rel, NoLock);
2980 
2981  /* Mark statement as successfully transformed */
2982  stmt->transformed = true;
2983 
2984  return stmt;
2985 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:698
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:46
Node * expr
Definition: parsenodes.h:2919
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:181
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define copyObject(obj)
Definition: nodes.h:655
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:182