PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
Include dependency graph for parse_utilcmd.c:

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 
struct  CreateSchemaStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

static void transformColumnDefinition (CreateStmtContext *cxt, ColumnDef *column)
 
static void transformTableConstraint (CreateStmtContext *cxt, Constraint *constraint)
 
static void transformTableLikeClause (CreateStmtContext *cxt, TableLikeClause *table_like_clause)
 
static void transformOfType (CreateStmtContext *cxt, TypeName *ofTypename)
 
static CreateStatsStmtgenerateClonedExtStatsStmt (RangeVar *heapRel, Oid heapRelid, Oid source_statsid)
 
static Listget_collation (Oid collation, Oid actual_datatype)
 
static Listget_opclass (Oid opclass, Oid actual_datatype)
 
static void transformIndexConstraints (CreateStmtContext *cxt)
 
static IndexStmttransformIndexConstraint (Constraint *constraint, CreateStmtContext *cxt)
 
static void transformExtendedStatistics (CreateStmtContext *cxt)
 
static void transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (CreateStmtContext *cxt, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void setSchemaName (const char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionCmd *cmd)
 
static ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 
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)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
ListtransformCreateSchemaStmtElements (List *schemaElts, const char *schemaName)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))
@ CONSTR_FOREIGN
Definition: parsenodes.h:2548
@ CONSTR_UNIQUE
Definition: parsenodes.h:2546
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2547
@ CONSTR_PRIMARY
Definition: parsenodes.h:2545

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1298 of file parse_utilcmd.c.

1299 {
1300  List *result = NIL;
1301  List *atsubcmds = NIL;
1302  AttrNumber parent_attno;
1303  Relation relation;
1304  Relation childrel;
1305  TupleDesc tupleDesc;
1306  TupleConstr *constr;
1307  AttrMap *attmap;
1308  char *comment;
1309  bool at_pushed = false;
1310  ListCell *lc;
1311 
1312  /*
1313  * Open the relation referenced by the LIKE clause. We should still have
1314  * the table lock obtained by transformTableLikeClause (and this'll throw
1315  * an assertion failure if not). Hence, no need to recheck privileges
1316  * etc. We must open the rel by OID not name, to be sure we get the same
1317  * table.
1318  */
1319  if (!OidIsValid(table_like_clause->relationOid))
1320  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1321 
1322  relation = relation_open(table_like_clause->relationOid, NoLock);
1323 
1324  tupleDesc = RelationGetDescr(relation);
1325  constr = tupleDesc->constr;
1326 
1327  /*
1328  * Open the newly-created child relation; we have lock on that too.
1329  */
1330  childrel = relation_openrv(heapRel, NoLock);
1331 
1332  /*
1333  * Construct a map from the LIKE relation's attnos to the child rel's.
1334  * This re-checks type match etc, although it shouldn't be possible to
1335  * have a failure since both tables are locked.
1336  */
1337  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1338  tupleDesc,
1339  false);
1340 
1341  /*
1342  * Process defaults, if required.
1343  */
1344  if ((table_like_clause->options &
1346  constr != NULL)
1347  {
1348  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1349  parent_attno++)
1350  {
1351  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1352  parent_attno - 1);
1353 
1354  /*
1355  * Ignore dropped columns in the parent.
1356  */
1357  if (attribute->attisdropped)
1358  continue;
1359 
1360  /*
1361  * Copy default, if present and it should be copied. We have
1362  * separate options for plain default expressions and GENERATED
1363  * defaults.
1364  */
1365  if (attribute->atthasdef &&
1366  (attribute->attgenerated ?
1367  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1368  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1369  {
1370  Node *this_default;
1371  AlterTableCmd *atsubcmd;
1372  bool found_whole_row;
1373 
1374  this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1375  if (this_default == NULL)
1376  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1377  parent_attno, RelationGetRelationName(relation));
1378 
1379  atsubcmd = makeNode(AlterTableCmd);
1380  atsubcmd->subtype = AT_CookedColumnDefault;
1381  atsubcmd->num = attmap->attnums[parent_attno - 1];
1382  atsubcmd->def = map_variable_attnos(this_default,
1383  1, 0,
1384  attmap,
1385  InvalidOid,
1386  &found_whole_row);
1387 
1388  /*
1389  * Prevent this for the same reason as for constraints below.
1390  * Note that defaults cannot contain any vars, so it's OK that
1391  * the error message refers to generated columns.
1392  */
1393  if (found_whole_row)
1394  ereport(ERROR,
1395  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1396  errmsg("cannot convert whole-row table reference"),
1397  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1398  NameStr(attribute->attname),
1399  RelationGetRelationName(relation))));
1400 
1401  atsubcmds = lappend(atsubcmds, atsubcmd);
1402  }
1403  }
1404  }
1405 
1406  /*
1407  * Copy CHECK constraints if requested, being careful to adjust attribute
1408  * numbers so they match the child.
1409  */
1410  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1411  constr != NULL)
1412  {
1413  int ccnum;
1414 
1415  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1416  {
1417  char *ccname = constr->check[ccnum].ccname;
1418  char *ccbin = constr->check[ccnum].ccbin;
1419  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1420  Node *ccbin_node;
1421  bool found_whole_row;
1422  Constraint *n;
1423  AlterTableCmd *atsubcmd;
1424 
1425  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1426  1, 0,
1427  attmap,
1428  InvalidOid, &found_whole_row);
1429 
1430  /*
1431  * We reject whole-row variables because the whole point of LIKE
1432  * is that the new table's rowtype might later diverge from the
1433  * parent's. So, while translation might be possible right now,
1434  * it wouldn't be possible to guarantee it would work in future.
1435  */
1436  if (found_whole_row)
1437  ereport(ERROR,
1438  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1439  errmsg("cannot convert whole-row table reference"),
1440  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1441  ccname,
1442  RelationGetRelationName(relation))));
1443 
1444  n = makeNode(Constraint);
1445  n->contype = CONSTR_CHECK;
1446  n->conname = pstrdup(ccname);
1447  n->location = -1;
1448  n->is_no_inherit = ccnoinherit;
1449  n->raw_expr = NULL;
1450  n->cooked_expr = nodeToString(ccbin_node);
1451 
1452  /* We can skip validation, since the new table should be empty. */
1453  n->skip_validation = true;
1454  n->initially_valid = true;
1455 
1456  atsubcmd = makeNode(AlterTableCmd);
1457  atsubcmd->subtype = AT_AddConstraint;
1458  atsubcmd->def = (Node *) n;
1459  atsubcmds = lappend(atsubcmds, atsubcmd);
1460 
1461  /* Copy comment on constraint */
1462  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1464  n->conname, false),
1465  ConstraintRelationId,
1466  0)) != NULL)
1467  {
1469 
1470  stmt->objtype = OBJECT_TABCONSTRAINT;
1471  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1472  makeString(heapRel->relname),
1473  makeString(n->conname));
1474  stmt->comment = comment;
1475 
1476  result = lappend(result, stmt);
1477  }
1478  }
1479  }
1480 
1481  /*
1482  * Copy not-null constraints, too (these do not require any option to have
1483  * been given).
1484  */
1485  foreach(lc, RelationGetNotNullConstraints(RelationGetRelid(relation), false))
1486  {
1487  AlterTableCmd *atsubcmd;
1488 
1489  atsubcmd = makeNode(AlterTableCmd);
1490  atsubcmd->subtype = AT_AddConstraint;
1491  atsubcmd->def = (Node *) lfirst_node(Constraint, lc);
1492  atsubcmds = lappend(atsubcmds, atsubcmd);
1493  }
1494 
1495  /*
1496  * If we generated any ALTER TABLE actions above, wrap them into a single
1497  * ALTER TABLE command. Stick it at the front of the result, so it runs
1498  * before any CommentStmts we made above.
1499  */
1500  if (atsubcmds)
1501  {
1503 
1504  atcmd->relation = copyObject(heapRel);
1505  atcmd->cmds = atsubcmds;
1506  atcmd->objtype = OBJECT_TABLE;
1507  atcmd->missing_ok = false;
1508  result = lcons(atcmd, result);
1509 
1510  at_pushed = true;
1511  }
1512 
1513  /*
1514  * Process indexes if required.
1515  */
1516  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1517  relation->rd_rel->relhasindex)
1518  {
1519  List *parent_indexes;
1520  ListCell *l;
1521 
1522  parent_indexes = RelationGetIndexList(relation);
1523 
1524  foreach(l, parent_indexes)
1525  {
1526  Oid parent_index_oid = lfirst_oid(l);
1527  Relation parent_index;
1528  IndexStmt *index_stmt;
1529 
1530  parent_index = index_open(parent_index_oid, AccessShareLock);
1531 
1532  /* Build CREATE INDEX statement to recreate the parent_index */
1533  index_stmt = generateClonedIndexStmt(heapRel,
1534  parent_index,
1535  attmap,
1536  NULL);
1537 
1538  /*
1539  * The PK columns might not yet non-nullable, so make sure they
1540  * become so.
1541  */
1542  if (index_stmt->primary)
1543  {
1544  foreach(lc, index_stmt->indexParams)
1545  {
1546  IndexElem *col = lfirst_node(IndexElem, lc);
1547  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
1548 
1549  notnullcmd->subtype = AT_SetAttNotNull;
1550  notnullcmd->name = pstrdup(col->name);
1551  /* Luckily we can still add more AT-subcmds here */
1552  atsubcmds = lappend(atsubcmds, notnullcmd);
1553  }
1554 
1555  /*
1556  * If we had already put the AlterTableStmt into the output
1557  * list, we don't need to do so again; otherwise do it.
1558  */
1559  if (!at_pushed)
1560  {
1562 
1563  atcmd->relation = copyObject(heapRel);
1564  atcmd->cmds = atsubcmds;
1565  atcmd->objtype = OBJECT_TABLE;
1566  atcmd->missing_ok = false;
1567  result = lcons(atcmd, result);
1568  }
1569  }
1570 
1571  /* Copy comment on index, if requested */
1572  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1573  {
1574  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1575 
1576  /*
1577  * We make use of IndexStmt's idxcomment option, so as not to
1578  * need to know now what name the index will have.
1579  */
1580  index_stmt->idxcomment = comment;
1581  }
1582 
1583  result = lappend(result, index_stmt);
1584 
1585  index_close(parent_index, AccessShareLock);
1586  }
1587  }
1588 
1589  /* Done with child rel */
1590  table_close(childrel, NoLock);
1591 
1592  /*
1593  * Close the parent rel, but keep our AccessShareLock on it until xact
1594  * commit. That will prevent someone else from deleting or ALTERing the
1595  * parent before the child is committed.
1596  */
1597  table_close(relation, NoLock);
1598 
1599  return result;
1600 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:178
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:735
#define OidIsValid(objectId)
Definition: c.h:764
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:182
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:138
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lcons(void *datum, List *list)
Definition: list.c:495
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1619
#define copyObject(obj)
Definition: nodes.h:223
#define makeNode(_type_)
Definition: nodes.h:155
char * nodeToString(const void *obj)
Definition: outfuncs.c:762
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2544
@ OBJECT_TABLE
Definition: parsenodes.h:2137
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2136
@ AT_SetAttNotNull
Definition: parsenodes.h:2194
@ AT_AddConstraint
Definition: parsenodes.h:2205
@ AT_CookedColumnDefault
Definition: parsenodes.h:2191
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:748
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:752
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:754
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:751
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:750
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
List * RelationGetNotNullConstraints(Oid relid, bool cooked)
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetRelationName(relation)
Definition: rel.h:538
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4755
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
AlterTableType subtype
Definition: parsenodes.h:2267
RangeVar * relation
Definition: parsenodes.h:2180
ObjectType objtype
Definition: parsenodes.h:2182
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ConstrType contype
Definition: parsenodes.h:2570
bool is_no_inherit
Definition: parsenodes.h:2576
char * cooked_expr
Definition: parsenodes.h:2579
bool initially_valid
Definition: parsenodes.h:2575
bool skip_validation
Definition: parsenodes.h:2574
Node * raw_expr
Definition: parsenodes.h:2577
char * conname
Definition: parsenodes.h:2571
char * name
Definition: parsenodes.h:770
List * indexParams
Definition: parsenodes.h:3195
char * idxcomment
Definition: parsenodes.h:3201
bool primary
Definition: parsenodes.h:3209
Definition: pg_list.h:54
Definition: nodes.h:129
char * relname
Definition: primnodes.h:82
char * schemaname
Definition: primnodes.h:79
Form_pg_class rd_rel
Definition: rel.h:111
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:851
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, AT_SetAttNotNull, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, 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, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), IndexStmt::idxcomment, index_close(), index_open(), IndexStmt::indexParams, Constraint::initially_valid, InvalidOid, Constraint::is_no_inherit, lappend(), lcons(), lfirst_node, lfirst_oid, list_make3, Constraint::location, makeNode, makeString(), map_variable_attnos(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, nodeToString(), NoLock, AlterTableCmd::num, TupleConstr::num_check, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, TableLikeClause::options, IndexStmt::primary, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, AlterTableStmt::relation, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetNotNullConstraints(), RelationGetRelationName, RelationGetRelid, TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stmt, stringToNode(), AlterTableCmd::subtype, table_close(), TupleDescAttr, and TupleDescGetDefault().

Referenced by ProcessUtilitySlow().

◆ generateClonedExtStatsStmt()

static CreateStatsStmt * generateClonedExtStatsStmt ( RangeVar heapRel,
Oid  heapRelid,
Oid  source_statsid 
)
static

Definition at line 2008 of file parse_utilcmd.c.

2010 {
2011  HeapTuple ht_stats;
2012  Form_pg_statistic_ext statsrec;
2013  CreateStatsStmt *stats;
2014  List *stat_types = NIL;
2015  List *def_names = NIL;
2016  bool isnull;
2017  Datum datum;
2018  ArrayType *arr;
2019  char *enabled;
2020  int i;
2021 
2022  Assert(OidIsValid(heapRelid));
2023  Assert(heapRel != NULL);
2024 
2025  /*
2026  * Fetch pg_statistic_ext tuple of source statistics object.
2027  */
2028  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
2029  if (!HeapTupleIsValid(ht_stats))
2030  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
2031  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
2032 
2033  /* Determine which statistics types exist */
2034  datum = SysCacheGetAttrNotNull(STATEXTOID, ht_stats,
2035  Anum_pg_statistic_ext_stxkind);
2036  arr = DatumGetArrayTypeP(datum);
2037  if (ARR_NDIM(arr) != 1 ||
2038  ARR_HASNULL(arr) ||
2039  ARR_ELEMTYPE(arr) != CHAROID)
2040  elog(ERROR, "stxkind is not a 1-D char array");
2041  enabled = (char *) ARR_DATA_PTR(arr);
2042  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
2043  {
2044  if (enabled[i] == STATS_EXT_NDISTINCT)
2045  stat_types = lappend(stat_types, makeString("ndistinct"));
2046  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
2047  stat_types = lappend(stat_types, makeString("dependencies"));
2048  else if (enabled[i] == STATS_EXT_MCV)
2049  stat_types = lappend(stat_types, makeString("mcv"));
2050  else if (enabled[i] == STATS_EXT_EXPRESSIONS)
2051  /* expression stats are not exposed to users */
2052  continue;
2053  else
2054  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
2055  }
2056 
2057  /* Determine which columns the statistics are on */
2058  for (i = 0; i < statsrec->stxkeys.dim1; i++)
2059  {
2060  StatsElem *selem = makeNode(StatsElem);
2061  AttrNumber attnum = statsrec->stxkeys.values[i];
2062 
2063  selem->name = get_attname(heapRelid, attnum, false);
2064  selem->expr = NULL;
2065 
2066  def_names = lappend(def_names, selem);
2067  }
2068 
2069  /*
2070  * Now handle expressions, if there are any. The order (with respect to
2071  * regular attributes) does not really matter for extended stats, so we
2072  * simply append them after simple column references.
2073  *
2074  * XXX Some places during build/estimation treat expressions as if they
2075  * are before attributes, but for the CREATE command that's entirely
2076  * irrelevant.
2077  */
2078  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
2079  Anum_pg_statistic_ext_stxexprs, &isnull);
2080 
2081  if (!isnull)
2082  {
2083  ListCell *lc;
2084  List *exprs = NIL;
2085  char *exprsString;
2086 
2087  exprsString = TextDatumGetCString(datum);
2088  exprs = (List *) stringToNode(exprsString);
2089 
2090  foreach(lc, exprs)
2091  {
2092  StatsElem *selem = makeNode(StatsElem);
2093 
2094  selem->name = NULL;
2095  selem->expr = (Node *) lfirst(lc);
2096 
2097  def_names = lappend(def_names, selem);
2098  }
2099 
2100  pfree(exprsString);
2101  }
2102 
2103  /* finally, build the output node */
2104  stats = makeNode(CreateStatsStmt);
2105  stats->defnames = NULL;
2106  stats->stat_types = stat_types;
2107  stats->exprs = def_names;
2108  stats->relations = list_make1(heapRel);
2109  stats->stxcomment = NULL;
2110  stats->transformed = true; /* don't need transformStatsStmt again */
2111  stats->if_not_exists = false;
2112 
2113  /* Clean up */
2114  ReleaseSysCache(ht_stats);
2115 
2116  return stats;
2117 }
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
#define ARR_HASNULL(a)
Definition: array.h:291
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:826
void pfree(void *pointer)
Definition: mcxt.c:1431
int16 attnum
Definition: pg_attribute.h:74
#define lfirst(lc)
Definition: pg_list.h:172
#define list_make1(x1)
Definition: pg_list.h:212
FormData_pg_statistic_ext * Form_pg_statistic_ext
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
char * name
Definition: parsenodes.h:3247
Node * expr
Definition: parsenodes.h:3248
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:480
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:511

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert(), attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog(), ERROR, StatsElem::expr, CreateStatsStmt::exprs, get_attname(), GETSTRUCT, HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, lappend(), lfirst, list_make1, makeNode, makeString(), StatsElem::name, NIL, ObjectIdGetDatum(), OidIsValid, pfree(), CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, stringToNode(), CreateStatsStmt::stxcomment, SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and CreateStatsStmt::transformed.

Referenced by transformTableLikeClause().

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const AttrMap attmap,
Oid constraintOid 
)

Definition at line 1656 of file parse_utilcmd.c.

1659 {
1660  Oid source_relid = RelationGetRelid(source_idx);
1661  HeapTuple ht_idxrel;
1662  HeapTuple ht_idx;
1663  HeapTuple ht_am;
1664  Form_pg_class idxrelrec;
1665  Form_pg_index idxrec;
1666  Form_pg_am amrec;
1667  oidvector *indcollation;
1668  oidvector *indclass;
1669  IndexStmt *index;
1670  List *indexprs;
1671  ListCell *indexpr_item;
1672  Oid indrelid;
1673  int keyno;
1674  Oid keycoltype;
1675  Datum datum;
1676  bool isnull;
1677 
1678  if (constraintOid)
1679  *constraintOid = InvalidOid;
1680 
1681  /*
1682  * Fetch pg_class tuple of source index. We can't use the copy in the
1683  * relcache entry because it doesn't include optional fields.
1684  */
1685  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1686  if (!HeapTupleIsValid(ht_idxrel))
1687  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1688  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1689 
1690  /* Fetch pg_index tuple for source index from relcache entry */
1691  ht_idx = source_idx->rd_indextuple;
1692  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1693  indrelid = idxrec->indrelid;
1694 
1695  /* Fetch the pg_am tuple of the index' access method */
1696  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1697  if (!HeapTupleIsValid(ht_am))
1698  elog(ERROR, "cache lookup failed for access method %u",
1699  idxrelrec->relam);
1700  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1701 
1702  /* Extract indcollation from the pg_index tuple */
1703  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1704  Anum_pg_index_indcollation);
1705  indcollation = (oidvector *) DatumGetPointer(datum);
1706 
1707  /* Extract indclass from the pg_index tuple */
1708  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
1709  indclass = (oidvector *) DatumGetPointer(datum);
1710 
1711  /* Begin building the IndexStmt */
1713  index->relation = heapRel;
1714  index->accessMethod = pstrdup(NameStr(amrec->amname));
1715  if (OidIsValid(idxrelrec->reltablespace))
1716  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1717  else
1718  index->tableSpace = NULL;
1719  index->excludeOpNames = NIL;
1720  index->idxcomment = NULL;
1721  index->indexOid = InvalidOid;
1722  index->oldNumber = InvalidRelFileNumber;
1723  index->oldCreateSubid = InvalidSubTransactionId;
1724  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1725  index->unique = idxrec->indisunique;
1726  index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1727  index->primary = idxrec->indisprimary;
1728  index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
1729  index->transformed = true; /* don't need transformIndexStmt */
1730  index->concurrent = false;
1731  index->if_not_exists = false;
1732  index->reset_default_tblspc = false;
1733 
1734  /*
1735  * We don't try to preserve the name of the source index; instead, just
1736  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1737  * the name, we'd get duplicate-relation-name failures unless the source
1738  * table was in a different schema.)
1739  */
1740  index->idxname = NULL;
1741 
1742  /*
1743  * If the index is marked PRIMARY or has an exclusion condition, it's
1744  * certainly from a constraint; else, if it's not marked UNIQUE, it
1745  * certainly isn't. If it is or might be from a constraint, we have to
1746  * fetch the pg_constraint record.
1747  */
1748  if (index->primary || index->unique || idxrec->indisexclusion)
1749  {
1750  Oid constraintId = get_index_constraint(source_relid);
1751 
1752  if (OidIsValid(constraintId))
1753  {
1754  HeapTuple ht_constr;
1755  Form_pg_constraint conrec;
1756 
1757  if (constraintOid)
1758  *constraintOid = constraintId;
1759 
1760  ht_constr = SearchSysCache1(CONSTROID,
1761  ObjectIdGetDatum(constraintId));
1762  if (!HeapTupleIsValid(ht_constr))
1763  elog(ERROR, "cache lookup failed for constraint %u",
1764  constraintId);
1765  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1766 
1767  index->isconstraint = true;
1768  index->deferrable = conrec->condeferrable;
1769  index->initdeferred = conrec->condeferred;
1770 
1771  /* If it's an exclusion constraint, we need the operator names */
1772  if (idxrec->indisexclusion)
1773  {
1774  Datum *elems;
1775  int nElems;
1776  int i;
1777 
1778  Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
1779  (index->iswithoutoverlaps &&
1780  (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
1781  /* Extract operator OIDs from the pg_constraint tuple */
1782  datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
1783  Anum_pg_constraint_conexclop);
1784  deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1785 
1786  for (i = 0; i < nElems; i++)
1787  {
1788  Oid operid = DatumGetObjectId(elems[i]);
1789  HeapTuple opertup;
1790  Form_pg_operator operform;
1791  char *oprname;
1792  char *nspname;
1793  List *namelist;
1794 
1795  opertup = SearchSysCache1(OPEROID,
1796  ObjectIdGetDatum(operid));
1797  if (!HeapTupleIsValid(opertup))
1798  elog(ERROR, "cache lookup failed for operator %u",
1799  operid);
1800  operform = (Form_pg_operator) GETSTRUCT(opertup);
1801  oprname = pstrdup(NameStr(operform->oprname));
1802  /* For simplicity we always schema-qualify the op name */
1803  nspname = get_namespace_name(operform->oprnamespace);
1804  namelist = list_make2(makeString(nspname),
1805  makeString(oprname));
1806  index->excludeOpNames = lappend(index->excludeOpNames,
1807  namelist);
1808  ReleaseSysCache(opertup);
1809  }
1810  }
1811 
1812  ReleaseSysCache(ht_constr);
1813  }
1814  else
1815  index->isconstraint = false;
1816  }
1817  else
1818  index->isconstraint = false;
1819 
1820  /* Get the index expressions, if any */
1821  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1822  Anum_pg_index_indexprs, &isnull);
1823  if (!isnull)
1824  {
1825  char *exprsString;
1826 
1827  exprsString = TextDatumGetCString(datum);
1828  indexprs = (List *) stringToNode(exprsString);
1829  }
1830  else
1831  indexprs = NIL;
1832 
1833  /* Build the list of IndexElem */
1834  index->indexParams = NIL;
1835  index->indexIncludingParams = NIL;
1836 
1837  indexpr_item = list_head(indexprs);
1838  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1839  {
1840  IndexElem *iparam;
1841  AttrNumber attnum = idxrec->indkey.values[keyno];
1843  keyno);
1844  int16 opt = source_idx->rd_indoption[keyno];
1845 
1846  iparam = makeNode(IndexElem);
1847 
1849  {
1850  /* Simple index column */
1851  char *attname;
1852 
1853  attname = get_attname(indrelid, attnum, false);
1854  keycoltype = get_atttype(indrelid, attnum);
1855 
1856  iparam->name = attname;
1857  iparam->expr = NULL;
1858  }
1859  else
1860  {
1861  /* Expressional index */
1862  Node *indexkey;
1863  bool found_whole_row;
1864 
1865  if (indexpr_item == NULL)
1866  elog(ERROR, "too few entries in indexprs list");
1867  indexkey = (Node *) lfirst(indexpr_item);
1868  indexpr_item = lnext(indexprs, indexpr_item);
1869 
1870  /* Adjust Vars to match new table's column numbering */
1871  indexkey = map_variable_attnos(indexkey,
1872  1, 0,
1873  attmap,
1874  InvalidOid, &found_whole_row);
1875 
1876  /* As in expandTableLikeClause, reject whole-row variables */
1877  if (found_whole_row)
1878  ereport(ERROR,
1879  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1880  errmsg("cannot convert whole-row table reference"),
1881  errdetail("Index \"%s\" contains a whole-row table reference.",
1882  RelationGetRelationName(source_idx))));
1883 
1884  iparam->name = NULL;
1885  iparam->expr = indexkey;
1886 
1887  keycoltype = exprType(indexkey);
1888  }
1889 
1890  /* Copy the original index column name */
1891  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1892 
1893  /* Add the collation name, if non-default */
1894  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1895 
1896  /* Add the operator class name, if non-default */
1897  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1898  iparam->opclassopts =
1899  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1900 
1901  iparam->ordering = SORTBY_DEFAULT;
1903 
1904  /* Adjust options if necessary */
1905  if (source_idx->rd_indam->amcanorder)
1906  {
1907  /*
1908  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1909  * set non-default settings unnecessarily, though, so as to
1910  * improve the chance of recognizing equivalence to constraint
1911  * indexes.
1912  */
1913  if (opt & INDOPTION_DESC)
1914  {
1915  iparam->ordering = SORTBY_DESC;
1916  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1918  }
1919  else
1920  {
1921  if (opt & INDOPTION_NULLS_FIRST)
1923  }
1924  }
1925 
1926  index->indexParams = lappend(index->indexParams, iparam);
1927  }
1928 
1929  /* Handle included columns separately */
1930  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1931  {
1932  IndexElem *iparam;
1933  AttrNumber attnum = idxrec->indkey.values[keyno];
1935  keyno);
1936 
1937  iparam = makeNode(IndexElem);
1938 
1940  {
1941  /* Simple index column */
1942  char *attname;
1943 
1944  attname = get_attname(indrelid, attnum, false);
1945 
1946  iparam->name = attname;
1947  iparam->expr = NULL;
1948  }
1949  else
1950  ereport(ERROR,
1951  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1952  errmsg("expressions are not supported in included columns")));
1953 
1954  /* Copy the original index column name */
1955  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1956 
1957  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1958  }
1959  /* Copy reloptions if any */
1960  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1961  Anum_pg_class_reloptions, &isnull);
1962  if (!isnull)
1963  index->options = untransformRelOptions(datum);
1964 
1965  /* If it's a partial index, decompile and append the predicate */
1966  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1967  Anum_pg_index_indpred, &isnull);
1968  if (!isnull)
1969  {
1970  char *pred_str;
1971  Node *pred_tree;
1972  bool found_whole_row;
1973 
1974  /* Convert text string to node tree */
1975  pred_str = TextDatumGetCString(datum);
1976  pred_tree = (Node *) stringToNode(pred_str);
1977 
1978  /* Adjust Vars to match new table's column numbering */
1979  pred_tree = map_variable_attnos(pred_tree,
1980  1, 0,
1981  attmap,
1982  InvalidOid, &found_whole_row);
1983 
1984  /* As in expandTableLikeClause, reject whole-row variables */
1985  if (found_whole_row)
1986  ereport(ERROR,
1987  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1988  errmsg("cannot convert whole-row table reference"),
1989  errdetail("Index \"%s\" contains a whole-row table reference.",
1990  RelationGetRelationName(source_idx))));
1991 
1992  index->whereClause = pred_tree;
1993  }
1994 
1995  /* Clean up */
1996  ReleaseSysCache(ht_idxrel);
1997  ReleaseSysCache(ht_am);
1998 
1999  return index;
2000 }
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3679
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1478
signed short int16
Definition: c.h:482
#define InvalidSubTransactionId
Definition: c.h:647
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3321
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:969
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:912
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
static List * get_collation(Oid collation, Oid actual_datatype)
static List * get_opclass(Oid opclass, Oid actual_datatype)
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
NameData attname
Definition: pg_attribute.h:41
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_constraint * Form_pg_constraint
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:968
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define list_make2(x1, x2)
Definition: pg_list.h:214
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1333
#define InvalidRelFileNumber
Definition: relpath.h:26
bool amcanorder
Definition: amapi.h:223
Node * expr
Definition: parsenodes.h:771
SortByDir ordering
Definition: parsenodes.h:776
List * opclassopts
Definition: parsenodes.h:775
char * indexcolname
Definition: parsenodes.h:772
SortByNulls nulls_ordering
Definition: parsenodes.h:777
List * opclass
Definition: parsenodes.h:774
List * collation
Definition: parsenodes.h:773
struct IndexAmRoutine * rd_indam
Definition: rel.h:205
struct HeapTupleData * rd_indextuple
Definition: rel.h:193
int16 * rd_indoption
Definition: rel.h:210
Definition: type.h:95
Definition: c.h:715
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:722

References IndexAmRoutine::amcanorder, Assert(), attname, attnum, AttributeNumberIsValid, IndexElem::collation, DatumGetArrayTypeP, DatumGetObjectId(), DatumGetPointer(), deconstruct_array_builtin(), elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, IndexElem::expr, exprType(), get_attname(), get_attoptions(), get_atttype(), get_collation(), get_index_constraint(), get_namespace_name(), get_opclass(), get_tablespace_name(), GETSTRUCT, HeapTupleIsValid, i, if(), IndexElem::indexcolname, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum(), OidIsValid, IndexElem::opclass, IndexElem::opclassopts, IndexElem::ordering, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TupleDescAttr, untransformRelOptions(), and oidvector::values.

Referenced by AttachPartitionEnsureIndexes(), DefineRelation(), and expandTableLikeClause().

◆ generateSerialExtraStmts()

static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
bool  col_exists,
char **  snamespace_p,
char **  sname_p 
)
static

Definition at line 370 of file parse_utilcmd.c.

374 {
375  ListCell *option;
376  DefElem *nameEl = NULL;
377  Oid snamespaceid;
378  char *snamespace;
379  char *sname;
380  CreateSeqStmt *seqstmt;
381  AlterSeqStmt *altseqstmt;
382  List *attnamelist;
383  int nameEl_idx = -1;
384 
385  /* Make a copy of this as we may end up modifying it in the code below */
386  seqoptions = list_copy(seqoptions);
387 
388  /*
389  * Determine namespace and name to use for the sequence.
390  *
391  * First, check if a sequence name was passed in as an option. This is
392  * used by pg_dump. Else, generate a name.
393  *
394  * Although we use ChooseRelationName, it's not guaranteed that the
395  * selected sequence name won't conflict; given sufficiently long field
396  * names, two different serial columns in the same table could be assigned
397  * the same sequence name, and we'd not notice since we aren't creating
398  * the sequence quite yet. In practice this seems quite unlikely to be a
399  * problem, especially since few people would need two serial columns in
400  * one table.
401  */
402  foreach(option, seqoptions)
403  {
404  DefElem *defel = lfirst_node(DefElem, option);
405 
406  if (strcmp(defel->defname, "sequence_name") == 0)
407  {
408  if (nameEl)
409  errorConflictingDefElem(defel, cxt->pstate);
410  nameEl = defel;
411  nameEl_idx = foreach_current_index(option);
412  }
413  }
414 
415  if (nameEl)
416  {
418 
419  snamespace = rv->schemaname;
420  if (!snamespace)
421  {
422  /* Given unqualified SEQUENCE NAME, select namespace */
423  if (cxt->rel)
424  snamespaceid = RelationGetNamespace(cxt->rel);
425  else
426  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
427  snamespace = get_namespace_name(snamespaceid);
428  }
429  sname = rv->relname;
430  /* Remove the SEQUENCE NAME item from seqoptions */
431  seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
432  }
433  else
434  {
435  if (cxt->rel)
436  snamespaceid = RelationGetNamespace(cxt->rel);
437  else
438  {
439  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
440  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
441  }
442  snamespace = get_namespace_name(snamespaceid);
443  sname = ChooseRelationName(cxt->relation->relname,
444  column->colname,
445  "seq",
446  snamespaceid,
447  false);
448  }
449 
450  ereport(DEBUG1,
451  (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
452  cxt->stmtType, sname,
453  cxt->relation->relname, column->colname)));
454 
455  /*
456  * Build a CREATE SEQUENCE command to create the sequence object, and add
457  * it to the list of things to be done before this CREATE/ALTER TABLE.
458  */
459  seqstmt = makeNode(CreateSeqStmt);
460  seqstmt->for_identity = for_identity;
461  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
462 
463  /*
464  * Copy the persistence of the table. For CREATE TABLE, we get the
465  * persistence from cxt->relation, which comes from the CreateStmt in
466  * progress. For ALTER TABLE, the parser won't set
467  * cxt->relation->relpersistence, but we have cxt->rel as the existing
468  * table, so we copy the persistence from there.
469  */
470  seqstmt->sequence->relpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
471 
472  seqstmt->options = seqoptions;
473 
474  /*
475  * If a sequence data type was specified, add it to the options. Prepend
476  * to the list rather than append; in case a user supplied their own AS
477  * clause, the "redundant options" error will point to their occurrence,
478  * not our synthetic one.
479  */
480  if (seqtypid)
481  seqstmt->options = lcons(makeDefElem("as",
482  (Node *) makeTypeNameFromOid(seqtypid, -1),
483  -1),
484  seqstmt->options);
485 
486  /*
487  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
488  * the table's owner. The current user might be someone else (perhaps a
489  * superuser, or someone who's only a member of the owning role), but the
490  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
491  * exactly the same owning role.
492  */
493  if (cxt->rel)
494  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
495  else
496  seqstmt->ownerId = InvalidOid;
497 
498  cxt->blist = lappend(cxt->blist, seqstmt);
499 
500  /*
501  * Store the identity sequence name that we decided on. ALTER TABLE ...
502  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
503  * with values from the sequence, while the association of the sequence
504  * with the table is not set until after the ALTER TABLE.
505  */
506  column->identitySequence = seqstmt->sequence;
507 
508  /*
509  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
510  * owned by this column, and add it to the appropriate list of things to
511  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
512  * COLUMN, it must be done after the statement because we don't know the
513  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
514  * we can do the marking immediately, which improves some ALTER TABLE
515  * behaviors.
516  */
517  altseqstmt = makeNode(AlterSeqStmt);
518  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
519  attnamelist = list_make3(makeString(snamespace),
520  makeString(cxt->relation->relname),
521  makeString(column->colname));
522  altseqstmt->options = list_make1(makeDefElem("owned_by",
523  (Node *) attnamelist, -1));
524  altseqstmt->for_identity = for_identity;
525 
526  if (col_exists)
527  cxt->blist = lappend(cxt->blist, altseqstmt);
528  else
529  cxt->alist = lappend(cxt->alist, altseqstmt);
530 
531  if (snamespace_p)
532  *snamespace_p = snamespace;
533  if (sname_p)
534  *sname_p = sname;
535 }
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1162
#define DEBUG1
Definition: elog.h:30
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2606
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:767
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:549
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:475
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:831
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:639
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3539
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define RelationGetNamespace(relation)
Definition: rel.h:545
List * options
Definition: parsenodes.h:2971
RangeVar * sequence
Definition: parsenodes.h:2970
bool for_identity
Definition: parsenodes.h:2972
RangeVar * identitySequence
Definition: parsenodes.h:725
char * colname
Definition: parsenodes.h:713
List * options
Definition: parsenodes.h:2961
RangeVar * sequence
Definition: parsenodes.h:2960
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parse_utilcmd.c:77
ParseState * pstate
Definition: parse_utilcmd.c:75
char * defname
Definition: parsenodes.h:802
Node * arg
Definition: parsenodes.h:803
char relpersistence
Definition: primnodes.h:88

References CreateStmtContext::alist, DefElem::arg, CreateStmtContext::blist, castNode, ChooseRelationName(), ColumnDef::colname, DEBUG1, DefElem::defname, ereport, errmsg_internal(), errorConflictingDefElem(), CreateSeqStmt::for_identity, AlterSeqStmt::for_identity, foreach_current_index, get_namespace_name(), ColumnDef::identitySequence, InvalidOid, lappend(), lcons(), lfirst_node, list_copy(), list_delete_nth_cell(), list_make1, list_make3, makeDefElem(), makeNode, makeRangeVar(), makeRangeVarFromNameList(), makeString(), makeTypeNameFromOid(), CreateSeqStmt::options, AlterSeqStmt::options, CreateSeqStmt::ownerId, CreateStmtContext::pstate, RangeVarAdjustRelationPersistence(), RangeVarGetCreationNamespace(), RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetNamespace, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, CreateSeqStmt::sequence, AlterSeqStmt::sequence, and CreateStmtContext::stmtType.

Referenced by transformAlterTableStmt(), transformColumnDefinition(), and transformTableLikeClause().

◆ get_collation()

static List * get_collation ( Oid  collation,
Oid  actual_datatype 
)
static

Definition at line 2126 of file parse_utilcmd.c.

2127 {
2128  List *result;
2129  HeapTuple ht_coll;
2130  Form_pg_collation coll_rec;
2131  char *nsp_name;
2132  char *coll_name;
2133 
2134  if (!OidIsValid(collation))
2135  return NIL; /* easy case */
2136  if (collation == get_typcollation(actual_datatype))
2137  return NIL; /* just let it default */
2138 
2139  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2140  if (!HeapTupleIsValid(ht_coll))
2141  elog(ERROR, "cache lookup failed for collation %u", collation);
2142  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
2143 
2144  /* For simplicity, we always schema-qualify the name */
2145  nsp_name = get_namespace_name(coll_rec->collnamespace);
2146  coll_name = pstrdup(NameStr(coll_rec->collname));
2147  result = list_make2(makeString(nsp_name), makeString(coll_name));
2148 
2149  ReleaseSysCache(ht_coll);
2150  return result;
2151 }
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3011
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58

References elog(), ERROR, get_namespace_name(), get_typcollation(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum(), OidIsValid, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

◆ get_opclass()

static List * get_opclass ( Oid  opclass,
Oid  actual_datatype 
)
static

Definition at line 2160 of file parse_utilcmd.c.

2161 {
2162  List *result = NIL;
2163  HeapTuple ht_opc;
2164  Form_pg_opclass opc_rec;
2165 
2166  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2167  if (!HeapTupleIsValid(ht_opc))
2168  elog(ERROR, "cache lookup failed for opclass %u", opclass);
2169  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2170 
2171  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2172  {
2173  /* For simplicity, we always schema-qualify the name */
2174  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2175  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2176 
2177  result = list_make2(makeString(nsp_name), makeString(opc_name));
2178  }
2179 
2180  ReleaseSysCache(ht_opc);
2181  return result;
2182 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2334
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

References elog(), ERROR, get_namespace_name(), GetDefaultOpClass(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

◆ setSchemaName()

static void setSchemaName ( const char *  context_schema,
char **  stmt_schema_name 
)
static

Definition at line 4072 of file parse_utilcmd.c.

4073 {
4074  if (*stmt_schema_name == NULL)
4075  *stmt_schema_name = unconstify(char *, context_schema);
4076  else if (strcmp(context_schema, *stmt_schema_name) != 0)
4077  ereport(ERROR,
4078  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
4079  errmsg("CREATE specifies a schema (%s) "
4080  "different from the one being created (%s)",
4081  *stmt_schema_name, context_schema)));
4082 }
#define unconstify(underlying_type, expr)
Definition: c.h:1234

References ereport, errcode(), errmsg(), ERROR, and unconstify.

Referenced by transformCreateSchemaStmtElements().

◆ transformAlterTableStmt()

AlterTableStmt* transformAlterTableStmt ( Oid  relid,
AlterTableStmt stmt,
const char *  queryString,
List **  beforeStmts,
List **  afterStmts 
)

Definition at line 3429 of file parse_utilcmd.c.

3432 {
3433  Relation rel;
3434  TupleDesc tupdesc;
3435  ParseState *pstate;
3436  CreateStmtContext cxt;
3437  List *save_alist;
3438  ListCell *lcmd,
3439  *l;
3440  List *newcmds = NIL;
3441  bool skipValidation = true;
3442  AlterTableCmd *newcmd;
3443  ParseNamespaceItem *nsitem;
3444 
3445  /* Caller is responsible for locking the relation */
3446  rel = relation_open(relid, NoLock);
3447  tupdesc = RelationGetDescr(rel);
3448 
3449  /* Set up pstate */
3450  pstate = make_parsestate(NULL);
3451  pstate->p_sourcetext = queryString;
3452  nsitem = addRangeTableEntryForRelation(pstate,
3453  rel,
3455  NULL,
3456  false,
3457  true);
3458  addNSItemToQuery(pstate, nsitem, false, true, true);
3459 
3460  /* Set up CreateStmtContext */
3461  cxt.pstate = pstate;
3462  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3463  {
3464  cxt.stmtType = "ALTER FOREIGN TABLE";
3465  cxt.isforeign = true;
3466  }
3467  else
3468  {
3469  cxt.stmtType = "ALTER TABLE";
3470  cxt.isforeign = false;
3471  }
3472  cxt.relation = stmt->relation;
3473  cxt.rel = rel;
3474  cxt.inhRelations = NIL;
3475  cxt.isalter = true;
3476  cxt.columns = NIL;
3477  cxt.ckconstraints = NIL;
3478  cxt.nnconstraints = NIL;
3479  cxt.fkconstraints = NIL;
3480  cxt.ixconstraints = NIL;
3481  cxt.likeclauses = NIL;
3482  cxt.extstats = NIL;
3483  cxt.blist = NIL;
3484  cxt.alist = NIL;
3485  cxt.pkey = NULL;
3486  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3487  cxt.partbound = NULL;
3488  cxt.ofType = false;
3489 
3490  /*
3491  * Transform ALTER subcommands that need it (most don't). These largely
3492  * re-use code from CREATE TABLE.
3493  */
3494  foreach(lcmd, stmt->cmds)
3495  {
3496  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3497 
3498  switch (cmd->subtype)
3499  {
3500  case AT_AddColumn:
3501  {
3502  ColumnDef *def = castNode(ColumnDef, cmd->def);
3503 
3504  transformColumnDefinition(&cxt, def);
3505 
3506  /*
3507  * If the column has a non-null default, we can't skip
3508  * validation of foreign keys.
3509  */
3510  if (def->raw_default != NULL)
3511  skipValidation = false;
3512 
3513  /*
3514  * All constraints are processed in other ways. Remove the
3515  * original list
3516  */
3517  def->constraints = NIL;
3518 
3519  newcmds = lappend(newcmds, cmd);
3520  break;
3521  }
3522 
3523  case AT_AddConstraint:
3524 
3525  /*
3526  * The original AddConstraint cmd node doesn't go to newcmds
3527  */
3528  if (IsA(cmd->def, Constraint))
3529  {
3530  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3531  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3532  skipValidation = false;
3533  }
3534  else
3535  elog(ERROR, "unrecognized node type: %d",
3536  (int) nodeTag(cmd->def));
3537  break;
3538 
3539  case AT_AlterColumnType:
3540  {
3541  ColumnDef *def = castNode(ColumnDef, cmd->def);
3543 
3544  /*
3545  * For ALTER COLUMN TYPE, transform the USING clause if
3546  * one was specified.
3547  */
3548  if (def->raw_default)
3549  {
3550  def->cooked_default =
3551  transformExpr(pstate, def->raw_default,
3553  }
3554 
3555  /*
3556  * For identity column, create ALTER SEQUENCE command to
3557  * change the data type of the sequence.
3558  */
3559  attnum = get_attnum(relid, cmd->name);
3560  if (attnum == InvalidAttrNumber)
3561  ereport(ERROR,
3562  (errcode(ERRCODE_UNDEFINED_COLUMN),
3563  errmsg("column \"%s\" of relation \"%s\" does not exist",
3564  cmd->name, RelationGetRelationName(rel))));
3565 
3566  if (attnum > 0 &&
3567  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3568  {
3569  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3570  Oid typeOid = typenameTypeId(pstate, def->typeName);
3571  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3572 
3573  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3574  get_rel_name(seq_relid),
3575  -1);
3576  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3577  altseqstmt->for_identity = true;
3578  cxt.blist = lappend(cxt.blist, altseqstmt);
3579  }
3580 
3581  newcmds = lappend(newcmds, cmd);
3582  break;
3583  }
3584 
3585  case AT_AddIdentity:
3586  {
3587  Constraint *def = castNode(Constraint, cmd->def);
3588  ColumnDef *newdef = makeNode(ColumnDef);
3590 
3591  newdef->colname = cmd->name;
3592  newdef->identity = def->generated_when;
3593  cmd->def = (Node *) newdef;
3594 
3595  attnum = get_attnum(relid, cmd->name);
3596  if (attnum == InvalidAttrNumber)
3597  ereport(ERROR,
3598  (errcode(ERRCODE_UNDEFINED_COLUMN),
3599  errmsg("column \"%s\" of relation \"%s\" does not exist",
3600  cmd->name, RelationGetRelationName(rel))));
3601 
3602  generateSerialExtraStmts(&cxt, newdef,
3603  get_atttype(relid, attnum),
3604  def->options, true, true,
3605  NULL, NULL);
3606 
3607  newcmds = lappend(newcmds, cmd);
3608  break;
3609  }
3610 
3611  case AT_SetIdentity:
3612  {
3613  /*
3614  * Create an ALTER SEQUENCE statement for the internal
3615  * sequence of the identity column.
3616  */
3617  ListCell *lc;
3618  List *newseqopts = NIL;
3619  List *newdef = NIL;
3621  Oid seq_relid;
3622 
3623  /*
3624  * Split options into those handled by ALTER SEQUENCE and
3625  * those for ALTER TABLE proper.
3626  */
3627  foreach(lc, castNode(List, cmd->def))
3628  {
3629  DefElem *def = lfirst_node(DefElem, lc);
3630 
3631  if (strcmp(def->defname, "generated") == 0)
3632  newdef = lappend(newdef, def);
3633  else
3634  newseqopts = lappend(newseqopts, def);
3635  }
3636 
3637  attnum = get_attnum(relid, cmd->name);
3638  if (attnum == InvalidAttrNumber)
3639  ereport(ERROR,
3640  (errcode(ERRCODE_UNDEFINED_COLUMN),
3641  errmsg("column \"%s\" of relation \"%s\" does not exist",
3642  cmd->name, RelationGetRelationName(rel))));
3643 
3644  seq_relid = getIdentitySequence(relid, attnum, true);
3645 
3646  if (seq_relid)
3647  {
3648  AlterSeqStmt *seqstmt;
3649 
3650  seqstmt = makeNode(AlterSeqStmt);
3652  get_rel_name(seq_relid), -1);
3653  seqstmt->options = newseqopts;
3654  seqstmt->for_identity = true;
3655  seqstmt->missing_ok = false;
3656 
3657  cxt.blist = lappend(cxt.blist, seqstmt);
3658  }
3659 
3660  /*
3661  * If column was not an identity column, we just let the
3662  * ALTER TABLE command error out later. (There are cases
3663  * this fails to cover, but we'll need to restructure
3664  * where creation of the sequence dependency linkage
3665  * happens before we can fix it.)
3666  */
3667 
3668  cmd->def = (Node *) newdef;
3669  newcmds = lappend(newcmds, cmd);
3670  break;
3671  }
3672 
3673  case AT_AttachPartition:
3674  case AT_DetachPartition:
3675  {
3676  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3677 
3678  transformPartitionCmd(&cxt, partcmd);
3679  /* assign transformed value of the partition bound */
3680  partcmd->bound = cxt.partbound;
3681  }
3682 
3683  newcmds = lappend(newcmds, cmd);
3684  break;
3685 
3686  default:
3687 
3688  /*
3689  * Currently, we shouldn't actually get here for subcommand
3690  * types that don't require transformation; but if we do, just
3691  * emit them unchanged.
3692  */
3693  newcmds = lappend(newcmds, cmd);
3694  break;
3695  }
3696  }
3697 
3698  /*
3699  * Transfer anything we already have in cxt.alist into save_alist, to keep
3700  * it separate from the output of transformIndexConstraints.
3701  */
3702  save_alist = cxt.alist;
3703  cxt.alist = NIL;
3704 
3705  /* Postprocess constraints */
3707  transformFKConstraints(&cxt, skipValidation, true);
3708  transformCheckConstraints(&cxt, false);
3709 
3710  /*
3711  * Push any index-creation commands into the ALTER, so that they can be
3712  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3713  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3714  * subcommand has already been through transformIndexStmt.
3715  */
3716  foreach(l, cxt.alist)
3717  {
3718  Node *istmt = (Node *) lfirst(l);
3719 
3720  /*
3721  * We assume here that cxt.alist contains only IndexStmts and possibly
3722  * AT_SetAttNotNull statements generated from primary key constraints.
3723  * We absorb the subcommands of the latter directly.
3724  */
3725  if (IsA(istmt, IndexStmt))
3726  {
3727  IndexStmt *idxstmt = (IndexStmt *) istmt;
3728 
3729  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3730  newcmd = makeNode(AlterTableCmd);
3732  newcmd->def = (Node *) idxstmt;
3733  newcmds = lappend(newcmds, newcmd);
3734  }
3735  else if (IsA(istmt, AlterTableStmt))
3736  {
3737  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3738 
3739  newcmds = list_concat(newcmds, alterstmt->cmds);
3740  }
3741  else
3742  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3743  }
3744  cxt.alist = NIL;
3745 
3746  /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3747  foreach(l, cxt.ckconstraints)
3748  {
3749  newcmd = makeNode(AlterTableCmd);
3750  newcmd->subtype = AT_AddConstraint;
3751  newcmd->def = (Node *) lfirst_node(Constraint, l);
3752  newcmds = lappend(newcmds, newcmd);
3753  }
3754  foreach(l, cxt.nnconstraints)
3755  {
3756  newcmd = makeNode(AlterTableCmd);
3757  newcmd->subtype = AT_AddConstraint;
3758  newcmd->def = (Node *) lfirst_node(Constraint, l);
3759  newcmds = lappend(newcmds, newcmd);
3760  }
3761  foreach(l, cxt.fkconstraints)
3762  {
3763  newcmd = makeNode(AlterTableCmd);
3764  newcmd->subtype = AT_AddConstraint;
3765  newcmd->def = (Node *) lfirst_node(Constraint, l);
3766  newcmds = lappend(newcmds, newcmd);
3767  }
3768 
3769  /* Append extended statistics objects */
3771 
3772  /* Close rel */
3773  relation_close(rel, NoLock);
3774 
3775  /*
3776  * Output results.
3777  */
3778  stmt->cmds = newcmds;
3779 
3780  *beforeStmts = cxt.blist;
3781  *afterStmts = list_concat(cxt.alist, save_alist);
3782 
3783  return stmt;
3784 }
#define InvalidAttrNumber
Definition: attnum.h:23
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:857
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1929
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1905
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:110
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformExtendedStatistics(CreateStmtContext *cxt)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ AT_AddIndexConstraint
Definition: parsenodes.h:2210
@ AT_SetIdentity
Definition: parsenodes.h:2252
@ AT_AddIndex
Definition: parsenodes.h:2203
@ AT_AddIdentity
Definition: parsenodes.h:2251
@ AT_AlterColumnType
Definition: parsenodes.h:2213
@ AT_DetachPartition
Definition: parsenodes.h:2249
@ AT_AttachPartition
Definition: parsenodes.h:2248
@ AT_AddColumn
Definition: parsenodes.h:2188
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:944
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
char identity
Definition: parsenodes.h:724
List * constraints
Definition: parsenodes.h:730
Node * cooked_default
Definition: parsenodes.h:723
TypeName * typeName
Definition: parsenodes.h:714
Node * raw_default
Definition: parsenodes.h:722
List * options
Definition: parsenodes.h:2592
char generated_when
Definition: parsenodes.h:2581
IndexStmt * pkey
Definition: parse_utilcmd.c:93
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:95
Oid indexOid
Definition: parsenodes.h:3202
const char * p_sourcetext
Definition: parse_node.h:192
PartitionBoundSpec * bound
Definition: parsenodes.h:934

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefElem::defname, elog(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, CreateStmtContext::nnconstraints, 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, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, stmt, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2853 of file parse_utilcmd.c.

2854 {
2855  ListCell *ckclist;
2856 
2857  if (cxt->ckconstraints == NIL)
2858  return;
2859 
2860  /*
2861  * If creating a new table (but not a foreign table), we can safely skip
2862  * validation of check constraints, and nonetheless mark them valid. (This
2863  * will override any user-supplied NOT VALID flag.)
2864  */
2865  if (skipValidation)
2866  {
2867  foreach(ckclist, cxt->ckconstraints)
2868  {
2869  Constraint *constraint = (Constraint *) lfirst(ckclist);
2870 
2871  constraint->skip_validation = true;
2872  constraint->initially_valid = true;
2873  }
2874  }
2875 }

References CreateStmtContext::ckconstraints, Constraint::initially_valid, lfirst, NIL, and Constraint::skip_validation.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 543 of file parse_utilcmd.c.

544 {
545  bool is_serial;
546  bool saw_nullable;
547  bool saw_default;
548  bool saw_identity;
549  bool saw_generated;
550  bool need_notnull = false;
551  ListCell *clist;
552 
553  cxt->columns = lappend(cxt->columns, column);
554 
555  /* Check for SERIAL pseudo-types */
556  is_serial = false;
557  if (column->typeName
558  && list_length(column->typeName->names) == 1
559  && !column->typeName->pct_type)
560  {
561  char *typname = strVal(linitial(column->typeName->names));
562 
563  if (strcmp(typname, "smallserial") == 0 ||
564  strcmp(typname, "serial2") == 0)
565  {
566  is_serial = true;
567  column->typeName->names = NIL;
568  column->typeName->typeOid = INT2OID;
569  }
570  else if (strcmp(typname, "serial") == 0 ||
571  strcmp(typname, "serial4") == 0)
572  {
573  is_serial = true;
574  column->typeName->names = NIL;
575  column->typeName->typeOid = INT4OID;
576  }
577  else if (strcmp(typname, "bigserial") == 0 ||
578  strcmp(typname, "serial8") == 0)
579  {
580  is_serial = true;
581  column->typeName->names = NIL;
582  column->typeName->typeOid = INT8OID;
583  }
584 
585  /*
586  * We have to reject "serial[]" explicitly, because once we've set
587  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
588  * special coding for serial(typmod) though.
589  */
590  if (is_serial && column->typeName->arrayBounds != NIL)
591  ereport(ERROR,
592  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
593  errmsg("array of serial is not implemented"),
595  column->typeName->location)));
596  }
597 
598  /* Do necessary work on the column type declaration */
599  if (column->typeName)
600  transformColumnType(cxt, column);
601 
602  /* Special actions for SERIAL pseudo-types */
603  if (is_serial)
604  {
605  char *snamespace;
606  char *sname;
607  char *qstring;
608  A_Const *snamenode;
609  TypeCast *castnode;
610  FuncCall *funccallnode;
611  Constraint *constraint;
612 
613  generateSerialExtraStmts(cxt, column,
614  column->typeName->typeOid, NIL,
615  false, false,
616  &snamespace, &sname);
617 
618  /*
619  * Create appropriate constraints for SERIAL. We do this in full,
620  * rather than shortcutting, so that we will detect any conflicting
621  * constraints the user wrote (like a different DEFAULT).
622  *
623  * Create an expression tree representing the function call
624  * nextval('sequencename'). We cannot reduce the raw tree to cooked
625  * form until after the sequence is created, but there's no need to do
626  * so.
627  */
628  qstring = quote_qualified_identifier(snamespace, sname);
629  snamenode = makeNode(A_Const);
630  snamenode->val.node.type = T_String;
631  snamenode->val.sval.sval = qstring;
632  snamenode->location = -1;
633  castnode = makeNode(TypeCast);
634  castnode->typeName = SystemTypeName("regclass");
635  castnode->arg = (Node *) snamenode;
636  castnode->location = -1;
637  funccallnode = makeFuncCall(SystemFuncName("nextval"),
638  list_make1(castnode),
640  -1);
641  constraint = makeNode(Constraint);
642  constraint->contype = CONSTR_DEFAULT;
643  constraint->location = -1;
644  constraint->raw_expr = (Node *) funccallnode;
645  constraint->cooked_expr = NULL;
646  column->constraints = lappend(column->constraints, constraint);
647 
648  /* have a not-null constraint added later */
649  need_notnull = true;
650  }
651 
652  /* Process column constraints, if any... */
654 
655  saw_nullable = false;
656  saw_default = false;
657  saw_identity = false;
658  saw_generated = false;
659 
660  foreach(clist, column->constraints)
661  {
662  Constraint *constraint = lfirst_node(Constraint, clist);
663 
664  switch (constraint->contype)
665  {
666  case CONSTR_NULL:
667  if ((saw_nullable && column->is_not_null) || need_notnull)
668  ereport(ERROR,
669  (errcode(ERRCODE_SYNTAX_ERROR),
670  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
671  column->colname, cxt->relation->relname),
673  constraint->location)));
674  column->is_not_null = false;
675  saw_nullable = true;
676  break;
677 
678  case CONSTR_NOTNULL:
679 
680  /*
681  * Disallow conflicting [NOT] NULL markings
682  */
683  if (saw_nullable && !column->is_not_null)
684  ereport(ERROR,
685  (errcode(ERRCODE_SYNTAX_ERROR),
686  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
687  column->colname, cxt->relation->relname),
689  constraint->location)));
690  /* Ignore redundant NOT NULL markings */
691 
692  /*
693  * If this is the first time we see this column being marked
694  * not null, add the constraint entry; and get rid of any
695  * previous markings to mark the column NOT NULL.
696  */
697  if (!column->is_not_null)
698  {
699  column->is_not_null = true;
700  saw_nullable = true;
701 
702  constraint->keys = list_make1(makeString(column->colname));
703  cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
704 
705  /* Don't need this anymore, if we had it */
706  need_notnull = false;
707  }
708 
709  break;
710 
711  case CONSTR_DEFAULT:
712  if (saw_default)
713  ereport(ERROR,
714  (errcode(ERRCODE_SYNTAX_ERROR),
715  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
716  column->colname, cxt->relation->relname),
718  constraint->location)));
719  column->raw_default = constraint->raw_expr;
720  Assert(constraint->cooked_expr == NULL);
721  saw_default = true;
722  break;
723 
724  case CONSTR_IDENTITY:
725  {
726  Type ctype;
727  Oid typeOid;
728 
729  if (cxt->ofType)
730  ereport(ERROR,
731  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
732  errmsg("identity columns are not supported on typed tables")));
733  if (cxt->partbound)
734  ereport(ERROR,
735  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
736  errmsg("identity columns are not supported on partitions")));
737 
738  ctype = typenameType(cxt->pstate, column->typeName, NULL);
739  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
740  ReleaseSysCache(ctype);
741 
742  if (saw_identity)
743  ereport(ERROR,
744  (errcode(ERRCODE_SYNTAX_ERROR),
745  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
746  column->colname, cxt->relation->relname),
748  constraint->location)));
749 
750  generateSerialExtraStmts(cxt, column,
751  typeOid, constraint->options,
752  true, false,
753  NULL, NULL);
754 
755  column->identity = constraint->generated_when;
756  saw_identity = true;
757 
758  /*
759  * Identity columns are always NOT NULL, but we may have a
760  * constraint already.
761  */
762  if (!saw_nullable)
763  need_notnull = true;
764  else if (!column->is_not_null)
765  ereport(ERROR,
766  (errcode(ERRCODE_SYNTAX_ERROR),
767  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
768  column->colname, cxt->relation->relname),
770  constraint->location)));
771  break;
772  }
773 
774  case CONSTR_GENERATED:
775  if (cxt->ofType)
776  ereport(ERROR,
777  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
778  errmsg("generated columns are not supported on typed tables")));
779  if (saw_generated)
780  ereport(ERROR,
781  (errcode(ERRCODE_SYNTAX_ERROR),
782  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
783  column->colname, cxt->relation->relname),
785  constraint->location)));
786  column->generated = ATTRIBUTE_GENERATED_STORED;
787  column->raw_default = constraint->raw_expr;
788  Assert(constraint->cooked_expr == NULL);
789  saw_generated = true;
790  break;
791 
792  case CONSTR_CHECK:
793  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
794  break;
795 
796  case CONSTR_PRIMARY:
797  if (cxt->isforeign)
798  ereport(ERROR,
799  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
800  errmsg("primary key constraints are not supported on foreign tables"),
802  constraint->location)));
803  /* FALL THRU */
804 
805  case CONSTR_UNIQUE:
806  if (cxt->isforeign)
807  ereport(ERROR,
808  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
809  errmsg("unique constraints are not supported on foreign tables"),
811  constraint->location)));
812  if (constraint->keys == NIL)
813  constraint->keys = list_make1(makeString(column->colname));
814  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
815  break;
816 
817  case CONSTR_EXCLUSION:
818  /* grammar does not allow EXCLUDE as a column constraint */
819  elog(ERROR, "column exclusion constraints are not supported");
820  break;
821 
822  case CONSTR_FOREIGN:
823  if (cxt->isforeign)
824  ereport(ERROR,
825  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
826  errmsg("foreign key constraints are not supported on foreign tables"),
828  constraint->location)));
829 
830  /*
831  * Fill in the current attribute's name and throw it into the
832  * list of FK constraints to be processed later.
833  */
834  constraint->fk_attrs = list_make1(makeString(column->colname));
835  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
836  break;
837 
842  /* transformConstraintAttrs took care of these */
843  break;
844 
845  default:
846  elog(ERROR, "unrecognized constraint type: %d",
847  constraint->contype);
848  break;
849  }
850 
851  if (saw_default && saw_identity)
852  ereport(ERROR,
853  (errcode(ERRCODE_SYNTAX_ERROR),
854  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
855  column->colname, cxt->relation->relname),
857  constraint->location)));
858 
859  if (saw_default && saw_generated)
860  ereport(ERROR,
861  (errcode(ERRCODE_SYNTAX_ERROR),
862  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
863  column->colname, cxt->relation->relname),
865  constraint->location)));
866 
867  if (saw_identity && saw_generated)
868  ereport(ERROR,
869  (errcode(ERRCODE_SYNTAX_ERROR),
870  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
871  column->colname, cxt->relation->relname),
873  constraint->location)));
874  }
875 
876  /*
877  * If we need a not-null constraint for SERIAL or IDENTITY, and one was
878  * not explicitly specified, add one now.
879  */
880  if (need_notnull && !(saw_nullable && column->is_not_null))
881  {
882  Constraint *notnull;
883 
884  column->is_not_null = true;
885 
886  notnull = makeNode(Constraint);
887  notnull->contype = CONSTR_NOTNULL;
888  notnull->conname = NULL;
889  notnull->deferrable = false;
890  notnull->initdeferred = false;
891  notnull->location = -1;
892  notnull->keys = list_make1(makeString(column->colname));
893  notnull->skip_validation = false;
894  notnull->initially_valid = true;
895 
896  cxt->nnconstraints = lappend(cxt->nnconstraints, notnull);
897  }
898 
899  /*
900  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
901  * per-column foreign data wrapper options to this column after creation.
902  */
903  if (column->fdwoptions != NIL)
904  {
906  AlterTableCmd *cmd;
907 
908  cmd = makeNode(AlterTableCmd);
910  cmd->name = column->colname;
911  cmd->def = (Node *) column->fdwoptions;
912  cmd->behavior = DROP_RESTRICT;
913  cmd->missing_ok = false;
914 
916  stmt->relation = cxt->relation;
917  stmt->cmds = NIL;
918  stmt->objtype = OBJECT_FOREIGN_TABLE;
919  stmt->cmds = lappend(stmt->cmds, cmd);
920 
921  cxt->alist = lappend(cxt->alist, stmt);
922  }
923 }
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:588
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
@ CONSTR_ATTR_DEFERRED
Definition: parsenodes.h:2551
@ CONSTR_IDENTITY
Definition: parsenodes.h:2542
@ CONSTR_ATTR_NOT_DEFERRABLE
Definition: parsenodes.h:2550
@ CONSTR_DEFAULT
Definition: parsenodes.h:2541
@ CONSTR_NOTNULL
Definition: parsenodes.h:2540
@ CONSTR_ATTR_IMMEDIATE
Definition: parsenodes.h:2552
@ CONSTR_NULL
Definition: parsenodes.h:2538
@ CONSTR_GENERATED
Definition: parsenodes.h:2543
@ CONSTR_ATTR_DEFERRABLE
Definition: parsenodes.h:2549
@ DROP_RESTRICT
Definition: parsenodes.h:2169
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:2114
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2214
TypeName * SystemTypeName(char *name)
List * SystemFuncName(char *name)
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial(l)
Definition: pg_list.h:178
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
NameData typname
Definition: pg_type.h:41
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:669
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12059
int location
Definition: parsenodes.h:354
union ValUnion val
Definition: parsenodes.h:352
DropBehavior behavior
Definition: parsenodes.h:2275
bool is_not_null
Definition: parsenodes.h:718
char generated
Definition: parsenodes.h:727
List * fdwoptions
Definition: parsenodes.h:731
bool initdeferred
Definition: parsenodes.h:2573
List * keys
Definition: parsenodes.h:2585
bool deferrable
Definition: parsenodes.h:2572
List * fk_attrs
Definition: parsenodes.h:2602
NodeTag type
Definition: nodes.h:130
char * sval
Definition: value.h:68
TypeName * typeName
Definition: parsenodes.h:364
int location
Definition: parsenodes.h:365
Node * arg
Definition: parsenodes.h:363
Oid typeOid
Definition: parsenodes.h:259
bool pct_type
Definition: parsenodes.h:261
List * names
Definition: parsenodes.h:258
List * arrayBounds
Definition: parsenodes.h:264
int location
Definition: parsenodes.h:265
Node node
Definition: parsenodes.h:339
String sval
Definition: parsenodes.h:343
#define strVal(v)
Definition: value.h:82

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert(), AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, COERCE_EXPLICIT_CALL, ColumnDef::colname, CreateStmtContext::columns, Constraint::conname, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, Constraint::deferrable, DROP_RESTRICT, elog(), ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, ColumnDef::identity, Constraint::initdeferred, Constraint::initially_valid, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, CreateStmtContext::nnconstraints, ValUnion::node, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, ReleaseSysCache(), RangeVar::relname, Constraint::skip_validation, stmt, strVal, AlterTableCmd::subtype, ValUnion::sval, String::sval, SystemFuncName(), SystemTypeName(), transformColumnType(), transformConstraintAttrs(), Node::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3912 of file parse_utilcmd.c.

3913 {
3914  /*
3915  * All we really need to do here is verify that the type is valid,
3916  * including any collation spec that might be present.
3917  */
3918  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3919 
3920  if (column->collClause)
3921  {
3922  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3923 
3924  LookupCollation(cxt->pstate,
3925  column->collClause->collname,
3926  column->collClause->location);
3927  /* Complain if COLLATE is applied to an uncollatable type */
3928  if (!OidIsValid(typtup->typcollation))
3929  ereport(ERROR,
3930  (errcode(ERRCODE_DATATYPE_MISMATCH),
3931  errmsg("collations are not supported by type %s",
3932  format_type_be(typtup->oid)),
3934  column->collClause->location)));
3935  }
3936 
3937  ReleaseSysCache(ctype);
3938 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
List * collname
Definition: parsenodes.h:375
CollateClause * collClause
Definition: parsenodes.h:728

References ColumnDef::collClause, CollateClause::collname, ereport, errcode(), errmsg(), ERROR, format_type_be(), GETSTRUCT, CollateClause::location, LookupCollation(), OidIsValid, parser_errposition(), CreateStmtContext::pstate, ReleaseSysCache(), ColumnDef::typeName, and typenameType().

Referenced by transformColumnDefinition().

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3797 of file parse_utilcmd.c.

3798 {
3799  Constraint *lastprimarycon = NULL;
3800  bool saw_deferrability = false;
3801  bool saw_initially = false;
3802  ListCell *clist;
3803 
3804 #define SUPPORTS_ATTRS(node) \
3805  ((node) != NULL && \
3806  ((node)->contype == CONSTR_PRIMARY || \
3807  (node)->contype == CONSTR_UNIQUE || \
3808  (node)->contype == CONSTR_EXCLUSION || \
3809  (node)->contype == CONSTR_FOREIGN))
3810 
3811  foreach(clist, constraintList)
3812  {
3813  Constraint *con = (Constraint *) lfirst(clist);
3814 
3815  if (!IsA(con, Constraint))
3816  elog(ERROR, "unrecognized node type: %d",
3817  (int) nodeTag(con));
3818  switch (con->contype)
3819  {
3821  if (!SUPPORTS_ATTRS(lastprimarycon))
3822  ereport(ERROR,
3823  (errcode(ERRCODE_SYNTAX_ERROR),
3824  errmsg("misplaced DEFERRABLE clause"),
3825  parser_errposition(cxt->pstate, con->location)));
3826  if (saw_deferrability)
3827  ereport(ERROR,
3828  (errcode(ERRCODE_SYNTAX_ERROR),
3829  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3830  parser_errposition(cxt->pstate, con->location)));
3831  saw_deferrability = true;
3832  lastprimarycon->deferrable = true;
3833  break;
3834 
3836  if (!SUPPORTS_ATTRS(lastprimarycon))
3837  ereport(ERROR,
3838  (errcode(ERRCODE_SYNTAX_ERROR),
3839  errmsg("misplaced NOT DEFERRABLE clause"),
3840  parser_errposition(cxt->pstate, con->location)));
3841  if (saw_deferrability)
3842  ereport(ERROR,
3843  (errcode(ERRCODE_SYNTAX_ERROR),
3844  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3845  parser_errposition(cxt->pstate, con->location)));
3846  saw_deferrability = true;
3847  lastprimarycon->deferrable = false;
3848  if (saw_initially &&
3849  lastprimarycon->initdeferred)
3850  ereport(ERROR,
3851  (errcode(ERRCODE_SYNTAX_ERROR),
3852  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3853  parser_errposition(cxt->pstate, con->location)));
3854  break;
3855 
3856  case CONSTR_ATTR_DEFERRED:
3857  if (!SUPPORTS_ATTRS(lastprimarycon))
3858  ereport(ERROR,
3859  (errcode(ERRCODE_SYNTAX_ERROR),
3860  errmsg("misplaced INITIALLY DEFERRED clause"),
3861  parser_errposition(cxt->pstate, con->location)));
3862  if (saw_initially)
3863  ereport(ERROR,
3864  (errcode(ERRCODE_SYNTAX_ERROR),
3865  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3866  parser_errposition(cxt->pstate, con->location)));
3867  saw_initially = true;
3868  lastprimarycon->initdeferred = true;
3869 
3870  /*
3871  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3872  */
3873  if (!saw_deferrability)
3874  lastprimarycon->deferrable = true;
3875  else if (!lastprimarycon->deferrable)
3876  ereport(ERROR,
3877  (errcode(ERRCODE_SYNTAX_ERROR),
3878  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3879  parser_errposition(cxt->pstate, con->location)));
3880  break;
3881 
3882  case CONSTR_ATTR_IMMEDIATE:
3883  if (!SUPPORTS_ATTRS(lastprimarycon))
3884  ereport(ERROR,
3885  (errcode(ERRCODE_SYNTAX_ERROR),
3886  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3887  parser_errposition(cxt->pstate, con->location)));
3888  if (saw_initially)
3889  ereport(ERROR,
3890  (errcode(ERRCODE_SYNTAX_ERROR),
3891  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3892  parser_errposition(cxt->pstate, con->location)));
3893  saw_initially = true;
3894  lastprimarycon->initdeferred = false;
3895  break;
3896 
3897  default:
3898  /* Otherwise it's not an attribute */
3899  lastprimarycon = con;
3900  /* reset flags for new primary node */
3901  saw_deferrability = false;
3902  saw_initially = false;
3903  break;
3904  }
3905  }
3906 }
#define SUPPORTS_ATTRS(node)

References CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, Constraint::contype, Constraint::deferrable, elog(), ereport, errcode(), errmsg(), ERROR, Constraint::initdeferred, IsA, lfirst, Constraint::location, nodeTag, parser_errposition(), CreateStmtContext::pstate, and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition().

◆ transformCreateSchemaStmtElements()

List* transformCreateSchemaStmtElements ( List schemaElts,
const char *  schemaName 
)

Definition at line 3969 of file parse_utilcmd.c.

3970 {
3972  List *result;
3973  ListCell *elements;
3974 
3975  cxt.schemaname = schemaName;
3976  cxt.sequences = NIL;
3977  cxt.tables = NIL;
3978  cxt.views = NIL;
3979  cxt.indexes = NIL;
3980  cxt.triggers = NIL;
3981  cxt.grants = NIL;
3982 
3983  /*
3984  * Run through each schema element in the schema element list. Separate
3985  * statements by type, and do preliminary analysis.
3986  */
3987  foreach(elements, schemaElts)
3988  {
3989  Node *element = lfirst(elements);
3990 
3991  switch (nodeTag(element))
3992  {
3993  case T_CreateSeqStmt:
3994  {
3995  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3996 
3998  cxt.sequences = lappend(cxt.sequences, element);
3999  }
4000  break;
4001 
4002  case T_CreateStmt:
4003  {
4004  CreateStmt *elp = (CreateStmt *) element;
4005 
4007 
4008  /*
4009  * XXX todo: deal with constraints
4010  */
4011  cxt.tables = lappend(cxt.tables, element);
4012  }
4013  break;
4014 
4015  case T_ViewStmt:
4016  {
4017  ViewStmt *elp = (ViewStmt *) element;
4018 
4019  setSchemaName(cxt.schemaname, &elp->view->schemaname);
4020 
4021  /*
4022  * XXX todo: deal with references between views
4023  */
4024  cxt.views = lappend(cxt.views, element);
4025  }
4026  break;
4027 
4028  case T_IndexStmt:
4029  {
4030  IndexStmt *elp = (IndexStmt *) element;
4031 
4033  cxt.indexes = lappend(cxt.indexes, element);
4034  }
4035  break;
4036 
4037  case T_CreateTrigStmt:
4038  {
4040 
4042  cxt.triggers = lappend(cxt.triggers, element);
4043  }
4044  break;
4045 
4046  case T_GrantStmt:
4047  cxt.grants = lappend(cxt.grants, element);
4048  break;
4049 
4050  default:
4051  elog(ERROR, "unrecognized node type: %d",
4052  (int) nodeTag(element));
4053  }
4054  }
4055 
4056  result = NIL;
4057  result = list_concat(result, cxt.sequences);
4058  result = list_concat(result, cxt.tables);
4059  result = list_concat(result, cxt.views);
4060  result = list_concat(result, cxt.indexes);
4061  result = list_concat(result, cxt.triggers);
4062  result = list_concat(result, cxt.grants);
4063 
4064  return result;
4065 }
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * relation
Definition: parsenodes.h:2489
RangeVar * relation
Definition: parsenodes.h:2847
RangeVar * relation
Definition: parsenodes.h:3192
RangeVar * view
Definition: parsenodes.h:3584

References element(), elog(), ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmtContext::schemaname, RangeVar::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

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

Definition at line 164 of file parse_utilcmd.c.

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

References CreateStmtContext::alist, Assert(), CreateStmtContext::blist, cancel_parser_errposition_callback(), checkMembershipInCurrentExtension(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, element(), elog(), ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmtContext::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, CreateStmtContext::likeclauses, list_concat(), make_parsestate(), NIL, CreateStmtContext::nnconstraints, nodeTag, NoLock, NOTICE, ObjectAddressSet, CreateStmtContext::ofType, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, setup_parser_errposition_callback(), stmt, CreateStmtContext::stmtType, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2838 of file parse_utilcmd.c.

2839 {
2840  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2841 }

References CreateStmtContext::alist, CreateStmtContext::extstats, and list_concat().

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformFKConstraints()

static void transformFKConstraints ( CreateStmtContext cxt,
bool  skipValidation,
bool  isAddConstraint 
)
static

Definition at line 2882 of file parse_utilcmd.c.

2884 {
2885  ListCell *fkclist;
2886 
2887  if (cxt->fkconstraints == NIL)
2888  return;
2889 
2890  /*
2891  * If CREATE TABLE or adding a column with NULL default, we can safely
2892  * skip validation of FK constraints, and nonetheless mark them valid.
2893  * (This will override any user-supplied NOT VALID flag.)
2894  */
2895  if (skipValidation)
2896  {
2897  foreach(fkclist, cxt->fkconstraints)
2898  {
2899  Constraint *constraint = (Constraint *) lfirst(fkclist);
2900 
2901  constraint->skip_validation = true;
2902  constraint->initially_valid = true;
2903  }
2904  }
2905 
2906  /*
2907  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2908  * CONSTRAINT command to execute after the basic command is complete. (If
2909  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2910  * its own subcommand list.)
2911  *
2912  * Note: the ADD CONSTRAINT command must also execute after any index
2913  * creation commands. Thus, this should run after
2914  * transformIndexConstraints, so that the CREATE INDEX commands are
2915  * already in cxt->alist. See also the handling of cxt->likeclauses.
2916  */
2917  if (!isAddConstraint)
2918  {
2919  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2920 
2921  alterstmt->relation = cxt->relation;
2922  alterstmt->cmds = NIL;
2923  alterstmt->objtype = OBJECT_TABLE;
2924 
2925  foreach(fkclist, cxt->fkconstraints)
2926  {
2927  Constraint *constraint = (Constraint *) lfirst(fkclist);
2928  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2929 
2930  altercmd->subtype = AT_AddConstraint;
2931  altercmd->name = NULL;
2932  altercmd->def = (Node *) constraint;
2933  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2934  }
2935 
2936  cxt->alist = lappend(cxt->alist, alterstmt);
2937  }
2938 }

References CreateStmtContext::alist, AT_AddConstraint, AlterTableStmt::cmds, AlterTableCmd::def, CreateStmtContext::fkconstraints, Constraint::initially_valid, lappend(), lfirst, makeNode, AlterTableCmd::name, NIL, OBJECT_TABLE, AlterTableStmt::objtype, CreateStmtContext::relation, AlterTableStmt::relation, Constraint::skip_validation, and AlterTableCmd::subtype.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexConstraint()

static IndexStmt * transformIndexConstraint ( Constraint constraint,
CreateStmtContext cxt 
)
static

Definition at line 2293 of file parse_utilcmd.c.

2294 {
2295  IndexStmt *index;
2296  List *notnullcmds = NIL;
2297  ListCell *lc;
2298 
2300 
2301  index->unique = (constraint->contype != CONSTR_EXCLUSION);
2302  index->primary = (constraint->contype == CONSTR_PRIMARY);
2303  if (index->primary)
2304  {
2305  if (cxt->pkey != NULL)
2306  ereport(ERROR,
2307  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2308  errmsg("multiple primary keys for table \"%s\" are not allowed",
2309  cxt->relation->relname),
2310  parser_errposition(cxt->pstate, constraint->location)));
2311  cxt->pkey = index;
2312 
2313  /*
2314  * In ALTER TABLE case, a primary index might already exist, but
2315  * DefineIndex will check for it.
2316  */
2317  }
2318  index->nulls_not_distinct = constraint->nulls_not_distinct;
2319  index->isconstraint = true;
2320  index->iswithoutoverlaps = constraint->without_overlaps;
2321  index->deferrable = constraint->deferrable;
2322  index->initdeferred = constraint->initdeferred;
2323 
2324  if (constraint->conname != NULL)
2325  index->idxname = pstrdup(constraint->conname);
2326  else
2327  index->idxname = NULL; /* DefineIndex will choose name */
2328 
2329  index->relation = cxt->relation;
2330  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2331  index->options = constraint->options;
2332  index->tableSpace = constraint->indexspace;
2333  index->whereClause = constraint->where_clause;
2334  index->indexParams = NIL;
2335  index->indexIncludingParams = NIL;
2336  index->excludeOpNames = NIL;
2337  index->idxcomment = NULL;
2338  index->indexOid = InvalidOid;
2339  index->oldNumber = InvalidRelFileNumber;
2340  index->oldCreateSubid = InvalidSubTransactionId;
2341  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2342  index->transformed = false;
2343  index->concurrent = false;
2344  index->if_not_exists = false;
2345  index->reset_default_tblspc = constraint->reset_default_tblspc;
2346 
2347  /*
2348  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2349  * verify it's usable, then extract the implied column name list. (We
2350  * will not actually need the column name list at runtime, but we need it
2351  * now to check for duplicate column entries below.)
2352  */
2353  if (constraint->indexname != NULL)
2354  {
2355  char *index_name = constraint->indexname;
2356  Relation heap_rel = cxt->rel;
2357  Oid index_oid;
2358  Relation index_rel;
2359  Form_pg_index index_form;
2360  oidvector *indclass;
2361  Datum indclassDatum;
2362  int i;
2363 
2364  /* Grammar should not allow this with explicit column list */
2365  Assert(constraint->keys == NIL);
2366 
2367  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2368  Assert(constraint->contype == CONSTR_PRIMARY ||
2369  constraint->contype == CONSTR_UNIQUE);
2370 
2371  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2372  if (!cxt->isalter)
2373  ereport(ERROR,
2374  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2375  errmsg("cannot use an existing index in CREATE TABLE"),
2376  parser_errposition(cxt->pstate, constraint->location)));
2377 
2378  /* Look for the index in the same schema as the table */
2379  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2380 
2381  if (!OidIsValid(index_oid))
2382  ereport(ERROR,
2383  (errcode(ERRCODE_UNDEFINED_OBJECT),
2384  errmsg("index \"%s\" does not exist", index_name),
2385  parser_errposition(cxt->pstate, constraint->location)));
2386 
2387  /* Open the index (this will throw an error if it is not an index) */
2388  index_rel = index_open(index_oid, AccessShareLock);
2389  index_form = index_rel->rd_index;
2390 
2391  /* Check that it does not have an associated constraint already */
2392  if (OidIsValid(get_index_constraint(index_oid)))
2393  ereport(ERROR,
2394  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2395  errmsg("index \"%s\" is already associated with a constraint",
2396  index_name),
2397  parser_errposition(cxt->pstate, constraint->location)));
2398 
2399  /* Perform validity checks on the index */
2400  if (index_form->indrelid != RelationGetRelid(heap_rel))
2401  ereport(ERROR,
2402  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2403  errmsg("index \"%s\" does not belong to table \"%s\"",
2404  index_name, RelationGetRelationName(heap_rel)),
2405  parser_errposition(cxt->pstate, constraint->location)));
2406 
2407  if (!index_form->indisvalid)
2408  ereport(ERROR,
2409  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2410  errmsg("index \"%s\" is not valid", index_name),
2411  parser_errposition(cxt->pstate, constraint->location)));
2412 
2413  /*
2414  * Today we forbid non-unique indexes, but we could permit GiST
2415  * indexes whose last entry is a range type and use that to create a
2416  * WITHOUT OVERLAPS constraint (i.e. a temporal constraint).
2417  */
2418  if (!index_form->indisunique)
2419  ereport(ERROR,
2420  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2421  errmsg("\"%s\" is not a unique index", index_name),
2422  errdetail("Cannot create a primary key or unique constraint using such an index."),
2423  parser_errposition(cxt->pstate, constraint->location)));
2424 
2425  if (RelationGetIndexExpressions(index_rel) != NIL)
2426  ereport(ERROR,
2427  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2428  errmsg("index \"%s\" contains expressions", index_name),
2429  errdetail("Cannot create a primary key or unique constraint using such an index."),
2430  parser_errposition(cxt->pstate, constraint->location)));
2431 
2432  if (RelationGetIndexPredicate(index_rel) != NIL)
2433  ereport(ERROR,
2434  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2435  errmsg("\"%s\" is a partial index", index_name),
2436  errdetail("Cannot create a primary key or unique constraint using such an index."),
2437  parser_errposition(cxt->pstate, constraint->location)));
2438 
2439  /*
2440  * It's probably unsafe to change a deferred index to non-deferred. (A
2441  * non-constraint index couldn't be deferred anyway, so this case
2442  * should never occur; no need to sweat, but let's check it.)
2443  */
2444  if (!index_form->indimmediate && !constraint->deferrable)
2445  ereport(ERROR,
2446  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2447  errmsg("\"%s\" is a deferrable index", index_name),
2448  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2449  parser_errposition(cxt->pstate, constraint->location)));
2450 
2451  /*
2452  * Insist on it being a btree. That's the only kind that supports
2453  * uniqueness at the moment anyway; but we must have an index that
2454  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2455  * else dump and reload will produce a different index (breaking
2456  * pg_upgrade in particular).
2457  */
2458  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2459  ereport(ERROR,
2460  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2461  errmsg("index \"%s\" is not a btree", index_name),
2462  parser_errposition(cxt->pstate, constraint->location)));
2463 
2464  /* Must get indclass the hard way */
2465  indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
2466  index_rel->rd_indextuple,
2467  Anum_pg_index_indclass);
2468  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2469 
2470  for (i = 0; i < index_form->indnatts; i++)
2471  {
2472  int16 attnum = index_form->indkey.values[i];
2473  const FormData_pg_attribute *attform;
2474  char *attname;
2475  Oid defopclass;
2476 
2477  /*
2478  * We shouldn't see attnum == 0 here, since we already rejected
2479  * expression indexes. If we do, SystemAttributeDefinition will
2480  * throw an error.
2481  */
2482  if (attnum > 0)
2483  {
2484  Assert(attnum <= heap_rel->rd_att->natts);
2485  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2486  }
2487  else
2488  attform = SystemAttributeDefinition(attnum);
2489  attname = pstrdup(NameStr(attform->attname));
2490 
2491  if (i < index_form->indnkeyatts)
2492  {
2493  /*
2494  * Insist on default opclass, collation, and sort options.
2495  * While the index would still work as a constraint with
2496  * non-default settings, it might not provide exactly the same
2497  * uniqueness semantics as you'd get from a normally-created
2498  * constraint; and there's also the dump/reload problem
2499  * mentioned above.
2500  */
2501  Datum attoptions =
2502  get_attoptions(RelationGetRelid(index_rel), i + 1);
2503 
2504  defopclass = GetDefaultOpClass(attform->atttypid,
2505  index_rel->rd_rel->relam);
2506  if (indclass->values[i] != defopclass ||
2507  attform->attcollation != index_rel->rd_indcollation[i] ||
2508  attoptions != (Datum) 0 ||
2509  index_rel->rd_indoption[i] != 0)
2510  ereport(ERROR,
2511  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2512  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2513  errdetail("Cannot create a primary key or unique constraint using such an index."),
2514  parser_errposition(cxt->pstate, constraint->location)));
2515 
2516  constraint->keys = lappend(constraint->keys, makeString(attname));
2517  }
2518  else
2519  constraint->including = lappend(constraint->including, makeString(attname));
2520  }
2521 
2522  /* Close the index relation but keep the lock */
2523  relation_close(index_rel, NoLock);
2524 
2525  index->indexOid = index_oid;
2526  }
2527 
2528  /*
2529  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2530  * IndexElems and operator names. We have to break that apart into
2531  * separate lists.
2532  */
2533  if (constraint->contype == CONSTR_EXCLUSION)
2534  {
2535  foreach(lc, constraint->exclusions)
2536  {
2537  List *pair = (List *) lfirst(lc);
2538  IndexElem *elem;
2539  List *opname;
2540 
2541  Assert(list_length(pair) == 2);
2542  elem = linitial_node(IndexElem, pair);
2543  opname = lsecond_node(List, pair);
2544 
2545  index->indexParams = lappend(index->indexParams, elem);
2546  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2547  }
2548  }
2549 
2550  /*
2551  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2552  *
2553  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2554  * also make sure they are not-null.
2555  */
2556  else
2557  {
2558  foreach(lc, constraint->keys)
2559  {
2560  char *key = strVal(lfirst(lc));
2561  bool found = false;
2562  ColumnDef *column = NULL;
2563  ListCell *columns;
2564  IndexElem *iparam;
2565 
2566  /* Make sure referenced column exists. */
2567  foreach(columns, cxt->columns)
2568  {
2569  column = lfirst_node(ColumnDef, columns);
2570  if (strcmp(column->colname, key) == 0)
2571  {
2572  found = true;
2573  break;
2574  }
2575  }
2576  if (found)
2577  {
2578  /*
2579  * column is defined in the new table. For PRIMARY KEY, we
2580  * can apply the not-null constraint cheaply here ... unless
2581  * the column is marked is_from_type, in which case marking it
2582  * here would be ineffective (see MergeAttributes). Note that
2583  * this isn't effective in ALTER TABLE either, unless the
2584  * column is being added in the same command.
2585  */
2586  if (constraint->contype == CONSTR_PRIMARY &&
2587  !column->is_from_type)
2588  {
2589  column->is_not_null = true;
2590  }
2591  }
2592  else if (SystemAttributeByName(key) != NULL)
2593  {
2594  /*
2595  * column will be a system column in the new table, so accept
2596  * it. System columns can't ever be null, so no need to worry
2597  * about PRIMARY/NOT NULL constraint.
2598  */
2599  found = true;
2600  }
2601  else if (cxt->inhRelations)
2602  {
2603  /* try inherited tables */
2604  ListCell *inher;
2605 
2606  foreach(inher, cxt->inhRelations)
2607  {
2608  RangeVar *inh = lfirst_node(RangeVar, inher);
2609  Relation rel;
2610  int count;
2611 
2612  rel = table_openrv(inh, AccessShareLock);
2613  /* check user requested inheritance from valid relkind */
2614  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2615  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2616  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2617  ereport(ERROR,
2618  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2619  errmsg("inherited relation \"%s\" is not a table or foreign table",
2620  inh->relname)));
2621  for (count = 0; count < rel->rd_att->natts; count++)
2622  {
2623  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2624  count);
2625  char *inhname = NameStr(inhattr->attname);
2626 
2627  if (inhattr->attisdropped)
2628  continue;
2629  if (strcmp(key, inhname) == 0)
2630  {
2631  found = true;
2632  break;
2633  }
2634  }
2635  table_close(rel, NoLock);
2636  if (found)
2637  break;
2638  }
2639  }
2640 
2641  /*
2642  * In the ALTER TABLE case, don't complain about index keys not
2643  * created in the command; they may well exist already.
2644  * DefineIndex will complain about them if not.
2645  */
2646  if (!found && !cxt->isalter)
2647  ereport(ERROR,
2648  (errcode(ERRCODE_UNDEFINED_COLUMN),
2649  errmsg("column \"%s\" named in key does not exist", key),
2650  parser_errposition(cxt->pstate, constraint->location)));
2651 
2652  /* Check for PRIMARY KEY(foo, foo) */
2653  foreach(columns, index->indexParams)
2654  {
2655  iparam = (IndexElem *) lfirst(columns);
2656  if (iparam->name && strcmp(key, iparam->name) == 0)
2657  {
2658  if (index->primary)
2659  ereport(ERROR,
2660  (errcode(ERRCODE_DUPLICATE_COLUMN),
2661  errmsg("column \"%s\" appears twice in primary key constraint",
2662  key),
2663  parser_errposition(cxt->pstate, constraint->location)));
2664  else
2665  ereport(ERROR,
2666  (errcode(ERRCODE_DUPLICATE_COLUMN),
2667  errmsg("column \"%s\" appears twice in unique constraint",
2668  key),
2669  parser_errposition(cxt->pstate, constraint->location)));
2670  }
2671  }
2672 
2673  /* OK, add it to the index definition */
2674  iparam = makeNode(IndexElem);
2675  iparam->name = pstrdup(key);
2676  iparam->expr = NULL;
2677  iparam->indexcolname = NULL;
2678  iparam->collation = NIL;
2679  iparam->opclass = NIL;
2680  iparam->opclassopts = NIL;
2681  iparam->ordering = SORTBY_DEFAULT;
2683  index->indexParams = lappend(index->indexParams, iparam);
2684 
2685  if (constraint->contype == CONSTR_PRIMARY)
2686  {
2687  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2688 
2689  notnullcmd->subtype = AT_SetAttNotNull;
2690  notnullcmd->name = pstrdup(key);
2691  notnullcmds = lappend(notnullcmds, notnullcmd);
2692  }
2693  }
2694 
2695  if (constraint->without_overlaps)
2696  {
2697  /*
2698  * This enforces that there is at least one equality column
2699  * besides the WITHOUT OVERLAPS columns. This is per SQL
2700  * standard. XXX Do we need this?
2701  */
2702  if (list_length(constraint->keys) < 2)
2703  ereport(ERROR,
2704  errcode(ERRCODE_SYNTAX_ERROR),
2705  errmsg("constraint using WITHOUT OVERLAPS needs at least two columns"));
2706 
2707  /* WITHOUT OVERLAPS requires a GiST index */
2708  index->accessMethod = "gist";
2709  }
2710 
2711  }
2712 
2713  /*
2714  * Add included columns to index definition. This is much like the
2715  * simple-column-name-list code above, except that we don't worry about
2716  * NOT NULL marking; included columns in a primary key should not be
2717  * forced NOT NULL. We don't complain about duplicate columns, either,
2718  * though maybe we should?
2719  */
2720  foreach(lc, constraint->including)
2721  {
2722  char *key = strVal(lfirst(lc));
2723  bool found = false;
2724  ColumnDef *column = NULL;
2725  ListCell *columns;
2726  IndexElem *iparam;
2727 
2728  foreach(columns, cxt->columns)
2729  {
2730  column = lfirst_node(ColumnDef, columns);
2731  if (strcmp(column->colname, key) == 0)
2732  {
2733  found = true;
2734  break;
2735  }
2736  }
2737 
2738  if (!found)
2739  {
2740  if (SystemAttributeByName(key) != NULL)
2741  {
2742  /*
2743  * column will be a system column in the new table, so accept
2744  * it.
2745  */
2746  found = true;
2747  }
2748  else if (cxt->inhRelations)
2749  {
2750  /* try inherited tables */
2751  ListCell *inher;
2752 
2753  foreach(inher, cxt->inhRelations)
2754  {
2755  RangeVar *inh = lfirst_node(RangeVar, inher);
2756  Relation rel;
2757  int count;
2758 
2759  rel = table_openrv(inh, AccessShareLock);
2760  /* check user requested inheritance from valid relkind */
2761  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2762  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2763  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2764  ereport(ERROR,
2765  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2766  errmsg("inherited relation \"%s\" is not a table or foreign table",
2767  inh->relname)));
2768  for (count = 0; count < rel->rd_att->natts; count++)
2769  {
2770  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2771  count);
2772  char *inhname = NameStr(inhattr->attname);
2773 
2774  if (inhattr->attisdropped)
2775  continue;
2776  if (strcmp(key, inhname) == 0)
2777  {
2778  found = true;
2779  break;
2780  }
2781  }
2782  table_close(rel, NoLock);
2783  if (found)
2784  break;
2785  }
2786  }
2787  }
2788 
2789  /*
2790  * In the ALTER TABLE case, don't complain about index keys not
2791  * created in the command; they may well exist already. DefineIndex
2792  * will complain about them if not.
2793  */
2794  if (!found && !cxt->isalter)
2795  ereport(ERROR,
2796  (errcode(ERRCODE_UNDEFINED_COLUMN),
2797  errmsg("column \"%s\" named in key does not exist", key),
2798  parser_errposition(cxt->pstate, constraint->location)));
2799 
2800  /* OK, add it to the index definition */
2801  iparam = makeNode(IndexElem);
2802  iparam->name = pstrdup(key);
2803  iparam->expr = NULL;
2804  iparam->indexcolname = NULL;
2805  iparam->collation = NIL;
2806  iparam->opclass = NIL;
2807  iparam->opclassopts = NIL;
2808  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2809  }
2810 
2811  /*
2812  * If we found anything that requires run-time SET NOT NULL, build a full
2813  * ALTER TABLE command for that and add it to cxt->alist.
2814  */
2815  if (notnullcmds)
2816  {
2817  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2818 
2819  alterstmt->relation = copyObject(cxt->relation);
2820  alterstmt->cmds = notnullcmds;
2821  alterstmt->objtype = OBJECT_TABLE;
2822  alterstmt->missing_ok = false;
2823 
2824  cxt->alist = lappend(cxt->alist, alterstmt);
2825  }
2826 
2827  return index;
2828 }
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:163
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:240
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:252
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1862
FormData_pg_attribute
Definition: pg_attribute.h:193
#define linitial_node(type, l)
Definition: pg_list.h:181
#define lsecond_node(type, l)
Definition: pg_list.h:186
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5124
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5011
bool is_from_type
Definition: parsenodes.h:719
List * exclusions
Definition: parsenodes.h:2590
bool reset_default_tblspc
Definition: parsenodes.h:2595
Node * where_clause
Definition: parsenodes.h:2598
char * indexname
Definition: parsenodes.h:2593
char * indexspace
Definition: parsenodes.h:2594
char * access_method
Definition: parsenodes.h:2597
bool nulls_not_distinct
Definition: parsenodes.h:2584
bool without_overlaps
Definition: parsenodes.h:2587
List * including
Definition: parsenodes.h:2588
TupleDesc rd_att
Definition: rel.h:112
Form_pg_index rd_index
Definition: rel.h:191
Oid * rd_indcollation
Definition: rel.h:216
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

References Constraint::access_method, AccessShareLock, CreateStmtContext::alist, Assert(), AT_SetAttNotNull, attname, attnum, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer(), DEFAULT_INDEX_TYPE, Constraint::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, Constraint::including, index_open(), IndexElem::indexcolname, Constraint::indexname, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, sort-test::key, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, NoLock, Constraint::nulls_not_distinct, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttrNotNull(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), TupleDescAttr, oidvector::values, Constraint::where_clause, and Constraint::without_overlaps.

Referenced by transformIndexConstraints().

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2192 of file parse_utilcmd.c.

2193 {
2194  IndexStmt *index;
2195  List *indexlist = NIL;
2196  List *finalindexlist = NIL;
2197  ListCell *lc;
2198 
2199  /*
2200  * Run through the constraints that need to generate an index, and do so.
2201  *
2202  * For PRIMARY KEY, in addition we set each column's attnotnull flag true.
2203  * We do not create a separate not-null constraint, as that would be
2204  * redundant: the PRIMARY KEY constraint itself fulfills that role. Other
2205  * constraint types don't need any not-null markings.
2206  */
2207  foreach(lc, cxt->ixconstraints)
2208  {
2209  Constraint *constraint = lfirst_node(Constraint, lc);
2210 
2211  Assert(constraint->contype == CONSTR_PRIMARY ||
2212  constraint->contype == CONSTR_UNIQUE ||
2213  constraint->contype == CONSTR_EXCLUSION);
2214 
2215  index = transformIndexConstraint(constraint, cxt);
2216 
2217  indexlist = lappend(indexlist, index);
2218  }
2219 
2220  /*
2221  * Scan the index list and remove any redundant index specifications. This
2222  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2223  * strict reading of SQL would suggest raising an error instead, but that
2224  * strikes me as too anal-retentive. - tgl 2001-02-14
2225  *
2226  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2227  * pre-existing indexes, too.
2228  */
2229  if (cxt->pkey != NULL)
2230  {
2231  /* Make sure we keep the PKEY index in preference to others... */
2232  finalindexlist = list_make1(cxt->pkey);
2233  }
2234 
2235  foreach(lc, indexlist)
2236  {
2237  bool keep = true;
2238  ListCell *k;
2239 
2240  index = lfirst(lc);
2241 
2242  /* if it's pkey, it's already in finalindexlist */
2243  if (index == cxt->pkey)
2244  continue;
2245 
2246  foreach(k, finalindexlist)
2247  {
2248  IndexStmt *priorindex = lfirst(k);
2249 
2250  if (equal(index->indexParams, priorindex->indexParams) &&
2251  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2252  equal(index->whereClause, priorindex->whereClause) &&
2253  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2254  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2255  index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2256  index->deferrable == priorindex->deferrable &&
2257  index->initdeferred == priorindex->initdeferred)
2258  {
2259  priorindex->unique |= index->unique;
2260 
2261  /*
2262  * If the prior index is as yet unnamed, and this one is
2263  * named, then transfer the name to the prior index. This
2264  * ensures that if we have named and unnamed constraints,
2265  * we'll use (at least one of) the names for the index.
2266  */
2267  if (priorindex->idxname == NULL)
2268  priorindex->idxname = index->idxname;
2269  keep = false;
2270  break;
2271  }
2272  }
2273 
2274  if (keep)
2275  finalindexlist = lappend(finalindexlist, index);
2276  }
2277 
2278  /*
2279  * Now append all the IndexStmts to cxt->alist.
2280  */
2281  cxt->alist = list_concat(cxt->alist, finalindexlist);
2282 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:3207
bool deferrable
Definition: parsenodes.h:3212
bool initdeferred
Definition: parsenodes.h:3213
List * excludeOpNames
Definition: parsenodes.h:3200
bool nulls_not_distinct
Definition: parsenodes.h:3208
char * idxname
Definition: parsenodes.h:3191
Node * whereClause
Definition: parsenodes.h:3199
char * accessMethod
Definition: parsenodes.h:3193
List * indexIncludingParams
Definition: parsenodes.h:3196

References IndexStmt::accessMethod, CreateStmtContext::alist, Assert(), CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, IndexStmt::deferrable, equal(), IndexStmt::excludeOpNames, IndexStmt::idxname, IndexStmt::indexIncludingParams, IndexStmt::indexParams, IndexStmt::initdeferred, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, NIL, IndexStmt::nulls_not_distinct, CreateStmtContext::pkey, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexStmt()

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

Definition at line 2953 of file parse_utilcmd.c.

2954 {
2955  ParseState *pstate;
2956  ParseNamespaceItem *nsitem;
2957  ListCell *l;
2958  Relation rel;
2959 
2960  /* Nothing to do if statement already transformed. */
2961  if (stmt->transformed)
2962  return stmt;
2963 
2964  /* Set up pstate */
2965  pstate = make_parsestate(NULL);
2966  pstate->p_sourcetext = queryString;
2967 
2968  /*
2969  * Put the parent table into the rtable so that the expressions can refer
2970  * to its fields without qualification. Caller is responsible for locking
2971  * relation, but we still need to open it.
2972  */
2973  rel = relation_open(relid, NoLock);
2974  nsitem = addRangeTableEntryForRelation(pstate, rel,
2976  NULL, false, true);
2977 
2978  /* no to join list, yes to namespaces */
2979  addNSItemToQuery(pstate, nsitem, false, true, true);
2980 
2981  /* take care of the where clause */
2982  if (stmt->whereClause)
2983  {
2984  stmt->whereClause = transformWhereClause(pstate,
2985  stmt->whereClause,
2987  "WHERE");
2988  /* we have to fix its collations too */
2989  assign_expr_collations(pstate, stmt->whereClause);
2990  }
2991 
2992  /* take care of any index expressions */
2993  foreach(l, stmt->indexParams)
2994  {
2995  IndexElem *ielem = (IndexElem *) lfirst(l);
2996 
2997  if (ielem->expr)
2998  {
2999  /* Extract preliminary index col name before transforming expr */
3000  if (ielem->indexcolname == NULL)
3001  ielem->indexcolname = FigureIndexColname(ielem->expr);
3002 
3003  /* Now do parse transformation of the expression */
3004  ielem->expr = transformExpr(pstate, ielem->expr,
3006 
3007  /* We have to fix its collations too */
3008  assign_expr_collations(pstate, ielem->expr);
3009 
3010  /*
3011  * transformExpr() should have already rejected subqueries,
3012  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3013  * for an index expression.
3014  *
3015  * DefineIndex() will make more checks.
3016  */
3017  }
3018  }
3019 
3020  /*
3021  * Check that only the base rel is mentioned. (This should be dead code
3022  * now that add_missing_from is history.)
3023  */
3024  if (list_length(pstate->p_rtable) != 1)
3025  ereport(ERROR,
3026  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3027  errmsg("index expressions and predicates can refer only to the table being indexed")));
3028 
3029  free_parsestate(pstate);
3030 
3031  /* Close relation */
3032  table_close(rel, NoLock);
3033 
3034  /* Mark statement as successfully transformed */
3035  stmt->transformed = true;
3036 
3037  return stmt;
3038 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
char * FigureIndexColname(Node *node)
List * p_rtable
Definition: parse_node.h:193

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, lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), transformExpr(), and transformWhereClause().

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

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1603 of file parse_utilcmd.c.

1604 {
1605  HeapTuple tuple;
1606  TupleDesc tupdesc;
1607  int i;
1608  Oid ofTypeId;
1609 
1610  Assert(ofTypename);
1611 
1612  tuple = typenameType(NULL, ofTypename, NULL);
1613  check_of_type(tuple);
1614  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1615  ofTypename->typeOid = ofTypeId; /* cached for later */
1616 
1617  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1618  for (i = 0; i < tupdesc->natts; i++)
1619  {
1620  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1621  ColumnDef *n;
1622 
1623  if (attr->attisdropped)
1624  continue;
1625 
1626  n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1627  attr->atttypmod, attr->attcollation);
1628  n->is_from_type = true;
1629 
1630  cxt->columns = lappend(cxt->columns, n);
1631  }
1632  ReleaseTupleDesc(tupdesc);
1633 
1634  ReleaseSysCache(tuple);
1635 }
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition: makefuncs.c:493
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:6962
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1832

References Assert(), check_of_type(), CreateStmtContext::columns, GETSTRUCT, i, ColumnDef::is_from_type, lappend(), lookup_rowtype_tupdesc(), makeColumnDef(), NameStr, TupleDescData::natts, ReleaseSysCache(), ReleaseTupleDesc, TupleDescAttr, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

◆ transformPartitionBound()

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

Definition at line 4145 of file parse_utilcmd.c.

4147 {
4148  PartitionBoundSpec *result_spec;
4150  char strategy = get_partition_strategy(key);
4151  int partnatts = get_partition_natts(key);
4152  List *partexprs = get_partition_exprs(key);
4153 
4154  /* Avoid scribbling on input */
4155  result_spec = copyObject(spec);
4156 
4157  if (spec->is_default)
4158  {
4159  /*
4160  * Hash partitioning does not support a default partition; there's no
4161  * use case for it (since the set of partitions to create is perfectly
4162  * defined), and if users do get into it accidentally, it's hard to
4163  * back out from it afterwards.
4164  */
4165  if (strategy == PARTITION_STRATEGY_HASH)
4166  ereport(ERROR,
4167  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4168  errmsg("a hash-partitioned table may not have a default partition")));
4169 
4170  /*
4171  * In case of the default partition, parser had no way to identify the
4172  * partition strategy. Assign the parent's strategy to the default
4173  * partition bound spec.
4174  */
4175  result_spec->strategy = strategy;
4176 
4177  return result_spec;
4178  }
4179 
4180  if (strategy == PARTITION_STRATEGY_HASH)
4181  {
4182  if (spec->strategy != PARTITION_STRATEGY_HASH)
4183  ereport(ERROR,
4184  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4185  errmsg("invalid bound specification for a hash partition"),
4186  parser_errposition(pstate, exprLocation((Node *) spec))));
4187 
4188  if (spec->modulus <= 0)
4189  ereport(ERROR,
4190  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4191  errmsg("modulus for hash partition must be an integer value greater than zero")));
4192 
4193  Assert(spec->remainder >= 0);
4194 
4195  if (spec->remainder >= spec->modulus)
4196  ereport(ERROR,
4197  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4198  errmsg("remainder for hash partition must be less than modulus")));
4199  }
4200  else if (strategy == PARTITION_STRATEGY_LIST)
4201  {
4202  ListCell *cell;
4203  char *colname;
4204  Oid coltype;
4205  int32 coltypmod;
4206  Oid partcollation;
4207 
4208  if (spec->strategy != PARTITION_STRATEGY_LIST)
4209  ereport(ERROR,
4210  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4211  errmsg("invalid bound specification for a list partition"),
4212  parser_errposition(pstate, exprLocation((Node *) spec))));
4213 
4214  /* Get the only column's name in case we need to output an error */
4215  if (key->partattrs[0] != 0)
4216  colname = get_attname(RelationGetRelid(parent),
4217  key->partattrs[0], false);
4218  else
4219  colname = deparse_expression((Node *) linitial(partexprs),
4221  RelationGetRelid(parent)),
4222  false, false);
4223  /* Need its type data too */
4224  coltype = get_partition_col_typid(key, 0);
4225  coltypmod = get_partition_col_typmod(key, 0);
4226  partcollation = get_partition_col_collation(key, 0);
4227 
4228  result_spec->listdatums = NIL;
4229  foreach(cell, spec->listdatums)
4230  {
4231  Node *expr = lfirst(cell);
4232  Const *value;
4233  ListCell *cell2;
4234  bool duplicate;
4235 
4236  value = transformPartitionBoundValue(pstate, expr,
4237  colname, coltype, coltypmod,
4238  partcollation);
4239 
4240  /* Don't add to the result if the value is a duplicate */
4241  duplicate = false;
4242  foreach(cell2, result_spec->listdatums)
4243  {
4244  Const *value2 = lfirst_node(Const, cell2);
4245 
4246  if (equal(value, value2))
4247  {
4248  duplicate = true;
4249  break;
4250  }
4251  }
4252  if (duplicate)
4253  continue;
4254 
4255  result_spec->listdatums = lappend(result_spec->listdatums,
4256  value);
4257  }
4258  }
4259  else if (strategy == PARTITION_STRATEGY_RANGE)
4260  {
4261  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4262  ereport(ERROR,
4263  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4264  errmsg("invalid bound specification for a range partition"),
4265  parser_errposition(pstate, exprLocation((Node *) spec))));
4266 
4267  if (list_length(spec->lowerdatums) != partnatts)
4268  ereport(ERROR,
4269  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4270  errmsg("FROM must specify exactly one value per partitioning column")));
4271  if (list_length(spec->upperdatums) != partnatts)
4272  ereport(ERROR,
4273  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4274  errmsg("TO must specify exactly one value per partitioning column")));
4275 
4276  /*
4277  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4278  * any necessary validation.
4279  */
4280  result_spec->lowerdatums =
4282  parent);
4283  result_spec->upperdatums =
4285  parent);
4286  }
4287  else
4288  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4289 
4290  return result_spec;
4291 }
signed int int32
Definition: c.h:483
static struct @148 value
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1312
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
static Const * transformPartitionBoundValue(ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:861
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:859
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:860
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:59
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:92
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:65
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:86
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:98
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:71
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3600
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3660

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

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformPartitionBoundValue()

static Const * transformPartitionBoundValue ( ParseState pstate,
Node val,
const char *  colName,
Oid  colType,
int32  colTypmod,
Oid  partCollation 
)
static

Definition at line 4455 of file parse_utilcmd.c.

4458 {
4459  Node *value;
4460 
4461  /* Transform raw parsetree */
4463 
4464  /*
4465  * transformExpr() should have already rejected column references,
4466  * subqueries, aggregates, window functions, and SRFs, based on the
4467  * EXPR_KIND_ of a partition bound expression.
4468  */
4470 
4471  /*
4472  * Coerce to the correct type. This might cause an explicit coercion step
4473  * to be added on top of the expression, which must be evaluated before
4474  * returning the result to the caller.
4475  */
4476  value = coerce_to_target_type(pstate,
4477  value, exprType(value),
4478  colType,
4479  colTypmod,
4482  -1);
4483 
4484  if (value == NULL)
4485  ereport(ERROR,
4486  (errcode(ERRCODE_DATATYPE_MISMATCH),
4487  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4488  format_type_be(colType), colName),
4489  parser_errposition(pstate, exprLocation(val))));
4490 
4491  /*
4492  * Evaluate the expression, if needed, assigning the partition key's data
4493  * type and collation to the resulting Const node.
4494  */
4495  if (!IsA(value, Const))
4496  {
4497  assign_expr_collations(pstate, value);
4498  value = (Node *) expression_planner((Expr *) value);
4499  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4500  partCollation);
4501  if (!IsA(value, Const))
4502  elog(ERROR, "could not evaluate partition bound expression");
4503  }
4504  else
4505  {
4506  /*
4507  * If the expression is already a Const, as is often the case, we can
4508  * skip the rather expensive steps above. But we still have to insert
4509  * the right collation, since coerce_to_target_type doesn't handle
4510  * that.
4511  */
4512  ((Const *) value)->constcollid = partCollation;
4513  }
4514 
4515  /*
4516  * Attach original expression's parse location to the Const, so that
4517  * that's what will be reported for any later errors related to this
4518  * partition bound.
4519  */
4520  ((Const *) value)->location = exprLocation(val);
4521 
4522  return (Const *) value;
4523 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4943
long val
Definition: informix.c:664
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
Expr * expression_planner(Expr *expr)
Definition: planner.c:6407
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:671
@ COERCION_ASSIGNMENT
Definition: primnodes.h:650
bool contain_var_clause(Node *node)
Definition: var.c:403

References Assert(), assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, contain_var_clause(), elog(), ereport, errcode(), errmsg(), ERROR, evaluate_expr(), EXPR_KIND_PARTITION_BOUND, expression_planner(), exprLocation(), exprType(), format_type_be(), IsA, parser_errposition(), transformExpr(), val, and value.

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 4092 of file parse_utilcmd.c.

4093 {
4094  Relation parentRel = cxt->rel;
4095 
4096  switch (parentRel->rd_rel->relkind)
4097  {
4098  case RELKIND_PARTITIONED_TABLE:
4099  /* transform the partition bound, if any */
4100  Assert(RelationGetPartitionKey(parentRel) != NULL);
4101  if (cmd->bound != NULL)
4102  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
4103  cmd->bound);
4104  break;
4105  case RELKIND_PARTITIONED_INDEX:
4106 
4107  /*
4108  * A partitioned index cannot have a partition bound set. ALTER
4109  * INDEX prevents that with its grammar, but not ALTER TABLE.
4110  */
4111  if (cmd->bound != NULL)
4112  ereport(ERROR,
4113  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4114  errmsg("\"%s\" is not a partitioned table",
4115  RelationGetRelationName(parentRel))));
4116  break;
4117  case RELKIND_RELATION:
4118  /* the table must be partitioned */
4119  ereport(ERROR,
4120  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4121  errmsg("table \"%s\" is not partitioned",
4122  RelationGetRelationName(parentRel))));
4123  break;
4124  case RELKIND_INDEX:
4125  /* the index must be partitioned */
4126  ereport(ERROR,
4127  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4128  errmsg("index \"%s\" is not partitioned",
4129  RelationGetRelationName(parentRel))));
4130  break;
4131  default:
4132  /* parser shouldn't let this case through */
4133  elog(ERROR, "\"%s\" is not a partitioned table or index",
4134  RelationGetRelationName(parentRel));
4135  break;
4136  }
4137 }
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)

References Assert(), PartitionCmd::bound, elog(), ereport, errcode(), errmsg(), ERROR, CreateStmtContext::partbound, CreateStmtContext::pstate, RelationData::rd_rel, CreateStmtContext::rel, RelationGetPartitionKey(), RelationGetRelationName, and transformPartitionBound().

Referenced by transformAlterTableStmt().

◆ transformPartitionRangeBounds()

static List * transformPartitionRangeBounds ( ParseState pstate,
List blist,
Relation  parent 
)
static

Definition at line 4299 of file parse_utilcmd.c.

4301 {
4302  List *result = NIL;
4304  List *partexprs = get_partition_exprs(key);
4305  ListCell *lc;
4306  int i,
4307  j;
4308 
4309  i = j = 0;
4310  foreach(lc, blist)
4311  {
4312  Node *expr = lfirst(lc);
4313  PartitionRangeDatum *prd = NULL;
4314 
4315  /*
4316  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
4317  * as ColumnRefs.
4318  */
4319  if (IsA(expr, ColumnRef))
4320  {
4321  ColumnRef *cref = (ColumnRef *) expr;
4322  char *cname = NULL;
4323 
4324  /*
4325  * There should be a single field named either "minvalue" or
4326  * "maxvalue".
4327  */
4328  if (list_length(cref->fields) == 1 &&
4329  IsA(linitial(cref->fields), String))
4330  cname = strVal(linitial(cref->fields));
4331 
4332  if (cname == NULL)
4333  {
4334  /*
4335  * ColumnRef is not in the desired single-field-name form. For
4336  * consistency between all partition strategies, let the
4337  * expression transformation report any errors rather than
4338  * doing it ourselves.
4339  */
4340  }
4341  else if (strcmp("minvalue", cname) == 0)
4342  {
4345  prd->value = NULL;
4346  }
4347  else if (strcmp("maxvalue", cname) == 0)
4348  {
4351  prd->value = NULL;
4352  }
4353  }
4354 
4355  if (prd == NULL)
4356  {
4357  char *colname;
4358  Oid coltype;
4359  int32 coltypmod;
4360  Oid partcollation;
4361  Const *value;
4362 
4363  /* Get the column's name in case we need to output an error */
4364  if (key->partattrs[i] != 0)
4365  colname = get_attname(RelationGetRelid(parent),
4366  key->partattrs[i], false);
4367  else
4368  {
4369  colname = deparse_expression((Node *) list_nth(partexprs, j),
4371  RelationGetRelid(parent)),
4372  false, false);
4373  ++j;
4374  }
4375 
4376  /* Need its type data too */
4377  coltype = get_partition_col_typid(key, i);
4378  coltypmod = get_partition_col_typmod(key, i);
4379  partcollation = get_partition_col_collation(key, i);
4380 
4381  value = transformPartitionBoundValue(pstate, expr,
4382  colname,
4383  coltype, coltypmod,
4384  partcollation);
4385  if (value->constisnull)
4386  ereport(ERROR,
4387  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4388  errmsg("cannot specify NULL in range bound")));
4391  prd->value = (Node *) value;
4392  ++i;
4393  }
4394 
4395  prd->location = exprLocation(expr);
4396 
4397  result = lappend(result, prd);
4398  }
4399 
4400  /*
4401  * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
4402  * must be the same.
4403  */
4404  validateInfiniteBounds(pstate, result);
4405 
4406  return result;
4407 }
int j
Definition: isn.c:74
static void validateInfiniteBounds(ParseState *pstate, List *blist)
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition: parsenodes.h:913
@ PARTITION_RANGE_DATUM_VALUE
Definition: parsenodes.h:912
@ PARTITION_RANGE_DATUM_MINVALUE
Definition: parsenodes.h:911
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * fields
Definition: parsenodes.h:284
PartitionRangeDatumKind kind
Definition: parsenodes.h:920
Definition: value.h:64

References deparse_context_for(), deparse_expression(), ereport, errcode(), errmsg(), ERROR, exprLocation(), ColumnRef::fields, get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), i, IsA, j, sort-test::key, PartitionRangeDatum::kind, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionRangeDatum::location, makeNode, NIL, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, strVal, transformPartitionBoundValue(), validateInfiniteBounds(), PartitionRangeDatum::value, and value.

Referenced by transformPartitionBound().

◆ transformRuleStmt()

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

Definition at line 3123 of file parse_utilcmd.c.

3125 {
3126  Relation rel;
3127  ParseState *pstate;
3128  ParseNamespaceItem *oldnsitem;
3129  ParseNamespaceItem *newnsitem;
3130 
3131  /*
3132  * To avoid deadlock, make sure the first thing we do is grab
3133  * AccessExclusiveLock on the target relation. This will be needed by
3134  * DefineQueryRewrite(), and we don't want to grab a lesser lock
3135  * beforehand.
3136  */
3137  rel = table_openrv(stmt->relation, AccessExclusiveLock);
3138 
3139  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3140  ereport(ERROR,
3141  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3142  errmsg("rules on materialized views are not supported")));
3143 
3144  /* Set up pstate */
3145  pstate = make_parsestate(NULL);
3146  pstate->p_sourcetext = queryString;
3147 
3148  /*
3149  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3150  * Set up their ParseNamespaceItems in the main pstate for use in parsing
3151  * the rule qualification.
3152  */
3153  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3155  makeAlias("old", NIL),
3156  false, false);
3157  newnsitem = addRangeTableEntryForRelation(pstate, rel,
3159  makeAlias("new", NIL),
3160  false, false);
3161 
3162  /*
3163  * They must be in the namespace too for lookup purposes, but only add the
3164  * one(s) that are relevant for the current kind of rule. In an UPDATE
3165  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3166  * there's no need to be so picky for INSERT & DELETE. We do not add them
3167  * to the joinlist.
3168  */
3169  switch (stmt->event)
3170  {
3171  case CMD_SELECT:
3172  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3173  break;
3174  case CMD_UPDATE:
3175  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3176  addNSItemToQuery(pstate, newnsitem, false, true, true);
3177  break;
3178  case CMD_INSERT:
3179  addNSItemToQuery(pstate, newnsitem, false, true, true);
3180  break;
3181  case CMD_DELETE:
3182  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3183  break;
3184  default:
3185  elog(ERROR, "unrecognized event type: %d",
3186  (int) stmt->event);
3187  break;
3188  }
3189 
3190  /* take care of the where clause */
3191  *whereClause = transformWhereClause(pstate,
3192  stmt->whereClause,
3194  "WHERE");
3195  /* we have to fix its collations too */
3196  assign_expr_collations(pstate, *whereClause);
3197 
3198  /* this is probably dead code without add_missing_from: */
3199  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3200  ereport(ERROR,
3201  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3202  errmsg("rule WHERE condition cannot contain references to other relations")));
3203 
3204  /*
3205  * 'instead nothing' rules with a qualification need a query rangetable so
3206  * the rewrite handler can add the negated rule qualification to the
3207  * original query. We create a query with the new command type CMD_NOTHING
3208  * here that is treated specially by the rewrite system.
3209  */
3210  if (stmt->actions == NIL)
3211  {
3212  Query *nothing_qry = makeNode(Query);
3213 
3214  nothing_qry->commandType = CMD_NOTHING;
3215  nothing_qry->rtable = pstate->p_rtable;
3216  nothing_qry->rteperminfos = pstate->p_rteperminfos;
3217  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3218 
3219  *actions = list_make1(nothing_qry);
3220  }
3221  else
3222  {
3223  ListCell *l;
3224  List *newactions = NIL;
3225 
3226  /*
3227  * transform each statement, like parse_sub_analyze()
3228  */
3229  foreach(l, stmt->actions)
3230  {
3231  Node *action = (Node *) lfirst(l);
3232  ParseState *sub_pstate = make_parsestate(NULL);
3233  Query *sub_qry,
3234  *top_subqry;
3235  bool has_old,
3236  has_new;
3237 
3238  /*
3239  * Since outer ParseState isn't parent of inner, have to pass down
3240  * the query text by hand.
3241  */
3242  sub_pstate->p_sourcetext = queryString;
3243 
3244  /*
3245  * Set up OLD/NEW in the rtable for this statement. The entries
3246  * are added only to relnamespace, not varnamespace, because we
3247  * don't want them to be referred to by unqualified field names
3248  * nor "*" in the rule actions. We decide later whether to put
3249  * them in the joinlist.
3250  */
3251  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3253  makeAlias("old", NIL),
3254  false, false);
3255  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3257  makeAlias("new", NIL),
3258  false, false);
3259  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3260  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3261 
3262  /* Transform the rule action statement */
3263  top_subqry = transformStmt(sub_pstate, action);
3264 
3265  /*
3266  * We cannot support utility-statement actions (eg NOTIFY) with
3267  * nonempty rule WHERE conditions, because there's no way to make
3268  * the utility action execute conditionally.
3269  */
3270  if (top_subqry->commandType == CMD_UTILITY &&
3271  *whereClause != NULL)
3272  ereport(ERROR,
3273  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3274  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3275 
3276  /*
3277  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3278  * into the SELECT, and that's what we need to look at. (Ugly
3279  * kluge ... try to fix this when we redesign querytrees.)
3280  */
3281  sub_qry = getInsertSelectQuery(top_subqry, NULL);
3282 
3283  /*
3284  * If the sub_qry is a setop, we cannot attach any qualifications
3285  * to it, because the planner won't notice them. This could
3286  * perhaps be relaxed someday, but for now, we may as well reject
3287  * such a rule immediately.
3288  */
3289  if (sub_qry->setOperations != NULL && *whereClause != NULL)
3290  ereport(ERROR,
3291  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3292  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3293 
3294  /*
3295  * Validate action's use of OLD/NEW, qual too
3296  */
3297  has_old =
3298  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3299  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3300  has_new =
3301  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3302  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3303 
3304  switch (stmt->event)
3305  {
3306  case CMD_SELECT:
3307  if (has_old)
3308  ereport(ERROR,
3309  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3310  errmsg("ON SELECT rule cannot use OLD")));
3311  if (has_new)
3312  ereport(ERROR,
3313  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3314  errmsg("ON SELECT rule cannot use NEW")));
3315  break;
3316  case CMD_UPDATE:
3317  /* both are OK */
3318  break;
3319  case CMD_INSERT:
3320  if (has_old)
3321  ereport(ERROR,
3322  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3323  errmsg("ON INSERT rule cannot use OLD")));
3324  break;
3325  case CMD_DELETE:
3326  if (has_new)
3327  ereport(ERROR,
3328  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3329  errmsg("ON DELETE rule cannot use NEW")));
3330  break;
3331  default:
3332  elog(ERROR, "unrecognized event type: %d",
3333  (int) stmt->event);
3334  break;
3335  }
3336 
3337  /*
3338  * OLD/NEW are not allowed in WITH queries, because they would
3339  * amount to outer references for the WITH, which we disallow.
3340  * However, they were already in the outer rangetable when we
3341  * analyzed the query, so we have to check.
3342  *
3343  * Note that in the INSERT...SELECT case, we need to examine the
3344  * CTE lists of both top_subqry and sub_qry.
3345  *
3346  * Note that we aren't digging into the body of the query looking
3347  * for WITHs in nested sub-SELECTs. A WITH down there can
3348  * legitimately refer to OLD/NEW, because it'd be an
3349  * indirect-correlated outer reference.
3350  */
3351  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3352  PRS2_OLD_VARNO, 0) ||
3353  rangeTableEntry_used((Node *) sub_qry->cteList,
3354  PRS2_OLD_VARNO, 0))
3355  ereport(ERROR,
3356  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357  errmsg("cannot refer to OLD within WITH query")));
3358  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3359  PRS2_NEW_VARNO, 0) ||
3360  rangeTableEntry_used((Node *) sub_qry->cteList,
3361  PRS2_NEW_VARNO, 0))
3362  ereport(ERROR,
3363  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364  errmsg("cannot refer to NEW within WITH query")));
3365 
3366  /*
3367  * For efficiency's sake, add OLD to the rule action's jointree
3368  * only if it was actually referenced in the statement or qual.
3369  *
3370  * For INSERT, NEW is not really a relation (only a reference to
3371  * the to-be-inserted tuple) and should never be added to the
3372  * jointree.
3373  *
3374  * For UPDATE, we treat NEW as being another kind of reference to
3375  * OLD, because it represents references to *transformed* tuples
3376  * of the existing relation. It would be wrong to enter NEW
3377  * separately in the jointree, since that would cause a double
3378  * join of the updated relation. It's also wrong to fail to make
3379  * a jointree entry if only NEW and not OLD is mentioned.
3380  */
3381  if (has_old || (has_new && stmt->event == CMD_UPDATE))
3382  {
3383  RangeTblRef *rtr;
3384 
3385  /*
3386  * If sub_qry is a setop, manipulating its jointree will do no
3387  * good at all, because the jointree is dummy. (This should be
3388  * a can't-happen case because of prior tests.)
3389  */
3390  if (sub_qry->setOperations != NULL)
3391  ereport(ERROR,
3392  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3393  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3394  /* hackishly add OLD to the already-built FROM clause */
3395  rtr = makeNode(RangeTblRef);
3396  rtr->rtindex = oldnsitem->p_rtindex;
3397  sub_qry->jointree->fromlist =
3398  lappend(sub_qry->jointree->fromlist, rtr);
3399  }
3400 
3401  newactions = lappend(newactions, top_subqry);
3402 
3403  free_parsestate(sub_pstate);
3404  }
3405 
3406  *actions = newactions;
3407  }
3408 
3409  free_parsestate(pstate);
3410 
3411  /* Close relation, but keep the exclusive lock */
3412  table_close(rel, NoLock);
3413 }
#define AccessExclusiveLock
Definition: lockdefs.h:43
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:390
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:288
@ CMD_UTILITY
Definition: nodes.h:260
@ CMD_INSERT
Definition: nodes.h:257
@ CMD_DELETE
Definition: nodes.h:258
@ CMD_UPDATE
Definition: nodes.h:256
@ CMD_SELECT
Definition: nodes.h:255
@ CMD_NOTHING
Definition: nodes.h:262
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:314
#define PRS2_OLD_VARNO
Definition: primnodes.h:230
#define PRS2_NEW_VARNO
Definition: primnodes.h:231
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:990
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:958
List * fromlist
Definition: primnodes.h:2040
List * p_rteperminfos
Definition: parse_node.h:194
FromExpr * jointree
Definition: parsenodes.h:174
Node * setOperations
Definition: parsenodes.h:209
List * cteList
Definition: parsenodes.h:165
List * rtable
Definition: parsenodes.h:167
CmdType commandType
Definition: parsenodes.h:120

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, 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, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, Query::rtable, RangeTblRef::rtindex, Query::setOperations, stmt, table_close(), table_openrv(), transformStmt(), and transformWhereClause().

Referenced by DefineRule().

◆ transformStatsStmt()

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

Definition at line 3048 of file parse_utilcmd.c.

3049 {
3050  ParseState *pstate;
3051  ParseNamespaceItem *nsitem;
3052  ListCell *l;
3053  Relation rel;
3