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

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

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

3815 {
3817  List *result;
3818  ListCell *elements;
3819 
3820  cxt.stmtType = "CREATE SCHEMA";
3821  cxt.schemaname = stmt->schemaname;
3822  cxt.authrole = (RoleSpec *) stmt->authrole;
3823  cxt.sequences = NIL;
3824  cxt.tables = NIL;
3825  cxt.views = NIL;
3826  cxt.indexes = NIL;
3827  cxt.triggers = NIL;
3828  cxt.grants = NIL;
3829 
3830  /*
3831  * Run through each schema element in the schema element list. Separate
3832  * statements by type, and do preliminary analysis.
3833  */
3834  foreach(elements, stmt->schemaElts)
3835  {
3836  Node *element = lfirst(elements);
3837 
3838  switch (nodeTag(element))
3839  {
3840  case T_CreateSeqStmt:
3841  {
3842  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3843 
3845  cxt.sequences = lappend(cxt.sequences, element);
3846  }
3847  break;
3848 
3849  case T_CreateStmt:
3850  {
3851  CreateStmt *elp = (CreateStmt *) element;
3852 
3854 
3855  /*
3856  * XXX todo: deal with constraints
3857  */
3858  cxt.tables = lappend(cxt.tables, element);
3859  }
3860  break;
3861 
3862  case T_ViewStmt:
3863  {
3864  ViewStmt *elp = (ViewStmt *) element;
3865 
3866  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3867 
3868  /*
3869  * XXX todo: deal with references between views
3870  */
3871  cxt.views = lappend(cxt.views, element);
3872  }
3873  break;
3874 
3875  case T_IndexStmt:
3876  {
3877  IndexStmt *elp = (IndexStmt *) element;
3878 
3880  cxt.indexes = lappend(cxt.indexes, element);
3881  }
3882  break;
3883 
3884  case T_CreateTrigStmt:
3885  {
3886  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3887 
3889  cxt.triggers = lappend(cxt.triggers, element);
3890  }
3891  break;
3892 
3893  case T_GrantStmt:
3894  cxt.grants = lappend(cxt.grants, element);
3895  break;
3896 
3897  default:
3898  elog(ERROR, "unrecognized node type: %d",
3899  (int) nodeTag(element));
3900  }
3901  }
3902 
3903  result = NIL;
3904  result = list_concat(result, cxt.sequences);
3905  result = list_concat(result, cxt.tables);
3906  result = list_concat(result, cxt.views);
3907  result = list_concat(result, cxt.indexes);
3908  result = list_concat(result, cxt.triggers);
3909  result = list_concat(result, cxt.grants);
3910 
3911  return result;
3912 }
RangeVar * relation
Definition: parsenodes.h:2183
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:536
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
RangeVar * view
Definition: parsenodes.h:3266
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2889
RoleSpec * authrole
Definition: parsenodes.h:1853
#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:2657
#define lfirst(lc)
Definition: pg_list.h:169
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:541
#define elog(elevel,...)
Definition: elog.h:232
RangeVar * relation
Definition: parsenodes.h:2544
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, 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().

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

◆ transformIndexStmt()

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

Definition at line 2805 of file parse_utilcmd.c.

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

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

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

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

◆ transformRuleStmt()

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

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

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

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

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