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

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 
struct  CreateSchemaStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

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

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))
@ CONSTR_FOREIGN
Definition: parsenodes.h:2571
@ CONSTR_UNIQUE
Definition: parsenodes.h:2569
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2570
@ CONSTR_PRIMARY
Definition: parsenodes.h:2568

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1289 of file parse_utilcmd.c.

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

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

Referenced by ProcessUtilitySlow().

◆ generateClonedExtStatsStmt()

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

Definition at line 1996 of file parse_utilcmd.c.

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

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

Referenced by transformTableLikeClause().

◆ generateClonedIndexStmt()

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

Definition at line 1647 of file parse_utilcmd.c.

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

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

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

◆ generateSerialExtraStmts()

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

Definition at line 370 of file parse_utilcmd.c.

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

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

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

◆ get_collation()

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

Definition at line 2114 of file parse_utilcmd.c.

2115 {
2116  List *result;
2117  HeapTuple ht_coll;
2118  Form_pg_collation coll_rec;
2119  char *nsp_name;
2120  char *coll_name;
2121 
2122  if (!OidIsValid(collation))
2123  return NIL; /* easy case */
2124  if (collation == get_typcollation(actual_datatype))
2125  return NIL; /* just let it default */
2126 
2127  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2128  if (!HeapTupleIsValid(ht_coll))
2129  elog(ERROR, "cache lookup failed for collation %u", collation);
2130  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
2131 
2132  /* For simplicity, we always schema-qualify the name */
2133  nsp_name = get_namespace_name(coll_rec->collnamespace);
2134  coll_name = pstrdup(NameStr(coll_rec->collname));
2135  result = list_make2(makeString(nsp_name), makeString(coll_name));
2136 
2137  ReleaseSysCache(ht_coll);
2138  return result;
2139 }
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3038
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58
@ COLLOID
Definition: syscache.h:50

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

◆ get_opclass()

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

Definition at line 2148 of file parse_utilcmd.c.

2149 {
2150  List *result = NIL;
2151  HeapTuple ht_opc;
2152  Form_pg_opclass opc_rec;
2153 
2154  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2155  if (!HeapTupleIsValid(ht_opc))
2156  elog(ERROR, "cache lookup failed for opclass %u", opclass);
2157  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2158 
2159  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2160  {
2161  /* For simplicity, we always schema-qualify the name */
2162  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2163  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2164 
2165  result = list_make2(makeString(nsp_name), makeString(opc_name));
2166  }
2167 
2168  ReleaseSysCache(ht_opc);
2169  return result;
2170 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2310
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
@ CLAOID
Definition: syscache.h:48

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

Referenced by generateClonedIndexStmt().

◆ setSchemaName()

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

Definition at line 4037 of file parse_utilcmd.c.

4038 {
4039  if (*stmt_schema_name == NULL)
4040  *stmt_schema_name = unconstify(char *, context_schema);
4041  else if (strcmp(context_schema, *stmt_schema_name) != 0)
4042  ereport(ERROR,
4043  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
4044  errmsg("CREATE specifies a schema (%s) "
4045  "different from the one being created (%s)",
4046  *stmt_schema_name, context_schema)));
4047 }
#define unconstify(underlying_type, expr)
Definition: c.h:1255

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

Referenced by transformCreateSchemaStmtElements().

◆ transformAlterTableStmt()

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

Definition at line 3394 of file parse_utilcmd.c.

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

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

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2818 of file parse_utilcmd.c.

2819 {
2820  ListCell *ckclist;
2821 
2822  if (cxt->ckconstraints == NIL)
2823  return;
2824 
2825  /*
2826  * If creating a new table (but not a foreign table), we can safely skip
2827  * validation of check constraints, and nonetheless mark them valid. (This
2828  * will override any user-supplied NOT VALID flag.)
2829  */
2830  if (skipValidation)
2831  {
2832  foreach(ckclist, cxt->ckconstraints)
2833  {
2834  Constraint *constraint = (Constraint *) lfirst(ckclist);
2835 
2836  constraint->skip_validation = true;
2837  constraint->initially_valid = true;
2838  }
2839  }
2840 }

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 534 of file parse_utilcmd.c.

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

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3877 of file parse_utilcmd.c.

3878 {
3879  /*
3880  * All we really need to do here is verify that the type is valid,
3881  * including any collation spec that might be present.
3882  */
3883  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3884 
3885  if (column->collClause)
3886  {
3887  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3888 
3889  LookupCollation(cxt->pstate,
3890  column->collClause->collname,
3891  column->collClause->location);
3892  /* Complain if COLLATE is applied to an uncollatable type */
3893  if (!OidIsValid(typtup->typcollation))
3894  ereport(ERROR,
3895  (errcode(ERRCODE_DATATYPE_MISMATCH),
3896  errmsg("collations are not supported by type %s",
3897  format_type_be(typtup->oid)),
3899  column->collClause->location)));
3900  }
3901 
3902  ReleaseSysCache(ctype);
3903 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
List * collname
Definition: parsenodes.h:382
CollateClause * collClause
Definition: parsenodes.h:735

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

Referenced by transformColumnDefinition().

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3762 of file parse_utilcmd.c.

3763 {
3764  Constraint *lastprimarycon = NULL;
3765  bool saw_deferrability = false;
3766  bool saw_initially = false;
3767  ListCell *clist;
3768 
3769 #define SUPPORTS_ATTRS(node) \
3770  ((node) != NULL && \
3771  ((node)->contype == CONSTR_PRIMARY || \
3772  (node)->contype == CONSTR_UNIQUE || \
3773  (node)->contype == CONSTR_EXCLUSION || \
3774  (node)->contype == CONSTR_FOREIGN))
3775 
3776  foreach(clist, constraintList)
3777  {
3778  Constraint *con = (Constraint *) lfirst(clist);
3779 
3780  if (!IsA(con, Constraint))
3781  elog(ERROR, "unrecognized node type: %d",
3782  (int) nodeTag(con));
3783  switch (con->contype)
3784  {
3786  if (!SUPPORTS_ATTRS(lastprimarycon))
3787  ereport(ERROR,
3788  (errcode(ERRCODE_SYNTAX_ERROR),
3789  errmsg("misplaced DEFERRABLE clause"),
3790  parser_errposition(cxt->pstate, con->location)));
3791  if (saw_deferrability)
3792  ereport(ERROR,
3793  (errcode(ERRCODE_SYNTAX_ERROR),
3794  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3795  parser_errposition(cxt->pstate, con->location)));
3796  saw_deferrability = true;
3797  lastprimarycon->deferrable = true;
3798  break;
3799 
3801  if (!SUPPORTS_ATTRS(lastprimarycon))
3802  ereport(ERROR,
3803  (errcode(ERRCODE_SYNTAX_ERROR),
3804  errmsg("misplaced NOT DEFERRABLE clause"),
3805  parser_errposition(cxt->pstate, con->location)));
3806  if (saw_deferrability)
3807  ereport(ERROR,
3808  (errcode(ERRCODE_SYNTAX_ERROR),
3809  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3810  parser_errposition(cxt->pstate, con->location)));
3811  saw_deferrability = true;
3812  lastprimarycon->deferrable = false;
3813  if (saw_initially &&
3814  lastprimarycon->initdeferred)
3815  ereport(ERROR,
3816  (errcode(ERRCODE_SYNTAX_ERROR),
3817  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3818  parser_errposition(cxt->pstate, con->location)));
3819  break;
3820 
3821  case CONSTR_ATTR_DEFERRED:
3822  if (!SUPPORTS_ATTRS(lastprimarycon))
3823  ereport(ERROR,
3824  (errcode(ERRCODE_SYNTAX_ERROR),
3825  errmsg("misplaced INITIALLY DEFERRED clause"),
3826  parser_errposition(cxt->pstate, con->location)));
3827  if (saw_initially)
3828  ereport(ERROR,
3829  (errcode(ERRCODE_SYNTAX_ERROR),
3830  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3831  parser_errposition(cxt->pstate, con->location)));
3832  saw_initially = true;
3833  lastprimarycon->initdeferred = true;
3834 
3835  /*
3836  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3837  */
3838  if (!saw_deferrability)
3839  lastprimarycon->deferrable = true;
3840  else if (!lastprimarycon->deferrable)
3841  ereport(ERROR,
3842  (errcode(ERRCODE_SYNTAX_ERROR),
3843  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3844  parser_errposition(cxt->pstate, con->location)));
3845  break;
3846 
3847  case CONSTR_ATTR_IMMEDIATE:
3848  if (!SUPPORTS_ATTRS(lastprimarycon))
3849  ereport(ERROR,
3850  (errcode(ERRCODE_SYNTAX_ERROR),
3851  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3852  parser_errposition(cxt->pstate, con->location)));
3853  if (saw_initially)
3854  ereport(ERROR,
3855  (errcode(ERRCODE_SYNTAX_ERROR),
3856  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3857  parser_errposition(cxt->pstate, con->location)));
3858  saw_initially = true;
3859  lastprimarycon->initdeferred = false;
3860  break;
3861 
3862  default:
3863  /* Otherwise it's not an attribute */
3864  lastprimarycon = con;
3865  /* reset flags for new primary node */
3866  saw_deferrability = false;
3867  saw_initially = false;
3868  break;
3869  }
3870  }
3871 }
#define SUPPORTS_ATTRS(node)

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

Referenced by transformColumnDefinition().

◆ transformCreateSchemaStmtElements()

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

Definition at line 3934 of file parse_utilcmd.c.

3935 {
3937  List *result;
3938  ListCell *elements;
3939 
3940  cxt.schemaname = schemaName;
3941  cxt.sequences = NIL;
3942  cxt.tables = NIL;
3943  cxt.views = NIL;
3944  cxt.indexes = NIL;
3945  cxt.triggers = NIL;
3946  cxt.grants = NIL;
3947 
3948  /*
3949  * Run through each schema element in the schema element list. Separate
3950  * statements by type, and do preliminary analysis.
3951  */
3952  foreach(elements, schemaElts)
3953  {
3954  Node *element = lfirst(elements);
3955 
3956  switch (nodeTag(element))
3957  {
3958  case T_CreateSeqStmt:
3959  {
3960  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3961 
3963  cxt.sequences = lappend(cxt.sequences, element);
3964  }
3965  break;
3966 
3967  case T_CreateStmt:
3968  {
3969  CreateStmt *elp = (CreateStmt *) element;
3970 
3972 
3973  /*
3974  * XXX todo: deal with constraints
3975  */
3976  cxt.tables = lappend(cxt.tables, element);
3977  }
3978  break;
3979 
3980  case T_ViewStmt:
3981  {
3982  ViewStmt *elp = (ViewStmt *) element;
3983 
3984  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3985 
3986  /*
3987  * XXX todo: deal with references between views
3988  */
3989  cxt.views = lappend(cxt.views, element);
3990  }
3991  break;
3992 
3993  case T_IndexStmt:
3994  {
3995  IndexStmt *elp = (IndexStmt *) element;
3996 
3998  cxt.indexes = lappend(cxt.indexes, element);
3999  }
4000  break;
4001 
4002  case T_CreateTrigStmt:
4003  {
4005 
4007  cxt.triggers = lappend(cxt.triggers, element);
4008  }
4009  break;
4010 
4011  case T_GrantStmt:
4012  cxt.grants = lappend(cxt.grants, element);
4013  break;
4014 
4015  default:
4016  elog(ERROR, "unrecognized node type: %d",
4017  (int) nodeTag(element));
4018  }
4019  }
4020 
4021  result = NIL;
4022  result = list_concat(result, cxt.sequences);
4023  result = list_concat(result, cxt.tables);
4024  result = list_concat(result, cxt.views);
4025  result = list_concat(result, cxt.indexes);
4026  result = list_concat(result, cxt.triggers);
4027  result = list_concat(result, cxt.grants);
4028 
4029  return result;
4030 }
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * relation
Definition: parsenodes.h:2512
RangeVar * relation
Definition: parsenodes.h:2881
RangeVar * relation
Definition: parsenodes.h:3226
RangeVar * view
Definition: parsenodes.h:3616

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

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

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

Definition at line 164 of file parse_utilcmd.c.

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

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

Referenced by ProcessUtilitySlow().

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2803 of file parse_utilcmd.c.

2804 {
2805  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2806 }

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformFKConstraints()

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

Definition at line 2847 of file parse_utilcmd.c.

2849 {
2850  ListCell *fkclist;
2851 
2852  if (cxt->fkconstraints == NIL)
2853  return;
2854 
2855  /*
2856  * If CREATE TABLE or adding a column with NULL default, we can safely
2857  * skip validation of FK constraints, and nonetheless mark them valid.
2858  * (This will override any user-supplied NOT VALID flag.)
2859  */
2860  if (skipValidation)
2861  {
2862  foreach(fkclist, cxt->fkconstraints)
2863  {
2864  Constraint *constraint = (Constraint *) lfirst(fkclist);
2865 
2866  constraint->skip_validation = true;
2867  constraint->initially_valid = true;
2868  }
2869  }
2870 
2871  /*
2872  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2873  * CONSTRAINT command to execute after the basic command is complete. (If
2874  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2875  * its own subcommand list.)
2876  *
2877  * Note: the ADD CONSTRAINT command must also execute after any index
2878  * creation commands. Thus, this should run after
2879  * transformIndexConstraints, so that the CREATE INDEX commands are
2880  * already in cxt->alist. See also the handling of cxt->likeclauses.
2881  */
2882  if (!isAddConstraint)
2883  {
2884  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2885 
2886  alterstmt->relation = cxt->relation;
2887  alterstmt->cmds = NIL;
2888  alterstmt->objtype = OBJECT_TABLE;
2889 
2890  foreach(fkclist, cxt->fkconstraints)
2891  {
2892  Constraint *constraint = (Constraint *) lfirst(fkclist);
2893  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2894 
2895  altercmd->subtype = AT_AddConstraint;
2896  altercmd->name = NULL;
2897  altercmd->def = (Node *) constraint;
2898  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2899  }
2900 
2901  cxt->alist = lappend(cxt->alist, alterstmt);
2902  }
2903 }

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexConstraint()

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

Definition at line 2281 of file parse_utilcmd.c.

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

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

Referenced by transformIndexConstraints().

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2180 of file parse_utilcmd.c.

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

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexStmt()

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

Definition at line 2918 of file parse_utilcmd.c.

2919 {
2920  ParseState *pstate;
2921  ParseNamespaceItem *nsitem;
2922  ListCell *l;
2923  Relation rel;
2924 
2925  /* Nothing to do if statement already transformed. */
2926  if (stmt->transformed)
2927  return stmt;
2928 
2929  /* Set up pstate */
2930  pstate = make_parsestate(NULL);
2931  pstate->p_sourcetext = queryString;
2932 
2933  /*
2934  * Put the parent table into the rtable so that the expressions can refer
2935  * to its fields without qualification. Caller is responsible for locking
2936  * relation, but we still need to open it.
2937  */
2938  rel = relation_open(relid, NoLock);
2939  nsitem = addRangeTableEntryForRelation(pstate, rel,
2941  NULL, false, true);
2942 
2943  /* no to join list, yes to namespaces */
2944  addNSItemToQuery(pstate, nsitem, false, true, true);
2945 
2946  /* take care of the where clause */
2947  if (stmt->whereClause)
2948  {
2949  stmt->whereClause = transformWhereClause(pstate,
2950  stmt->whereClause,
2952  "WHERE");
2953  /* we have to fix its collations too */
2954  assign_expr_collations(pstate, stmt->whereClause);
2955  }
2956 
2957  /* take care of any index expressions */
2958  foreach(l, stmt->indexParams)
2959  {
2960  IndexElem *ielem = (IndexElem *) lfirst(l);
2961 
2962  if (ielem->expr)
2963  {
2964  /* Extract preliminary index col name before transforming expr */
2965  if (ielem->indexcolname == NULL)
2966  ielem->indexcolname = FigureIndexColname(ielem->expr);
2967 
2968  /* Now do parse transformation of the expression */
2969  ielem->expr = transformExpr(pstate, ielem->expr,
2971 
2972  /* We have to fix its collations too */
2973  assign_expr_collations(pstate, ielem->expr);
2974 
2975  /*
2976  * transformExpr() should have already rejected subqueries,
2977  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2978  * for an index expression.
2979  *
2980  * DefineIndex() will make more checks.
2981  */
2982  }
2983  }
2984 
2985  /*
2986  * Check that only the base rel is mentioned. (This should be dead code
2987  * now that add_missing_from is history.)
2988  */
2989  if (list_length(pstate->p_rtable) != 1)
2990  ereport(ERROR,
2991  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2992  errmsg("index expressions and predicates can refer only to the table being indexed")));
2993 
2994  free_parsestate(pstate);
2995 
2996  /* Close relation */
2997  table_close(rel, NoLock);
2998 
2999  /* Mark statement as successfully transformed */
3000  stmt->transformed = true;
3001 
3002  return stmt;
3003 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
char * FigureIndexColname(Node *node)
List * p_rtable
Definition: parse_node.h:193

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

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

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1594 of file parse_utilcmd.c.

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

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

Referenced by transformCreateStmt().

◆ transformPartitionBound()

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

Definition at line 4110 of file parse_utilcmd.c.

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

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

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformPartitionBoundValue()

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

Definition at line 4420 of file parse_utilcmd.c.

4423 {
4424  Node *value;
4425 
4426  /* Transform raw parsetree */
4428 
4429  /*
4430  * transformExpr() should have already rejected column references,
4431  * subqueries, aggregates, window functions, and SRFs, based on the
4432  * EXPR_KIND_ of a partition bound expression.
4433  */
4435 
4436  /*
4437  * Coerce to the correct type. This might cause an explicit coercion step
4438  * to be added on top of the expression, which must be evaluated before
4439  * returning the result to the caller.
4440  */
4441  value = coerce_to_target_type(pstate,
4442  value, exprType(value),
4443  colType,
4444  colTypmod,
4447  -1);
4448 
4449  if (value == NULL)
4450  ereport(ERROR,
4451  (errcode(ERRCODE_DATATYPE_MISMATCH),
4452  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4453  format_type_be(colType), colName),
4454  parser_errposition(pstate, exprLocation(val))));
4455 
4456  /*
4457  * Evaluate the expression, if needed, assigning the partition key's data
4458  * type and collation to the resulting Const node.
4459  */
4460  if (!IsA(value, Const))
4461  {
4462  assign_expr_collations(pstate, value);
4463  value = (Node *) expression_planner((Expr *) value);
4464  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4465  partCollation);
4466  if (!IsA(value, Const))
4467  elog(ERROR, "could not evaluate partition bound expression");
4468  }
4469  else
4470  {
4471  /*
4472  * If the expression is already a Const, as is often the case, we can
4473  * skip the rather expensive steps above. But we still have to insert
4474  * the right collation, since coerce_to_target_type doesn't handle
4475  * that.
4476  */
4477  ((Const *) value)->constcollid = partCollation;
4478  }
4479 
4480  /*
4481  * Attach original expression's parse location to the Const, so that
4482  * that's what will be reported for any later errors related to this
4483  * partition bound.
4484  */
4485  ((Const *) value)->location = exprLocation(val);
4486 
4487  return (Const *) value;
4488 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4866
long val
Definition: informix.c:664
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
Expr * expression_planner(Expr *expr)
Definition: planner.c:6488
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:663
@ COERCION_ASSIGNMENT
Definition: primnodes.h:642
bool contain_var_clause(Node *node)
Definition: var.c:403

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

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 4057 of file parse_utilcmd.c.

4058 {
4059  Relation parentRel = cxt->rel;
4060 
4061  switch (parentRel->rd_rel->relkind)
4062  {
4063  case RELKIND_PARTITIONED_TABLE:
4064  /* transform the partition bound, if any */
4065  Assert(RelationGetPartitionKey(parentRel) != NULL);
4066  if (cmd->bound != NULL)
4067  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
4068  cmd->bound);
4069  break;
4070  case RELKIND_PARTITIONED_INDEX:
4071 
4072  /*
4073  * A partitioned index cannot have a partition bound set. ALTER
4074  * INDEX prevents that with its grammar, but not ALTER TABLE.
4075  */
4076  if (cmd->bound != NULL)
4077  ereport(ERROR,
4078  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4079  errmsg("\"%s\" is not a partitioned table",
4080  RelationGetRelationName(parentRel))));
4081  break;
4082  case RELKIND_RELATION:
4083  /* the table must be partitioned */
4084  ereport(ERROR,
4085  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4086  errmsg("table \"%s\" is not partitioned",
4087  RelationGetRelationName(parentRel))));
4088  break;
4089  case RELKIND_INDEX:
4090  /* the index must be partitioned */
4091  ereport(ERROR,
4092  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4093  errmsg("index \"%s\" is not partitioned",
4094  RelationGetRelationName(parentRel))));
4095  break;
4096  default:
4097  /* parser shouldn't let this case through */
4098  elog(ERROR, "\"%s\" is not a partitioned table or index",
4099  RelationGetRelationName(parentRel));
4100  break;
4101  }
4102 }
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)

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

Referenced by transformAlterTableStmt().

◆ transformPartitionRangeBounds()

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

Definition at line 4264 of file parse_utilcmd.c.

4266 {
4267  List *result = NIL;
4269  List *partexprs = get_partition_exprs(key);
4270  ListCell *lc;
4271  int i,
4272  j;
4273 
4274  i = j = 0;
4275  foreach(lc, blist)
4276  {
4277  Node *expr = lfirst(lc);
4278  PartitionRangeDatum *prd = NULL;
4279 
4280  /*
4281  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
4282  * as ColumnRefs.
4283  */
4284  if (IsA(expr, ColumnRef))
4285  {
4286  ColumnRef *cref = (ColumnRef *) expr;
4287  char *cname = NULL;
4288 
4289  /*
4290  * There should be a single field named either "minvalue" or
4291  * "maxvalue".
4292  */
4293  if (list_length(cref->fields) == 1 &&
4294  IsA(linitial(cref->fields), String))
4295  cname = strVal(linitial(cref->fields));
4296 
4297  if (cname == NULL)
4298  {
4299  /*
4300  * ColumnRef is not in the desired single-field-name form. For
4301  * consistency between all partition strategies, let the
4302  * expression transformation report any errors rather than
4303  * doing it ourselves.
4304  */
4305  }
4306  else if (strcmp("minvalue", cname) == 0)
4307  {
4310  prd->value = NULL;
4311  }
4312  else if (strcmp("maxvalue", cname) == 0)
4313  {
4316  prd->value = NULL;
4317  }
4318  }
4319 
4320  if (prd == NULL)
4321  {
4322  char *colname;
4323  Oid coltype;
4324  int32 coltypmod;
4325  Oid partcollation;
4326  Const *value;
4327 
4328  /* Get the column's name in case we need to output an error */
4329  if (key->partattrs[i] != 0)
4330  colname = get_attname(RelationGetRelid(parent),
4331  key->partattrs[i], false);
4332  else
4333  {
4334  colname = deparse_expression((Node *) list_nth(partexprs, j),
4336  RelationGetRelid(parent)),
4337  false, false);
4338  ++j;
4339  }
4340 
4341  /* Need its type data too */
4342  coltype = get_partition_col_typid(key, i);
4343  coltypmod = get_partition_col_typmod(key, i);
4344  partcollation = get_partition_col_collation(key, i);
4345 
4346  value = transformPartitionBoundValue(pstate, expr,
4347  colname,
4348  coltype, coltypmod,
4349  partcollation);
4350  if (value->constisnull)
4351  ereport(ERROR,
4352  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4353  errmsg("cannot specify NULL in range bound")));
4356  prd->value = (Node *) value;
4357  ++i;
4358  }
4359 
4360  prd->location = exprLocation(expr);
4361 
4362  result = lappend(result, prd);
4363  }
4364 
4365  /*
4366  * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
4367  * must be the same.
4368  */
4369  validateInfiniteBounds(pstate, result);
4370 
4371  return result;
4372 }
int j
Definition: isn.c:74
static void validateInfiniteBounds(ParseState *pstate, List *blist)
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition: parsenodes.h:920
@ PARTITION_RANGE_DATUM_VALUE
Definition: parsenodes.h:919
@ PARTITION_RANGE_DATUM_MINVALUE
Definition: parsenodes.h:918
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * fields
Definition: parsenodes.h:291
PartitionRangeDatumKind kind
Definition: parsenodes.h:927
Definition: value.h:64

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

Referenced by transformPartitionBound().

◆ transformRuleStmt()

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

Definition at line 3088 of file parse_utilcmd.c.

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

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, Query::cteList, elog(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, Query::rtable, RangeTblRef::rtindex, Query::setOperations, stmt, table_close(), table_openrv(), transformStmt(), and transformWhereClause().

Referenced by DefineRule().

◆ transformStatsStmt()

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

Definition at line 3013 of file parse_utilcmd.c.

3014 {
3015  ParseState *pstate;
3016  ParseNamespaceItem *nsitem;
3017  ListCell *l;
3018  Relation rel;
3019 
3020  /* Nothing to do if statement already transformed. */
3021  if (stmt->transformed)
3022  return stmt;
3023 
3024  /* Set up pstate */
3025  pstate = make_parsestate(NULL);
3026  pstate->p_sourcetext = queryString;
3027 
3028  /*
3029  * Put the parent table into the rtable so that the expressions can refer
3030