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:638
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:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1385
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:572
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
#define ARR_NDIM(a)
Definition: array.h:278
#define elog(elevel,...)
Definition: elog.h:226
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:345
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:588
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:442
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:1161
Node * whereClause
Definition: parsenodes.h:2760
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
void * stringToNode(const char *str)
Definition: read.c:89
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
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:596
bool transformed
Definition: parsenodes.h:2770
int errdetail(const char *fmt,...)
Definition: elog.c:860
char * indexcolname
Definition: parsenodes.h:701
#define RelationGetRelationName(relation)
Definition: rel.h:450
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:321
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:1124
#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:1172
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1385
bool unique
Definition: parsenodes.h:2765
List * untransformRelOptions(Datum options)
Definition: reloptions.c:960
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:572
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2756
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
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:84
#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:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
#define elog(elevel,...)
Definition: elog.h:226
int i
#define NameStr(name)
Definition: c.h:609
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:416
#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:593
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3054
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:793
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2133
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:321
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:453
#define makeNode(_type_)
Definition: nodes.h:572
const char * stmtType
Definition: parse_utilcmd.c:79
int errmsg(const char *fmt,...)
Definition: elog.c:784
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:457

◆ 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:1161
#define OidIsValid(objectId)
Definition: c.h:638
#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:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
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:226
#define NameStr(name)
Definition: c.h:609
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:1938
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#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:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:226
#define NameStr(name)
Definition: c.h:609
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 3651 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3652 {
3653  if (*stmt_schema_name == NULL)
3654  *stmt_schema_name = context_schema;
3655  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3656  ereport(ERROR,
3657  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3658  errmsg("CREATE specifies a schema (%s) "
3659  "different from the one being created (%s)",
3660  *stmt_schema_name, context_schema)));
3661 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ transformAlterTableStmt()

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

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

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

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2496 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2497 {
2498  ListCell *ckclist;
2499 
2500  if (cxt->ckconstraints == NIL)
2501  return;
2502 
2503  /*
2504  * If creating a new table (but not a foreign table), we can safely skip
2505  * validation of check constraints, and nonetheless mark them valid. (This
2506  * will override any user-supplied NOT VALID flag.)
2507  */
2508  if (skipValidation)
2509  {
2510  foreach(ckclist, cxt->ckconstraints)
2511  {
2512  Constraint *constraint = (Constraint *) lfirst(ckclist);
2513 
2514  constraint->skip_validation = true;
2515  constraint->initially_valid = true;
2516  }
2517  }
2518 }
#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:265
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:524
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:570
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:321
NameData typname
Definition: pg_type.h:42
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10712
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:583
TypeName * SystemTypeName(char *name)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
TypeName * typeName
Definition: parsenodes.h:299
#define makeNode(_type_)
Definition: nodes.h:572
#define Assert(condition)
Definition: c.h:732
int location
Definition: parsenodes.h:289
int location
Definition: parsenodes.h:216
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:647
List * arrayBounds
Definition: parsenodes.h:215
int errmsg(const char *fmt,...)
Definition: elog.c:784
RangeVar * relation
Definition: parsenodes.h:1753
char * str
Definition: value.h:48
#define elog(elevel,...)
Definition: elog.h:226
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 3493 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().

3494 {
3495  /*
3496  * All we really need to do here is verify that the type is valid,
3497  * including any collation spec that might be present.
3498  */
3499  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3500 
3501  if (column->collClause)
3502  {
3503  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3504 
3505  LookupCollation(cxt->pstate,
3506  column->collClause->collname,
3507  column->collClause->location);
3508  /* Complain if COLLATE is applied to an uncollatable type */
3509  if (!OidIsValid(typtup->typcollation))
3510  ereport(ERROR,
3511  (errcode(ERRCODE_DATATYPE_MISMATCH),
3512  errmsg("collations are not supported by type %s",
3513  format_type_be(typtup->oid)),
3515  column->collClause->location)));
3516  }
3517 
3518  ReleaseSysCache(ctype);
3519 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:265
int errcode(int sqlerrcode)
Definition: elog.c:570
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
#define OidIsValid(objectId)
Definition: c.h:638
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:1172
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:514
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
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:784

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

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

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

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

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

3547 {
3549  List *result;
3550  ListCell *elements;
3551 
3552  cxt.stmtType = "CREATE SCHEMA";
3553  cxt.schemaname = stmt->schemaname;
3554  cxt.authrole = (RoleSpec *) stmt->authrole;
3555  cxt.sequences = NIL;
3556  cxt.tables = NIL;
3557  cxt.views = NIL;
3558  cxt.indexes = NIL;
3559  cxt.triggers = NIL;
3560  cxt.grants = NIL;
3561 
3562  /*
3563  * Run through each schema element in the schema element list. Separate
3564  * statements by type, and do preliminary analysis.
3565  */
3566  foreach(elements, stmt->schemaElts)
3567  {
3568  Node *element = lfirst(elements);
3569 
3570  switch (nodeTag(element))
3571  {
3572  case T_CreateSeqStmt:
3573  {
3574  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3575 
3577  cxt.sequences = lappend(cxt.sequences, element);
3578  }
3579  break;
3580 
3581  case T_CreateStmt:
3582  {
3583  CreateStmt *elp = (CreateStmt *) element;
3584 
3586 
3587  /*
3588  * XXX todo: deal with constraints
3589  */
3590  cxt.tables = lappend(cxt.tables, element);
3591  }
3592  break;
3593 
3594  case T_ViewStmt:
3595  {
3596  ViewStmt *elp = (ViewStmt *) element;
3597 
3598  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3599 
3600  /*
3601  * XXX todo: deal with references between views
3602  */
3603  cxt.views = lappend(cxt.views, element);
3604  }
3605  break;
3606 
3607  case T_IndexStmt:
3608  {
3609  IndexStmt *elp = (IndexStmt *) element;
3610 
3612  cxt.indexes = lappend(cxt.indexes, element);
3613  }
3614  break;
3615 
3616  case T_CreateTrigStmt:
3617  {
3618  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3619 
3621  cxt.triggers = lappend(cxt.triggers, element);
3622  }
3623  break;
3624 
3625  case T_GrantStmt:
3626  cxt.grants = lappend(cxt.grants, element);
3627  break;
3628 
3629  default:
3630  elog(ERROR, "unrecognized node type: %d",
3631  (int) nodeTag(element));
3632  }
3633  }
3634 
3635  result = NIL;
3636  result = list_concat(result, cxt.sequences);
3637  result = list_concat(result, cxt.tables);
3638  result = list_concat(result, cxt.views);
3639  result = list_concat(result, cxt.indexes);
3640  result = list_concat(result, cxt.triggers);
3641  result = list_concat(result, cxt.grants);
3642 
3643  return result;
3644 }
RangeVar * relation
Definition: parsenodes.h:2049
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:524
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
RangeVar * view
Definition: parsenodes.h:3080
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:321
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:529
#define elog(elevel,...)
Definition: elog.h:226
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:575
Definition: nodes.h:524
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
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:161
#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:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
List * lappend(List *list, void *datum)
Definition: list.c:321
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:732
#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:529
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:784
#define elog(elevel,...)
Definition: elog.h:226
#define copyObject(obj)
Definition: nodes.h:640
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 2481 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2482 {
2483  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2484 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:515

◆ transformFKConstraints()

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

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

2527 {
2528  ListCell *fkclist;
2529 
2530  if (cxt->fkconstraints == NIL)
2531  return;
2532 
2533  /*
2534  * If CREATE TABLE or adding a column with NULL default, we can safely
2535  * skip validation of FK constraints, and nonetheless mark them valid.
2536  * (This will override any user-supplied NOT VALID flag.)
2537  */
2538  if (skipValidation)
2539  {
2540  foreach(fkclist, cxt->fkconstraints)
2541  {
2542  Constraint *constraint = (Constraint *) lfirst(fkclist);
2543 
2544  constraint->skip_validation = true;
2545  constraint->initially_valid = true;
2546  }
2547  }
2548 
2549  /*
2550  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2551  * CONSTRAINT command to execute after the basic command is complete. (If
2552  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2553  * its own subcommand list.)
2554  *
2555  * Note: the ADD CONSTRAINT command must also execute after any index
2556  * creation commands. Thus, this should run after
2557  * transformIndexConstraints, so that the CREATE INDEX commands are
2558  * already in cxt->alist.
2559  */
2560  if (!isAddConstraint)
2561  {
2562  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2563 
2564  alterstmt->relation = cxt->relation;
2565  alterstmt->cmds = NIL;
2566  alterstmt->relkind = OBJECT_TABLE;
2567 
2568  foreach(fkclist, cxt->fkconstraints)
2569  {
2570  Constraint *constraint = (Constraint *) lfirst(fkclist);
2571  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2572 
2573  altercmd->subtype = AT_ProcessedConstraint;
2574  altercmd->name = NULL;
2575  altercmd->def = (Node *) constraint;
2576  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2577  }
2578 
2579  cxt->alist = lappend(cxt->alist, alterstmt);
2580  }
2581 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:524
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:321
bool initially_valid
Definition: parsenodes.h:2175
#define makeNode(_type_)
Definition: nodes.h:572
#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_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 and sort options. While the
2151  * index would still work as a constraint with non-default
2152  * settings, it might not provide exactly the same uniqueness
2153  * semantics as you'd get from a normally-created constraint;
2154  * and there's also the dump/reload problem mentioned above.
2155  */
2156  defopclass = GetDefaultOpClass(attform->atttypid,
2157  index_rel->rd_rel->relam);
2158  if (indclass->values[i] != defopclass ||
2159  index_rel->rd_indoption[i] != 0)
2160  ereport(ERROR,
2161  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2162  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2163  errdetail("Cannot create a primary key or unique constraint using such an index."),
2164  parser_errposition(cxt->pstate, constraint->location)));
2165 
2166  constraint->keys = lappend(constraint->keys, makeString(attname));
2167  }
2168  else
2169  constraint->including = lappend(constraint->including, makeString(attname));
2170  }
2171 
2172  /* Close the index relation but keep the lock */
2173  relation_close(index_rel, NoLock);
2174 
2175  index->indexOid = index_oid;
2176  }
2177 
2178  /*
2179  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2180  * IndexElems and operator names. We have to break that apart into
2181  * separate lists.
2182  */
2183  if (constraint->contype == CONSTR_EXCLUSION)
2184  {
2185  foreach(lc, constraint->exclusions)
2186  {
2187  List *pair = (List *) lfirst(lc);
2188  IndexElem *elem;
2189  List *opname;
2190 
2191  Assert(list_length(pair) == 2);
2192  elem = linitial_node(IndexElem, pair);
2193  opname = lsecond_node(List, pair);
2194 
2195  index->indexParams = lappend(index->indexParams, elem);
2196  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2197  }
2198  }
2199 
2200  /*
2201  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2202  *
2203  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2204  * also make sure they are NOT NULL.
2205  */
2206  else
2207  {
2208  foreach(lc, constraint->keys)
2209  {
2210  char *key = strVal(lfirst(lc));
2211  bool found = false;
2212  bool forced_not_null = false;
2213  ColumnDef *column = NULL;
2214  ListCell *columns;
2215  IndexElem *iparam;
2216 
2217  /* Make sure referenced column exists. */
2218  foreach(columns, cxt->columns)
2219  {
2220  column = castNode(ColumnDef, lfirst(columns));
2221  if (strcmp(column->colname, key) == 0)
2222  {
2223  found = true;
2224  break;
2225  }
2226  }
2227  if (found)
2228  {
2229  /*
2230  * column is defined in the new table. For PRIMARY KEY, we
2231  * can apply the NOT NULL constraint cheaply here ... unless
2232  * the column is marked is_from_type, in which case marking it
2233  * here would be ineffective (see MergeAttributes).
2234  */
2235  if (constraint->contype == CONSTR_PRIMARY &&
2236  !column->is_from_type)
2237  {
2238  column->is_not_null = true;
2239  forced_not_null = true;
2240  }
2241  }
2242  else if (SystemAttributeByName(key) != NULL)
2243  {
2244  /*
2245  * column will be a system column in the new table, so accept
2246  * it. System columns can't ever be null, so no need to worry
2247  * about PRIMARY/NOT NULL constraint.
2248  */
2249  found = true;
2250  }
2251  else if (cxt->inhRelations)
2252  {
2253  /* try inherited tables */
2254  ListCell *inher;
2255 
2256  foreach(inher, cxt->inhRelations)
2257  {
2258  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2259  Relation rel;
2260  int count;
2261 
2262  rel = table_openrv(inh, AccessShareLock);
2263  /* check user requested inheritance from valid relkind */
2264  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2265  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2266  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2267  ereport(ERROR,
2268  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2269  errmsg("inherited relation \"%s\" is not a table or foreign table",
2270  inh->relname)));
2271  for (count = 0; count < rel->rd_att->natts; count++)
2272  {
2273  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2274  count);
2275  char *inhname = NameStr(inhattr->attname);
2276 
2277  if (inhattr->attisdropped)
2278  continue;
2279  if (strcmp(key, inhname) == 0)
2280  {
2281  found = true;
2282 
2283  /*
2284  * It's tempting to set forced_not_null if the
2285  * parent column is already NOT NULL, but that
2286  * seems unsafe because the column's NOT NULL
2287  * marking might disappear between now and
2288  * execution. Do the runtime check to be safe.
2289  */
2290  break;
2291  }
2292  }
2293  table_close(rel, NoLock);
2294  if (found)
2295  break;
2296  }
2297  }
2298 
2299  /*
2300  * In the ALTER TABLE case, don't complain about index keys not
2301  * created in the command; they may well exist already.
2302  * DefineIndex will complain about them if not.
2303  */
2304  if (!found && !cxt->isalter)
2305  ereport(ERROR,
2306  (errcode(ERRCODE_UNDEFINED_COLUMN),
2307  errmsg("column \"%s\" named in key does not exist", key),
2308  parser_errposition(cxt->pstate, constraint->location)));
2309 
2310  /* Check for PRIMARY KEY(foo, foo) */
2311  foreach(columns, index->indexParams)
2312  {
2313  iparam = (IndexElem *) lfirst(columns);
2314  if (iparam->name && strcmp(key, iparam->name) == 0)
2315  {
2316  if (index->primary)
2317  ereport(ERROR,
2318  (errcode(ERRCODE_DUPLICATE_COLUMN),
2319  errmsg("column \"%s\" appears twice in primary key constraint",
2320  key),
2321  parser_errposition(cxt->pstate, constraint->location)));
2322  else
2323  ereport(ERROR,
2324  (errcode(ERRCODE_DUPLICATE_COLUMN),
2325  errmsg("column \"%s\" appears twice in unique constraint",
2326  key),
2327  parser_errposition(cxt->pstate, constraint->location)));
2328  }
2329  }
2330 
2331  /* OK, add it to the index definition */
2332  iparam = makeNode(IndexElem);
2333  iparam->name = pstrdup(key);
2334  iparam->expr = NULL;
2335  iparam->indexcolname = NULL;
2336  iparam->collation = NIL;
2337  iparam->opclass = NIL;
2338  iparam->ordering = SORTBY_DEFAULT;
2340  index->indexParams = lappend(index->indexParams, iparam);
2341 
2342  /*
2343  * For a primary-key column, also create an item for ALTER TABLE
2344  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2345  */
2346  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2347  {
2348  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2349 
2350  notnullcmd->subtype = AT_SetNotNull;
2351  notnullcmd->name = pstrdup(key);
2352  notnullcmds = lappend(notnullcmds, notnullcmd);
2353  }
2354  }
2355  }
2356 
2357  /*
2358  * Add included columns to index definition. This is much like the
2359  * simple-column-name-list code above, except that we don't worry about
2360  * NOT NULL marking; included columns in a primary key should not be
2361  * forced NOT NULL. We don't complain about duplicate columns, either,
2362  * though maybe we should?
2363  */
2364  foreach(lc, constraint->including)
2365  {
2366  char *key = strVal(lfirst(lc));
2367  bool found = false;
2368  ColumnDef *column = NULL;
2369  ListCell *columns;
2370  IndexElem *iparam;
2371 
2372  foreach(columns, cxt->columns)
2373  {
2374  column = lfirst_node(ColumnDef, columns);
2375  if (strcmp(column->colname, key) == 0)
2376  {
2377  found = true;
2378  break;
2379  }
2380  }
2381 
2382  if (!found)
2383  {
2384  if (SystemAttributeByName(key) != NULL)
2385  {
2386  /*
2387  * column will be a system column in the new table, so accept
2388  * it.
2389  */
2390  found = true;
2391  }
2392  else if (cxt->inhRelations)
2393  {
2394  /* try inherited tables */
2395  ListCell *inher;
2396 
2397  foreach(inher, cxt->inhRelations)
2398  {
2399  RangeVar *inh = lfirst_node(RangeVar, inher);
2400  Relation rel;
2401  int count;
2402 
2403  rel = table_openrv(inh, AccessShareLock);
2404  /* check user requested inheritance from valid relkind */
2405  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2406  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2407  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2408  ereport(ERROR,
2409  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2410  errmsg("inherited relation \"%s\" is not a table or foreign table",
2411  inh->relname)));
2412  for (count = 0; count < rel->rd_att->natts; count++)
2413  {
2414  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2415  count);
2416  char *inhname = NameStr(inhattr->attname);
2417 
2418  if (inhattr->attisdropped)
2419  continue;
2420  if (strcmp(key, inhname) == 0)
2421  {
2422  found = true;
2423  break;
2424  }
2425  }
2426  table_close(rel, NoLock);
2427  if (found)
2428  break;
2429  }
2430  }
2431  }
2432 
2433  /*
2434  * In the ALTER TABLE case, don't complain about index keys not
2435  * created in the command; they may well exist already. DefineIndex
2436  * will complain about them if not.
2437  */
2438  if (!found && !cxt->isalter)
2439  ereport(ERROR,
2440  (errcode(ERRCODE_UNDEFINED_COLUMN),
2441  errmsg("column \"%s\" named in key does not exist", key),
2442  parser_errposition(cxt->pstate, constraint->location)));
2443 
2444  /* OK, add it to the index definition */
2445  iparam = makeNode(IndexElem);
2446  iparam->name = pstrdup(key);
2447  iparam->expr = NULL;
2448  iparam->indexcolname = NULL;
2449  iparam->collation = NIL;
2450  iparam->opclass = NIL;
2451  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2452  }
2453 
2454  /*
2455  * If we found anything that requires run-time SET NOT NULL, build a full
2456  * ALTER TABLE command for that and add it to cxt->alist.
2457  */
2458  if (notnullcmds)
2459  {
2460  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2461 
2462  alterstmt->relation = copyObject(cxt->relation);
2463  alterstmt->cmds = notnullcmds;
2464  alterstmt->relkind = OBJECT_TABLE;
2465  alterstmt->missing_ok = false;
2466 
2467  cxt->alist = lappend(cxt->alist, alterstmt);
2468  }
2469 
2470  return index;
2471 }
bool deferrable
Definition: parsenodes.h:2768
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:345
#define NIL
Definition: pg_list.h:65
Definition: c.h:588
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:1938
SortByDir ordering
Definition: parsenodes.h:704
List * options
Definition: parsenodes.h:2759
#define castNode(_type_, nodeptr)
Definition: nodes.h:593
char * tableSpace
Definition: parsenodes.h:2755
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1161
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:570
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:638
List * options
Definition: parsenodes.h:2153
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4644
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
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:4582
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:596
bool transformed
Definition: parsenodes.h:2770
int errdetail(const char *fmt,...)
Definition: elog.c:860
char * indexcolname
Definition: parsenodes.h:701
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:450
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:321
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:1385
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:572
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
#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:111
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:784
RangeVar * relation
Definition: parsenodes.h:1753
int i
#define NameStr(name)
Definition: c.h:609
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:640
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:416
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:457

◆ 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:2998
Node * whereClause
Definition: parsenodes.h:2760
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:570
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:321
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:732
#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:784
ConstrType contype
Definition: parsenodes.h:2129
Definition: pg_list.h:50

◆ transformIndexStmt()

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

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

2597 {
2598  ParseState *pstate;
2599  RangeTblEntry *rte;
2600  ListCell *l;
2601  Relation rel;
2602 
2603  /* Nothing to do if statement already transformed. */
2604  if (stmt->transformed)
2605  return stmt;
2606 
2607  /*
2608  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2609  * overkill, but easy.)
2610  */
2611  stmt = copyObject(stmt);
2612 
2613  /* Set up pstate */
2614  pstate = make_parsestate(NULL);
2615  pstate->p_sourcetext = queryString;
2616 
2617  /*
2618  * Put the parent table into the rtable so that the expressions can refer
2619  * to its fields without qualification. Caller is responsible for locking
2620  * relation, but we still need to open it.
2621  */
2622  rel = relation_open(relid, NoLock);
2623  rte = addRangeTableEntryForRelation(pstate, rel,
2625  NULL, false, true);
2626 
2627  /* no to join list, yes to namespaces */
2628  addRTEtoQuery(pstate, rte, false, true, true);
2629 
2630  /* take care of the where clause */
2631  if (stmt->whereClause)
2632  {
2633  stmt->whereClause = transformWhereClause(pstate,
2634  stmt->whereClause,
2636  "WHERE");
2637  /* we have to fix its collations too */
2638  assign_expr_collations(pstate, stmt->whereClause);
2639  }
2640 
2641  /* take care of any index expressions */
2642  foreach(l, stmt->indexParams)
2643  {
2644  IndexElem *ielem = (IndexElem *) lfirst(l);
2645 
2646  if (ielem->expr)
2647  {
2648  /* Extract preliminary index col name before transforming expr */
2649  if (ielem->indexcolname == NULL)
2650  ielem->indexcolname = FigureIndexColname(ielem->expr);
2651 
2652  /* Now do parse transformation of the expression */
2653  ielem->expr = transformExpr(pstate, ielem->expr,
2655 
2656  /* We have to fix its collations too */
2657  assign_expr_collations(pstate, ielem->expr);
2658 
2659  /*
2660  * transformExpr() should have already rejected subqueries,
2661  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2662  * for an index expression.
2663  *
2664  * DefineIndex() will make more checks.
2665  */
2666  }
2667  }
2668 
2669  /*
2670  * Check that only the base rel is mentioned. (This should be dead code
2671  * now that add_missing_from is history.)
2672  */
2673  if (list_length(pstate->p_rtable) != 1)
2674  ereport(ERROR,
2675  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2676  errmsg("index expressions and predicates can refer only to the table being indexed")));
2677 
2678  free_parsestate(pstate);
2679 
2680  /* Close relation */
2681  table_close(rel, NoLock);
2682 
2683  /* Mark statement as successfully transformed */
2684  stmt->transformed = true;
2685 
2686  return stmt;
2687 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Node * whereClause
Definition: parsenodes.h:2760
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
char * FigureIndexColname(Node *node)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
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:784
#define copyObject(obj)
Definition: nodes.h:640
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
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:265
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:1161
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:5516
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:734
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:321
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
bool is_from_type
Definition: parsenodes.h:651
#define makeNode(_type_)
Definition: nodes.h:572
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:393
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
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:609
char * colname
Definition: parsenodes.h:646

◆ transformPartitionBound()

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

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

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

◆ transformPartitionBoundValue()

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

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

4029 {
4030  Node *value;
4031 
4032  /* Transform raw parsetree */
4033  value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
4034 
4035  /*
4036  * Check that the input expression's collation is compatible with one
4037  * specified for the parent's partition key (partcollation). Don't throw
4038  * an error if it's the default collation which we'll replace with the
4039  * parent's collation anyway.
4040  */
4041  if (IsA(value, CollateExpr))
4042  {
4043  Oid exprCollOid = exprCollation(value);
4044 
4045  if (OidIsValid(exprCollOid) &&
4046  exprCollOid != DEFAULT_COLLATION_OID &&
4047  exprCollOid != partCollation)
4048  ereport(ERROR,
4049  (errcode(ERRCODE_DATATYPE_MISMATCH),
4050  errmsg("collation of partition bound value for column \"%s\" does not match partition key collation \"%s\"",
4051  colName, get_collation_name(partCollation)),
4052  parser_errposition(pstate, exprLocation(value))));
4053  }
4054 
4055  /* Coerce to correct type */
4056  value = coerce_to_target_type(pstate,
4057  value, exprType(value),
4058  colType,
4059  colTypmod,
4062  -1);
4063 
4064  if (value == NULL)
4065  ereport(ERROR,
4066  (errcode(ERRCODE_DATATYPE_MISMATCH),
4067  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4068  format_type_be(colType), colName),
4069  parser_errposition(pstate, exprLocation(val))));
4070 
4071  /* Simplify the expression, in case we had a coercion */
4072  if (!IsA(value, Const))
4073  value = (Node *) expression_planner((Expr *) value);
4074 
4075  /*
4076  * transformExpr() should have already rejected column references,
4077  * subqueries, aggregates, window functions, and SRFs, based on the
4078  * EXPR_KIND_ for a default expression.
4079  */
4080  Assert(!contain_var_clause(value));
4081 
4082  /*
4083  * Evaluate the expression, assigning the partition key's collation to the
4084  * resulting Const expression.
4085  */
4086  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4087  partCollation);
4088  if (!IsA(value, Const))
4089  elog(ERROR, "could not evaluate partition bound expression");
4090 
4091  return (Const *) value;
4092 }
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:575
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1192
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:923
Expr * expression_planner(Expr *expr)
Definition: planner.c:6046
static struct @144 value
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
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:638
#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:732
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
long val
Definition: informix.c:684

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

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

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

◆ transformPartitionRangeBounds()

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

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

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