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, char **snamespace_p, char **sname_p)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
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 1689 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().

1691 {
1692  HeapTuple ht_stats;
1693  Form_pg_statistic_ext statsrec;
1694  CreateStatsStmt *stats;
1695  List *stat_types = NIL;
1696  List *def_names = NIL;
1697  bool isnull;
1698  Datum datum;
1699  ArrayType *arr;
1700  char *enabled;
1701  int i;
1702 
1703  Assert(OidIsValid(heapRelid));
1704  Assert(heapRel != NULL);
1705 
1706  /*
1707  * Fetch pg_statistic_ext tuple of source statistics object.
1708  */
1709  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1710  if (!HeapTupleIsValid(ht_stats))
1711  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1712  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1713 
1714  /* Determine which statistics types exist */
1715  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1716  Anum_pg_statistic_ext_stxkind, &isnull);
1717  Assert(!isnull);
1718  arr = DatumGetArrayTypeP(datum);
1719  if (ARR_NDIM(arr) != 1 ||
1720  ARR_HASNULL(arr) ||
1721  ARR_ELEMTYPE(arr) != CHAROID)
1722  elog(ERROR, "stxkind is not a 1-D char array");
1723  enabled = (char *) ARR_DATA_PTR(arr);
1724  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1725  {
1726  if (enabled[i] == STATS_EXT_NDISTINCT)
1727  stat_types = lappend(stat_types, makeString("ndistinct"));
1728  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1729  stat_types = lappend(stat_types, makeString("dependencies"));
1730  else if (enabled[i] == STATS_EXT_MCV)
1731  stat_types = lappend(stat_types, makeString("mcv"));
1732  else
1733  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1734  }
1735 
1736  /* Determine which columns the statistics are on */
1737  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1738  {
1739  ColumnRef *cref = makeNode(ColumnRef);
1740  AttrNumber attnum = statsrec->stxkeys.values[i];
1741 
1742  cref->fields = list_make1(makeString(get_attname(heapRelid,
1743  attnum, false)));
1744  cref->location = -1;
1745 
1746  def_names = lappend(def_names, cref);
1747  }
1748 
1749  /* finally, build the output node */
1750  stats = makeNode(CreateStatsStmt);
1751  stats->defnames = NULL;
1752  stats->stat_types = stat_types;
1753  stats->exprs = def_names;
1754  stats->relations = list_make1(heapRel);
1755  stats->stxcomment = NULL;
1756  stats->if_not_exists = false;
1757 
1758  /* Clean up */
1759  ReleaseSysCache(ht_stats);
1760 
1761  return stats;
1762 }
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 AttrNumber attmap,
int  attmap_length,
Oid constraintOid 
)

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

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

◆ generateSerialExtraStmts()

static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
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().

352 {
353  ListCell *option;
354  DefElem *nameEl = NULL;
355  Oid snamespaceid;
356  char *snamespace;
357  char *sname;
358  CreateSeqStmt *seqstmt;
359  AlterSeqStmt *altseqstmt;
360  List *attnamelist;
361 
362  /*
363  * Determine namespace and name to use for the sequence.
364  *
365  * First, check if a sequence name was passed in as an option. This is
366  * used by pg_dump. Else, generate a name.
367  *
368  * Although we use ChooseRelationName, it's not guaranteed that the
369  * selected sequence name won't conflict; given sufficiently long field
370  * names, two different serial columns in the same table could be assigned
371  * the same sequence name, and we'd not notice since we aren't creating
372  * the sequence quite yet. In practice this seems quite unlikely to be a
373  * problem, especially since few people would need two serial columns in
374  * one table.
375  */
376  foreach(option, seqoptions)
377  {
378  DefElem *defel = lfirst_node(DefElem, option);
379 
380  if (strcmp(defel->defname, "sequence_name") == 0)
381  {
382  if (nameEl)
383  ereport(ERROR,
384  (errcode(ERRCODE_SYNTAX_ERROR),
385  errmsg("conflicting or redundant options")));
386  nameEl = defel;
387  }
388  }
389 
390  if (nameEl)
391  {
393 
394  snamespace = rv->schemaname;
395  if (!snamespace)
396  {
397  /* Given unqualified SEQUENCE NAME, select namespace */
398  if (cxt->rel)
399  snamespaceid = RelationGetNamespace(cxt->rel);
400  else
401  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
402  snamespace = get_namespace_name(snamespaceid);
403  }
404  sname = rv->relname;
405  /* Remove the SEQUENCE NAME item from seqoptions */
406  seqoptions = list_delete_ptr(seqoptions, nameEl);
407  }
408  else
409  {
410  if (cxt->rel)
411  snamespaceid = RelationGetNamespace(cxt->rel);
412  else
413  {
414  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
415  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
416  }
417  snamespace = get_namespace_name(snamespaceid);
418  sname = ChooseRelationName(cxt->relation->relname,
419  column->colname,
420  "seq",
421  snamespaceid,
422  false);
423  }
424 
425  ereport(DEBUG1,
426  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
427  cxt->stmtType, sname,
428  cxt->relation->relname, column->colname)));
429 
430  /*
431  * Build a CREATE SEQUENCE command to create the sequence object, and add
432  * it to the list of things to be done before this CREATE/ALTER TABLE.
433  */
434  seqstmt = makeNode(CreateSeqStmt);
435  seqstmt->for_identity = for_identity;
436  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
437  seqstmt->options = seqoptions;
438 
439  /*
440  * If a sequence data type was specified, add it to the options. Prepend
441  * to the list rather than append; in case a user supplied their own AS
442  * clause, the "redundant options" error will point to their occurrence,
443  * not our synthetic one.
444  */
445  if (seqtypid)
446  seqstmt->options = lcons(makeDefElem("as",
447  (Node *) makeTypeNameFromOid(seqtypid, -1),
448  -1),
449  seqstmt->options);
450 
451  /*
452  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
453  * the table's owner. The current user might be someone else (perhaps a
454  * superuser, or someone who's only a member of the owning role), but the
455  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
456  * exactly the same owning role.
457  */
458  if (cxt->rel)
459  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
460  else
461  seqstmt->ownerId = InvalidOid;
462 
463  cxt->blist = lappend(cxt->blist, seqstmt);
464 
465  /*
466  * Store the identity sequence name that we decided on. ALTER TABLE ...
467  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
468  * with values from the sequence, while the association of the sequence
469  * with the table is not set until after the ALTER TABLE.
470  */
471  column->identitySequence = seqstmt->sequence;
472 
473  /*
474  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
475  * owned by this column, and add it to the list of things to be done after
476  * this CREATE/ALTER TABLE.
477  */
478  altseqstmt = makeNode(AlterSeqStmt);
479  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
480  attnamelist = list_make3(makeString(snamespace),
481  makeString(cxt->relation->relname),
482  makeString(column->colname));
483  altseqstmt->options = list_make1(makeDefElem("owned_by",
484  (Node *) attnamelist, -1));
485  altseqstmt->for_identity = for_identity;
486 
487  cxt->alist = lappend(cxt->alist, altseqstmt);
488 
489  if (snamespace_p)
490  *snamespace_p = snamespace;
491  if (sname_p)
492  *sname_p = sname;
493 }
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:2134
Form_pg_class rd_rel
Definition: rel.h:83
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:2533
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:2532
RangeVar * sequence
Definition: parsenodes.h:2522
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:2534
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:2523
#define RelationGetNamespace(relation)
Definition: rel.h:463

◆ get_collation()

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

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

1772 {
1773  List *result;
1774  HeapTuple ht_coll;
1775  Form_pg_collation coll_rec;
1776  char *nsp_name;
1777  char *coll_name;
1778 
1779  if (!OidIsValid(collation))
1780  return NIL; /* easy case */
1781  if (collation == get_typcollation(actual_datatype))
1782  return NIL; /* just let it default */
1783 
1784  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1785  if (!HeapTupleIsValid(ht_coll))
1786  elog(ERROR, "cache lookup failed for collation %u", collation);
1787  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1788 
1789  /* For simplicity, we always schema-qualify the name */
1790  nsp_name = get_namespace_name(coll_rec->collnamespace);
1791  coll_name = pstrdup(NameStr(coll_rec->collname));
1792  result = list_make2(makeString(nsp_name), makeString(coll_name));
1793 
1794  ReleaseSysCache(ht_coll);
1795  return result;
1796 }
#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 1805 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().

1806 {
1807  List *result = NIL;
1808  HeapTuple ht_opc;
1809  Form_pg_opclass opc_rec;
1810 
1811  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1812  if (!HeapTupleIsValid(ht_opc))
1813  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1814  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1815 
1816  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1817  {
1818  /* For simplicity, we always schema-qualify the name */
1819  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1820  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1821 
1822  result = list_make2(makeString(nsp_name), makeString(opc_name));
1823  }
1824 
1825  ReleaseSysCache(ht_opc);
1826  return result;
1827 }
#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:1939
#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 3653 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3654 {
3655  if (*stmt_schema_name == NULL)
3656  *stmt_schema_name = context_schema;
3657  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3658  ereport(ERROR,
3659  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3660  errmsg("CREATE specifies a schema (%s) "
3661  "different from the one being created (%s)",
3662  *stmt_schema_name, context_schema)));
3663 }
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()

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

Definition at line 3014 of file parse_utilcmd.c.

References AccessShareLock, addRangeTableEntryForRelation(), addRTEtoQuery(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_ProcessedConstraint, 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, 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, OBJECT_FOREIGN_TABLE, 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, AlterTableStmt::relkind, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

3016 {
3017  Relation rel;
3018  TupleDesc tupdesc;
3019  ParseState *pstate;
3020  CreateStmtContext cxt;
3021  List *result;
3022  List *save_alist;
3023  ListCell *lcmd,
3024  *l;
3025  List *newcmds = NIL;
3026  bool skipValidation = true;
3027  AlterTableCmd *newcmd;
3028  RangeTblEntry *rte;
3029 
3030  /*
3031  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3032  * is overkill, but easy.)
3033  */
3034  stmt = copyObject(stmt);
3035 
3036  /* Caller is responsible for locking the relation */
3037  rel = relation_open(relid, NoLock);
3038  tupdesc = RelationGetDescr(rel);
3039 
3040  /* Set up pstate */
3041  pstate = make_parsestate(NULL);
3042  pstate->p_sourcetext = queryString;
3043  rte = addRangeTableEntryForRelation(pstate,
3044  rel,
3046  NULL,
3047  false,
3048  true);
3049  addRTEtoQuery(pstate, rte, false, true, true);
3050 
3051  /* Set up CreateStmtContext */
3052  cxt.pstate = pstate;
3053  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
3054  {
3055  cxt.stmtType = "ALTER FOREIGN TABLE";
3056  cxt.isforeign = true;
3057  }
3058  else
3059  {
3060  cxt.stmtType = "ALTER TABLE";
3061  cxt.isforeign = false;
3062  }
3063  cxt.relation = stmt->relation;
3064  cxt.rel = rel;
3065  cxt.inhRelations = NIL;
3066  cxt.isalter = true;
3067  cxt.columns = NIL;
3068  cxt.ckconstraints = NIL;
3069  cxt.fkconstraints = NIL;
3070  cxt.ixconstraints = NIL;
3071  cxt.inh_indexes = NIL;
3072  cxt.extstats = NIL;
3073  cxt.blist = NIL;
3074  cxt.alist = NIL;
3075  cxt.pkey = NULL;
3076  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3077  cxt.partbound = NULL;
3078  cxt.ofType = false;
3079 
3080  /*
3081  * The only subtypes that currently require parse transformation handling
3082  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
3083  * code from CREATE TABLE.
3084  */
3085  foreach(lcmd, stmt->cmds)
3086  {
3087  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3088 
3089  switch (cmd->subtype)
3090  {
3091  case AT_AddColumn:
3092  case AT_AddColumnToView:
3093  {
3094  ColumnDef *def = castNode(ColumnDef, cmd->def);
3095 
3096  transformColumnDefinition(&cxt, def);
3097 
3098  /*
3099  * If the column has a non-null default, we can't skip
3100  * validation of foreign keys.
3101  */
3102  if (def->raw_default != NULL)
3103  skipValidation = false;
3104 
3105  /*
3106  * All constraints are processed in other ways. Remove the
3107  * original list
3108  */
3109  def->constraints = NIL;
3110 
3111  newcmds = lappend(newcmds, cmd);
3112  break;
3113  }
3114 
3115  case AT_AddConstraint:
3116 
3117  /*
3118  * The original AddConstraint cmd node doesn't go to newcmds
3119  */
3120  if (IsA(cmd->def, Constraint))
3121  {
3122  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3123  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3124  skipValidation = false;
3125  }
3126  else
3127  elog(ERROR, "unrecognized node type: %d",
3128  (int) nodeTag(cmd->def));
3129  break;
3130 
3132 
3133  /*
3134  * Already-transformed ADD CONSTRAINT, so just make it look
3135  * like the standard case.
3136  */
3137  cmd->subtype = AT_AddConstraint;
3138  newcmds = lappend(newcmds, cmd);
3139  break;
3140 
3141  case AT_AlterColumnType:
3142  {
3143  ColumnDef *def = (ColumnDef *) cmd->def;
3145 
3146  /*
3147  * For ALTER COLUMN TYPE, transform the USING clause if
3148  * one was specified.
3149  */
3150  if (def->raw_default)
3151  {
3152  def->cooked_default =
3153  transformExpr(pstate, def->raw_default,
3155  }
3156 
3157  /*
3158  * For identity column, create ALTER SEQUENCE command to
3159  * change the data type of the sequence.
3160  */
3161  attnum = get_attnum(relid, cmd->name);
3162 
3163  /*
3164  * if attribute not found, something will error about it
3165  * later
3166  */
3167  if (attnum != InvalidAttrNumber &&
3168  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3169  {
3170  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3171  Oid typeOid = typenameTypeId(pstate, def->typeName);
3172  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3173 
3174  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3175  get_rel_name(seq_relid),
3176  -1);
3177  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3178  altseqstmt->for_identity = true;
3179  cxt.blist = lappend(cxt.blist, altseqstmt);
3180  }
3181 
3182  newcmds = lappend(newcmds, cmd);
3183  break;
3184  }
3185 
3186  case AT_AddIdentity:
3187  {
3188  Constraint *def = castNode(Constraint, cmd->def);
3189  ColumnDef *newdef = makeNode(ColumnDef);
3191 
3192  newdef->colname = cmd->name;
3193  newdef->identity = def->generated_when;
3194  cmd->def = (Node *) newdef;
3195 
3196  attnum = get_attnum(relid, cmd->name);
3197 
3198  /*
3199  * if attribute not found, something will error about it
3200  * later
3201  */
3202  if (attnum != InvalidAttrNumber)
3203  generateSerialExtraStmts(&cxt, newdef,
3204  get_atttype(relid, attnum),
3205  def->options, true,
3206  NULL, NULL);
3207 
3208  newcmds = lappend(newcmds, cmd);
3209  break;
3210  }
3211 
3212  case AT_SetIdentity:
3213  {
3214  /*
3215  * Create an ALTER SEQUENCE statement for the internal
3216  * sequence of the identity column.
3217  */
3218  ListCell *lc;
3219  List *newseqopts = NIL;
3220  List *newdef = NIL;
3222 
3223  /*
3224  * Split options into those handled by ALTER SEQUENCE and
3225  * those for ALTER TABLE proper.
3226  */
3227  foreach(lc, castNode(List, cmd->def))
3228  {
3229  DefElem *def = lfirst_node(DefElem, lc);
3230 
3231  if (strcmp(def->defname, "generated") == 0)
3232  newdef = lappend(newdef, def);
3233  else
3234  newseqopts = lappend(newseqopts, def);
3235  }
3236 
3237  attnum = get_attnum(relid, cmd->name);
3238 
3239  if (attnum)
3240  {
3241  Oid seq_relid = getIdentitySequence(relid, attnum, true);
3242 
3243  if (seq_relid)
3244  {
3245  AlterSeqStmt *seqstmt;
3246 
3247  seqstmt = makeNode(AlterSeqStmt);
3249  get_rel_name(seq_relid), -1);
3250  seqstmt->options = newseqopts;
3251  seqstmt->for_identity = true;
3252  seqstmt->missing_ok = false;
3253 
3254  cxt.alist = lappend(cxt.alist, seqstmt);
3255  }
3256  }
3257 
3258  /*
3259  * If column was not found or was not an identity column,
3260  * we just let the ALTER TABLE command error out later.
3261  */
3262 
3263  cmd->def = (Node *) newdef;
3264  newcmds = lappend(newcmds, cmd);
3265  break;
3266  }
3267 
3268  case AT_AttachPartition:
3269  case AT_DetachPartition:
3270  {
3271  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3272 
3273  transformPartitionCmd(&cxt, partcmd);
3274  /* assign transformed value of the partition bound */
3275  partcmd->bound = cxt.partbound;
3276  }
3277 
3278  newcmds = lappend(newcmds, cmd);
3279  break;
3280 
3281  default:
3282  newcmds = lappend(newcmds, cmd);
3283  break;
3284  }
3285  }
3286 
3287  /*
3288  * Transfer anything we already have in cxt.alist into save_alist, to keep
3289  * it separate from the output of transformIndexConstraints.
3290  */
3291  save_alist = cxt.alist;
3292  cxt.alist = NIL;
3293 
3294  /* Postprocess constraints */
3296  transformFKConstraints(&cxt, skipValidation, true);
3297  transformCheckConstraints(&cxt, false);
3298 
3299  /*
3300  * Push any index-creation commands into the ALTER, so that they can be
3301  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3302  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3303  * subcommand has already been through transformIndexStmt.
3304  */
3305  foreach(l, cxt.alist)
3306  {
3307  Node *istmt = (Node *) lfirst(l);
3308 
3309  /*
3310  * We assume here that cxt.alist contains only IndexStmts and possibly
3311  * ALTER TABLE SET NOT NULL statements generated from primary key
3312  * constraints. We absorb the subcommands of the latter directly.
3313  */
3314  if (IsA(istmt, IndexStmt))
3315  {
3316  IndexStmt *idxstmt = (IndexStmt *) istmt;
3317 
3318  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3319  newcmd = makeNode(AlterTableCmd);
3321  newcmd->def = (Node *) idxstmt;
3322  newcmds = lappend(newcmds, newcmd);
3323  }
3324  else if (IsA(istmt, AlterTableStmt))
3325  {
3326  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3327 
3328  newcmds = list_concat(newcmds, alterstmt->cmds);
3329  }
3330  else
3331  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3332  }
3333  cxt.alist = NIL;
3334 
3335  /* Append any CHECK or FK constraints to the commands list */
3336  foreach(l, cxt.ckconstraints)
3337  {
3338  newcmd = makeNode(AlterTableCmd);
3339  newcmd->subtype = AT_AddConstraint;
3340  newcmd->def = (Node *) lfirst(l);
3341  newcmds = lappend(newcmds, newcmd);
3342  }
3343  foreach(l, cxt.fkconstraints)
3344  {
3345  newcmd = makeNode(AlterTableCmd);
3346  newcmd->subtype = AT_AddConstraint;
3347  newcmd->def = (Node *) lfirst(l);
3348  newcmds = lappend(newcmds, newcmd);
3349  }
3350 
3351  /* Append extended statistic objects */
3353 
3354  /* Close rel */
3355  relation_close(rel, NoLock);
3356 
3357  /*
3358  * Output results.
3359  */
3360  stmt->cmds = newcmds;
3361 
3362  result = lappend(cxt.blist, stmt);
3363  result = list_concat(result, cxt.alist);
3364  result = list_concat(result, save_alist);
3365 
3366  return result;
3367 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
char generated_when
Definition: parsenodes.h:2141
#define RelationGetDescr(relation)
Definition: rel.h:448
#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:144
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
AlterTableType subtype
Definition: parsenodes.h:1840
Form_pg_class rd_rel
Definition: rel.h:83
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:2533
List * options
Definition: parsenodes.h:2153
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:2763
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
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
const char * p_sourcetext
Definition: parse_node.h:176
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
ObjectType relkind
Definition: parsenodes.h:1755
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
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:2532
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)
RangeVar * relation
Definition: parsenodes.h:1753
#define elog(elevel,...)
Definition: elog.h:228
bool for_identity
Definition: parsenodes.h:2534
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 2498 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2499 {
2500  ListCell *ckclist;
2501 
2502  if (cxt->ckconstraints == NIL)
2503  return;
2504 
2505  /*
2506  * If creating a new table (but not a foreign table), we can safely skip
2507  * validation of check constraints, and nonetheless mark them valid. (This
2508  * will override any user-supplied NOT VALID flag.)
2509  */
2510  if (skipValidation)
2511  {
2512  foreach(ckclist, cxt->ckconstraints)
2513  {
2514  Constraint *constraint = (Constraint *) lfirst(ckclist);
2515 
2516  constraint->skip_validation = true;
2517  constraint->initially_valid = true;
2518  }
2519  }
2520 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2175
#define lfirst(lc)
Definition: pg_list.h:190
bool skip_validation
Definition: parsenodes.h:2174

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

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

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

3496 {
3497  /*
3498  * All we really need to do here is verify that the type is valid,
3499  * including any collation spec that might be present.
3500  */
3501  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3502 
3503  if (column->collClause)
3504  {
3505  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3506 
3507  LookupCollation(cxt->pstate,
3508  column->collClause->collname,
3509  column->collClause->location);
3510  /* Complain if COLLATE is applied to an uncollatable type */
3511  if (!OidIsValid(typtup->typcollation))
3512  ereport(ERROR,
3513  (errcode(ERRCODE_DATATYPE_MISMATCH),
3514  errmsg("collations are not supported by type %s",
3515  format_type_be(typtup->oid)),
3517  column->collClause->location)));
3518  }
3519 
3520  ReleaseSysCache(ctype);
3521 }
#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 3380 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().

3381 {
3382  Constraint *lastprimarycon = NULL;
3383  bool saw_deferrability = false;
3384  bool saw_initially = false;
3385  ListCell *clist;
3386 
3387 #define SUPPORTS_ATTRS(node) \
3388  ((node) != NULL && \
3389  ((node)->contype == CONSTR_PRIMARY || \
3390  (node)->contype == CONSTR_UNIQUE || \
3391  (node)->contype == CONSTR_EXCLUSION || \
3392  (node)->contype == CONSTR_FOREIGN))
3393 
3394  foreach(clist, constraintList)
3395  {
3396  Constraint *con = (Constraint *) lfirst(clist);
3397 
3398  if (!IsA(con, Constraint))
3399  elog(ERROR, "unrecognized node type: %d",
3400  (int) nodeTag(con));
3401  switch (con->contype)
3402  {
3404  if (!SUPPORTS_ATTRS(lastprimarycon))
3405  ereport(ERROR,
3406  (errcode(ERRCODE_SYNTAX_ERROR),
3407  errmsg("misplaced DEFERRABLE clause"),
3408  parser_errposition(cxt->pstate, con->location)));
3409  if (saw_deferrability)
3410  ereport(ERROR,
3411  (errcode(ERRCODE_SYNTAX_ERROR),
3412  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3413  parser_errposition(cxt->pstate, con->location)));
3414  saw_deferrability = true;
3415  lastprimarycon->deferrable = true;
3416  break;
3417 
3419  if (!SUPPORTS_ATTRS(lastprimarycon))
3420  ereport(ERROR,
3421  (errcode(ERRCODE_SYNTAX_ERROR),
3422  errmsg("misplaced NOT DEFERRABLE clause"),
3423  parser_errposition(cxt->pstate, con->location)));
3424  if (saw_deferrability)
3425  ereport(ERROR,
3426  (errcode(ERRCODE_SYNTAX_ERROR),
3427  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3428  parser_errposition(cxt->pstate, con->location)));
3429  saw_deferrability = true;
3430  lastprimarycon->deferrable = false;
3431  if (saw_initially &&
3432  lastprimarycon->initdeferred)
3433  ereport(ERROR,
3434  (errcode(ERRCODE_SYNTAX_ERROR),
3435  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3436  parser_errposition(cxt->pstate, con->location)));
3437  break;
3438 
3439  case CONSTR_ATTR_DEFERRED:
3440  if (!SUPPORTS_ATTRS(lastprimarycon))
3441  ereport(ERROR,
3442  (errcode(ERRCODE_SYNTAX_ERROR),
3443  errmsg("misplaced INITIALLY DEFERRED clause"),
3444  parser_errposition(cxt->pstate, con->location)));
3445  if (saw_initially)
3446  ereport(ERROR,
3447  (errcode(ERRCODE_SYNTAX_ERROR),
3448  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3449  parser_errposition(cxt->pstate, con->location)));
3450  saw_initially = true;
3451  lastprimarycon->initdeferred = true;
3452 
3453  /*
3454  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3455  */
3456  if (!saw_deferrability)
3457  lastprimarycon->deferrable = true;
3458  else if (!lastprimarycon->deferrable)
3459  ereport(ERROR,
3460  (errcode(ERRCODE_SYNTAX_ERROR),
3461  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3462  parser_errposition(cxt->pstate, con->location)));
3463  break;
3464 
3465  case CONSTR_ATTR_IMMEDIATE:
3466  if (!SUPPORTS_ATTRS(lastprimarycon))
3467  ereport(ERROR,
3468  (errcode(ERRCODE_SYNTAX_ERROR),
3469  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3470  parser_errposition(cxt->pstate, con->location)));
3471  if (saw_initially)
3472  ereport(ERROR,
3473  (errcode(ERRCODE_SYNTAX_ERROR),
3474  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3475  parser_errposition(cxt->pstate, con->location)));
3476  saw_initially = true;
3477  lastprimarycon->initdeferred = false;
3478  break;
3479 
3480  default:
3481  /* Otherwise it's not an attribute */
3482  lastprimarycon = con;
3483  /* reset flags for new primary node */
3484  saw_deferrability = false;
3485  saw_initially = false;
3486  break;
3487  }
3488  }
3489 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int errcode(int sqlerrcode)
Definition: elog.c:608
bool initdeferred
Definition: parsenodes.h:2134
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2133
#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:2129

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

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

3549 {
3551  List *result;
3552  ListCell *elements;
3553 
3554  cxt.stmtType = "CREATE SCHEMA";
3555  cxt.schemaname = stmt->schemaname;
3556  cxt.authrole = (RoleSpec *) stmt->authrole;
3557  cxt.sequences = NIL;
3558  cxt.tables = NIL;
3559  cxt.views = NIL;
3560  cxt.indexes = NIL;
3561  cxt.triggers = NIL;
3562  cxt.grants = NIL;
3563 
3564  /*
3565  * Run through each schema element in the schema element list. Separate
3566  * statements by type, and do preliminary analysis.
3567  */
3568  foreach(elements, stmt->schemaElts)
3569  {
3570  Node *element = lfirst(elements);
3571 
3572  switch (nodeTag(element))
3573  {
3574  case T_CreateSeqStmt:
3575  {
3576  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3577 
3579  cxt.sequences = lappend(cxt.sequences, element);
3580  }
3581  break;
3582 
3583  case T_CreateStmt:
3584  {
3585  CreateStmt *elp = (CreateStmt *) element;
3586 
3588 
3589  /*
3590  * XXX todo: deal with constraints
3591  */
3592  cxt.tables = lappend(cxt.tables, element);
3593  }
3594  break;
3595 
3596  case T_ViewStmt:
3597  {
3598  ViewStmt *elp = (ViewStmt *) element;
3599 
3600  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3601 
3602  /*
3603  * XXX todo: deal with references between views
3604  */
3605  cxt.views = lappend(cxt.views, element);
3606  }
3607  break;
3608 
3609  case T_IndexStmt:
3610  {
3611  IndexStmt *elp = (IndexStmt *) element;
3612 
3614  cxt.indexes = lappend(cxt.indexes, element);
3615  }
3616  break;
3617 
3618  case T_CreateTrigStmt:
3619  {
3620  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3621 
3623  cxt.triggers = lappend(cxt.triggers, element);
3624  }
3625  break;
3626 
3627  case T_GrantStmt:
3628  cxt.grants = lappend(cxt.grants, element);
3629  break;
3630 
3631  default:
3632  elog(ERROR, "unrecognized node type: %d",
3633  (int) nodeTag(element));
3634  }
3635  }
3636 
3637  result = NIL;
3638  result = list_concat(result, cxt.sequences);
3639  result = list_concat(result, cxt.tables);
3640  result = list_concat(result, cxt.views);
3641  result = list_concat(result, cxt.indexes);
3642  result = list_concat(result, cxt.triggers);
3643  result = list_concat(result, cxt.grants);
3644 
3645  return result;
3646 }
RangeVar * relation
Definition: parsenodes.h:2049
#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:3092
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2753
RoleSpec * authrole
Definition: parsenodes.h:1735
#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:2522
#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:2408
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:2049
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2051
#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:2056
bool if_not_exists
Definition: parsenodes.h:2061
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2053
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:176
#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:2050
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:2054
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2055
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2483 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2484 {
2485  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2486 }
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 2527 of file parse_utilcmd.c.

References CreateStmtContext::alist, AT_ProcessedConstraint, 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().

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

◆ transformIndexConstraint()

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

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

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

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

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

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

◆ transformIndexStmt()

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

Definition at line 2598 of file parse_utilcmd.c.

References AccessShareLock, addRangeTableEntryForRelation(), addRTEtoQuery(), 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().

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

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

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

1272 {
1273  HeapTuple tuple;
1274  TupleDesc tupdesc;
1275  int i;
1276  Oid ofTypeId;
1277 
1278  AssertArg(ofTypename);
1279 
1280  tuple = typenameType(NULL, ofTypename, NULL);
1281  check_of_type(tuple);
1282  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1283  ofTypename->typeOid = ofTypeId; /* cached for later */
1284 
1285  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1286  for (i = 0; i < tupdesc->natts; i++)
1287  {
1288  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1289  ColumnDef *n;
1290 
1291  if (attr->attisdropped)
1292  continue;
1293 
1294  n = makeNode(ColumnDef);
1295  n->colname = pstrdup(NameStr(attr->attname));
1296  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1297  n->inhcount = 0;
1298  n->is_local = true;
1299  n->is_not_null = false;
1300  n->is_from_type = true;
1301  n->storage = 0;
1302  n->raw_default = NULL;
1303  n->cooked_default = NULL;
1304  n->collClause = NULL;
1305  n->collOid = attr->attcollation;
1306  n->constraints = NIL;
1307  n->location = -1;
1308  cxt->columns = lappend(cxt->columns, n);
1309  }
1310  DecrTupleDescRefCount(tupdesc);
1311 
1312  ReleaseSysCache(tuple);
1313 }
#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:5533
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 3718 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().

3720 {
3721  PartitionBoundSpec *result_spec;
3723  char strategy = get_partition_strategy(key);
3724  int partnatts = get_partition_natts(key);
3725  List *partexprs = get_partition_exprs(key);
3726 
3727  /* Avoid scribbling on input */
3728  result_spec = copyObject(spec);
3729 
3730  if (spec->is_default)
3731  {
3732  /*
3733  * Hash partitioning does not support a default partition; there's no
3734  * use case for it (since the set of partitions to create is perfectly
3735  * defined), and if users do get into it accidentally, it's hard to
3736  * back out from it afterwards.
3737  */
3738  if (strategy == PARTITION_STRATEGY_HASH)
3739  ereport(ERROR,
3740  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3741  errmsg("a hash-partitioned table may not have a default partition")));
3742 
3743  /*
3744  * In case of the default partition, parser had no way to identify the
3745  * partition strategy. Assign the parent's strategy to the default
3746  * partition bound spec.
3747  */
3748  result_spec->strategy = strategy;
3749 
3750  return result_spec;
3751  }
3752 
3753  if (strategy == PARTITION_STRATEGY_HASH)
3754  {
3755  if (spec->strategy != PARTITION_STRATEGY_HASH)
3756  ereport(ERROR,
3757  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3758  errmsg("invalid bound specification for a hash partition"),
3759  parser_errposition(pstate, exprLocation((Node *) spec))));
3760 
3761  if (spec->modulus <= 0)
3762  ereport(ERROR,
3763  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3764  errmsg("modulus for hash partition must be a positive integer")));
3765 
3766  Assert(spec->remainder >= 0);
3767 
3768  if (spec->remainder >= spec->modulus)
3769  ereport(ERROR,
3770  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3771  errmsg("remainder for hash partition must be less than modulus")));
3772  }
3773  else if (strategy == PARTITION_STRATEGY_LIST)
3774  {
3775  ListCell *cell;
3776  char *colname;
3777  Oid coltype;
3778  int32 coltypmod;
3779  Oid partcollation;
3780 
3781  if (spec->strategy != PARTITION_STRATEGY_LIST)
3782  ereport(ERROR,
3783  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3784  errmsg("invalid bound specification for a list partition"),
3785  parser_errposition(pstate, exprLocation((Node *) spec))));
3786 
3787  /* Get the only column's name in case we need to output an error */
3788  if (key->partattrs[0] != 0)
3789  colname = get_attname(RelationGetRelid(parent),
3790  key->partattrs[0], false);
3791  else
3792  colname = deparse_expression((Node *) linitial(partexprs),
3794  RelationGetRelid(parent)),
3795  false, false);
3796  /* Need its type data too */
3797  coltype = get_partition_col_typid(key, 0);
3798  coltypmod = get_partition_col_typmod(key, 0);
3799  partcollation = get_partition_col_collation(key, 0);
3800 
3801  result_spec->listdatums = NIL;
3802  foreach(cell, spec->listdatums)
3803  {
3804  Node *expr = lfirst(cell);
3805  Const *value;
3806  ListCell *cell2;
3807  bool duplicate;
3808 
3809  value = transformPartitionBoundValue(pstate, expr,
3810  colname, coltype, coltypmod,
3811  partcollation);
3812 
3813  /* Don't add to the result if the value is a duplicate */
3814  duplicate = false;
3815  foreach(cell2, result_spec->listdatums)
3816  {
3817  Const *value2 = castNode(Const, lfirst(cell2));
3818 
3819  if (equal(value, value2))
3820  {
3821  duplicate = true;
3822  break;
3823  }
3824  }
3825  if (duplicate)
3826  continue;
3827 
3828  result_spec->listdatums = lappend(result_spec->listdatums,
3829  value);
3830  }
3831  }
3832  else if (strategy == PARTITION_STRATEGY_RANGE)
3833  {
3834  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3835  ereport(ERROR,
3836  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3837  errmsg("invalid bound specification for a range partition"),
3838  parser_errposition(pstate, exprLocation((Node *) spec))));
3839 
3840  if (list_length(spec->lowerdatums) != partnatts)
3841  ereport(ERROR,
3842  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3843  errmsg("FROM must specify exactly one value per partitioning column")));
3844  if (list_length(spec->upperdatums) != partnatts)
3845  ereport(ERROR,
3846  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3847  errmsg("TO must specify exactly one value per partitioning column")));
3848 
3849  /*
3850  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3851  * any necessary validation.
3852  */
3853  result_spec->lowerdatums =
3855  parent);
3856  result_spec->upperdatums =
3858  parent);
3859  }
3860  else
3861  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3862 
3863  return result_spec;
3864 }
#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:3011
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:90
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:84
static struct @145 value
Definition: nodes.h:525
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:63
int errcode(int sqlerrcode)
Definition: elog.c:608
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:69
#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:3256
#define RelationGetRelationName(relation)
Definition: rel.h:456
#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:3197
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
#define RelationGetPartitionKey(relation)
Definition: rel.h:603
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:96
#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:57
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:422

◆ transformPartitionBoundValue()

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

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

4031 {
4032  Node *value;
4033 
4034  /* Transform raw parsetree */
4035  value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
4036 
4037  /*
4038  * Check that the input expression's collation is compatible with one
4039  * specified for the parent's partition key (partcollation). Don't throw
4040  * an error if it's the default collation which we'll replace with the
4041  * parent's collation anyway.
4042  */
4043  if (IsA(value, CollateExpr))
4044  {
4045  Oid exprCollOid = exprCollation(value);
4046 
4047  if (OidIsValid(exprCollOid) &&
4048  exprCollOid != DEFAULT_COLLATION_OID &&
4049  exprCollOid != partCollation)
4050  ereport(ERROR,
4051  (errcode(ERRCODE_DATATYPE_MISMATCH),
4052  errmsg("collation of partition bound value for column \"%s\" does not match partition key collation \"%s\"",
4053  colName, get_collation_name(partCollation)),
4054  parser_errposition(pstate, exprLocation(value))));
4055  }
4056 
4057  /* Coerce to correct type */
4058  value = coerce_to_target_type(pstate,
4059  value, exprType(value),
4060  colType,
4061  colTypmod,
4064  -1);
4065 
4066  if (value == NULL)
4067  ereport(ERROR,
4068  (errcode(ERRCODE_DATATYPE_MISMATCH),
4069  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4070  format_type_be(colType), colName),
4071  parser_errposition(pstate, exprLocation(val))));
4072 
4073  /* Simplify the expression, in case we had a coercion */
4074  if (!IsA(value, Const))
4075  value = (Node *) expression_planner((Expr *) value);
4076 
4077  /*
4078  * transformExpr() should have already rejected column references,
4079  * subqueries, aggregates, window functions, and SRFs, based on the
4080  * EXPR_KIND_ for a default expression.
4081  */
4082  Assert(!contain_var_clause(value));
4083 
4084  /*
4085  * Evaluate the expression, assigning the partition key's collation to the
4086  * resulting Const expression.
4087  */
4088  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4089  partCollation);
4090  if (!IsA(value, Const))
4091  elog(ERROR, "could not evaluate partition bound expression");
4092 
4093  return (Const *) value;
4094 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4778
#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:6045
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
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 3673 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().

3674 {
3675  Relation parentRel = cxt->rel;
3676 
3677  switch (parentRel->rd_rel->relkind)
3678  {
3679  case RELKIND_PARTITIONED_TABLE:
3680  /* transform the partition bound, if any */
3681  Assert(RelationGetPartitionKey(parentRel) != NULL);
3682  if (cmd->bound != NULL)
3683  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3684  cmd->bound);
3685  break;
3686  case RELKIND_PARTITIONED_INDEX:
3687  /* nothing to check */
3688  Assert(cmd->bound == NULL);
3689  break;
3690  case RELKIND_RELATION:
3691  /* the table must be partitioned */
3692  ereport(ERROR,
3693  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3694  errmsg("table \"%s\" is not partitioned",
3695  RelationGetRelationName(parentRel))));
3696  break;
3697  case RELKIND_INDEX:
3698  /* the index must be partitioned */
3699  ereport(ERROR,
3700  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3701  errmsg("index \"%s\" is not partitioned",
3702  RelationGetRelationName(parentRel))));
3703  break;
3704  default:
3705  /* parser shouldn't let this case through */
3706  elog(ERROR, "\"%s\" is not a partitioned table or index",
3707  RelationGetRelationName(parentRel));
3708  break;
3709  }
3710 }
int errcode(int sqlerrcode)
Definition: elog.c:608
Form_pg_class rd_rel
Definition: rel.h:83
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:456
#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
#define RelationGetPartitionKey(relation)
Definition: rel.h:603
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 3872 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().

3874 {
3875  List *result = NIL;
3877  List *partexprs = get_partition_exprs(key);
3878  ListCell *lc;
3879  int i,
3880  j;
3881 
3882  i = j = 0;
3883  foreach(lc, blist)
3884  {
3885  Node *expr = lfirst(lc);
3886  PartitionRangeDatum *prd = NULL;
3887 
3888  /*
3889  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
3890  * as ColumnRefs.
3891  */
3892  if (IsA(expr, ColumnRef))
3893  {
3894  ColumnRef *cref = (ColumnRef *) expr;
3895  char *cname = NULL;
3896 
3897  /*
3898  * There should be a single field named either "minvalue" or
3899  * "maxvalue".
3900  */
3901  if (list_length(cref->fields) == 1 &&
3902  IsA(linitial(cref->fields), String))
3903  cname = strVal(linitial(cref->fields));
3904 
3905  if (cname == NULL)
3906  {
3907  /*
3908  * ColumnRef is not in the desired single-field-name form. For
3909  * consistency between all partition strategies, let the
3910  * expression transformation report any errors rather than
3911  * doing it ourselves.
3912  */
3913  }
3914  else if (strcmp("minvalue", cname) == 0)
3915  {
3918  prd->value = NULL;
3919  }
3920  else if (strcmp("maxvalue", cname) == 0)
3921  {
3924  prd->value = NULL;
3925  }
3926  }
3927 
3928  if (prd == NULL)
3929  {
3930  char *colname;
3931  Oid coltype;
3932  int32 coltypmod;
3933  Oid partcollation;
3934  Const *value;
3935 
3936  /* Get the column's name in case we need to output an error */
3937  if (key->partattrs[i] != 0)
3938  colname = get_attname(RelationGetRelid(parent),
3939  key->partattrs[i], false);
3940  else
3941  {
3942  colname = deparse_expression((Node *) list_nth(partexprs, j),
3944  RelationGetRelid(parent)),
3945  false, false);
3946  ++j;
3947  }
3948 
3949  /* Need its type data too */
3950  coltype = get_partition_col_typid(key, i);
3951  coltypmod = get_partition_col_typmod(key, i);
3952  partcollation = get_partition_col_collation(key, i);
3953 
3954  value = transformPartitionBoundValue(pstate, expr,
3955  colname,
3956  coltype, coltypmod,
3957  partcollation);
3958  if (value->constisnull)
3959