PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
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 (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 *con, 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)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *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)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
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))

Referenced by transformConstraintAttrs().

Function Documentation

◆ generateClonedExtStatsStmt()

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

Definition at line 1700 of file parse_utilcmd.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog, ERROR, CreateStatsStmt::exprs, ColumnRef::fields, get_attname(), GETSTRUCT, HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, lappend(), list_make1, ColumnRef::location, makeNode, makeString(), NIL, ObjectIdGetDatum, OidIsValid, CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, STATEXTOID, CreateStatsStmt::stxcomment, and SysCacheGetAttr().

Referenced by transformTableLikeClause().

1702 {
1703  HeapTuple ht_stats;
1704  Form_pg_statistic_ext statsrec;
1705  CreateStatsStmt *stats;
1706  List *stat_types = NIL;
1707  List *def_names = NIL;
1708  bool isnull;
1709  Datum datum;
1710  ArrayType *arr;
1711  char *enabled;
1712  int i;
1713 
1714  Assert(OidIsValid(heapRelid));
1715  Assert(heapRel != NULL);
1716 
1717  /*
1718  * Fetch pg_statistic_ext tuple of source statistics object.
1719  */
1720  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1721  if (!HeapTupleIsValid(ht_stats))
1722  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1723  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1724 
1725  /* Determine which statistics types exist */
1726  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1727  Anum_pg_statistic_ext_stxkind, &isnull);
1728  Assert(!isnull);
1729  arr = DatumGetArrayTypeP(datum);
1730  if (ARR_NDIM(arr) != 1 ||
1731  ARR_HASNULL(arr) ||
1732  ARR_ELEMTYPE(arr) != CHAROID)
1733  elog(ERROR, "stxkind is not a 1-D char array");
1734  enabled = (char *) ARR_DATA_PTR(arr);
1735  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1736  {
1737  if (enabled[i] == STATS_EXT_NDISTINCT)
1738  stat_types = lappend(stat_types, makeString("ndistinct"));
1739  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1740  stat_types = lappend(stat_types, makeString("dependencies"));
1741  else if (enabled[i] == STATS_EXT_MCV)
1742  stat_types = lappend(stat_types, makeString("mcv"));
1743  else
1744  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1745  }
1746 
1747  /* Determine which columns the statistics are on */
1748  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1749  {
1750  ColumnRef *cref = makeNode(ColumnRef);
1751  AttrNumber attnum = statsrec->stxkeys.values[i];
1752 
1753  cref->fields = list_make1(makeString(get_attname(heapRelid,
1754  attnum, false)));
1755  cref->location = -1;
1756 
1757  def_names = lappend(def_names, cref);
1758  }
1759 
1760  /* finally, build the output node */
1761  stats = makeNode(CreateStatsStmt);
1762  stats->defnames = NULL;
1763  stats->stat_types = stat_types;
1764  stats->exprs = def_names;
1765  stats->relations = list_make1(heapRel);
1766  stats->stxcomment = NULL;
1767  stats->if_not_exists = false;
1768 
1769  /* Clean up */
1770  ReleaseSysCache(ht_stats);
1771 
1772  return stats;
1773 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define OidIsValid(objectId)
Definition: c.h:645
int location
Definition: parsenodes.h:236
#define list_make1(x1)
Definition: pg_list.h:227
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
#define ARR_HASNULL(a)
Definition: array.h:279
List * lappend(List *list, void *datum)
Definition: list.c:322
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:573
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define ARR_NDIM(a)
Definition: array.h:278
#define elog(elevel,...)
Definition: elog.h:228
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
Definition: pg_list.h:50
#define ARR_ELEMTYPE(a)
Definition: array.h:280
int16 AttrNumber
Definition: attnum.h:21
List * fields
Definition: parsenodes.h:235
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ generateClonedIndexStmt()

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

Definition at line 1345 of file parse_utilcmd.c.

References IndexStmt::accessMethod, IndexAmRoutine::amcanorder, AMOID, Assert, attname, attnum, AttributeNumberIsValid, IndexElem::collation, IndexStmt::concurrent, CONSTROID, DatumGetArrayTypeP, DatumGetObjectId, DatumGetPointer, deconstruct_array(), IndexStmt::deferrable, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, IndexElem::expr, exprType(), get_attname(), get_atttype(), get_collation(), get_index_constraint(), get_namespace_name(), get_opclass(), get_tablespace_name(), GETSTRUCT, HeapTupleIsValid, i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexElem::indexcolname, IndexStmt::indexIncludingParams, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, IndexStmt::initdeferred, InvalidOid, IndexStmt::isconstraint, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexStmt::oldNode, IndexElem::opclass, OPEROID, IndexStmt::options, IndexElem::ordering, IndexStmt::primary, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELOID, IndexStmt::reset_default_tblspc, SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), IndexStmt::tableSpace, TextDatumGetCString, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

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

1348 {
1349  Oid source_relid = RelationGetRelid(source_idx);
1350  HeapTuple ht_idxrel;
1351  HeapTuple ht_idx;
1352  HeapTuple ht_am;
1353  Form_pg_class idxrelrec;
1354  Form_pg_index idxrec;
1355  Form_pg_am amrec;
1356  oidvector *indcollation;
1357  oidvector *indclass;
1358  IndexStmt *index;
1359  List *indexprs;
1360  ListCell *indexpr_item;
1361  Oid indrelid;
1362  int keyno;
1363  Oid keycoltype;
1364  Datum datum;
1365  bool isnull;
1366 
1367  if (constraintOid)
1368  *constraintOid = InvalidOid;
1369 
1370  /*
1371  * Fetch pg_class tuple of source index. We can't use the copy in the
1372  * relcache entry because it doesn't include optional fields.
1373  */
1374  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1375  if (!HeapTupleIsValid(ht_idxrel))
1376  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1377  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1378 
1379  /* Fetch pg_index tuple for source index from relcache entry */
1380  ht_idx = source_idx->rd_indextuple;
1381  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1382  indrelid = idxrec->indrelid;
1383 
1384  /* Fetch the pg_am tuple of the index' access method */
1385  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1386  if (!HeapTupleIsValid(ht_am))
1387  elog(ERROR, "cache lookup failed for access method %u",
1388  idxrelrec->relam);
1389  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1390 
1391  /* Extract indcollation from the pg_index tuple */
1392  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1393  Anum_pg_index_indcollation, &isnull);
1394  Assert(!isnull);
1395  indcollation = (oidvector *) DatumGetPointer(datum);
1396 
1397  /* Extract indclass from the pg_index tuple */
1398  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1399  Anum_pg_index_indclass, &isnull);
1400  Assert(!isnull);
1401  indclass = (oidvector *) DatumGetPointer(datum);
1402 
1403  /* Begin building the IndexStmt */
1404  index = makeNode(IndexStmt);
1405  index->relation = heapRel;
1406  index->accessMethod = pstrdup(NameStr(amrec->amname));
1407  if (OidIsValid(idxrelrec->reltablespace))
1408  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1409  else
1410  index->tableSpace = NULL;
1411  index->excludeOpNames = NIL;
1412  index->idxcomment = NULL;
1413  index->indexOid = InvalidOid;
1414  index->oldNode = InvalidOid;
1415  index->unique = idxrec->indisunique;
1416  index->primary = idxrec->indisprimary;
1417  index->transformed = true; /* don't need transformIndexStmt */
1418  index->concurrent = false;
1419  index->if_not_exists = false;
1420  index->reset_default_tblspc = false;
1421 
1422  /*
1423  * We don't try to preserve the name of the source index; instead, just
1424  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1425  * the name, we'd get duplicate-relation-name failures unless the source
1426  * table was in a different schema.)
1427  */
1428  index->idxname = NULL;
1429 
1430  /*
1431  * If the index is marked PRIMARY or has an exclusion condition, it's
1432  * certainly from a constraint; else, if it's not marked UNIQUE, it
1433  * certainly isn't. If it is or might be from a constraint, we have to
1434  * fetch the pg_constraint record.
1435  */
1436  if (index->primary || index->unique || idxrec->indisexclusion)
1437  {
1438  Oid constraintId = get_index_constraint(source_relid);
1439 
1440  if (OidIsValid(constraintId))
1441  {
1442  HeapTuple ht_constr;
1443  Form_pg_constraint conrec;
1444 
1445  if (constraintOid)
1446  *constraintOid = constraintId;
1447 
1448  ht_constr = SearchSysCache1(CONSTROID,
1449  ObjectIdGetDatum(constraintId));
1450  if (!HeapTupleIsValid(ht_constr))
1451  elog(ERROR, "cache lookup failed for constraint %u",
1452  constraintId);
1453  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1454 
1455  index->isconstraint = true;
1456  index->deferrable = conrec->condeferrable;
1457  index->initdeferred = conrec->condeferred;
1458 
1459  /* If it's an exclusion constraint, we need the operator names */
1460  if (idxrec->indisexclusion)
1461  {
1462  Datum *elems;
1463  int nElems;
1464  int i;
1465 
1466  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1467  /* Extract operator OIDs from the pg_constraint tuple */
1468  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1469  Anum_pg_constraint_conexclop,
1470  &isnull);
1471  if (isnull)
1472  elog(ERROR, "null conexclop for constraint %u",
1473  constraintId);
1474 
1476  OIDOID, sizeof(Oid), true, 'i',
1477  &elems, NULL, &nElems);
1478 
1479  for (i = 0; i < nElems; i++)
1480  {
1481  Oid operid = DatumGetObjectId(elems[i]);
1482  HeapTuple opertup;
1483  Form_pg_operator operform;
1484  char *oprname;
1485  char *nspname;
1486  List *namelist;
1487 
1488  opertup = SearchSysCache1(OPEROID,
1489  ObjectIdGetDatum(operid));
1490  if (!HeapTupleIsValid(opertup))
1491  elog(ERROR, "cache lookup failed for operator %u",
1492  operid);
1493  operform = (Form_pg_operator) GETSTRUCT(opertup);
1494  oprname = pstrdup(NameStr(operform->oprname));
1495  /* For simplicity we always schema-qualify the op name */
1496  nspname = get_namespace_name(operform->oprnamespace);
1497  namelist = list_make2(makeString(nspname),
1498  makeString(oprname));
1499  index->excludeOpNames = lappend(index->excludeOpNames,
1500  namelist);
1501  ReleaseSysCache(opertup);
1502  }
1503  }
1504 
1505  ReleaseSysCache(ht_constr);
1506  }
1507  else
1508  index->isconstraint = false;
1509  }
1510  else
1511  index->isconstraint = false;
1512 
1513  /* Get the index expressions, if any */
1514  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1515  Anum_pg_index_indexprs, &isnull);
1516  if (!isnull)
1517  {
1518  char *exprsString;
1519 
1520  exprsString = TextDatumGetCString(datum);
1521  indexprs = (List *) stringToNode(exprsString);
1522  }
1523  else
1524  indexprs = NIL;
1525 
1526  /* Build the list of IndexElem */
1527  index->indexParams = NIL;
1528  index->indexIncludingParams = NIL;
1529 
1530  indexpr_item = list_head(indexprs);
1531  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1532  {
1533  IndexElem *iparam;
1534  AttrNumber attnum = idxrec->indkey.values[keyno];
1536  keyno);
1537  int16 opt = source_idx->rd_indoption[keyno];
1538 
1539  iparam = makeNode(IndexElem);
1540 
1541  if (AttributeNumberIsValid(attnum))
1542  {
1543  /* Simple index column */
1544  char *attname;
1545 
1546  attname = get_attname(indrelid, attnum, false);
1547  keycoltype = get_atttype(indrelid, attnum);
1548 
1549  iparam->name = attname;
1550  iparam->expr = NULL;
1551  }
1552  else
1553  {
1554  /* Expressional index */
1555  Node *indexkey;
1556  bool found_whole_row;
1557 
1558  if (indexpr_item == NULL)
1559  elog(ERROR, "too few entries in indexprs list");
1560  indexkey = (Node *) lfirst(indexpr_item);
1561  indexpr_item = lnext(indexprs, indexpr_item);
1562 
1563  /* Adjust Vars to match new table's column numbering */
1564  indexkey = map_variable_attnos(indexkey,
1565  1, 0,
1566  attmap,
1567  InvalidOid, &found_whole_row);
1568 
1569  /* As in transformTableLikeClause, reject whole-row variables */
1570  if (found_whole_row)
1571  ereport(ERROR,
1572  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1573  errmsg("cannot convert whole-row table reference"),
1574  errdetail("Index \"%s\" contains a whole-row table reference.",
1575  RelationGetRelationName(source_idx))));
1576 
1577  iparam->name = NULL;
1578  iparam->expr = indexkey;
1579 
1580  keycoltype = exprType(indexkey);
1581  }
1582 
1583  /* Copy the original index column name */
1584  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1585 
1586  /* Add the collation name, if non-default */
1587  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1588 
1589  /* Add the operator class name, if non-default */
1590  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1591 
1592  iparam->ordering = SORTBY_DEFAULT;
1594 
1595  /* Adjust options if necessary */
1596  if (source_idx->rd_indam->amcanorder)
1597  {
1598  /*
1599  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1600  * set non-default settings unnecessarily, though, so as to
1601  * improve the chance of recognizing equivalence to constraint
1602  * indexes.
1603  */
1604  if (opt & INDOPTION_DESC)
1605  {
1606  iparam->ordering = SORTBY_DESC;
1607  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1609  }
1610  else
1611  {
1612  if (opt & INDOPTION_NULLS_FIRST)
1614  }
1615  }
1616 
1617  index->indexParams = lappend(index->indexParams, iparam);
1618  }
1619 
1620  /* Handle included columns separately */
1621  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1622  {
1623  IndexElem *iparam;
1624  AttrNumber attnum = idxrec->indkey.values[keyno];
1626  keyno);
1627 
1628  iparam = makeNode(IndexElem);
1629 
1630  if (AttributeNumberIsValid(attnum))
1631  {
1632  /* Simple index column */
1633  char *attname;
1634 
1635  attname = get_attname(indrelid, attnum, false);
1636  keycoltype = get_atttype(indrelid, attnum);
1637 
1638  iparam->name = attname;
1639  iparam->expr = NULL;
1640  }
1641  else
1642  ereport(ERROR,
1643  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1644  errmsg("expressions are not supported in included columns")));
1645 
1646  /* Copy the original index column name */
1647  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1648 
1649  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1650  }
1651  /* Copy reloptions if any */
1652  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1653  Anum_pg_class_reloptions, &isnull);
1654  if (!isnull)
1655  index->options = untransformRelOptions(datum);
1656 
1657  /* If it's a partial index, decompile and append the predicate */
1658  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1659  Anum_pg_index_indpred, &isnull);
1660  if (!isnull)
1661  {
1662  char *pred_str;
1663  Node *pred_tree;
1664  bool found_whole_row;
1665 
1666  /* Convert text string to node tree */
1667  pred_str = TextDatumGetCString(datum);
1668  pred_tree = (Node *) stringToNode(pred_str);
1669 
1670  /* Adjust Vars to match new table's column numbering */
1671  pred_tree = map_variable_attnos(pred_tree,
1672  1, 0,
1673  attmap,
1674  InvalidOid, &found_whole_row);
1675 
1676  /* As in transformTableLikeClause, reject whole-row variables */
1677  if (found_whole_row)
1678  ereport(ERROR,
1679  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1680  errmsg("cannot convert whole-row table reference"),
1681  errdetail("Index \"%s\" contains a whole-row table reference.",
1682  RelationGetRelationName(source_idx))));
1683 
1684  index->whereClause = pred_tree;
1685  }
1686 
1687  /* Clean up */
1688  ReleaseSysCache(ht_idxrel);
1689  ReleaseSysCache(ht_am);
1690 
1691  return index;
1692 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
bool deferrable
Definition: parsenodes.h:2788
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:346
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:595
bool primary
Definition: parsenodes.h:2786
struct IndexAmRoutine * rd_indam
Definition: rel.h:163
int16 * rd_indoption
Definition: rel.h:168
SortByDir ordering
Definition: parsenodes.h:704
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2779
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:454
char * tableSpace
Definition: parsenodes.h:2775
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * whereClause
Definition: parsenodes.h:2780
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
void * stringToNode(const char *str)
Definition: read.c:89
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
struct HeapTupleData * rd_indextuple
Definition: rel.h:151
List * indexIncludingParams
Definition: parsenodes.h:2777
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2783
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parsenodes.h:2773
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:603
bool transformed
Definition: parsenodes.h:2790
int errdetail(const char *fmt,...)
Definition: elog.c:955
char * indexcolname
Definition: parsenodes.h:701
#define RelationGetRelationName(relation)
Definition: rel.h:462
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:873
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
char * idxname
Definition: parsenodes.h:2772
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:84
bool reset_default_tblspc
Definition: parsenodes.h:2793
bool if_not_exists
Definition: parsenodes.h:2792
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2785
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1039
char * accessMethod
Definition: parsenodes.h:2774
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
List * opclass
Definition: parsenodes.h:703
#define makeNode(_type_)
Definition: nodes.h:573
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2776
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2781
bool initdeferred
Definition: parsenodes.h:2789
bool amcanorder
Definition: amapi.h:175
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2782
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define DatumGetPointer(X)
Definition: postgres.h:549
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3461
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
bool concurrent
Definition: parsenodes.h:2791
bool isconstraint
Definition: parsenodes.h:2787
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1462
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:616
List * collation
Definition: parsenodes.h:702
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:428
#define DatumGetArrayTypeP(X)
Definition: array.h:249

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

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

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

353 {
354  ListCell *option;
355  DefElem *nameEl = NULL;
356  Oid snamespaceid;
357  char *snamespace;
358  char *sname;
359  CreateSeqStmt *seqstmt;
360  AlterSeqStmt *altseqstmt;
361  List *attnamelist;
362 
363  /*
364  * Determine namespace and name to use for the sequence.
365  *
366  * First, check if a sequence name was passed in as an option. This is
367  * used by pg_dump. Else, generate a name.
368  *
369  * Although we use ChooseRelationName, it's not guaranteed that the
370  * selected sequence name won't conflict; given sufficiently long field
371  * names, two different serial columns in the same table could be assigned
372  * the same sequence name, and we'd not notice since we aren't creating
373  * the sequence quite yet. In practice this seems quite unlikely to be a
374  * problem, especially since few people would need two serial columns in
375  * one table.
376  */
377  foreach(option, seqoptions)
378  {
379  DefElem *defel = lfirst_node(DefElem, option);
380 
381  if (strcmp(defel->defname, "sequence_name") == 0)
382  {
383  if (nameEl)
384  ereport(ERROR,
385  (errcode(ERRCODE_SYNTAX_ERROR),
386  errmsg("conflicting or redundant options")));
387  nameEl = defel;
388  }
389  }
390 
391  if (nameEl)
392  {
394 
395  snamespace = rv->schemaname;
396  if (!snamespace)
397  {
398  /* Given unqualified SEQUENCE NAME, select namespace */
399  if (cxt->rel)
400  snamespaceid = RelationGetNamespace(cxt->rel);
401  else
402  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
403  snamespace = get_namespace_name(snamespaceid);
404  }
405  sname = rv->relname;
406  /* Remove the SEQUENCE NAME item from seqoptions */
407  seqoptions = list_delete_ptr(seqoptions, nameEl);
408  }
409  else
410  {
411  if (cxt->rel)
412  snamespaceid = RelationGetNamespace(cxt->rel);
413  else
414  {
415  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
416  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
417  }
418  snamespace = get_namespace_name(snamespaceid);
419  sname = ChooseRelationName(cxt->relation->relname,
420  column->colname,
421  "seq",
422  snamespaceid,
423  false);
424  }
425 
426  ereport(DEBUG1,
427  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
428  cxt->stmtType, sname,
429  cxt->relation->relname, column->colname)));
430 
431  /*
432  * Build a CREATE SEQUENCE command to create the sequence object, and add
433  * it to the list of things to be done before this CREATE/ALTER TABLE.
434  */
435  seqstmt = makeNode(CreateSeqStmt);
436  seqstmt->for_identity = for_identity;
437  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
438  seqstmt->options = seqoptions;
439 
440  /*
441  * If a sequence data type was specified, add it to the options. Prepend
442  * to the list rather than append; in case a user supplied their own AS
443  * clause, the "redundant options" error will point to their occurrence,
444  * not our synthetic one.
445  */
446  if (seqtypid)
447  seqstmt->options = lcons(makeDefElem("as",
448  (Node *) makeTypeNameFromOid(seqtypid, -1),
449  -1),
450  seqstmt->options);
451 
452  /*
453  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
454  * the table's owner. The current user might be someone else (perhaps a
455  * superuser, or someone who's only a member of the owning role), but the
456  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
457  * exactly the same owning role.
458  */
459  if (cxt->rel)
460  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
461  else
462  seqstmt->ownerId = InvalidOid;
463 
464  cxt->blist = lappend(cxt->blist, seqstmt);
465 
466  /*
467  * Store the identity sequence name that we decided on. ALTER TABLE ...
468  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
469  * with values from the sequence, while the association of the sequence
470  * with the table is not set until after the ALTER TABLE.
471  */
472  column->identitySequence = seqstmt->sequence;
473 
474  /*
475  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
476  * owned by this column, and add it to the appropriate list of things to
477  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
478  * COLUMN, it must be done after the statement because we don't know the
479  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
480  * we can do the marking immediately, which improves some ALTER TABLE
481  * behaviors.
482  */
483  altseqstmt = makeNode(AlterSeqStmt);
484  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
485  attnamelist = list_make3(makeString(snamespace),
486  makeString(cxt->relation->relname),
487  makeString(column->colname));
488  altseqstmt->options = list_make1(makeDefElem("owned_by",
489  (Node *) attnamelist, -1));
490  altseqstmt->for_identity = for_identity;
491 
492  if (col_exists)
493  cxt->blist = lappend(cxt->blist, altseqstmt);
494  else
495  cxt->alist = lappend(cxt->alist, altseqstmt);
496 
497  if (snamespace_p)
498  *snamespace_p = snamespace;
499  if (sname_p)
500  *sname_p = sname;
501 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:231
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3054
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:797
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2151
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:633
List * options
Definition: parsenodes.h:2553
char * schemaname
Definition: primnodes.h:67
#define list_make1(x1)
Definition: pg_list.h:227
RangeVar * identitySequence
Definition: parsenodes.h:656
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define ereport(elevel, rest)
Definition: elog.h:141
Node * arg
Definition: parsenodes.h:731
List * lappend(List *list, void *datum)
Definition: list.c:322
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2552
RangeVar * sequence
Definition: parsenodes.h:2542
List * lcons(void *datum, List *list)
Definition: list.c:454
#define makeNode(_type_)
Definition: nodes.h:573
const char * stmtType
Definition: parse_utilcmd.c:79
int errmsg(const char *fmt,...)
Definition: elog.c:822
bool for_identity
Definition: parsenodes.h:2554
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:646
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:441
List * options
Definition: parsenodes.h:2543
#define RelationGetNamespace(relation)
Definition: rel.h:469

◆ get_collation()

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

Definition at line 1782 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1783 {
1784  List *result;
1785  HeapTuple ht_coll;
1786  Form_pg_collation coll_rec;
1787  char *nsp_name;
1788  char *coll_name;
1789 
1790  if (!OidIsValid(collation))
1791  return NIL; /* easy case */
1792  if (collation == get_typcollation(actual_datatype))
1793  return NIL; /* just let it default */
1794 
1795  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1796  if (!HeapTupleIsValid(ht_coll))
1797  elog(ERROR, "cache lookup failed for collation %u", collation);
1798  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1799 
1800  /* For simplicity, we always schema-qualify the name */
1801  nsp_name = get_namespace_name(coll_rec->collnamespace);
1802  coll_name = pstrdup(NameStr(coll_rec->collname));
1803  result = list_make2(makeString(nsp_name), makeString(coll_name));
1804 
1805  ReleaseSysCache(ht_coll);
1806  return result;
1807 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define OidIsValid(objectId)
Definition: c.h:645
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616
Definition: pg_list.h:50

◆ get_opclass()

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

Definition at line 1816 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1817 {
1818  List *result = NIL;
1819  HeapTuple ht_opc;
1820  Form_pg_opclass opc_rec;
1821 
1822  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1823  if (!HeapTupleIsValid(ht_opc))
1824  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1825  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1826 
1827  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1828  {
1829  /* For simplicity, we always schema-qualify the name */
1830  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1831  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1832 
1833  result = list_make2(makeString(nsp_name), makeString(opc_name));
1834  }
1835 
1836  ReleaseSysCache(ht_opc);
1837  return result;
1838 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1956
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
Definition: pg_list.h:50

◆ setSchemaName()

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

Definition at line 3667 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3668 {
3669  if (*stmt_schema_name == NULL)
3670  *stmt_schema_name = context_schema;
3671  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3672  ereport(ERROR,
3673  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3674  errmsg("CREATE specifies a schema (%s) "
3675  "different from the one being created (%s)",
3676  *stmt_schema_name, context_schema)));
3677 }
int errcode(int sqlerrcode)
Definition: elog.c:608
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ transformAlterTableStmt()

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

Definition at line 3027 of file parse_utilcmd.c.

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

3030 {
3031  Relation rel;
3032  TupleDesc tupdesc;
3033  ParseState *pstate;
3034  CreateStmtContext cxt;
3035  List *save_alist;
3036  ListCell *lcmd,
3037  *l;
3038  List *newcmds = NIL;
3039  bool skipValidation = true;
3040  AlterTableCmd *newcmd;
3041  ParseNamespaceItem *nsitem;
3042 
3043  /*
3044  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3045  * is overkill, but easy.)
3046  */
3047  stmt = copyObject(stmt);
3048 
3049  /* Caller is responsible for locking the relation */
3050  rel = relation_open(relid, NoLock);
3051  tupdesc = RelationGetDescr(rel);
3052 
3053  /* Set up pstate */
3054  pstate = make_parsestate(NULL);
3055  pstate->p_sourcetext = queryString;
3056  nsitem = addRangeTableEntryForRelation(pstate,
3057  rel,
3059  NULL,
3060  false,
3061  true);
3062  addNSItemToQuery(pstate, nsitem, false, true, true);
3063 
3064  /* Set up CreateStmtContext */
3065  cxt.pstate = pstate;
3066  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3067  {
3068  cxt.stmtType = "ALTER FOREIGN TABLE";
3069  cxt.isforeign = true;
3070  }
3071  else
3072  {
3073  cxt.stmtType = "ALTER TABLE";
3074  cxt.isforeign = false;
3075  }
3076  cxt.relation = stmt->relation;
3077  cxt.rel = rel;
3078  cxt.inhRelations = NIL;
3079  cxt.isalter = true;
3080  cxt.columns = NIL;
3081  cxt.ckconstraints = NIL;
3082  cxt.fkconstraints = NIL;
3083  cxt.ixconstraints = NIL;
3084  cxt.inh_indexes = NIL;
3085  cxt.extstats = NIL;
3086  cxt.blist = NIL;
3087  cxt.alist = NIL;
3088  cxt.pkey = NULL;
3089  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3090  cxt.partbound = NULL;
3091  cxt.ofType = false;
3092 
3093  /*
3094  * Transform ALTER subcommands that need it (most don't). These largely
3095  * re-use code from CREATE TABLE.
3096  */
3097  foreach(lcmd, stmt->cmds)
3098  {
3099  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3100 
3101  switch (cmd->subtype)
3102  {
3103  case AT_AddColumn:
3104  case AT_AddColumnRecurse:
3105  {
3106  ColumnDef *def = castNode(ColumnDef, cmd->def);
3107 
3108  transformColumnDefinition(&cxt, def);
3109 
3110  /*
3111  * If the column has a non-null default, we can't skip
3112  * validation of foreign keys.
3113  */
3114  if (def->raw_default != NULL)
3115  skipValidation = false;
3116 
3117  /*
3118  * All constraints are processed in other ways. Remove the
3119  * original list
3120  */
3121  def->constraints = NIL;
3122 
3123  newcmds = lappend(newcmds, cmd);
3124  break;
3125  }
3126 
3127  case AT_AddConstraint:
3129 
3130  /*
3131  * The original AddConstraint cmd node doesn't go to newcmds
3132  */
3133  if (IsA(cmd->def, Constraint))
3134  {
3135  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3136  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3137  skipValidation = false;
3138  }
3139  else
3140  elog(ERROR, "unrecognized node type: %d",
3141  (int) nodeTag(cmd->def));
3142  break;
3143 
3144  case AT_AlterColumnType:
3145  {
3146  ColumnDef *def = castNode(ColumnDef, cmd->def);
3148 
3149  /*
3150  * For ALTER COLUMN TYPE, transform the USING clause if
3151  * one was specified.
3152  */
3153  if (def->raw_default)
3154  {
3155  def->cooked_default =
3156  transformExpr(pstate, def->raw_default,
3158  }
3159 
3160  /*
3161  * For identity column, create ALTER SEQUENCE command to
3162  * change the data type of the sequence.
3163  */
3164  attnum = get_attnum(relid, cmd->name);
3165  if (attnum == InvalidAttrNumber)
3166  ereport(ERROR,
3167  (errcode(ERRCODE_UNDEFINED_COLUMN),
3168  errmsg("column \"%s\" of relation \"%s\" does not exist",
3169  cmd->name, RelationGetRelationName(rel))));
3170 
3171  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3172  {
3173  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3174  Oid typeOid = typenameTypeId(pstate, def->typeName);
3175  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3176 
3177  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3178  get_rel_name(seq_relid),
3179  -1);
3180  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3181  altseqstmt->for_identity = true;
3182  cxt.blist = lappend(cxt.blist, altseqstmt);
3183  }
3184 
3185  newcmds = lappend(newcmds, cmd);
3186  break;
3187  }
3188 
3189  case AT_AddIdentity:
3190  {
3191  Constraint *def = castNode(Constraint, cmd->def);
3192  ColumnDef *newdef = makeNode(ColumnDef);
3194 
3195  newdef->colname = cmd->name;
3196  newdef->identity = def->generated_when;
3197  cmd->def = (Node *) newdef;
3198 
3199  attnum = get_attnum(relid, cmd->name);
3200  if (attnum == InvalidAttrNumber)
3201  ereport(ERROR,
3202  (errcode(ERRCODE_UNDEFINED_COLUMN),
3203  errmsg("column \"%s\" of relation \"%s\" does not exist",
3204  cmd->name, RelationGetRelationName(rel))));
3205 
3206  generateSerialExtraStmts(&cxt, newdef,
3207  get_atttype(relid, attnum),
3208  def->options, true, true,
3209  NULL, NULL);
3210 
3211  newcmds = lappend(newcmds, cmd);
3212  break;
3213  }
3214 
3215  case AT_SetIdentity:
3216  {
3217  /*
3218  * Create an ALTER SEQUENCE statement for the internal
3219  * sequence of the identity column.
3220  */
3221  ListCell *lc;
3222  List *newseqopts = NIL;
3223  List *newdef = NIL;
3225  Oid seq_relid;
3226 
3227  /*
3228  * Split options into those handled by ALTER SEQUENCE and
3229  * those for ALTER TABLE proper.
3230  */
3231  foreach(lc, castNode(List, cmd->def))
3232  {
3233  DefElem *def = lfirst_node(DefElem, lc);
3234 
3235  if (strcmp(def->defname, "generated") == 0)
3236  newdef = lappend(newdef, def);
3237  else
3238  newseqopts = lappend(newseqopts, def);
3239  }
3240 
3241  attnum = get_attnum(relid, cmd->name);
3242  if (attnum == InvalidAttrNumber)
3243  ereport(ERROR,
3244  (errcode(ERRCODE_UNDEFINED_COLUMN),
3245  errmsg("column \"%s\" of relation \"%s\" does not exist",
3246  cmd->name, RelationGetRelationName(rel))));
3247 
3248  seq_relid = getIdentitySequence(relid, attnum, true);
3249 
3250  if (seq_relid)
3251  {
3252  AlterSeqStmt *seqstmt;
3253 
3254  seqstmt = makeNode(AlterSeqStmt);
3256  get_rel_name(seq_relid), -1);
3257  seqstmt->options = newseqopts;
3258  seqstmt->for_identity = true;
3259  seqstmt->missing_ok = false;
3260 
3261  cxt.blist = lappend(cxt.blist, seqstmt);
3262  }
3263 
3264  /*
3265  * If column was not an identity column, we just let the
3266  * ALTER TABLE command error out later. (There are cases
3267  * this fails to cover, but we'll need to restructure
3268  * where creation of the sequence dependency linkage
3269  * happens before we can fix it.)
3270  */
3271 
3272  cmd->def = (Node *) newdef;
3273  newcmds = lappend(newcmds, cmd);
3274  break;
3275  }
3276 
3277  case AT_AttachPartition:
3278  case AT_DetachPartition:
3279  {
3280  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3281 
3282  transformPartitionCmd(&cxt, partcmd);
3283  /* assign transformed value of the partition bound */
3284  partcmd->bound = cxt.partbound;
3285  }
3286 
3287  newcmds = lappend(newcmds, cmd);
3288  break;
3289 
3290  default:
3291 
3292  /*
3293  * Currently, we shouldn't actually get here for subcommand
3294  * types that don't require transformation; but if we do, just
3295  * emit them unchanged.
3296  */
3297  newcmds = lappend(newcmds, cmd);
3298  break;
3299  }
3300  }
3301 
3302  /*
3303  * Transfer anything we already have in cxt.alist into save_alist, to keep
3304  * it separate from the output of transformIndexConstraints.
3305  */
3306  save_alist = cxt.alist;
3307  cxt.alist = NIL;
3308 
3309  /* Postprocess constraints */
3311  transformFKConstraints(&cxt, skipValidation, true);
3312  transformCheckConstraints(&cxt, false);
3313 
3314  /*
3315  * Push any index-creation commands into the ALTER, so that they can be
3316  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3317  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3318  * subcommand has already been through transformIndexStmt.
3319  */
3320  foreach(l, cxt.alist)
3321  {
3322  Node *istmt = (Node *) lfirst(l);
3323 
3324  /*
3325  * We assume here that cxt.alist contains only IndexStmts and possibly
3326  * ALTER TABLE SET NOT NULL statements generated from primary key
3327  * constraints. We absorb the subcommands of the latter directly.
3328  */
3329  if (IsA(istmt, IndexStmt))
3330  {
3331  IndexStmt *idxstmt = (IndexStmt *) istmt;
3332 
3333  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3334  newcmd = makeNode(AlterTableCmd);
3336  newcmd->def = (Node *) idxstmt;
3337  newcmds = lappend(newcmds, newcmd);
3338  }
3339  else if (IsA(istmt, AlterTableStmt))
3340  {
3341  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3342 
3343  newcmds = list_concat(newcmds, alterstmt->cmds);
3344  }
3345  else
3346  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3347  }
3348  cxt.alist = NIL;
3349 
3350  /* Append any CHECK or FK constraints to the commands list */
3351  foreach(l, cxt.ckconstraints)
3352  {
3353  newcmd = makeNode(AlterTableCmd);
3354  newcmd->subtype = AT_AddConstraint;
3355  newcmd->def = (Node *) lfirst(l);
3356  newcmds = lappend(newcmds, newcmd);
3357  }
3358  foreach(l, cxt.fkconstraints)
3359  {
3360  newcmd = makeNode(AlterTableCmd);
3361  newcmd->subtype = AT_AddConstraint;
3362  newcmd->def = (Node *) lfirst(l);
3363  newcmds = lappend(newcmds, newcmd);
3364  }
3365 
3366  /* Append extended statistic objects */
3368 
3369  /* Close rel */
3370  relation_close(rel, NoLock);
3371 
3372  /*
3373  * Output results.
3374  */
3375  stmt->cmds = newcmds;
3376 
3377  *beforeStmts = cxt.blist;
3378  *afterStmts = list_concat(cxt.alist, save_alist);
3379 
3380  return stmt;
3381 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
char generated_when
Definition: parsenodes.h:2161
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:454
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char identity
Definition: parsenodes.h:655
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:661
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
AlterTableType subtype
Definition: parsenodes.h:1860
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:780
#define OidIsValid(objectId)
Definition: c.h:645
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
List * options
Definition: parsenodes.h:2553
List * options
Definition: parsenodes.h:2173
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
ParseState * pstate
Definition: parse_utilcmd.c:78
Node * cooked_default
Definition: parsenodes.h:654
Oid indexOid
Definition: parsenodes.h:2783
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
#define RelationGetRelationName(relation)
Definition: rel.h:462
const char * p_sourcetext
Definition: parse_node.h:179
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
#define ereport(elevel, rest)
Definition: elog.h:141
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
RangeVar * sequence
Definition: parsenodes.h:2552
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:573
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:859
TypeName * typeName
Definition: parsenodes.h:647
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:822
RangeVar * relation
Definition: parsenodes.h:1774
#define elog(elevel,...)
Definition: elog.h:228
bool for_identity
Definition: parsenodes.h:2554
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:641
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2509 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2510 {
2511  ListCell *ckclist;
2512 
2513  if (cxt->ckconstraints == NIL)
2514  return;
2515 
2516  /*
2517  * If creating a new table (but not a foreign table), we can safely skip
2518  * validation of check constraints, and nonetheless mark them valid. (This
2519  * will override any user-supplied NOT VALID flag.)
2520  */
2521  if (skipValidation)
2522  {
2523  foreach(ckclist, cxt->ckconstraints)
2524  {
2525  Constraint *constraint = (Constraint *) lfirst(ckclist);
2526 
2527  constraint->skip_validation = true;
2528  constraint->initially_valid = true;
2529  }
2530  }
2531 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2195
#define lfirst(lc)
Definition: pg_list.h:190
bool skip_validation
Definition: parsenodes.h:2194

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 509 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, 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, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, ColumnDef::identity, 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, 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, AlterTableStmt::relation, ReleaseSysCache(), AlterTableStmt::relkind, RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

510 {
511  bool is_serial;
512  bool saw_nullable;
513  bool saw_default;
514  bool saw_identity;
515  bool saw_generated;
516  ListCell *clist;
517 
518  cxt->columns = lappend(cxt->columns, column);
519 
520  /* Check for SERIAL pseudo-types */
521  is_serial = false;
522  if (column->typeName
523  && list_length(column->typeName->names) == 1
524  && !column->typeName->pct_type)
525  {
526  char *typname = strVal(linitial(column->typeName->names));
527 
528  if (strcmp(typname, "smallserial") == 0 ||
529  strcmp(typname, "serial2") == 0)
530  {
531  is_serial = true;
532  column->typeName->names = NIL;
533  column->typeName->typeOid = INT2OID;
534  }
535  else if (strcmp(typname, "serial") == 0 ||
536  strcmp(typname, "serial4") == 0)
537  {
538  is_serial = true;
539  column->typeName->names = NIL;
540  column->typeName->typeOid = INT4OID;
541  }
542  else if (strcmp(typname, "bigserial") == 0 ||
543  strcmp(typname, "serial8") == 0)
544  {
545  is_serial = true;
546  column->typeName->names = NIL;
547  column->typeName->typeOid = INT8OID;
548  }
549 
550  /*
551  * We have to reject "serial[]" explicitly, because once we've set
552  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
553  * special coding for serial(typmod) though.
554  */
555  if (is_serial && column->typeName->arrayBounds != NIL)
556  ereport(ERROR,
557  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
558  errmsg("array of serial is not implemented"),
560  column->typeName->location)));
561  }
562 
563  /* Do necessary work on the column type declaration */
564  if (column->typeName)
565  transformColumnType(cxt, column);
566 
567  /* Special actions for SERIAL pseudo-types */
568  if (is_serial)
569  {
570  char *snamespace;
571  char *sname;
572  char *qstring;
573  A_Const *snamenode;
574  TypeCast *castnode;
575  FuncCall *funccallnode;
576  Constraint *constraint;
577 
578  generateSerialExtraStmts(cxt, column,
579  column->typeName->typeOid, NIL,
580  false, false,
581  &snamespace, &sname);
582 
583  /*
584  * Create appropriate constraints for SERIAL. We do this in full,
585  * rather than shortcutting, so that we will detect any conflicting
586  * constraints the user wrote (like a different DEFAULT).
587  *
588  * Create an expression tree representing the function call
589  * nextval('sequencename'). We cannot reduce the raw tree to cooked
590  * form until after the sequence is created, but there's no need to do
591  * so.
592  */
593  qstring = quote_qualified_identifier(snamespace, sname);
594  snamenode = makeNode(A_Const);
595  snamenode->val.type = T_String;
596  snamenode->val.val.str = qstring;
597  snamenode->location = -1;
598  castnode = makeNode(TypeCast);
599  castnode->typeName = SystemTypeName("regclass");
600  castnode->arg = (Node *) snamenode;
601  castnode->location = -1;
602  funccallnode = makeFuncCall(SystemFuncName("nextval"),
603  list_make1(castnode),
604  -1);
605  constraint = makeNode(Constraint);
606  constraint->contype = CONSTR_DEFAULT;
607  constraint->location = -1;
608  constraint->raw_expr = (Node *) funccallnode;
609  constraint->cooked_expr = NULL;
610  column->constraints = lappend(column->constraints, constraint);
611 
612  constraint = makeNode(Constraint);
613  constraint->contype = CONSTR_NOTNULL;
614  constraint->location = -1;
615  column->constraints = lappend(column->constraints, constraint);
616  }
617 
618  /* Process column constraints, if any... */
620 
621  saw_nullable = false;
622  saw_default = false;
623  saw_identity = false;
624  saw_generated = false;
625 
626  foreach(clist, column->constraints)
627  {
628  Constraint *constraint = lfirst_node(Constraint, clist);
629 
630  switch (constraint->contype)
631  {
632  case CONSTR_NULL:
633  if (saw_nullable && column->is_not_null)
634  ereport(ERROR,
635  (errcode(ERRCODE_SYNTAX_ERROR),
636  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
637  column->colname, cxt->relation->relname),
639  constraint->location)));
640  column->is_not_null = false;
641  saw_nullable = true;
642  break;
643 
644  case CONSTR_NOTNULL:
645  if (saw_nullable && !column->is_not_null)
646  ereport(ERROR,
647  (errcode(ERRCODE_SYNTAX_ERROR),
648  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
649  column->colname, cxt->relation->relname),
651  constraint->location)));
652  column->is_not_null = true;
653  saw_nullable = true;
654  break;
655 
656  case CONSTR_DEFAULT:
657  if (saw_default)
658  ereport(ERROR,
659  (errcode(ERRCODE_SYNTAX_ERROR),
660  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
661  column->colname, cxt->relation->relname),
663  constraint->location)));
664  column->raw_default = constraint->raw_expr;
665  Assert(constraint->cooked_expr == NULL);
666  saw_default = true;
667  break;
668 
669  case CONSTR_IDENTITY:
670  {
671  Type ctype;
672  Oid typeOid;
673 
674  if (cxt->ofType)
675  ereport(ERROR,
676  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
677  errmsg("identity columns are not supported on typed tables")));
678  if (cxt->partbound)
679  ereport(ERROR,
680  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
681  errmsg("identity columns are not supported on partitions")));
682 
683  ctype = typenameType(cxt->pstate, column->typeName, NULL);
684  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
685  ReleaseSysCache(ctype);
686 
687  if (saw_identity)
688  ereport(ERROR,
689  (errcode(ERRCODE_SYNTAX_ERROR),
690  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
691  column->colname, cxt->relation->relname),
693  constraint->location)));
694 
695  generateSerialExtraStmts(cxt, column,
696  typeOid, constraint->options,
697  true, false,
698  NULL, NULL);
699 
700  column->identity = constraint->generated_when;
701  saw_identity = true;
702  column->is_not_null = true;
703  break;
704  }
705 
706  case CONSTR_GENERATED:
707  if (cxt->ofType)
708  ereport(ERROR,
709  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
710  errmsg("generated columns are not supported on typed tables")));
711  if (cxt->partbound)
712  ereport(ERROR,
713  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
714  errmsg("generated columns are not supported on partitions")));
715 
716  if (saw_generated)
717  ereport(ERROR,
718  (errcode(ERRCODE_SYNTAX_ERROR),
719  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
720  column->colname, cxt->relation->relname),
722  constraint->location)));
723  column->generated = ATTRIBUTE_GENERATED_STORED;
724  column->raw_default = constraint->raw_expr;
725  Assert(constraint->cooked_expr == NULL);
726  saw_generated = true;
727  break;
728 
729  case CONSTR_CHECK:
730  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
731  break;
732 
733  case CONSTR_PRIMARY:
734  if (cxt->isforeign)
735  ereport(ERROR,
736  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
737  errmsg("primary key constraints are not supported on foreign tables"),
739  constraint->location)));
740  /* FALL THRU */
741 
742  case CONSTR_UNIQUE:
743  if (cxt->isforeign)
744  ereport(ERROR,
745  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
746  errmsg("unique constraints are not supported on foreign tables"),
748  constraint->location)));
749  if (constraint->keys == NIL)
750  constraint->keys = list_make1(makeString(column->colname));
751  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
752  break;
753 
754  case CONSTR_EXCLUSION:
755  /* grammar does not allow EXCLUDE as a column constraint */
756  elog(ERROR, "column exclusion constraints are not supported");
757  break;
758 
759  case CONSTR_FOREIGN:
760  if (cxt->isforeign)
761  ereport(ERROR,
762  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
763  errmsg("foreign key constraints are not supported on foreign tables"),
765  constraint->location)));
766 
767  /*
768  * Fill in the current attribute's name and throw it into the
769  * list of FK constraints to be processed later.
770  */
771  constraint->fk_attrs = list_make1(makeString(column->colname));
772  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
773  break;
774 
779  /* transformConstraintAttrs took care of these */
780  break;
781 
782  default:
783  elog(ERROR, "unrecognized constraint type: %d",
784  constraint->contype);
785  break;
786  }
787 
788  if (saw_default && saw_identity)
789  ereport(ERROR,
790  (errcode(ERRCODE_SYNTAX_ERROR),
791  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
792  column->colname, cxt->relation->relname),
794  constraint->location)));
795 
796  if (saw_default && saw_generated)
797  ereport(ERROR,
798  (errcode(ERRCODE_SYNTAX_ERROR),
799  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
800  column->colname, cxt->relation->relname),
802  constraint->location)));
803 
804  if (saw_identity && saw_generated)
805  ereport(ERROR,
806  (errcode(ERRCODE_SYNTAX_ERROR),
807  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
808  column->colname, cxt->relation->relname),
810  constraint->location)));
811  }
812 
813  /*
814  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
815  * per-column foreign data wrapper options to this column after creation.
816  */
817  if (column->fdwoptions != NIL)
818  {
819  AlterTableStmt *stmt;
820  AlterTableCmd *cmd;
821 
822  cmd = makeNode(AlterTableCmd);
824  cmd->name = column->colname;
825  cmd->def = (Node *) column->fdwoptions;
826  cmd->behavior = DROP_RESTRICT;
827  cmd->missing_ok = false;
828 
829  stmt = makeNode(AlterTableStmt);
830  stmt->relation = cxt->relation;
831  stmt->cmds = NIL;
833  stmt->cmds = lappend(stmt->cmds, cmd);
834 
835  cxt->alist = lappend(cxt->alist, stmt);
836  }
837 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
Oid typeOid
Definition: parsenodes.h:210
List * keys
Definition: parsenodes.h:2164
char generated_when
Definition: parsenodes.h:2161
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
List * names
Definition: parsenodes.h:209
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
char identity
Definition: parsenodes.h:655
List * constraints
Definition: parsenodes.h:661
Node * raw_expr
Definition: parsenodes.h:2159
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
AlterTableType subtype
Definition: parsenodes.h:1860
char generated
Definition: parsenodes.h:658
bool is_not_null
Definition: parsenodes.h:650
unsigned int Oid
Definition: postgres_ext.h:31
List * options
Definition: parsenodes.h:2173
int location
Definition: parsenodes.h:300
#define list_make1(x1)
Definition: pg_list.h:227
ParseState * pstate
Definition: parse_utilcmd.c:78
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
#define lfirst_node(type, lc)
Definition: pg_list.h:193
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:662
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
#define ereport(elevel, rest)
Definition: elog.h:141
ObjectType relkind
Definition: parsenodes.h:1776
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:583
TypeName * SystemTypeName(char *name)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
TypeName * typeName
Definition: parsenodes.h:299
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:739
int location
Definition: parsenodes.h:289
int location
Definition: parsenodes.h:216
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
TypeName * typeName
Definition: parsenodes.h:647
List * arrayBounds
Definition: parsenodes.h:215
int errmsg(const char *fmt,...)
Definition: elog.c:822
RangeVar * relation
Definition: parsenodes.h:1774
char * str
Definition: value.h:48
#define elog(elevel,...)
Definition: elog.h:228
ConstrType contype
Definition: parsenodes.h:2149
DropBehavior behavior
Definition: parsenodes.h:1868
char * colname
Definition: parsenodes.h:646
char * cooked_expr
Definition: parsenodes.h:2160
Value val
Definition: parsenodes.h:288
List * fk_attrs
Definition: parsenodes.h:2184
NodeTag type
Definition: value.h:44
bool pct_type
Definition: parsenodes.h:212
Node * arg
Definition: parsenodes.h:298

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3509 of file parse_utilcmd.c.

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

3510 {
3511  /*
3512  * All we really need to do here is verify that the type is valid,
3513  * including any collation spec that might be present.
3514  */
3515  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3516 
3517  if (column->collClause)
3518  {
3519  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3520 
3521  LookupCollation(cxt->pstate,
3522  column->collClause->collname,
3523  column->collClause->location);
3524  /* Complain if COLLATE is applied to an uncollatable type */
3525  if (!OidIsValid(typtup->typcollation))
3526  ereport(ERROR,
3527  (errcode(ERRCODE_DATATYPE_MISMATCH),
3528  errmsg("collations are not supported by type %s",
3529  format_type_be(typtup->oid)),
3531  column->collClause->location)));
3532  }
3533 
3534  ReleaseSysCache(ctype);
3535 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
#define OidIsValid(objectId)
Definition: c.h:645
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
TypeName * typeName
Definition: parsenodes.h:647
CollateClause * collClause
Definition: parsenodes.h:659
List * collname
Definition: parsenodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3394 of file parse_utilcmd.c.

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

3395 {
3396  Constraint *lastprimarycon = NULL;
3397  bool saw_deferrability = false;
3398  bool saw_initially = false;
3399  ListCell *clist;
3400 
3401 #define SUPPORTS_ATTRS(node) \
3402  ((node) != NULL && \
3403  ((node)->contype == CONSTR_PRIMARY || \
3404  (node)->contype == CONSTR_UNIQUE || \
3405  (node)->contype == CONSTR_EXCLUSION || \
3406  (node)->contype == CONSTR_FOREIGN))
3407 
3408  foreach(clist, constraintList)
3409  {
3410  Constraint *con = (Constraint *) lfirst(clist);
3411 
3412  if (!IsA(con, Constraint))
3413  elog(ERROR, "unrecognized node type: %d",
3414  (int) nodeTag(con));
3415  switch (con->contype)
3416  {
3418  if (!SUPPORTS_ATTRS(lastprimarycon))
3419  ereport(ERROR,
3420  (errcode(ERRCODE_SYNTAX_ERROR),
3421  errmsg("misplaced DEFERRABLE clause"),
3422  parser_errposition(cxt->pstate, con->location)));
3423  if (saw_deferrability)
3424  ereport(ERROR,
3425  (errcode(ERRCODE_SYNTAX_ERROR),
3426  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3427  parser_errposition(cxt->pstate, con->location)));
3428  saw_deferrability = true;
3429  lastprimarycon->deferrable = true;
3430  break;
3431 
3433  if (!SUPPORTS_ATTRS(lastprimarycon))
3434  ereport(ERROR,
3435  (errcode(ERRCODE_SYNTAX_ERROR),
3436  errmsg("misplaced NOT DEFERRABLE clause"),
3437  parser_errposition(cxt->pstate, con->location)));
3438  if (saw_deferrability)
3439  ereport(ERROR,
3440  (errcode(ERRCODE_SYNTAX_ERROR),
3441  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3442  parser_errposition(cxt->pstate, con->location)));
3443  saw_deferrability = true;
3444  lastprimarycon->deferrable = false;
3445  if (saw_initially &&
3446  lastprimarycon->initdeferred)
3447  ereport(ERROR,
3448  (errcode(ERRCODE_SYNTAX_ERROR),
3449  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3450  parser_errposition(cxt->pstate, con->location)));
3451  break;
3452 
3453  case CONSTR_ATTR_DEFERRED:
3454  if (!SUPPORTS_ATTRS(lastprimarycon))
3455  ereport(ERROR,
3456  (errcode(ERRCODE_SYNTAX_ERROR),
3457  errmsg("misplaced INITIALLY DEFERRED clause"),
3458  parser_errposition(cxt->pstate, con->location)));
3459  if (saw_initially)
3460  ereport(ERROR,
3461  (errcode(ERRCODE_SYNTAX_ERROR),
3462  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3463  parser_errposition(cxt->pstate, con->location)));
3464  saw_initially = true;
3465  lastprimarycon->initdeferred = true;
3466 
3467  /*
3468  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3469  */
3470  if (!saw_deferrability)
3471  lastprimarycon->deferrable = true;
3472  else if (!lastprimarycon->deferrable)
3473  ereport(ERROR,
3474  (errcode(ERRCODE_SYNTAX_ERROR),
3475  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3476  parser_errposition(cxt->pstate, con->location)));
3477  break;
3478 
3479  case CONSTR_ATTR_IMMEDIATE:
3480  if (!SUPPORTS_ATTRS(lastprimarycon))
3481  ereport(ERROR,
3482  (errcode(ERRCODE_SYNTAX_ERROR),
3483  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3484  parser_errposition(cxt->pstate, con->location)));
3485  if (saw_initially)
3486  ereport(ERROR,
3487  (errcode(ERRCODE_SYNTAX_ERROR),
3488  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3489  parser_errposition(cxt->pstate, con->location)));
3490  saw_initially = true;
3491  lastprimarycon->initdeferred = false;
3492  break;
3493 
3494  default:
3495  /* Otherwise it's not an attribute */
3496  lastprimarycon = con;
3497  /* reset flags for new primary node */
3498  saw_deferrability = false;
3499  saw_initially = false;
3500  break;
3501  }
3502  }
3503 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int errcode(int sqlerrcode)
Definition: elog.c:608
bool initdeferred
Definition: parsenodes.h:2154
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2153
#define ereport(elevel, rest)
Definition: elog.h:141
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define nodeTag(nodeptr)
Definition: nodes.h:530
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define SUPPORTS_ATTRS(node)
#define elog(elevel,...)
Definition: elog.h:228
ConstrType contype
Definition: parsenodes.h:2149

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3562 of file parse_utilcmd.c.

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

Referenced by CreateSchemaCommand().

3563 {
3565  List *result;
3566  ListCell *elements;
3567 
3568  cxt.stmtType = "CREATE SCHEMA";
3569  cxt.schemaname = stmt->schemaname;
3570  cxt.authrole = (RoleSpec *) stmt->authrole;
3571  cxt.sequences = NIL;
3572  cxt.tables = NIL;
3573  cxt.views = NIL;
3574  cxt.indexes = NIL;
3575  cxt.triggers = NIL;
3576  cxt.grants = NIL;
3577 
3578  /*
3579  * Run through each schema element in the schema element list. Separate
3580  * statements by type, and do preliminary analysis.
3581  */
3582  foreach(elements, stmt->schemaElts)
3583  {
3584  Node *element = lfirst(elements);
3585 
3586  switch (nodeTag(element))
3587  {
3588  case T_CreateSeqStmt:
3589  {
3590  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3591 
3593  cxt.sequences = lappend(cxt.sequences, element);
3594  }
3595  break;
3596 
3597  case T_CreateStmt:
3598  {
3599  CreateStmt *elp = (CreateStmt *) element;
3600 
3602 
3603  /*
3604  * XXX todo: deal with constraints
3605  */
3606  cxt.tables = lappend(cxt.tables, element);
3607  }
3608  break;
3609 
3610  case T_ViewStmt:
3611  {
3612  ViewStmt *elp = (ViewStmt *) element;
3613 
3614  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3615 
3616  /*
3617  * XXX todo: deal with references between views
3618  */
3619  cxt.views = lappend(cxt.views, element);
3620  }
3621  break;
3622 
3623  case T_IndexStmt:
3624  {
3625  IndexStmt *elp = (IndexStmt *) element;
3626 
3628  cxt.indexes = lappend(cxt.indexes, element);
3629  }
3630  break;
3631 
3632  case T_CreateTrigStmt:
3633  {
3634  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3635 
3637  cxt.triggers = lappend(cxt.triggers, element);
3638  }
3639  break;
3640 
3641  case T_GrantStmt:
3642  cxt.grants = lappend(cxt.grants, element);
3643  break;
3644 
3645  default:
3646  elog(ERROR, "unrecognized node type: %d",
3647  (int) nodeTag(element));
3648  }
3649  }
3650 
3651  result = NIL;
3652  result = list_concat(result, cxt.sequences);
3653  result = list_concat(result, cxt.tables);
3654  result = list_concat(result, cxt.views);
3655  result = list_concat(result, cxt.indexes);
3656  result = list_concat(result, cxt.triggers);
3657  result = list_concat(result, cxt.grants);
3658 
3659  return result;
3660 }
RangeVar * relation
Definition: parsenodes.h:2069
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
RangeVar * view
Definition: parsenodes.h:3112
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2773
RoleSpec * authrole
Definition: parsenodes.h:1756
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:322
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2542
#define lfirst(lc)
Definition: pg_list.h:190
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228
RangeVar * relation
Definition: parsenodes.h:2428
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, copyObject, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, list_concat(), RangeVar::location, make_parsestate(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

166 {
167  ParseState *pstate;
168  CreateStmtContext cxt;
169  List *result;
170  List *save_alist;
171  ListCell *elements;
172  Oid namespaceid;
173  Oid existing_relid;
174  ParseCallbackState pcbstate;
175  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
176 
177  /*
178  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
179  * overkill, but easy.)
180  */
181  stmt = copyObject(stmt);
182 
183  /* Set up pstate */
184  pstate = make_parsestate(NULL);
185  pstate->p_sourcetext = queryString;
186 
187  /*
188  * Look up the creation namespace. This also checks permissions on the
189  * target namespace, locks it against concurrent drops, checks for a
190  * preexisting relation in that namespace with the same name, and updates
191  * stmt->relation->relpersistence if the selected namespace is temporary.
192  */
193  setup_parser_errposition_callback(&pcbstate, pstate,
194  stmt->relation->location);
195  namespaceid =
197  &existing_relid);
199 
200  /*
201  * If the relation already exists and the user specified "IF NOT EXISTS",
202  * bail out with a NOTICE.
203  */
204  if (stmt->if_not_exists && OidIsValid(existing_relid))
205  {
206  ereport(NOTICE,
207  (errcode(ERRCODE_DUPLICATE_TABLE),
208  errmsg("relation \"%s\" already exists, skipping",
209  stmt->relation->relname)));
210  return NIL;
211  }
212 
213  /*
214  * If the target relation name isn't schema-qualified, make it so. This
215  * prevents some corner cases in which added-on rewritten commands might
216  * think they should apply to other relations that have the same name and
217  * are earlier in the search path. But a local temp table is effectively
218  * specified to be in pg_temp, so no need for anything extra in that case.
219  */
220  if (stmt->relation->schemaname == NULL
221  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
222  stmt->relation->schemaname = get_namespace_name(namespaceid);
223 
224  /* Set up CreateStmtContext */
225  cxt.pstate = pstate;
226  if (IsA(stmt, CreateForeignTableStmt))
227  {
228  cxt.stmtType = "CREATE FOREIGN TABLE";
229  cxt.isforeign = true;
230  }
231  else
232  {
233  cxt.stmtType = "CREATE TABLE";
234  cxt.isforeign = false;
235  }
236  cxt.relation = stmt->relation;
237  cxt.rel = NULL;
238  cxt.inhRelations = stmt->inhRelations;
239  cxt.isalter = false;
240  cxt.columns = NIL;
241  cxt.ckconstraints = NIL;
242  cxt.fkconstraints = NIL;
243  cxt.ixconstraints = NIL;
244  cxt.inh_indexes = NIL;
245  cxt.extstats = NIL;
246  cxt.blist = NIL;
247  cxt.alist = NIL;
248  cxt.pkey = NULL;
249  cxt.ispartitioned = stmt->partspec != NULL;
250  cxt.partbound = stmt->partbound;
251  cxt.ofType = (stmt->ofTypename != NULL);
252 
253  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
254 
255  if (stmt->ofTypename)
256  transformOfType(&cxt, stmt->ofTypename);
257 
258  if (stmt->partspec)
259  {
260  if (stmt->inhRelations && !stmt->partbound)
261  ereport(ERROR,
262  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
263  errmsg("cannot create partitioned table as inheritance child")));
264  }
265 
266  /*
267  * Run through each primary element in the table creation clause. Separate
268  * column defs from constraints, and do preliminary analysis.
269  */
270  foreach(elements, stmt->tableElts)
271  {
272  Node *element = lfirst(elements);
273 
274  switch (nodeTag(element))
275  {
276  case T_ColumnDef:
277  transformColumnDefinition(&cxt, (ColumnDef *) element);
278  break;
279 
280  case T_Constraint:
281  transformTableConstraint(&cxt, (Constraint *) element);
282  break;
283 
284  case T_TableLikeClause:
285  transformTableLikeClause(&cxt, (TableLikeClause *) element);
286  break;
287 
288  default:
289  elog(ERROR, "unrecognized node type: %d",
290  (int) nodeTag(element));
291  break;
292  }
293  }
294 
295  /*
296  * Transfer anything we already have in cxt.alist into save_alist, to keep
297  * it separate from the output of transformIndexConstraints. (This may
298  * not be necessary anymore, but we'll keep doing it to preserve the
299  * historical order of execution of the alist commands.)
300  */
301  save_alist = cxt.alist;
302  cxt.alist = NIL;
303 
304  Assert(stmt->constraints == NIL);
305 
306  /*
307  * Postprocess constraints that give rise to index definitions.
308  */
310 
311  /*
312  * Postprocess foreign-key constraints.
313  */
314  transformFKConstraints(&cxt, true, false);
315 
316  /*
317  * Postprocess check constraints.
318  */
319  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
320 
321  /*
322  * Postprocess extended statistics.
323  */
325 
326  /*
327  * Output results.
328  */
329  stmt->tableElts = cxt.columns;
330  stmt->constraints = cxt.ckconstraints;
331 
332  result = lappend(cxt.blist, stmt);
333  result = list_concat(result, cxt.alist);
334  result = list_concat(result, save_alist);
335 
336  return result;
337 }
RangeVar * relation
Definition: parsenodes.h:2069
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2071
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
List * constraints
Definition: parsenodes.h:2076
bool if_not_exists
Definition: parsenodes.h:2081
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2073
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
List * lappend(List *list, void *datum)
Definition: list.c:322
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2070
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define copyObject(obj)
Definition: nodes.h:641
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2074
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2075
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2494 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2495 {
2496  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2497 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:516

◆ transformFKConstraints()

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

Definition at line 2538 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2540 {
2541  ListCell *fkclist;
2542 
2543  if (cxt->fkconstraints == NIL)
2544  return;
2545 
2546  /*
2547  * If CREATE TABLE or adding a column with NULL default, we can safely
2548  * skip validation of FK constraints, and nonetheless mark them valid.
2549  * (This will override any user-supplied NOT VALID flag.)
2550  */
2551  if (skipValidation)
2552  {
2553  foreach(fkclist, cxt->fkconstraints)
2554  {
2555  Constraint *constraint = (Constraint *) lfirst(fkclist);
2556 
2557  constraint->skip_validation = true;
2558  constraint->initially_valid = true;
2559  }
2560  }
2561 
2562  /*
2563  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2564  * CONSTRAINT command to execute after the basic command is complete. (If
2565  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2566  * its own subcommand list.)
2567  *
2568  * Note: the ADD CONSTRAINT command must also execute after any index
2569  * creation commands. Thus, this should run after
2570  * transformIndexConstraints, so that the CREATE INDEX commands are
2571  * already in cxt->alist.
2572  */
2573  if (!isAddConstraint)
2574  {
2575  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2576 
2577  alterstmt->relation = cxt->relation;
2578  alterstmt->cmds = NIL;
2579  alterstmt->relkind = OBJECT_TABLE;
2580 
2581  foreach(fkclist, cxt->fkconstraints)
2582  {
2583  Constraint *constraint = (Constraint *) lfirst(fkclist);
2584  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2585 
2586  altercmd->subtype = AT_AddConstraint;
2587  altercmd->name = NULL;
2588  altercmd->def = (Node *) constraint;
2589  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2590  }
2591 
2592  cxt->alist = lappend(cxt->alist, alterstmt);
2593  }
2594 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
AlterTableType subtype
Definition: parsenodes.h:1860
RangeVar * relation
Definition: parse_utilcmd.c:80
ObjectType relkind
Definition: parsenodes.h:1776
List * lappend(List *list, void *datum)
Definition: list.c:322
bool initially_valid
Definition: parsenodes.h:2195
#define makeNode(_type_)
Definition: nodes.h:573
#define lfirst(lc)
Definition: pg_list.h:190
RangeVar * relation
Definition: parsenodes.h:1774
bool skip_validation
Definition: parsenodes.h:2194

◆ transformIndexConstraint()

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

Definition at line 1968 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, castNode, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, Constraint::including, index_open(), IndexElem::indexcolname, IndexStmt::indexIncludingParams, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, 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, IndexElem::nulls_ordering, OBJECT_TABLE, OidIsValid, IndexStmt::oldNode, IndexElem::opclass, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, 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, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, AlterTableStmt::relkind, RangeVar::relname, Constraint::reset_default_tblspc, IndexStmt::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

1969 {
1970  IndexStmt *index;
1971  List *notnullcmds = NIL;
1972  ListCell *lc;
1973 
1974  index = makeNode(IndexStmt);
1975 
1976  index->unique = (constraint->contype != CONSTR_EXCLUSION);
1977  index->primary = (constraint->contype == CONSTR_PRIMARY);
1978  if (index->primary)
1979  {
1980  if (cxt->pkey != NULL)
1981  ereport(ERROR,
1982  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1983  errmsg("multiple primary keys for table \"%s\" are not allowed",
1984  cxt->relation->relname),
1985  parser_errposition(cxt->pstate, constraint->location)));
1986  cxt->pkey = index;
1987 
1988  /*
1989  * In ALTER TABLE case, a primary index might already exist, but
1990  * DefineIndex will check for it.
1991  */
1992  }
1993  index->isconstraint = true;
1994  index->deferrable = constraint->deferrable;
1995  index->initdeferred = constraint->initdeferred;
1996 
1997  if (constraint->conname != NULL)
1998  index->idxname = pstrdup(constraint->conname);
1999  else
2000  index->idxname = NULL; /* DefineIndex will choose name */
2001 
2002  index->relation = cxt->relation;
2003  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2004  index->options = constraint->options;
2005  index->tableSpace = constraint->indexspace;
2006  index->whereClause = constraint->where_clause;
2007  index->indexParams = NIL;
2008  index->indexIncludingParams = NIL;
2009  index->excludeOpNames = NIL;
2010  index->idxcomment = NULL;
2011  index->indexOid = InvalidOid;
2012  index->oldNode = InvalidOid;
2013  index->transformed = false;
2014  index->concurrent = false;
2015  index->if_not_exists = false;
2016  index->reset_default_tblspc = constraint->reset_default_tblspc;
2017 
2018  /*
2019  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2020  * verify it's usable, then extract the implied column name list. (We
2021  * will not actually need the column name list at runtime, but we need it
2022  * now to check for duplicate column entries below.)
2023  */
2024  if (constraint->indexname != NULL)
2025  {
2026  char *index_name = constraint->indexname;
2027  Relation heap_rel = cxt->rel;
2028  Oid index_oid;
2029  Relation index_rel;
2030  Form_pg_index index_form;
2031  oidvector *indclass;
2032  Datum indclassDatum;
2033  bool isnull;
2034  int i;
2035 
2036  /* Grammar should not allow this with explicit column list */
2037  Assert(constraint->keys == NIL);
2038 
2039  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2040  Assert(constraint->contype == CONSTR_PRIMARY ||
2041  constraint->contype == CONSTR_UNIQUE);
2042 
2043  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2044  if (!cxt->isalter)
2045  ereport(ERROR,
2046  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2047  errmsg("cannot use an existing index in CREATE TABLE"),
2048  parser_errposition(cxt->pstate, constraint->location)));
2049 
2050  /* Look for the index in the same schema as the table */
2051  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2052 
2053  if (!OidIsValid(index_oid))
2054  ereport(ERROR,
2055  (errcode(ERRCODE_UNDEFINED_OBJECT),
2056  errmsg("index \"%s\" does not exist", index_name),
2057  parser_errposition(cxt->pstate, constraint->location)));
2058 
2059  /* Open the index (this will throw an error if it is not an index) */
2060  index_rel = index_open(index_oid, AccessShareLock);
2061  index_form = index_rel->rd_index;
2062 
2063  /* Check that it does not have an associated constraint already */
2064  if (OidIsValid(get_index_constraint(index_oid)))
2065  ereport(ERROR,
2066  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2067  errmsg("index \"%s\" is already associated with a constraint",
2068  index_name),
2069  parser_errposition(cxt->pstate, constraint->location)));
2070 
2071  /* Perform validity checks on the index */
2072  if (index_form->indrelid != RelationGetRelid(heap_rel))
2073  ereport(ERROR,
2074  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2075  errmsg("index \"%s\" does not belong to table \"%s\"",
2076  index_name, RelationGetRelationName(heap_rel)),
2077  parser_errposition(cxt->pstate, constraint->location)));
2078 
2079  if (!index_form->indisvalid)
2080  ereport(ERROR,
2081  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2082  errmsg("index \"%s\" is not valid", index_name),
2083  parser_errposition(cxt->pstate, constraint->location)));
2084 
2085  if (!index_form->indisunique)
2086  ereport(ERROR,
2087  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2088  errmsg("\"%s\" is not a unique index", index_name),
2089  errdetail("Cannot create a primary key or unique constraint using such an index."),
2090  parser_errposition(cxt->pstate, constraint->location)));
2091 
2092  if (RelationGetIndexExpressions(index_rel) != NIL)
2093  ereport(ERROR,
2094  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2095  errmsg("index \"%s\" contains expressions", index_name),
2096  errdetail("Cannot create a primary key or unique constraint using such an index."),
2097  parser_errposition(cxt->pstate, constraint->location)));
2098 
2099  if (RelationGetIndexPredicate(index_rel) != NIL)
2100  ereport(ERROR,
2101  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2102  errmsg("\"%s\" is a partial index", index_name),
2103  errdetail("Cannot create a primary key or unique constraint using such an index."),
2104  parser_errposition(cxt->pstate, constraint->location)));
2105 
2106  /*
2107  * It's probably unsafe to change a deferred index to non-deferred. (A
2108  * non-constraint index couldn't be deferred anyway, so this case
2109  * should never occur; no need to sweat, but let's check it.)
2110  */
2111  if (!index_form->indimmediate && !constraint->deferrable)
2112  ereport(ERROR,
2113  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2114  errmsg("\"%s\" is a deferrable index", index_name),
2115  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2116  parser_errposition(cxt->pstate, constraint->location)));
2117 
2118  /*
2119  * Insist on it being a btree. That's the only kind that supports
2120  * uniqueness at the moment anyway; but we must have an index that
2121  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2122  * else dump and reload will produce a different index (breaking
2123  * pg_upgrade in particular).
2124  */
2125  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2126  ereport(ERROR,
2127  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2128  errmsg("index \"%s\" is not a btree", index_name),
2129  parser_errposition(cxt->pstate, constraint->location)));
2130 
2131  /* Must get indclass the hard way */
2132  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
2133  Anum_pg_index_indclass, &isnull);
2134  Assert(!isnull);
2135  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2136 
2137  for (i = 0; i < index_form->indnatts; i++)
2138  {
2139  int16 attnum = index_form->indkey.values[i];
2140  const FormData_pg_attribute *attform;
2141  char *attname;
2142  Oid defopclass;
2143 
2144  /*
2145  * We shouldn't see attnum == 0 here, since we already rejected
2146  * expression indexes. If we do, SystemAttributeDefinition will
2147  * throw an error.
2148  */
2149  if (attnum > 0)
2150  {
2151  Assert(attnum <= heap_rel->rd_att->natts);
2152  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2153  }
2154  else
2155  attform = SystemAttributeDefinition(attnum);
2156  attname = pstrdup(NameStr(attform->attname));
2157 
2158  if (i < index_form->indnkeyatts)
2159  {
2160  /*
2161  * Insist on default opclass, collation, and sort options.
2162  * While the index would still work as a constraint with
2163  * non-default settings, it might not provide exactly the same
2164  * uniqueness semantics as you'd get from a normally-created
2165  * constraint; and there's also the dump/reload problem
2166  * mentioned above.
2167  */
2168  defopclass = GetDefaultOpClass(attform->atttypid,
2169  index_rel->rd_rel->relam);
2170  if (indclass->values[i] != defopclass ||
2171  attform->attcollation != index_rel->rd_indcollation[i] ||
2172  index_rel->rd_indoption[i] != 0)
2173  ereport(ERROR,
2174  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2175  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2176  errdetail("Cannot create a primary key or unique constraint using such an index."),
2177  parser_errposition(cxt->pstate, constraint->location)));
2178 
2179  constraint->keys = lappend(constraint->keys, makeString(attname));
2180  }
2181  else
2182  constraint->including = lappend(constraint->including, makeString(attname));
2183  }
2184 
2185  /* Close the index relation but keep the lock */
2186  relation_close(index_rel, NoLock);
2187 
2188  index->indexOid = index_oid;
2189  }
2190 
2191  /*
2192  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2193  * IndexElems and operator names. We have to break that apart into
2194  * separate lists.
2195  */
2196  if (constraint->contype == CONSTR_EXCLUSION)
2197  {
2198  foreach(lc, constraint->exclusions)
2199  {
2200  List *pair = (List *) lfirst(lc);
2201  IndexElem *elem;
2202  List *opname;
2203 
2204  Assert(list_length(pair) == 2);
2205  elem = linitial_node(IndexElem, pair);
2206  opname = lsecond_node(List, pair);
2207 
2208  index->indexParams = lappend(index->indexParams, elem);
2209  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2210  }
2211  }
2212 
2213  /*
2214  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2215  *
2216  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2217  * also make sure they are NOT NULL.
2218  */
2219  else
2220  {
2221  foreach(lc, constraint->keys)
2222  {
2223  char *key = strVal(lfirst(lc));
2224  bool found = false;
2225  bool forced_not_null = false;
2226  ColumnDef *column = NULL;
2227  ListCell *columns;
2228  IndexElem *iparam;
2229 
2230  /* Make sure referenced column exists. */
2231  foreach(columns, cxt->columns)
2232  {
2233  column = castNode(ColumnDef, lfirst(columns));
2234  if (strcmp(column->colname, key) == 0)
2235  {
2236  found = true;
2237  break;
2238  }
2239  }
2240  if (found)
2241  {
2242  /*
2243  * column is defined in the new table. For PRIMARY KEY, we
2244  * can apply the NOT NULL constraint cheaply here ... unless
2245  * the column is marked is_from_type, in which case marking it
2246  * here would be ineffective (see MergeAttributes).
2247  */
2248  if (constraint->contype == CONSTR_PRIMARY &&
2249  !column->is_from_type)
2250  {
2251  column->is_not_null = true;
2252  forced_not_null = true;
2253  }
2254  }
2255  else if (SystemAttributeByName(key) != NULL)
2256  {
2257  /*
2258  * column will be a system column in the new table, so accept
2259  * it. System columns can't ever be null, so no need to worry
2260  * about PRIMARY/NOT NULL constraint.
2261  */
2262  found = true;
2263  }
2264  else if (cxt->inhRelations)
2265  {
2266  /* try inherited tables */
2267  ListCell *inher;
2268 
2269  foreach(inher, cxt->inhRelations)
2270  {
2271  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2272  Relation rel;
2273  int count;
2274 
2275  rel = table_openrv(inh, AccessShareLock);
2276  /* check user requested inheritance from valid relkind */
2277  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2278  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2279  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2280  ereport(ERROR,
2281  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2282  errmsg("inherited relation \"%s\" is not a table or foreign table",
2283  inh->relname)));
2284  for (count = 0; count < rel->rd_att->natts; count++)
2285  {
2286  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2287  count);
2288  char *inhname = NameStr(inhattr->attname);
2289 
2290  if (inhattr->attisdropped)
2291  continue;
2292  if (strcmp(key, inhname) == 0)
2293  {
2294  found = true;
2295 
2296  /*
2297  * It's tempting to set forced_not_null if the
2298  * parent column is already NOT NULL, but that
2299  * seems unsafe because the column's NOT NULL
2300  * marking might disappear between now and
2301  * execution. Do the runtime check to be safe.
2302  */
2303  break;
2304  }
2305  }
2306  table_close(rel, NoLock);
2307  if (found)
2308  break;
2309  }
2310  }
2311 
2312  /*
2313  * In the ALTER TABLE case, don't complain about index keys not
2314  * created in the command; they may well exist already.
2315  * DefineIndex will complain about them if not.
2316  */
2317  if (!found && !cxt->isalter)
2318  ereport(ERROR,
2319  (errcode(ERRCODE_UNDEFINED_COLUMN),
2320  errmsg("column \"%s\" named in key does not exist", key),
2321  parser_errposition(cxt->pstate, constraint->location)));
2322 
2323  /* Check for PRIMARY KEY(foo, foo) */
2324  foreach(columns, index->indexParams)
2325  {
2326  iparam = (IndexElem *) lfirst(columns);
2327  if (iparam->name && strcmp(key, iparam->name) == 0)
2328  {
2329  if (index->primary)
2330  ereport(ERROR,
2331  (errcode(ERRCODE_DUPLICATE_COLUMN),
2332  errmsg("column \"%s\" appears twice in primary key constraint",
2333  key),
2334  parser_errposition(cxt->pstate, constraint->location)));
2335  else
2336  ereport(ERROR,
2337  (errcode(ERRCODE_DUPLICATE_COLUMN),
2338  errmsg("column \"%s\" appears twice in unique constraint",
2339  key),
2340  parser_errposition(cxt->pstate, constraint->location)));
2341  }
2342  }
2343 
2344  /* OK, add it to the index definition */
2345  iparam = makeNode(IndexElem);
2346  iparam->name = pstrdup(key);
2347  iparam->expr = NULL;
2348  iparam->indexcolname = NULL;
2349  iparam->collation = NIL;
2350  iparam->opclass = NIL;
2351  iparam->ordering = SORTBY_DEFAULT;
2353  index->indexParams = lappend(index->indexParams, iparam);
2354 
2355  /*
2356  * For a primary-key column, also create an item for ALTER TABLE
2357  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2358  */
2359  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2360  {
2361  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2362 
2363  notnullcmd->subtype = AT_SetNotNull;
2364  notnullcmd->name = pstrdup(key);
2365  notnullcmds = lappend(notnullcmds, notnullcmd);
2366  }
2367  }
2368  }
2369 
2370  /*
2371  * Add included columns to index definition. This is much like the
2372  * simple-column-name-list code above, except that we don't worry about
2373  * NOT NULL marking; included columns in a primary key should not be
2374  * forced NOT NULL. We don't complain about duplicate columns, either,
2375  * though maybe we should?
2376  */
2377  foreach(lc, constraint->including)
2378  {
2379  char *key = strVal(lfirst(lc));
2380  bool found = false;
2381  ColumnDef *column = NULL;
2382  ListCell *columns;
2383  IndexElem *iparam;
2384 
2385  foreach(columns, cxt->columns)
2386  {
2387  column = lfirst_node(ColumnDef, columns);
2388  if (strcmp(column->colname, key) == 0)
2389  {
2390  found = true;
2391  break;
2392  }
2393  }
2394 
2395  if (!found)
2396  {
2397  if (SystemAttributeByName(key) != NULL)
2398  {
2399  /*
2400  * column will be a system column in the new table, so accept
2401  * it.
2402  */
2403  found = true;
2404  }
2405  else if (cxt->inhRelations)
2406  {
2407  /* try inherited tables */
2408  ListCell *inher;
2409 
2410  foreach(inher, cxt->inhRelations)
2411  {
2412  RangeVar *inh = lfirst_node(RangeVar, inher);
2413  Relation rel;
2414  int count;
2415 
2416  rel = table_openrv(inh, AccessShareLock);
2417  /* check user requested inheritance from valid relkind */
2418  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2419  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2420  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2421  ereport(ERROR,
2422  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2423  errmsg("inherited relation \"%s\" is not a table or foreign table",
2424  inh->relname)));
2425  for (count = 0; count < rel->rd_att->natts; count++)
2426  {
2427  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2428  count);
2429  char *inhname = NameStr(inhattr->attname);
2430 
2431  if (inhattr->attisdropped)
2432  continue;
2433  if (strcmp(key, inhname) == 0)
2434  {
2435  found = true;
2436  break;
2437  }
2438  }
2439  table_close(rel, NoLock);
2440  if (found)
2441  break;
2442  }
2443  }
2444  }
2445 
2446  /*
2447  * In the ALTER TABLE case, don't complain about index keys not
2448  * created in the command; they may well exist already. DefineIndex
2449  * will complain about them if not.
2450  */
2451  if (!found && !cxt->isalter)
2452  ereport(ERROR,
2453  (errcode(ERRCODE_UNDEFINED_COLUMN),
2454  errmsg("column \"%s\" named in key does not exist", key),
2455  parser_errposition(cxt->pstate, constraint->location)));
2456 
2457  /* OK, add it to the index definition */
2458  iparam = makeNode(IndexElem);
2459  iparam->name = pstrdup(key);
2460  iparam->expr = NULL;
2461  iparam->indexcolname = NULL;
2462  iparam->collation = NIL;
2463  iparam->opclass = NIL;
2464  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2465  }
2466 
2467  /*
2468  * If we found anything that requires run-time SET NOT NULL, build a full
2469  * ALTER TABLE command for that and add it to cxt->alist.
2470  */
2471  if (notnullcmds)
2472  {
2473  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2474 
2475  alterstmt->relation = copyObject(cxt->relation);
2476  alterstmt->cmds = notnullcmds;
2477  alterstmt->relkind = OBJECT_TABLE;
2478  alterstmt->missing_ok = false;
2479 
2480  cxt->alist = lappend(cxt->alist, alterstmt);
2481  }
2482 
2483  return index;
2484 }
bool deferrable
Definition: parsenodes.h:2788
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:346
#define NIL
Definition: pg_list.h:65
Definition: c.h:595
bool primary
Definition: parsenodes.h:2786
List * keys
Definition: parsenodes.h:2164
List * exclusions
Definition: parsenodes.h:2170
int16 * rd_indoption
Definition: rel.h:168
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1956
SortByDir ordering
Definition: parsenodes.h:704
List * options
Definition: parsenodes.h:2779
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char * tableSpace
Definition: parsenodes.h:2775
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * whereClause
Definition: parsenodes.h:2780
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
bool initdeferred
Definition: parsenodes.h:2154
AlterTableType subtype
Definition: parsenodes.h:1860
char * conname
Definition: parsenodes.h:2152
bool is_not_null
Definition: parsenodes.h:650
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:198
#define OidIsValid(objectId)
Definition: c.h:645
List * options
Definition: parsenodes.h:2173
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4677
struct HeapTupleData * rd_indextuple
Definition: rel.h:151
List * indexIncludingParams
Definition: parsenodes.h:2777
Definition: type.h:89
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:249
ParseState * pstate
Definition: parse_utilcmd.c:78
char * relname
Definition: primnodes.h:68
Oid indexOid
Definition: parsenodes.h:2783
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parse_utilcmd.c:80
RangeVar * relation
Definition: parsenodes.h:2773
IndexStmt * pkey
Definition: parse_utilcmd.c:95
Form_pg_index rd_index
Definition: rel.h:149
Oid * rd_indcollation
Definition: rel.h:174
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
bool deferrable
Definition: parsenodes.h:2153
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
#define lfirst_node(type, lc)
Definition: pg_list.h:193
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:261
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:187
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4564
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:603
bool transformed
Definition: parsenodes.h:2790
int errdetail(const char *fmt,...)
Definition: elog.c:955
char * indexcolname
Definition: parsenodes.h:701
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:462
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:873
bool reset_default_tblspc
Definition: parsenodes.h:2176
#define ereport(elevel, rest)
Definition: elog.h:141
ObjectType relkind
Definition: parsenodes.h:1776
List * lappend(List *list, void *datum)
Definition: list.c:322
char * idxname
Definition: parsenodes.h:2772
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
bool reset_default_tblspc
Definition: parsenodes.h:2793
bool if_not_exists
Definition: parsenodes.h:2792
#define lsecond_node(type, l)
Definition: pg_list.h:203
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2785
TupleDesc rd_att
Definition: rel.h:85
char * accessMethod
Definition: parsenodes.h:2774
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_attribute
Definition: pg_attribute.h:184
int16 attnum
Definition: pg_attribute.h:79
List * opclass
Definition: parsenodes.h:703
bool is_from_type
Definition: parsenodes.h:651
Node * where_clause
Definition: parsenodes.h:2180
#define makeNode(_type_)
Definition: nodes.h:573
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2776
List * excludeOpNames
Definition: parsenodes.h:2781
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool initdeferred
Definition: parsenodes.h:2789
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2782
#define DatumGetPointer(X)
Definition: postgres.h:549
bool concurrent
Definition: parsenodes.h:2791
bool isconstraint
Definition: parsenodes.h:2787
char * indexname
Definition: parsenodes.h:2174
int errmsg(const char *fmt,...)
Definition: elog.c:822
RangeVar * relation
Definition: parsenodes.h:1774
int i
#define NameStr(name)
Definition: c.h:616
ConstrType contype
Definition: parsenodes.h:2149
List * collation
Definition: parsenodes.h:702
char * colname
Definition: parsenodes.h:646
List * including
Definition: parsenodes.h:2166
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:428
char * access_method
Definition: parsenodes.h:2179
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
char * indexspace
Definition: parsenodes.h:2175
#define RelationGetNamespace(relation)
Definition: rel.h:469

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 1848 of file parse_utilcmd.c.

References IndexStmt::accessMethod, CreateStmtContext::alist, Assert, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, IndexStmt::deferrable, equal(), ereport, errcode(), errmsg(), ERROR, IndexStmt::excludeOpNames, IndexStmt::idxname, IndexStmt::indexIncludingParams, IndexStmt::indexParams, CreateStmtContext::inh_indexes, IndexStmt::initdeferred, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, NIL, CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::relation, RangeVar::relname, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1849 {
1850  IndexStmt *index;
1851  List *indexlist = NIL;
1852  List *finalindexlist = NIL;
1853  ListCell *lc;
1854 
1855  /*
1856  * Run through the constraints that need to generate an index. For PRIMARY
1857  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1858  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1859  * NULL.
1860  */
1861  foreach(lc, cxt->ixconstraints)
1862  {
1863  Constraint *constraint = lfirst_node(Constraint, lc);
1864 
1865  Assert(constraint->contype == CONSTR_PRIMARY ||
1866  constraint->contype == CONSTR_UNIQUE ||
1867  constraint->contype == CONSTR_EXCLUSION);
1868 
1869  index = transformIndexConstraint(constraint, cxt);
1870 
1871  indexlist = lappend(indexlist, index);
1872  }
1873 
1874  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1875  foreach(lc, cxt->inh_indexes)
1876  {
1877  index = (IndexStmt *) lfirst(lc);
1878 
1879  if (index->primary)
1880  {
1881  if (cxt->pkey != NULL)
1882  ereport(ERROR,
1883  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1884  errmsg("multiple primary keys for table \"%s\" are not allowed",
1885  cxt->relation->relname)));
1886  cxt->pkey = index;
1887  }
1888 
1889  indexlist = lappend(indexlist, index);
1890  }
1891 
1892  /*
1893  * Scan the index list and remove any redundant index specifications. This
1894  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1895  * strict reading of SQL would suggest raising an error instead, but that
1896  * strikes me as too anal-retentive. - tgl 2001-02-14
1897  *
1898  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1899  * pre-existing indexes, too.
1900  */
1901  if (cxt->pkey != NULL)
1902  {
1903  /* Make sure we keep the PKEY index in preference to others... */
1904  finalindexlist = list_make1(cxt->pkey);
1905  }
1906 
1907  foreach(lc, indexlist)
1908  {
1909  bool keep = true;
1910  ListCell *k;
1911 
1912  index = lfirst(lc);
1913 
1914  /* if it's pkey, it's already in finalindexlist */
1915  if (index == cxt->pkey)
1916  continue;
1917 
1918  foreach(k, finalindexlist)
1919  {
1920  IndexStmt *priorindex = lfirst(k);
1921 
1922  if (equal(index->indexParams, priorindex->indexParams) &&
1923  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
1924  equal(index->whereClause, priorindex->whereClause) &&
1925  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1926  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1927  index->deferrable == priorindex->deferrable &&
1928  index->initdeferred == priorindex->initdeferred)
1929  {
1930  priorindex->unique |= index->unique;
1931 
1932  /*
1933  * If the prior index is as yet unnamed, and this one is
1934  * named, then transfer the name to the prior index. This
1935  * ensures that if we have named and unnamed constraints,
1936  * we'll use (at least one of) the names for the index.
1937  */
1938  if (priorindex->idxname == NULL)
1939  priorindex->idxname = index->idxname;
1940  keep = false;
1941  break;
1942  }
1943  }
1944 
1945  if (keep)
1946  finalindexlist = lappend(finalindexlist, index);
1947  }
1948 
1949  /*
1950  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
1951  * TABLE SET NOT NULL statement to support a primary key, it's already in
1952  * cxt->alist.
1953  */
1954  cxt->alist = list_concat(cxt->alist, finalindexlist);
1955 }
bool deferrable
Definition: parsenodes.h:2788
#define NIL
Definition: pg_list.h:65
bool primary
Definition: parsenodes.h:2786
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3018
Node * whereClause
Definition: parsenodes.h:2780
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
List * indexIncludingParams
Definition: parsenodes.h:2777
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:227
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
char * idxname
Definition: parsenodes.h:2772
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2785
char * accessMethod
Definition: parsenodes.h:2774
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2776
List * excludeOpNames
Definition: parsenodes.h:2781
bool initdeferred
Definition: parsenodes.h:2789
int errmsg(const char *fmt,...)
Definition: elog.c:822
ConstrType contype
Definition: parsenodes.h:2149
Definition: pg_list.h:50

◆ transformIndexStmt()

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

Definition at line 2609 of file parse_utilcmd.c.

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

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

2610 {
2611  ParseState *pstate;
2612  ParseNamespaceItem *nsitem;
2613  ListCell *l;
2614  Relation rel;
2615 
2616  /* Nothing to do if statement already transformed. */
2617  if (stmt->transformed)
2618  return stmt;
2619 
2620  /*
2621  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2622  * overkill, but easy.)
2623  */
2624  stmt = copyObject(stmt);
2625 
2626  /* Set up pstate */
2627  pstate = make_parsestate(NULL);
2628  pstate->p_sourcetext = queryString;
2629 
2630  /*
2631  * Put the parent table into the rtable so that the expressions can refer
2632  * to its fields without qualification. Caller is responsible for locking
2633  * relation, but we still need to open it.
2634  */
2635  rel = relation_open(relid, NoLock);
2636  nsitem = addRangeTableEntryForRelation(pstate, rel,
2638  NULL, false, true);
2639 
2640  /* no to join list, yes to namespaces */
2641  addNSItemToQuery(pstate, nsitem, false, true, true);
2642 
2643  /* take care of the where clause */
2644  if (stmt->whereClause)
2645  {
2646  stmt->whereClause = transformWhereClause(pstate,
2647  stmt->whereClause,
2649  "WHERE");
2650  /* we have to fix its collations too */
2651  assign_expr_collations(pstate, stmt->whereClause);
2652  }
2653 
2654  /* take care of any index expressions */
2655  foreach(l, stmt->indexParams)
2656  {
2657  IndexElem *ielem = (IndexElem *) lfirst(l);
2658 
2659  if (ielem->expr)
2660  {
2661  /* Extract preliminary index col name before transforming expr */
2662  if (ielem->indexcolname == NULL)
2663  ielem->indexcolname = FigureIndexColname(ielem->expr);
2664 
2665  /* Now do parse transformation of the expression */
2666  ielem->expr = transformExpr(pstate, ielem->expr,
2668 
2669  /* We have to fix its collations too */
2670  assign_expr_collations(pstate, ielem->expr);
2671 
2672  /*
2673  * transformExpr() should have already rejected subqueries,
2674  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2675  * for an index expression.
2676  *
2677  * DefineIndex() will make more checks.
2678  */
2679  }
2680  }
2681 
2682  /*
2683  * Check that only the base rel is mentioned. (This should be dead code
2684  * now that add_missing_from is history.)
2685  */
2686  if (list_length(pstate->p_rtable) != 1)
2687  ereport(ERROR,
2688  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2689  errmsg("index expressions and predicates can refer only to the table being indexed")));
2690 
2691  free_parsestate(pstate);
2692 
2693  /* Close relation */
2694  table_close(rel, NoLock);
2695 
2696  /* Mark statement as successfully transformed */
2697  stmt->transformed = true;
2698 
2699  return stmt;
2700 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Node * whereClause
Definition: parsenodes.h:2780
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:608
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:700
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2790
char * indexcolname
Definition: parsenodes.h:701
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel, rest)
Definition: elog.h:141
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2776
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
List * p_rtable
Definition: parse_node.h:180

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1282 of file parse_utilcmd.c.

References AssertArg, check_of_type(), ColumnDef::collClause, ColumnDef::collOid, ColumnDef::colname, CreateStmtContext::columns, ColumnDef::constraints, ColumnDef::cooked_default, DecrTupleDescRefCount(), GETSTRUCT, i, ColumnDef::inhcount, ColumnDef::is_from_type, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), ColumnDef::location, lookup_rowtype_tupdesc(), makeNode, makeTypeNameFromOid(), NameStr, TupleDescData::natts, NIL, pstrdup(), ColumnDef::raw_default, ReleaseSysCache(), ColumnDef::storage, TupleDescAttr, ColumnDef::typeName, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

1283 {
1284  HeapTuple tuple;
1285  TupleDesc tupdesc;
1286  int i;
1287  Oid ofTypeId;
1288 
1289  AssertArg(ofTypename);
1290 
1291  tuple = typenameType(NULL, ofTypename, NULL);
1292  check_of_type(tuple);
1293  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1294  ofTypename->typeOid = ofTypeId; /* cached for later */
1295 
1296  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1297  for (i = 0; i < tupdesc->natts; i++)
1298  {
1299  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1300  ColumnDef *n;
1301 
1302  if (attr->attisdropped)
1303  continue;
1304 
1305  n = makeNode(ColumnDef);
1306  n->colname = pstrdup(NameStr(attr->attname));
1307  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1308  n->inhcount = 0;
1309  n->is_local = true;
1310  n->is_not_null = false;
1311  n->is_from_type = true;
1312  n->storage = 0;
1313  n->raw_default = NULL;
1314  n->cooked_default = NULL;
1315  n->collClause = NULL;
1316  n->collOid = attr->attcollation;
1317  n->constraints = NIL;
1318  n->location = -1;
1319  cxt->columns = lappend(cxt->columns, n);
1320  }
1321  DecrTupleDescRefCount(tupdesc);
1322 
1323  ReleaseSysCache(tuple);
1324 }
#define NIL
Definition: pg_list.h:65
Oid typeOid
Definition: parsenodes.h:210
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
char storage
Definition: parsenodes.h:652
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1652
bool is_local
Definition: parsenodes.h:649
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:661
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool is_not_null
Definition: parsenodes.h:650
unsigned int Oid
Definition: postgres_ext.h:31
Node * cooked_default
Definition: parsenodes.h:654
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5814
Oid collOid
Definition: parsenodes.h:660
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
int location
Definition: parsenodes.h:663
#define AssertArg(condition)
Definition: c.h:741
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
bool is_from_type
Definition: parsenodes.h:651
#define makeNode(_type_)
Definition: nodes.h:573
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:393
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
TypeName * typeName
Definition: parsenodes.h:647
CollateClause * collClause
Definition: parsenodes.h:659
int i
int inhcount
Definition: parsenodes.h:648
#define NameStr(name)
Definition: c.h:616
char * colname
Definition: parsenodes.h:646

◆ transformPartitionBound()

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

Definition at line 3732 of file parse_utilcmd.c.

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

Referenced by DefineRelation(), and transformPartitionCmd().

3734 {
3735  PartitionBoundSpec *result_spec;
3737  char strategy = get_partition_strategy(key);
3738  int partnatts = get_partition_natts(key);
3739  List *partexprs = get_partition_exprs(key);
3740 
3741  /* Avoid scribbling on input */
3742  result_spec = copyObject(spec);
3743 
3744  if (spec->is_default)
3745  {
3746  /*
3747  * Hash partitioning does not support a default partition; there's no
3748  * use case for it (since the set of partitions to create is perfectly
3749  * defined), and if users do get into it accidentally, it's hard to
3750  * back out from it afterwards.
3751  */
3752  if (strategy == PARTITION_STRATEGY_HASH)
3753  ereport(ERROR,
3754  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3755  errmsg("a hash-partitioned table may not have a default partition")));
3756 
3757  /*
3758  * In case of the default partition, parser had no way to identify the
3759  * partition strategy. Assign the parent's strategy to the default
3760  * partition bound spec.
3761  */
3762  result_spec->strategy = strategy;
3763 
3764  return result_spec;
3765  }
3766 
3767  if (strategy == PARTITION_STRATEGY_HASH)
3768  {
3769  if (spec->strategy != PARTITION_STRATEGY_HASH)
3770  ereport(ERROR,
3771  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3772  errmsg("invalid bound specification for a hash partition"),
3773  parser_errposition(pstate, exprLocation((Node *) spec))));
3774 
3775  if (spec->modulus <= 0)
3776  ereport(ERROR,
3777  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3778  errmsg("modulus for hash partition must be a positive integer")));
3779 
3780  Assert(spec->remainder >= 0);
3781 
3782  if (spec->remainder >= spec->modulus)
3783  ereport(ERROR,
3784  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3785  errmsg("remainder for hash partition must be less than modulus")));
3786  }
3787  else if (strategy == PARTITION_STRATEGY_LIST)
3788  {
3789  ListCell *cell;
3790  char *colname;
3791  Oid coltype;
3792  int32 coltypmod;
3793  Oid partcollation;
3794 
3795  if (spec->strategy != PARTITION_STRATEGY_LIST)
3796  ereport(ERROR,
3797  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3798  errmsg("invalid bound specification for a list partition"),
3799  parser_errposition(pstate, exprLocation((Node *) spec))));
3800 
3801  /* Get the only column's name in case we need to output an error */
3802  if (key->partattrs[0] != 0)
3803  colname = get_attname(RelationGetRelid(parent),
3804  key->partattrs[0], false);
3805  else
3806  colname = deparse_expression((Node *) linitial(partexprs),
3808  RelationGetRelid(parent)),
3809  false, false);
3810  /* Need its type data too */
3811  coltype = get_partition_col_typid(key, 0);
3812  coltypmod = get_partition_col_typmod(key, 0);
3813  partcollation = get_partition_col_collation(key, 0);
3814 
3815  result_spec->listdatums = NIL;
3816  foreach(cell, spec->listdatums)
3817  {
3818  Node *expr = lfirst(cell);
3819  Const *value;
3820  ListCell *cell2;
3821  bool duplicate;
3822 
3823  value = transformPartitionBoundValue(pstate, expr,
3824  colname, coltype, coltypmod,
3825  partcollation);
3826 
3827  /* Don't add to the result if the value is a duplicate */
3828  duplicate = false;
3829  foreach(cell2, result_spec->listdatums)
3830  {
3831  Const *value2 = castNode(Const, lfirst(cell2));
3832 
3833  if (equal(value, value2))
3834  {
3835  duplicate = true;
3836  break;
3837  }
3838  }
3839  if (duplicate)
3840  continue;
3841 
3842  result_spec->listdatums = lappend(result_spec->listdatums,
3843  value);
3844  }
3845  }
3846  else if (strategy == PARTITION_STRATEGY_RANGE)
3847  {
3848  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3849  ereport(ERROR,
3850  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3851  errmsg("invalid bound specification for a range partition"),
3852  parser_errposition(pstate, exprLocation((Node *) spec))));
3853 
3854  if (list_length(spec->lowerdatums) != partnatts)
3855  ereport(ERROR,
3856  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3857  errmsg("FROM must specify exactly one value per partitioning column")));
3858  if (list_length(spec->upperdatums) != partnatts)
3859  ereport(ERROR,
3860  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3861  errmsg("TO must specify exactly one value per partitioning column")));
3862 
3863  /*
3864  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3865  * any necessary validation.
3866  */
3867  result_spec->lowerdatums =
3869  parent);
3870  result_spec->upperdatums =
3872  parent);
3873  }
3874  else
3875  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3876 
3877  return result_spec;
3878 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3018
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
static struct @145 value
Definition: nodes.h:525
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:608
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:347
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static Const * transformPartitionBoundValue(ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3272
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:798
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3212
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:799
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:800
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define copyObject(obj)
Definition: nodes.h:641
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:428

◆ transformPartitionBoundValue()

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

Definition at line 4042 of file parse_utilcmd.c.

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

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

4045 {
4046  Node *value;
4047 
4048  /* Transform raw parsetree */
4049  value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
4050 
4051  /*
4052  * Check that the input expression's collation is compatible with one
4053  * specified for the parent's partition key (partcollation). Don't throw
4054  * an error if it's the default collation which we'll replace with the
4055  * parent's collation anyway.
4056  */
4057  if (IsA(value, CollateExpr))
4058  {
4059  Oid exprCollOid = exprCollation(value);
4060 
4061  if (OidIsValid(exprCollOid) &&
4062  exprCollOid != DEFAULT_COLLATION_OID &&
4063  exprCollOid != partCollation)
4064  ereport(ERROR,
4065  (errcode(ERRCODE_DATATYPE_MISMATCH),
4066  errmsg("collation of partition bound value for column \"%s\" does not match partition key collation \"%s\"",
4067  colName, get_collation_name(partCollation)),
4068  parser_errposition(pstate, exprLocation(value))));
4069  }
4070 
4071  /* Coerce to correct type */
4072  value = coerce_to_target_type(pstate,
4073  value, exprType(value),
4074  colType,
4075  colTypmod,
4078  -1);
4079 
4080  if (value == NULL)
4081  ereport(ERROR,
4082  (errcode(ERRCODE_DATATYPE_MISMATCH),
4083  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4084  format_type_be(colType), colName),
4085  parser_errposition(pstate, exprLocation(val))));
4086 
4087  /* Simplify the expression, in case we had a coercion */
4088  if (!IsA(value, Const))
4089  value = (Node *) expression_planner((Expr *) value);
4090 
4091  /*
4092  * transformExpr() should have already rejected column references,
4093  * subqueries, aggregates, window functions, and SRFs, based on the
4094  * EXPR_KIND_ for a default expression.
4095  */
4096  Assert(!contain_var_clause(value));
4097 
4098  /*
4099  * Evaluate the expression, assigning the partition key's collation to the
4100  * resulting Const expression.
4101  */
4102  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4103  partCollation);
4104  if (!IsA(value, Const))
4105  elog(ERROR, "could not evaluate partition bound expression");
4106 
4107  return (Const *) value;
4108 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4788
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:923
Expr * expression_planner(Expr *expr)
Definition: planner.c:6051
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
static struct @145 value
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
bool contain_var_clause(Node *node)
Definition: var.c:331
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
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
#define ereport(elevel, rest)
Definition: elog.h:141
#define Assert(condition)
Definition: c.h:739
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
long val
Definition: informix.c:664

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 3687 of file parse_utilcmd.c.

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

3688 {
3689  Relation parentRel = cxt->rel;
3690 
3691  switch (parentRel->rd_rel->relkind)
3692  {
3693  case RELKIND_PARTITIONED_TABLE:
3694  /* transform the partition bound, if any */
3695  Assert(RelationGetPartitionKey(parentRel) != NULL);
3696  if (cmd->bound != NULL)
3697  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3698  cmd->bound);
3699  break;
3700  case RELKIND_PARTITIONED_INDEX:
3701  /* nothing to check */
3702  Assert(cmd->bound == NULL);
3703  break;
3704  case RELKIND_RELATION:
3705  /* the table must be partitioned */
3706  ereport(ERROR,
3707  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3708  errmsg("table \"%s\" is not partitioned",
3709  RelationGetRelationName(parentRel))));
3710  break;
3711  case RELKIND_INDEX:
3712  /* the index must be partitioned */
3713  ereport(ERROR,
3714  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3715  errmsg("index \"%s\" is not partitioned",
3716  RelationGetRelationName(parentRel))));
3717  break;
3718  default:
3719  /* parser shouldn't let this case through */
3720  elog(ERROR, "\"%s\" is not a partitioned table or index",
3721  RelationGetRelationName(parentRel));
3722  break;
3723  }
3724 }
int errcode(int sqlerrcode)
Definition: elog.c:608
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
Form_pg_class rd_rel
Definition: rel.h:84
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
#define Assert(condition)
Definition: c.h:739
PartitionBoundSpec * bound
Definition: parsenodes.h:859
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228

◆ transformPartitionRangeBounds()

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

Definition at line 3886 of file parse_utilcmd.c.

References Const::constisnull, 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, sort-test::key, PartitionRangeDatum::kind, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionRangeDatum::location, makeNode, NIL, PartitionKeyData::partattrs, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, strVal, transformPartitionBoundValue(), validateInfiniteBounds(), value, and PartitionRangeDatum::value.

Referenced by transformPartitionBound().

3888 {
3889  List *result = NIL;
3891  List *partexprs = get_partition_exprs(key);
3892  ListCell *lc;
3893  int i,
3894  j;
3895 
3896  i = j = 0;
3897  foreach(lc, blist)
3898  {
3899  Node *expr = lfirst(lc);
3900  PartitionRangeDatum *prd = NULL;
3901 
3902  /*
3903  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
3904  * as ColumnRefs.
3905  */
3906  if (IsA(expr, ColumnRef))
3907  {
3908  ColumnRef *cref = (ColumnRef *) expr;
3909  char *cname = NULL;
3910 
3911  /*
3912  * There should be a single field named either "minvalue" or
3913  * "maxvalue".
3914  */
3915  if (list_length(cref->fields) == 1 &&
3916  IsA(linitial(cref->fields), String))
3917  cname = strVal(linitial(cref->fields));
3918 
3919  if (cname == NULL)
3920  {
3921  /*
3922  * ColumnRef is not in the desired single-field-name form. For
3923  * consistency between all partition strategies, let the
3924  * expression transformation report any errors rather than
3925  * doing it ourselves.
3926  */
3927  }
3928  else if (strcmp("minvalue", cname) == 0)
3929  {
3932  prd->value = NULL;
3933  }
3934  else if (strcmp("maxvalue", cname) == 0)
3935  {
3938  prd->value = NULL;
3939  }
3940  }
3941 
3942  if (prd == NULL)
3943  {
3944  char *colname;
3945  Oid coltype;
3946  int32 coltypmod;
3947  Oid partcollation;
3948  Const *value;
3949