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 IndexStmtgenerateClonedIndexStmt (CreateStmtContext *cxt, Relation source_idx, const AttrNumber *attmap, int attmap_length)
 
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 transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (CreateStmtContext *cxt, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void setSchemaName (char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionCmd *cmd)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))

Referenced by transformConstraintAttrs().

Function Documentation

◆ generateClonedIndexStmt()

static IndexStmt * generateClonedIndexStmt ( CreateStmtContext cxt,
Relation  source_idx,
const AttrNumber attmap,
int  attmap_length 
)
static

Definition at line 1269 of file parse_utilcmd.c.

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

Referenced by transformTableLikeClause().

1271 {
1272  Oid source_relid = RelationGetRelid(source_idx);
1273  HeapTuple ht_idxrel;
1274  HeapTuple ht_idx;
1275  HeapTuple ht_am;
1276  Form_pg_class idxrelrec;
1277  Form_pg_index idxrec;
1278  Form_pg_am amrec;
1279  oidvector *indcollation;
1280  oidvector *indclass;
1281  IndexStmt *index;
1282  List *indexprs;
1283  ListCell *indexpr_item;
1284  Oid indrelid;
1285  int keyno;
1286  Oid keycoltype;
1287  Datum datum;
1288  bool isnull;
1289 
1290  /*
1291  * Fetch pg_class tuple of source index. We can't use the copy in the
1292  * relcache entry because it doesn't include optional fields.
1293  */
1294  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1295  if (!HeapTupleIsValid(ht_idxrel))
1296  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1297  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1298 
1299  /* Fetch pg_index tuple for source index from relcache entry */
1300  ht_idx = source_idx->rd_indextuple;
1301  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1302  indrelid = idxrec->indrelid;
1303 
1304  /* Fetch the pg_am tuple of the index' access method */
1305  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1306  if (!HeapTupleIsValid(ht_am))
1307  elog(ERROR, "cache lookup failed for access method %u",
1308  idxrelrec->relam);
1309  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1310 
1311  /* Extract indcollation from the pg_index tuple */
1312  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1313  Anum_pg_index_indcollation, &isnull);
1314  Assert(!isnull);
1315  indcollation = (oidvector *) DatumGetPointer(datum);
1316 
1317  /* Extract indclass from the pg_index tuple */
1318  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1319  Anum_pg_index_indclass, &isnull);
1320  Assert(!isnull);
1321  indclass = (oidvector *) DatumGetPointer(datum);
1322 
1323  /* Begin building the IndexStmt */
1324  index = makeNode(IndexStmt);
1325  index->relation = cxt->relation;
1326  index->accessMethod = pstrdup(NameStr(amrec->amname));
1327  if (OidIsValid(idxrelrec->reltablespace))
1328  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1329  else
1330  index->tableSpace = NULL;
1331  index->excludeOpNames = NIL;
1332  index->idxcomment = NULL;
1333  index->indexOid = InvalidOid;
1334  index->oldNode = InvalidOid;
1335  index->unique = idxrec->indisunique;
1336  index->primary = idxrec->indisprimary;
1337  index->transformed = true; /* don't need transformIndexStmt */
1338  index->concurrent = false;
1339  index->if_not_exists = false;
1340 
1341  /*
1342  * We don't try to preserve the name of the source index; instead, just
1343  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1344  * the name, we'd get duplicate-relation-name failures unless the source
1345  * table was in a different schema.)
1346  */
1347  index->idxname = NULL;
1348 
1349  /*
1350  * If the index is marked PRIMARY or has an exclusion condition, it's
1351  * certainly from a constraint; else, if it's not marked UNIQUE, it
1352  * certainly isn't. If it is or might be from a constraint, we have to
1353  * fetch the pg_constraint record.
1354  */
1355  if (index->primary || index->unique || idxrec->indisexclusion)
1356  {
1357  Oid constraintId = get_index_constraint(source_relid);
1358 
1359  if (OidIsValid(constraintId))
1360  {
1361  HeapTuple ht_constr;
1362  Form_pg_constraint conrec;
1363 
1364  ht_constr = SearchSysCache1(CONSTROID,
1365  ObjectIdGetDatum(constraintId));
1366  if (!HeapTupleIsValid(ht_constr))
1367  elog(ERROR, "cache lookup failed for constraint %u",
1368  constraintId);
1369  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1370 
1371  index->isconstraint = true;
1372  index->deferrable = conrec->condeferrable;
1373  index->initdeferred = conrec->condeferred;
1374 
1375  /* If it's an exclusion constraint, we need the operator names */
1376  if (idxrec->indisexclusion)
1377  {
1378  Datum *elems;
1379  int nElems;
1380  int i;
1381 
1382  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1383  /* Extract operator OIDs from the pg_constraint tuple */
1384  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1386  &isnull);
1387  if (isnull)
1388  elog(ERROR, "null conexclop for constraint %u",
1389  constraintId);
1390 
1392  OIDOID, sizeof(Oid), true, 'i',
1393  &elems, NULL, &nElems);
1394 
1395  for (i = 0; i < nElems; i++)
1396  {
1397  Oid operid = DatumGetObjectId(elems[i]);
1398  HeapTuple opertup;
1399  Form_pg_operator operform;
1400  char *oprname;
1401  char *nspname;
1402  List *namelist;
1403 
1404  opertup = SearchSysCache1(OPEROID,
1405  ObjectIdGetDatum(operid));
1406  if (!HeapTupleIsValid(opertup))
1407  elog(ERROR, "cache lookup failed for operator %u",
1408  operid);
1409  operform = (Form_pg_operator) GETSTRUCT(opertup);
1410  oprname = pstrdup(NameStr(operform->oprname));
1411  /* For simplicity we always schema-qualify the op name */
1412  nspname = get_namespace_name(operform->oprnamespace);
1413  namelist = list_make2(makeString(nspname),
1414  makeString(oprname));
1415  index->excludeOpNames = lappend(index->excludeOpNames,
1416  namelist);
1417  ReleaseSysCache(opertup);
1418  }
1419  }
1420 
1421  ReleaseSysCache(ht_constr);
1422  }
1423  else
1424  index->isconstraint = false;
1425  }
1426  else
1427  index->isconstraint = false;
1428 
1429  /* Get the index expressions, if any */
1430  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1431  Anum_pg_index_indexprs, &isnull);
1432  if (!isnull)
1433  {
1434  char *exprsString;
1435 
1436  exprsString = TextDatumGetCString(datum);
1437  indexprs = (List *) stringToNode(exprsString);
1438  }
1439  else
1440  indexprs = NIL;
1441 
1442  /* Build the list of IndexElem */
1443  index->indexParams = NIL;
1444 
1445  indexpr_item = list_head(indexprs);
1446  for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1447  {
1448  IndexElem *iparam;
1449  AttrNumber attnum = idxrec->indkey.values[keyno];
1451  keyno);
1452  int16 opt = source_idx->rd_indoption[keyno];
1453 
1454  iparam = makeNode(IndexElem);
1455 
1456  if (AttributeNumberIsValid(attnum))
1457  {
1458  /* Simple index column */
1459  char *attname;
1460 
1461  attname = get_relid_attribute_name(indrelid, attnum);
1462  keycoltype = get_atttype(indrelid, attnum);
1463 
1464  iparam->name = attname;
1465  iparam->expr = NULL;
1466  }
1467  else
1468  {
1469  /* Expressional index */
1470  Node *indexkey;
1471  bool found_whole_row;
1472 
1473  if (indexpr_item == NULL)
1474  elog(ERROR, "too few entries in indexprs list");
1475  indexkey = (Node *) lfirst(indexpr_item);
1476  indexpr_item = lnext(indexpr_item);
1477 
1478  /* Adjust Vars to match new table's column numbering */
1479  indexkey = map_variable_attnos(indexkey,
1480  1, 0,
1481  attmap, attmap_length,
1482  InvalidOid, &found_whole_row);
1483 
1484  /* As in transformTableLikeClause, reject whole-row variables */
1485  if (found_whole_row)
1486  ereport(ERROR,
1487  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1488  errmsg("cannot convert whole-row table reference"),
1489  errdetail("Index \"%s\" contains a whole-row table reference.",
1490  RelationGetRelationName(source_idx))));
1491 
1492  iparam->name = NULL;
1493  iparam->expr = indexkey;
1494 
1495  keycoltype = exprType(indexkey);
1496  }
1497 
1498  /* Copy the original index column name */
1499  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1500 
1501  /* Add the collation name, if non-default */
1502  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1503 
1504  /* Add the operator class name, if non-default */
1505  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1506 
1507  iparam->ordering = SORTBY_DEFAULT;
1509 
1510  /* Adjust options if necessary */
1511  if (source_idx->rd_amroutine->amcanorder)
1512  {
1513  /*
1514  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1515  * set non-default settings unnecessarily, though, so as to
1516  * improve the chance of recognizing equivalence to constraint
1517  * indexes.
1518  */
1519  if (opt & INDOPTION_DESC)
1520  {
1521  iparam->ordering = SORTBY_DESC;
1522  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1524  }
1525  else
1526  {
1527  if (opt & INDOPTION_NULLS_FIRST)
1529  }
1530  }
1531 
1532  index->indexParams = lappend(index->indexParams, iparam);
1533  }
1534 
1535  /* Copy reloptions if any */
1536  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1537  Anum_pg_class_reloptions, &isnull);
1538  if (!isnull)
1539  index->options = untransformRelOptions(datum);
1540 
1541  /* If it's a partial index, decompile and append the predicate */
1542  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1543  Anum_pg_index_indpred, &isnull);
1544  if (!isnull)
1545  {
1546  char *pred_str;
1547  Node *pred_tree;
1548  bool found_whole_row;
1549 
1550  /* Convert text string to node tree */
1551  pred_str = TextDatumGetCString(datum);
1552  pred_tree = (Node *) stringToNode(pred_str);
1553 
1554  /* Adjust Vars to match new table's column numbering */
1555  pred_tree = map_variable_attnos(pred_tree,
1556  1, 0,
1557  attmap, attmap_length,
1558  InvalidOid, &found_whole_row);
1559 
1560  /* As in transformTableLikeClause, reject whole-row variables */
1561  if (found_whole_row)
1562  ereport(ERROR,
1563  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1564  errmsg("cannot convert whole-row table reference"),
1565  errdetail("Index \"%s\" contains a whole-row table reference.",
1566  RelationGetRelationName(source_idx))));
1567 
1568  index->whereClause = pred_tree;
1569  }
1570 
1571  /* Clean up */
1572  ReleaseSysCache(ht_idxrel);
1573  ReleaseSysCache(ht_am);
1574 
1575  return index;
1576 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
bool deferrable
Definition: parsenodes.h:2724
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:293
#define NIL
Definition: pg_list.h:69
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:536
bool primary
Definition: parsenodes.h:2722
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
void * stringToNode(char *str)
Definition: read.c:38
int16 * rd_indoption
Definition: rel.h:186
SortByDir ordering
Definition: parsenodes.h:693
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2715
#define RelationGetDescr(relation)
Definition: rel.h:437
#define OIDOID
Definition: pg_type.h:328
char * tableSpace
Definition: parsenodes.h:2713
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
#define Anum_pg_class_reloptions
Definition: pg_class.h:134
#define DatumGetObjectId(X)
Definition: postgres.h:506
char * pstrdup(const char *in)
Definition: mcxt.c:1063
Node * whereClause
Definition: parsenodes.h:2716
#define Anum_pg_index_indclass
Definition: pg_index.h:89
Definition: nodes.h:512
#define CONSTRAINT_EXCLUSION
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2719
Node * expr
Definition: parsenodes.h:689
RangeVar * relation
Definition: parse_utilcmd.c:77
RangeVar * relation
Definition: parsenodes.h:2711
SortByNulls nulls_ordering
Definition: parsenodes.h:694
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:544
bool transformed
Definition: parsenodes.h:2726
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:690
#define RelationGetRelationName(relation)
Definition: rel.h:445
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:684
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:878
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, Oid to_rowtype, bool *found_whole_row)
List * lappend(List *list, void *datum)
Definition: list.c:128
char * idxname
Definition: parsenodes.h:2710
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:92
bool if_not_exists
Definition: parsenodes.h:2728
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
bool unique
Definition: parsenodes.h:2721
List * untransformRelOptions(Datum options)
Definition: reloptions.c:917
char * accessMethod
Definition: parsenodes.h:2712
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:692
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:560
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
#define INDOPTION_DESC
Definition: pg_index.h:99
List * indexParams
Definition: parsenodes.h:2714
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
List * excludeOpNames
Definition: parsenodes.h:2717
bool initdeferred
Definition: parsenodes.h:2725
bool amcanorder
Definition: amapi.h:171
char * name
Definition: parsenodes.h:688
char * idxcomment
Definition: parsenodes.h:2718
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:57
#define DatumGetPointer(X)
Definition: postgres.h:555
#define Anum_pg_index_indcollation
Definition: pg_index.h:88
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3449
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
bool concurrent
Definition: parsenodes.h:2727
bool isconstraint
Definition: parsenodes.h:2723
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
int i
#define NameStr(name)
Definition: c.h:557
List * collation
Definition: parsenodes.h:691
#define elog
Definition: elog.h:219
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:425
#define Anum_pg_constraint_conexclop
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ generateSerialExtraStmts()

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

Definition at line 363 of file parse_utilcmd.c.

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

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

366 {
367  ListCell *option;
368  DefElem *nameEl = NULL;
369  Oid snamespaceid;
370  char *snamespace;
371  char *sname;
372  CreateSeqStmt *seqstmt;
373  AlterSeqStmt *altseqstmt;
374  List *attnamelist;
375 
376  /*
377  * Determine namespace and name to use for the sequence.
378  *
379  * First, check if a sequence name was passed in as an option. This is
380  * used by pg_dump. Else, generate a name.
381  *
382  * Although we use ChooseRelationName, it's not guaranteed that the
383  * selected sequence name won't conflict; given sufficiently long field
384  * names, two different serial columns in the same table could be assigned
385  * the same sequence name, and we'd not notice since we aren't creating
386  * the sequence quite yet. In practice this seems quite unlikely to be a
387  * problem, especially since few people would need two serial columns in
388  * one table.
389  */
390  foreach(option, seqoptions)
391  {
392  DefElem *defel = lfirst_node(DefElem, option);
393 
394  if (strcmp(defel->defname, "sequence_name") == 0)
395  {
396  if (nameEl)
397  ereport(ERROR,
398  (errcode(ERRCODE_SYNTAX_ERROR),
399  errmsg("conflicting or redundant options")));
400  nameEl = defel;
401  }
402  }
403 
404  if (nameEl)
405  {
407 
408  snamespace = rv->schemaname;
409  if (!snamespace)
410  {
411  /* Given unqualified SEQUENCE NAME, select namespace */
412  if (cxt->rel)
413  snamespaceid = RelationGetNamespace(cxt->rel);
414  else
415  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
416  snamespace = get_namespace_name(snamespaceid);
417  }
418  sname = rv->relname;
419  /* Remove the SEQUENCE NAME item from seqoptions */
420  seqoptions = list_delete_ptr(seqoptions, nameEl);
421  }
422  else
423  {
424  if (cxt->rel)
425  snamespaceid = RelationGetNamespace(cxt->rel);
426  else
427  {
428  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
429  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
430  }
431  snamespace = get_namespace_name(snamespaceid);
432  sname = ChooseRelationName(cxt->relation->relname,
433  column->colname,
434  "seq",
435  snamespaceid);
436  }
437 
438  ereport(DEBUG1,
439  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
440  cxt->stmtType, sname,
441  cxt->relation->relname, column->colname)));
442 
443  /*
444  * Build a CREATE SEQUENCE command to create the sequence object, and add
445  * it to the list of things to be done before this CREATE/ALTER TABLE.
446  */
447  seqstmt = makeNode(CreateSeqStmt);
448  seqstmt->for_identity = for_identity;
449  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
450  seqstmt->options = seqoptions;
451 
452  /*
453  * If a sequence data type was specified, add it to the options. Prepend
454  * to the list rather than append; in case a user supplied their own AS
455  * clause, the "redundant options" error will point to their occurrence,
456  * not our synthetic one.
457  */
458  if (seqtypid)
459  seqstmt->options = lcons(makeDefElem("as",
460  (Node *) makeTypeNameFromOid(seqtypid, -1),
461  -1),
462  seqstmt->options);
463 
464  /*
465  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
466  * the table's owner. The current user might be someone else (perhaps a
467  * superuser, or someone who's only a member of the owning role), but the
468  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
469  * exactly the same owning role.
470  */
471  if (cxt->rel)
472  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
473  else
474  seqstmt->ownerId = InvalidOid;
475 
476  cxt->blist = lappend(cxt->blist, seqstmt);
477 
478  /*
479  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
480  * owned by this column, and add it to the list of things to be done after
481  * this CREATE/ALTER TABLE.
482  */
483  altseqstmt = makeNode(AlterSeqStmt);
484  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
485  attnamelist = list_make3(makeString(snamespace),
486  makeString(cxt->relation->relname),
487  makeString(column->colname));
488  altseqstmt->options = list_make1(makeDefElem("owned_by",
489  (Node *) attnamelist, -1));
490  altseqstmt->for_identity = for_identity;
491 
492  cxt->alist = lappend(cxt->alist, altseqstmt);
493 
494  if (snamespace_p)
495  *snamespace_p = snamespace;
496  if (sname_p)
497  *sname_p = sname;
498 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:141
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3023
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:615
List * options
Definition: parsenodes.h:2492
char * schemaname
Definition: primnodes.h:67
#define list_make1(x1)
Definition: pg_list.h:139
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:77
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define ereport(elevel, rest)
Definition: elog.h:122
Node * arg
Definition: parsenodes.h:720
List * lappend(List *list, void *datum)
Definition: list.c:128
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2491
RangeVar * sequence
Definition: parsenodes.h:2481
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:560
const char * stmtType
Definition: parse_utilcmd.c:76
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool for_identity
Definition: parsenodes.h:2493
char * defname
Definition: parsenodes.h:719
char * colname
Definition: parsenodes.h:639
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1595
Definition: pg_list.h:45
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:421
List * options
Definition: parsenodes.h:2482
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ get_collation()

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

Definition at line 1585 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1586 {
1587  List *result;
1588  HeapTuple ht_coll;
1589  Form_pg_collation coll_rec;
1590  char *nsp_name;
1591  char *coll_name;
1592 
1593  if (!OidIsValid(collation))
1594  return NIL; /* easy case */
1595  if (collation == get_typcollation(actual_datatype))
1596  return NIL; /* just let it default */
1597 
1598  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1599  if (!HeapTupleIsValid(ht_coll))
1600  elog(ERROR, "cache lookup failed for collation %u", collation);
1601  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1602 
1603  /* For simplicity, we always schema-qualify the name */
1604  nsp_name = get_namespace_name(coll_rec->collnamespace);
1605  coll_name = pstrdup(NameStr(coll_rec->collname));
1606  result = list_make2(makeString(nsp_name), makeString(coll_name));
1607 
1608  ReleaseSysCache(ht_coll);
1609  return result;
1610 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
char * pstrdup(const char *in)
Definition: mcxt.c:1063
#define OidIsValid(objectId)
Definition: c.h:586
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2814
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:52
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ get_opclass()

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

Definition at line 1619 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1620 {
1621  List *result = NIL;
1622  HeapTuple ht_opc;
1623  Form_pg_opclass opc_rec;
1624 
1625  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1626  if (!HeapTupleIsValid(ht_opc))
1627  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1628  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1629 
1630  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1631  {
1632  /* For simplicity, we always schema-qualify the name */
1633  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1634  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1635 
1636  result = list_make2(makeString(nsp_name), makeString(opc_name));
1637  }
1638 
1639  ReleaseSysCache(ht_opc);
1640  return result;
1641 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1407
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
char * pstrdup(const char *in)
Definition: mcxt.c:1063
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
Definition: pg_list.h:45

◆ setSchemaName()

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

Definition at line 3268 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3269 {
3270  if (*stmt_schema_name == NULL)
3271  *stmt_schema_name = context_schema;
3272  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3273  ereport(ERROR,
3274  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3275  errmsg("CREATE specifies a schema (%s) "
3276  "different from the one being created (%s)",
3277  *stmt_schema_name, context_schema)));
3278 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ transformAlterTableStmt()

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

Definition at line 2651 of file parse_utilcmd.c.

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

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

2653 {
2654  Relation rel;
2655  ParseState *pstate;
2656  CreateStmtContext cxt;
2657  List *result;
2658  List *save_alist;
2659  ListCell *lcmd,
2660  *l;
2661  List *newcmds = NIL;
2662  bool skipValidation = true;
2663  AlterTableCmd *newcmd;
2664  RangeTblEntry *rte;
2665 
2666  /*
2667  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2668  * is overkill, but easy.)
2669  */
2670  stmt = copyObject(stmt);
2671 
2672  /* Caller is responsible for locking the relation */
2673  rel = relation_open(relid, NoLock);
2674 
2675  /* Set up pstate */
2676  pstate = make_parsestate(NULL);
2677  pstate->p_sourcetext = queryString;
2678  rte = addRangeTableEntryForRelation(pstate,
2679  rel,
2680  NULL,
2681  false,
2682  true);
2683  addRTEtoQuery(pstate, rte, false, true, true);
2684 
2685  /* Set up CreateStmtContext */
2686  cxt.pstate = pstate;
2687  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2688  {
2689  cxt.stmtType = "ALTER FOREIGN TABLE";
2690  cxt.isforeign = true;
2691  }
2692  else
2693  {
2694  cxt.stmtType = "ALTER TABLE";
2695  cxt.isforeign = false;
2696  }
2697  cxt.relation = stmt->relation;
2698  cxt.rel = rel;
2699  cxt.inhRelations = NIL;
2700  cxt.isalter = true;
2701  cxt.hasoids = false; /* need not be right */
2702  cxt.columns = NIL;
2703  cxt.ckconstraints = NIL;
2704  cxt.fkconstraints = NIL;
2705  cxt.ixconstraints = NIL;
2706  cxt.inh_indexes = NIL;
2707  cxt.blist = NIL;
2708  cxt.alist = NIL;
2709  cxt.pkey = NULL;
2710  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
2711  cxt.partbound = NULL;
2712  cxt.ofType = false;
2713 
2714  /*
2715  * The only subtypes that currently require parse transformation handling
2716  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2717  * code from CREATE TABLE.
2718  */
2719  foreach(lcmd, stmt->cmds)
2720  {
2721  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2722 
2723  switch (cmd->subtype)
2724  {
2725  case AT_AddColumn:
2726  case AT_AddColumnToView:
2727  {
2728  ColumnDef *def = castNode(ColumnDef, cmd->def);
2729 
2730  transformColumnDefinition(&cxt, def);
2731 
2732  /*
2733  * If the column has a non-null default, we can't skip
2734  * validation of foreign keys.
2735  */
2736  if (def->raw_default != NULL)
2737  skipValidation = false;
2738 
2739  /*
2740  * All constraints are processed in other ways. Remove the
2741  * original list
2742  */
2743  def->constraints = NIL;
2744 
2745  newcmds = lappend(newcmds, cmd);
2746  break;
2747  }
2748 
2749  case AT_AddConstraint:
2750 
2751  /*
2752  * The original AddConstraint cmd node doesn't go to newcmds
2753  */
2754  if (IsA(cmd->def, Constraint))
2755  {
2756  transformTableConstraint(&cxt, (Constraint *) cmd->def);
2757  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2758  skipValidation = false;
2759  }
2760  else
2761  elog(ERROR, "unrecognized node type: %d",
2762  (int) nodeTag(cmd->def));
2763  break;
2764 
2766 
2767  /*
2768  * Already-transformed ADD CONSTRAINT, so just make it look
2769  * like the standard case.
2770  */
2771  cmd->subtype = AT_AddConstraint;
2772  newcmds = lappend(newcmds, cmd);
2773  break;
2774 
2775  case AT_AlterColumnType:
2776  {
2777  ColumnDef *def = (ColumnDef *) cmd->def;
2778  AttrNumber attnum;
2779 
2780  /*
2781  * For ALTER COLUMN TYPE, transform the USING clause if
2782  * one was specified.
2783  */
2784  if (def->raw_default)
2785  {
2786  def->cooked_default =
2787  transformExpr(pstate, def->raw_default,
2789  }
2790 
2791  /*
2792  * For identity column, create ALTER SEQUENCE command to
2793  * change the data type of the sequence.
2794  */
2795  attnum = get_attnum(relid, cmd->name);
2796 
2797  /*
2798  * if attribute not found, something will error about it
2799  * later
2800  */
2801  if (attnum != InvalidAttrNumber && get_attidentity(relid, attnum))
2802  {
2803  Oid seq_relid = getOwnedSequence(relid, attnum);
2804  Oid typeOid = typenameTypeId(pstate, def->typeName);
2805  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
2806 
2807  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
2808  get_rel_name(seq_relid),
2809  -1);
2810  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
2811  altseqstmt->for_identity = true;
2812  cxt.blist = lappend(cxt.blist, altseqstmt);
2813  }
2814 
2815  newcmds = lappend(newcmds, cmd);
2816  break;
2817  }
2818 
2819  case AT_AddIdentity:
2820  {
2821  Constraint *def = castNode(Constraint, cmd->def);
2822  ColumnDef *newdef = makeNode(ColumnDef);
2823  AttrNumber attnum;
2824 
2825  newdef->colname = cmd->name;
2826  newdef->identity = def->generated_when;
2827  cmd->def = (Node *) newdef;
2828 
2829  attnum = get_attnum(relid, cmd->name);
2830 
2831  /*
2832  * if attribute not found, something will error about it
2833  * later
2834  */
2835  if (attnum != InvalidAttrNumber)
2836  generateSerialExtraStmts(&cxt, newdef,
2837  get_atttype(relid, attnum),
2838  def->options, true,
2839  NULL, NULL);
2840 
2841  newcmds = lappend(newcmds, cmd);
2842  break;
2843  }
2844 
2845  case AT_SetIdentity:
2846  {
2847  /*
2848  * Create an ALTER SEQUENCE statement for the internal
2849  * sequence of the identity column.
2850  */
2851  ListCell *lc;
2852  List *newseqopts = NIL;
2853  List *newdef = NIL;
2854  List *seqlist;
2855  AttrNumber attnum;
2856 
2857  /*
2858  * Split options into those handled by ALTER SEQUENCE and
2859  * those for ALTER TABLE proper.
2860  */
2861  foreach(lc, castNode(List, cmd->def))
2862  {
2863  DefElem *def = lfirst_node(DefElem, lc);
2864 
2865  if (strcmp(def->defname, "generated") == 0)
2866  newdef = lappend(newdef, def);
2867  else
2868  newseqopts = lappend(newseqopts, def);
2869  }
2870 
2871  attnum = get_attnum(relid, cmd->name);
2872 
2873  if (attnum)
2874  {
2875  seqlist = getOwnedSequences(relid, attnum);
2876  if (seqlist)
2877  {
2878  AlterSeqStmt *seqstmt;
2879  Oid seq_relid;
2880 
2881  seqstmt = makeNode(AlterSeqStmt);
2882  seq_relid = linitial_oid(seqlist);
2884  get_rel_name(seq_relid), -1);
2885  seqstmt->options = newseqopts;
2886  seqstmt->for_identity = true;
2887  seqstmt->missing_ok = false;
2888 
2889  cxt.alist = lappend(cxt.alist, seqstmt);
2890  }
2891  }
2892 
2893  /*
2894  * If column was not found or was not an identity column,
2895  * we just let the ALTER TABLE command error out later.
2896  */
2897 
2898  cmd->def = (Node *) newdef;
2899  newcmds = lappend(newcmds, cmd);
2900  break;
2901  }
2902 
2903  case AT_AttachPartition:
2904  case AT_DetachPartition:
2905  {
2906  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
2907 
2908  transformPartitionCmd(&cxt, partcmd);
2909  /* assign transformed value of the partition bound */
2910  partcmd->bound = cxt.partbound;
2911  }
2912 
2913  newcmds = lappend(newcmds, cmd);
2914  break;
2915 
2916  default:
2917  newcmds = lappend(newcmds, cmd);
2918  break;
2919  }
2920  }
2921 
2922  /*
2923  * transformIndexConstraints wants cxt.alist to contain only index
2924  * statements, so transfer anything we already have into save_alist
2925  * immediately.
2926  */
2927  save_alist = cxt.alist;
2928  cxt.alist = NIL;
2929 
2930  /* Postprocess constraints */
2932  transformFKConstraints(&cxt, skipValidation, true);
2933  transformCheckConstraints(&cxt, false);
2934 
2935  /*
2936  * Push any index-creation commands into the ALTER, so that they can be
2937  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2938  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2939  * subcommand has already been through transformIndexStmt.
2940  */
2941  foreach(l, cxt.alist)
2942  {
2943  IndexStmt *idxstmt = lfirst_node(IndexStmt, l);
2944 
2945  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2946  newcmd = makeNode(AlterTableCmd);
2948  newcmd->def = (Node *) idxstmt;
2949  newcmds = lappend(newcmds, newcmd);
2950  }
2951  cxt.alist = NIL;
2952 
2953  /* Append any CHECK or FK constraints to the commands list */
2954  foreach(l, cxt.ckconstraints)
2955  {
2956  newcmd = makeNode(AlterTableCmd);
2957  newcmd->subtype = AT_AddConstraint;
2958  newcmd->def = (Node *) lfirst(l);
2959  newcmds = lappend(newcmds, newcmd);
2960  }
2961  foreach(l, cxt.fkconstraints)
2962  {
2963  newcmd = makeNode(AlterTableCmd);
2964  newcmd->subtype = AT_AddConstraint;
2965  newcmd->def = (Node *) lfirst(l);
2966  newcmds = lappend(newcmds, newcmd);
2967  }
2968 
2969  /* Close rel */
2970  relation_close(rel, NoLock);
2971 
2972  /*
2973  * Output results.
2974  */
2975  stmt->cmds = newcmds;
2976 
2977  result = lappend(cxt.blist, stmt);
2978  result = list_concat(result, cxt.alist);
2979  result = list_concat(result, save_alist);
2980 
2981  return result;
2982 }
#define NIL
Definition: pg_list.h:69
Oid getOwnedSequence(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:605
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
char get_attidentity(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:851
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
char generated_when
Definition: parsenodes.h:2104
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
char identity
Definition: parsenodes.h:649
List * constraints
Definition: parsenodes.h:652
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1769
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:512
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
AlterTableType subtype
Definition: parsenodes.h:1787
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2492
List * options
Definition: parsenodes.h:2113
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
ParseState * pstate
Definition: parse_utilcmd.c:75
Node * cooked_default
Definition: parsenodes.h:648
Oid indexOid
Definition: parsenodes.h:2719
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:821
const char * p_sourcetext
Definition: parse_node.h:172
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:878
ObjectType relkind
Definition: parsenodes.h:1701
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
List * getOwnedSequences(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:548
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
RangeVar * sequence
Definition: parsenodes.h:2491
#define makeNode(_type_)
Definition: nodes.h:560
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:848
#define linitial_oid(l)
Definition: pg_list.h:113
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
TypeName * typeName
Definition: parsenodes.h:640
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:517
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parsenodes.h:1699
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
bool for_identity
Definition: parsenodes.h:2493
char * defname
Definition: parsenodes.h:719
char * colname
Definition: parsenodes.h:639
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2141 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2142 {
2143  ListCell *ckclist;
2144 
2145  if (cxt->ckconstraints == NIL)
2146  return;
2147 
2148  /*
2149  * If creating a new table (but not a foreign table), we can safely skip
2150  * validation of check constraints, and nonetheless mark them valid. (This
2151  * will override any user-supplied NOT VALID flag.)
2152  */
2153  if (skipValidation)
2154  {
2155  foreach(ckclist, cxt->ckconstraints)
2156  {
2157  Constraint *constraint = (Constraint *) lfirst(ckclist);
2158 
2159  constraint->skip_validation = true;
2160  constraint->initially_valid = true;
2161  }
2162  }
2163 }
#define NIL
Definition: pg_list.h:69
bool initially_valid
Definition: parsenodes.h:2133
#define lfirst(lc)
Definition: pg_list.h:106
bool skip_validation
Definition: parsenodes.h:2132

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 506 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, Constraint::generated_when, generateSerialExtraStmts(), HeapTupleGetOid, ColumnDef::identity, INT2OID, INT4OID, INT8OID, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, AlterTableStmt::relation, ReleaseSysCache(), AlterTableStmt::relkind, RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

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

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3110 of file parse_utilcmd.c.

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

Referenced by transformColumnDefinition().

3111 {
3112  /*
3113  * All we really need to do here is verify that the type is valid,
3114  * including any collation spec that might be present.
3115  */
3116  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3117 
3118  if (column->collClause)
3119  {
3120  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3121 
3122  LookupCollation(cxt->pstate,
3123  column->collClause->collname,
3124  column->collClause->location);
3125  /* Complain if COLLATE is applied to an uncollatable type */
3126  if (!OidIsValid(typtup->typcollation))
3127  ereport(ERROR,
3128  (errcode(ERRCODE_DATATYPE_MISMATCH),
3129  errmsg("collations are not supported by type %s",
3132  column->collClause->location)));
3133  }
3134 
3135  ReleaseSysCache(ctype);
3136 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
#define OidIsValid(objectId)
Definition: c.h:586
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:640
CollateClause * collClause
Definition: parsenodes.h:650
List * collname
Definition: parsenodes.h:309
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 2995 of file parse_utilcmd.c.

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

Referenced by transformColumnDefinition().

2996 {
2997  Constraint *lastprimarycon = NULL;
2998  bool saw_deferrability = false;
2999  bool saw_initially = false;
3000  ListCell *clist;
3001 
3002 #define SUPPORTS_ATTRS(node) \
3003  ((node) != NULL && \
3004  ((node)->contype == CONSTR_PRIMARY || \
3005  (node)->contype == CONSTR_UNIQUE || \
3006  (node)->contype == CONSTR_EXCLUSION || \
3007  (node)->contype == CONSTR_FOREIGN))
3008 
3009  foreach(clist, constraintList)
3010  {
3011  Constraint *con = (Constraint *) lfirst(clist);
3012 
3013  if (!IsA(con, Constraint))
3014  elog(ERROR, "unrecognized node type: %d",
3015  (int) nodeTag(con));
3016  switch (con->contype)
3017  {
3019  if (!SUPPORTS_ATTRS(lastprimarycon))
3020  ereport(ERROR,
3021  (errcode(ERRCODE_SYNTAX_ERROR),
3022  errmsg("misplaced DEFERRABLE clause"),
3023  parser_errposition(cxt->pstate, con->location)));
3024  if (saw_deferrability)
3025  ereport(ERROR,
3026  (errcode(ERRCODE_SYNTAX_ERROR),
3027  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3028  parser_errposition(cxt->pstate, con->location)));
3029  saw_deferrability = true;
3030  lastprimarycon->deferrable = true;
3031  break;
3032 
3034  if (!SUPPORTS_ATTRS(lastprimarycon))
3035  ereport(ERROR,
3036  (errcode(ERRCODE_SYNTAX_ERROR),
3037  errmsg("misplaced NOT DEFERRABLE clause"),
3038  parser_errposition(cxt->pstate, con->location)));
3039  if (saw_deferrability)
3040  ereport(ERROR,
3041  (errcode(ERRCODE_SYNTAX_ERROR),
3042  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3043  parser_errposition(cxt->pstate, con->location)));
3044  saw_deferrability = true;
3045  lastprimarycon->deferrable = false;
3046  if (saw_initially &&
3047  lastprimarycon->initdeferred)
3048  ereport(ERROR,
3049  (errcode(ERRCODE_SYNTAX_ERROR),
3050  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3051  parser_errposition(cxt->pstate, con->location)));
3052  break;
3053 
3054  case CONSTR_ATTR_DEFERRED:
3055  if (!SUPPORTS_ATTRS(lastprimarycon))
3056  ereport(ERROR,
3057  (errcode(ERRCODE_SYNTAX_ERROR),
3058  errmsg("misplaced INITIALLY DEFERRED clause"),
3059  parser_errposition(cxt->pstate, con->location)));
3060  if (saw_initially)
3061  ereport(ERROR,
3062  (errcode(ERRCODE_SYNTAX_ERROR),
3063  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3064  parser_errposition(cxt->pstate, con->location)));
3065  saw_initially = true;
3066  lastprimarycon->initdeferred = true;
3067 
3068  /*
3069  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3070  */
3071  if (!saw_deferrability)
3072  lastprimarycon->deferrable = true;
3073  else if (!lastprimarycon->deferrable)
3074  ereport(ERROR,
3075  (errcode(ERRCODE_SYNTAX_ERROR),
3076  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3077  parser_errposition(cxt->pstate, con->location)));
3078  break;
3079 
3080  case CONSTR_ATTR_IMMEDIATE:
3081  if (!SUPPORTS_ATTRS(lastprimarycon))
3082  ereport(ERROR,
3083  (errcode(ERRCODE_SYNTAX_ERROR),
3084  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3085  parser_errposition(cxt->pstate, con->location)));
3086  if (saw_initially)
3087  ereport(ERROR,
3088  (errcode(ERRCODE_SYNTAX_ERROR),
3089  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3090  parser_errposition(cxt->pstate, con->location)));
3091  saw_initially = true;
3092  lastprimarycon->initdeferred = false;
3093  break;
3094 
3095  default:
3096  /* Otherwise it's not an attribute */
3097  lastprimarycon = con;
3098  /* reset flags for new primary node */
3099  saw_deferrability = false;
3100  saw_initially = false;
3101  break;
3102  }
3103  }
3104 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:2097
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2096
#define ereport(elevel, rest)
Definition: elog.h:122
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define nodeTag(nodeptr)
Definition: nodes.h:517
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SUPPORTS_ATTRS(node)
ConstrType contype
Definition: parsenodes.h:2092
#define elog
Definition: elog.h:219

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3163 of file parse_utilcmd.c.

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

Referenced by CreateSchemaCommand().

3164 {
3166  List *result;
3167  ListCell *elements;
3168 
3169  cxt.stmtType = "CREATE SCHEMA";
3170  cxt.schemaname = stmt->schemaname;
3171  cxt.authrole = (RoleSpec *) stmt->authrole;
3172  cxt.sequences = NIL;
3173  cxt.tables = NIL;
3174  cxt.views = NIL;
3175  cxt.indexes = NIL;
3176  cxt.triggers = NIL;
3177  cxt.grants = NIL;
3178 
3179  /*
3180  * Run through each schema element in the schema element list. Separate
3181  * statements by type, and do preliminary analysis.
3182  */
3183  foreach(elements, stmt->schemaElts)
3184  {
3185  Node *element = lfirst(elements);
3186 
3187  switch (nodeTag(element))
3188  {
3189  case T_CreateSeqStmt:
3190  {
3191  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3192 
3194  cxt.sequences = lappend(cxt.sequences, element);
3195  }
3196  break;
3197 
3198  case T_CreateStmt:
3199  {
3200  CreateStmt *elp = (CreateStmt *) element;
3201 
3203 
3204  /*
3205  * XXX todo: deal with constraints
3206  */
3207  cxt.tables = lappend(cxt.tables, element);
3208  }
3209  break;
3210 
3211  case T_ViewStmt:
3212  {
3213  ViewStmt *elp = (ViewStmt *) element;
3214 
3215  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3216 
3217  /*
3218  * XXX todo: deal with references between views
3219  */
3220  cxt.views = lappend(cxt.views, element);
3221  }
3222  break;
3223 
3224  case T_IndexStmt:
3225  {
3226  IndexStmt *elp = (IndexStmt *) element;
3227 
3229  cxt.indexes = lappend(cxt.indexes, element);
3230  }
3231  break;
3232 
3233  case T_CreateTrigStmt:
3234  {
3235  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3236 
3238  cxt.triggers = lappend(cxt.triggers, element);
3239  }
3240  break;
3241 
3242  case T_GrantStmt:
3243  cxt.grants = lappend(cxt.grants, element);
3244  break;
3245 
3246  default:
3247  elog(ERROR, "unrecognized node type: %d",
3248  (int) nodeTag(element));
3249  }
3250  }
3251 
3252  result = NIL;
3253  result = list_concat(result, cxt.sequences);
3254  result = list_concat(result, cxt.tables);
3255  result = list_concat(result, cxt.views);
3256  result = list_concat(result, cxt.indexes);
3257  result = list_concat(result, cxt.triggers);
3258  result = list_concat(result, cxt.grants);
3259 
3260  return result;
3261 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:512
List * list_concat(List *list1, List *list2)
Definition: list.c:321
RangeVar * view
Definition: parsenodes.h:3024
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2711
RoleSpec * authrole
Definition: parsenodes.h:1681
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2481
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:517
RangeVar * relation
Definition: parsenodes.h:2366
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ transformCreateStmt()

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

Definition at line 159 of file parse_utilcmd.c.

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

Referenced by ProcessUtilitySlow().

160 {
161  ParseState *pstate;
162  CreateStmtContext cxt;
163  List *result;
164  List *save_alist;
165  ListCell *elements;
166  Oid namespaceid;
167  Oid existing_relid;
168  ParseCallbackState pcbstate;
169  bool like_found = false;
170  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
171 
172  /*
173  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
174  * overkill, but easy.)
175  */
176  stmt = copyObject(stmt);
177 
178  /* Set up pstate */
179  pstate = make_parsestate(NULL);
180  pstate->p_sourcetext = queryString;
181 
182  /*
183  * Look up the creation namespace. This also checks permissions on the
184  * target namespace, locks it against concurrent drops, checks for a
185  * preexisting relation in that namespace with the same name, and updates
186  * stmt->relation->relpersistence if the selected namespace is temporary.
187  */
188  setup_parser_errposition_callback(&pcbstate, pstate,
189  stmt->relation->location);
190  namespaceid =
192  &existing_relid);
194 
195  /*
196  * If the relation already exists and the user specified "IF NOT EXISTS",
197  * bail out with a NOTICE.
198  */
199  if (stmt->if_not_exists && OidIsValid(existing_relid))
200  {
201  ereport(NOTICE,
202  (errcode(ERRCODE_DUPLICATE_TABLE),
203  errmsg("relation \"%s\" already exists, skipping",
204  stmt->relation->relname)));
205  return NIL;
206  }
207 
208  /*
209  * If the target relation name isn't schema-qualified, make it so. This
210  * prevents some corner cases in which added-on rewritten commands might
211  * think they should apply to other relations that have the same name and
212  * are earlier in the search path. But a local temp table is effectively
213  * specified to be in pg_temp, so no need for anything extra in that case.
214  */
215  if (stmt->relation->schemaname == NULL
217  stmt->relation->schemaname = get_namespace_name(namespaceid);
218 
219  /* Set up CreateStmtContext */
220  cxt.pstate = pstate;
221  if (IsA(stmt, CreateForeignTableStmt))
222  {
223  cxt.stmtType = "CREATE FOREIGN TABLE";
224  cxt.isforeign = true;
225  }
226  else
227  {
228  cxt.stmtType = "CREATE TABLE";
229  cxt.isforeign = false;
230  }
231  cxt.relation = stmt->relation;
232  cxt.rel = NULL;
233  cxt.inhRelations = stmt->inhRelations;
234  cxt.isalter = false;
235  cxt.columns = NIL;
236  cxt.ckconstraints = NIL;
237  cxt.fkconstraints = NIL;
238  cxt.ixconstraints = NIL;
239  cxt.inh_indexes = NIL;
240  cxt.blist = NIL;
241  cxt.alist = NIL;
242  cxt.pkey = NULL;
243  cxt.ispartitioned = stmt->partspec != NULL;
244  cxt.partbound = stmt->partbound;
245  cxt.ofType = (stmt->ofTypename != NULL);
246 
247  /*
248  * Notice that we allow OIDs here only for plain tables, even though
249  * foreign tables also support them. This is necessary because the
250  * default_with_oids GUC must apply only to plain tables and not any other
251  * relkind; doing otherwise would break existing pg_dump files. We could
252  * allow explicit "WITH OIDS" while not allowing default_with_oids to
253  * affect other relkinds, but it would complicate interpretOidsOption(),
254  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
255  * anyway.
256  */
257  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
258 
259  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
260 
261  if (stmt->ofTypename)
262  transformOfType(&cxt, stmt->ofTypename);
263 
264  if (stmt->partspec)
265  {
266  if (stmt->inhRelations && !stmt->partbound)
267  ereport(ERROR,
268  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
269  errmsg("cannot create partitioned table as inheritance child")));
270  }
271 
272  /*
273  * Run through each primary element in the table creation clause. Separate
274  * column defs from constraints, and do preliminary analysis.
275  */
276  foreach(elements, stmt->tableElts)
277  {
278  Node *element = lfirst(elements);
279 
280  switch (nodeTag(element))
281  {
282  case T_ColumnDef:
283  transformColumnDefinition(&cxt, (ColumnDef *) element);
284  break;
285 
286  case T_Constraint:
287  transformTableConstraint(&cxt, (Constraint *) element);
288  break;
289 
290  case T_TableLikeClause:
291  like_found = true;
292  transformTableLikeClause(&cxt, (TableLikeClause *) element);
293  break;
294 
295  default:
296  elog(ERROR, "unrecognized node type: %d",
297  (int) nodeTag(element));
298  break;
299  }
300  }
301 
302  /*
303  * If we had any LIKE tables, they may require creation of an OID column
304  * even though the command's own WITH clause didn't ask for one (or,
305  * perhaps, even specifically rejected having one). Insert a WITH option
306  * to ensure that happens. We prepend to the list because the first oid
307  * option will be honored, and we want to override anything already there.
308  * (But note that DefineRelation will override this again to add an OID
309  * column if one appears in an inheritance parent table.)
310  */
311  if (like_found && cxt.hasoids)
312  stmt->options = lcons(makeDefElem("oids",
313  (Node *) makeInteger(true), -1),
314  stmt->options);
315 
316  /*
317  * transformIndexConstraints wants cxt.alist to contain only index
318  * statements, so transfer anything we already have into save_alist.
319  */
320  save_alist = cxt.alist;
321  cxt.alist = NIL;
322 
323  Assert(stmt->constraints == NIL);
324 
325  /*
326  * Postprocess constraints that give rise to index definitions.
327  */
329 
330  /*
331  * Postprocess foreign-key constraints.
332  */
333  transformFKConstraints(&cxt, true, false);
334 
335  /*
336  * Postprocess check constraints.
337  */
338  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
339 
340  /*
341  * Output results.
342  */
343  stmt->tableElts = cxt.columns;
344  stmt->constraints = cxt.ckconstraints;
345 
346  result = lappend(cxt.blist, stmt);
347  result = list_concat(result, cxt.alist);
348  result = list_concat(result, save_alist);
349 
350  return result;
351 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
List * inhRelations
Definition: parsenodes.h:2016
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2021
bool if_not_exists
Definition: parsenodes.h:2025
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parsenodes.h:2018
char * relname
Definition: primnodes.h:68
Value * makeInteger(long i)
Definition: value.c:23
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
List * options
Definition: parsenodes.h:2022
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2015
List * lcons(void *datum, List *list)
Definition: list.c:259
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:517
const char * stmtType
Definition: parse_utilcmd.c:76
char relpersistence
Definition: primnodes.h:71
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2019
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2020
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformFKConstraints()

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

Definition at line 2170 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2172 {
2173  ListCell *fkclist;
2174 
2175  if (cxt->fkconstraints == NIL)
2176  return;
2177 
2178  /*
2179  * If CREATE TABLE or adding a column with NULL default, we can safely
2180  * skip validation of FK constraints, and nonetheless mark them valid.
2181  * (This will override any user-supplied NOT VALID flag.)
2182  */
2183  if (skipValidation)
2184  {
2185  foreach(fkclist, cxt->fkconstraints)
2186  {
2187  Constraint *constraint = (Constraint *) lfirst(fkclist);
2188 
2189  constraint->skip_validation = true;
2190  constraint->initially_valid = true;
2191  }
2192  }
2193 
2194  /*
2195  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2196  * CONSTRAINT command to execute after the basic command is complete. (If
2197  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2198  * its own subcommand list.)
2199  *
2200  * Note: the ADD CONSTRAINT command must also execute after any index
2201  * creation commands. Thus, this should run after
2202  * transformIndexConstraints, so that the CREATE INDEX commands are
2203  * already in cxt->alist.
2204  */
2205  if (!isAddConstraint)
2206  {
2207  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2208 
2209  alterstmt->relation = cxt->relation;
2210  alterstmt->cmds = NIL;
2211  alterstmt->relkind = OBJECT_TABLE;
2212 
2213  foreach(fkclist, cxt->fkconstraints)
2214  {
2215  Constraint *constraint = (Constraint *) lfirst(fkclist);
2216  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2217 
2218  altercmd->subtype = AT_ProcessedConstraint;
2219  altercmd->name = NULL;
2220  altercmd->def = (Node *) constraint;
2221  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2222  }
2223 
2224  cxt->alist = lappend(cxt->alist, alterstmt);
2225  }
2226 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:512
AlterTableType subtype
Definition: parsenodes.h:1787
RangeVar * relation
Definition: parse_utilcmd.c:77
ObjectType relkind
Definition: parsenodes.h:1701
List * lappend(List *list, void *datum)
Definition: list.c:128
bool initially_valid
Definition: parsenodes.h:2133
#define makeNode(_type_)
Definition: nodes.h:560
#define lfirst(lc)
Definition: pg_list.h:106
RangeVar * relation
Definition: parsenodes.h:1699
bool skip_validation
Definition: parsenodes.h:2132

◆ transformIndexConstraint()

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

Definition at line 1758 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, Anum_pg_index_indclass, Assert, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), CreateStmtContext::hasoids, heap_close, heap_openrv(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, index_open(), IndexElem::indexcolname, IndexIsValid, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), IndexElem::name, NameStr, tupleDesc::natts, NIL, NoLock, IndexElem::nulls_ordering, OidIsValid, IndexStmt::oldNode, IndexElem::opclass, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RELKIND_FOREIGN_TABLE, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RangeVar::relname, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

1759 {
1760  IndexStmt *index;
1761  ListCell *lc;
1762 
1763  index = makeNode(IndexStmt);
1764 
1765  index->unique = (constraint->contype != CONSTR_EXCLUSION);
1766  index->primary = (constraint->contype == CONSTR_PRIMARY);
1767  if (index->primary)
1768  {
1769  if (cxt->pkey != NULL)
1770  ereport(ERROR,
1771  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1772  errmsg("multiple primary keys for table \"%s\" are not allowed",
1773  cxt->relation->relname),
1774  parser_errposition(cxt->pstate, constraint->location)));
1775  cxt->pkey = index;
1776 
1777  /*
1778  * In ALTER TABLE case, a primary index might already exist, but
1779  * DefineIndex will check for it.
1780  */
1781  }
1782  index->isconstraint = true;
1783  index->deferrable = constraint->deferrable;
1784  index->initdeferred = constraint->initdeferred;
1785 
1786  if (constraint->conname != NULL)
1787  index->idxname = pstrdup(constraint->conname);
1788  else
1789  index->idxname = NULL; /* DefineIndex will choose name */
1790 
1791  index->relation = cxt->relation;
1792  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1793  index->options = constraint->options;
1794  index->tableSpace = constraint->indexspace;
1795  index->whereClause = constraint->where_clause;
1796  index->indexParams = NIL;
1797  index->excludeOpNames = NIL;
1798  index->idxcomment = NULL;
1799  index->indexOid = InvalidOid;
1800  index->oldNode = InvalidOid;
1801  index->transformed = false;
1802  index->concurrent = false;
1803  index->if_not_exists = false;
1804 
1805  /*
1806  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1807  * verify it's usable, then extract the implied column name list. (We
1808  * will not actually need the column name list at runtime, but we need it
1809  * now to check for duplicate column entries below.)
1810  */
1811  if (constraint->indexname != NULL)
1812  {
1813  char *index_name = constraint->indexname;
1814  Relation heap_rel = cxt->rel;
1815  Oid index_oid;
1816  Relation index_rel;
1817  Form_pg_index index_form;
1818  oidvector *indclass;
1819  Datum indclassDatum;
1820  bool isnull;
1821  int i;
1822 
1823  /* Grammar should not allow this with explicit column list */
1824  Assert(constraint->keys == NIL);
1825 
1826  /* Grammar should only allow PRIMARY and UNIQUE constraints */
1827  Assert(constraint->contype == CONSTR_PRIMARY ||
1828  constraint->contype == CONSTR_UNIQUE);
1829 
1830  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1831  if (!cxt->isalter)
1832  ereport(ERROR,
1833  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1834  errmsg("cannot use an existing index in CREATE TABLE"),
1835  parser_errposition(cxt->pstate, constraint->location)));
1836 
1837  /* Look for the index in the same schema as the table */
1838  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1839 
1840  if (!OidIsValid(index_oid))
1841  ereport(ERROR,
1842  (errcode(ERRCODE_UNDEFINED_OBJECT),
1843  errmsg("index \"%s\" does not exist", index_name),
1844  parser_errposition(cxt->pstate, constraint->location)));
1845 
1846  /* Open the index (this will throw an error if it is not an index) */
1847  index_rel = index_open(index_oid, AccessShareLock);
1848  index_form = index_rel->rd_index;
1849 
1850  /* Check that it does not have an associated constraint already */
1851  if (OidIsValid(get_index_constraint(index_oid)))
1852  ereport(ERROR,
1853  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1854  errmsg("index \"%s\" is already associated with a constraint",
1855  index_name),
1856  parser_errposition(cxt->pstate, constraint->location)));
1857 
1858  /* Perform validity checks on the index */
1859  if (index_form->indrelid != RelationGetRelid(heap_rel))
1860  ereport(ERROR,
1861  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1862  errmsg("index \"%s\" does not belong to table \"%s\"",
1863  index_name, RelationGetRelationName(heap_rel)),
1864  parser_errposition(cxt->pstate, constraint->location)));
1865 
1866  if (!IndexIsValid(index_form))
1867  ereport(ERROR,
1868  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1869  errmsg("index \"%s\" is not valid", index_name),
1870  parser_errposition(cxt->pstate, constraint->location)));
1871 
1872  if (!index_form->indisunique)
1873  ereport(ERROR,
1874  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1875  errmsg("\"%s\" is not a unique index", index_name),
1876  errdetail("Cannot create a primary key or unique constraint using such an index."),
1877  parser_errposition(cxt->pstate, constraint->location)));
1878 
1879  if (RelationGetIndexExpressions(index_rel) != NIL)
1880  ereport(ERROR,
1881  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1882  errmsg("index \"%s\" contains expressions", index_name),
1883  errdetail("Cannot create a primary key or unique constraint using such an index."),
1884  parser_errposition(cxt->pstate, constraint->location)));
1885 
1886  if (RelationGetIndexPredicate(index_rel) != NIL)
1887  ereport(ERROR,
1888  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1889  errmsg("\"%s\" is a partial index", index_name),
1890  errdetail("Cannot create a primary key or unique constraint using such an index."),
1891  parser_errposition(cxt->pstate, constraint->location)));
1892 
1893  /*
1894  * It's probably unsafe to change a deferred index to non-deferred. (A
1895  * non-constraint index couldn't be deferred anyway, so this case
1896  * should never occur; no need to sweat, but let's check it.)
1897  */
1898  if (!index_form->indimmediate && !constraint->deferrable)
1899  ereport(ERROR,
1900  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1901  errmsg("\"%s\" is a deferrable index", index_name),
1902  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1903  parser_errposition(cxt->pstate, constraint->location)));
1904 
1905  /*
1906  * Insist on it being a btree. That's the only kind that supports
1907  * uniqueness at the moment anyway; but we must have an index that
1908  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1909  * else dump and reload will produce a different index (breaking
1910  * pg_upgrade in particular).
1911  */
1912  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
1913  ereport(ERROR,
1914  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1915  errmsg("index \"%s\" is not a btree", index_name),
1916  parser_errposition(cxt->pstate, constraint->location)));
1917 
1918  /* Must get indclass the hard way */
1919  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1920  Anum_pg_index_indclass, &isnull);
1921  Assert(!isnull);
1922  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1923 
1924  for (i = 0; i < index_form->indnatts; i++)
1925  {
1926  int16 attnum = index_form->indkey.values[i];
1927  Form_pg_attribute attform;
1928  char *attname;
1929  Oid defopclass;
1930 
1931  /*
1932  * We shouldn't see attnum == 0 here, since we already rejected
1933  * expression indexes. If we do, SystemAttributeDefinition will
1934  * throw an error.
1935  */
1936  if (attnum > 0)
1937  {
1938  Assert(attnum <= heap_rel->rd_att->natts);
1939  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
1940  }
1941  else
1942  attform = SystemAttributeDefinition(attnum,
1943  heap_rel->rd_rel->relhasoids);
1944  attname = pstrdup(NameStr(attform->attname));
1945 
1946  /*
1947  * Insist on default opclass and sort options. While the index
1948  * would still work as a constraint with non-default settings, it
1949  * might not provide exactly the same uniqueness semantics as
1950  * you'd get from a normally-created constraint; and there's also
1951  * the dump/reload problem mentioned above.
1952  */
1953  defopclass = GetDefaultOpClass(attform->atttypid,
1954  index_rel->rd_rel->relam);
1955  if (indclass->values[i] != defopclass ||
1956  index_rel->rd_indoption[i] != 0)
1957  ereport(ERROR,
1958  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1959  errmsg("index \"%s\" does not have default sorting behavior", index_name),
1960  errdetail("Cannot create a primary key or unique constraint using such an index."),
1961  parser_errposition(cxt->pstate, constraint->location)));
1962 
1963  constraint->keys = lappend(constraint->keys, makeString(attname));
1964  }
1965 
1966  /* Close the index relation but keep the lock */
1967  relation_close(index_rel, NoLock);
1968 
1969  index->indexOid = index_oid;
1970  }
1971 
1972  /*
1973  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1974  * IndexElems and operator names. We have to break that apart into
1975  * separate lists.
1976  */
1977  if (constraint->contype == CONSTR_EXCLUSION)
1978  {
1979  foreach(lc, constraint->exclusions)
1980  {
1981  List *pair = (List *) lfirst(lc);
1982  IndexElem *elem;
1983  List *opname;
1984 
1985  Assert(list_length(pair) == 2);
1986  elem = linitial_node(IndexElem, pair);
1987  opname = lsecond_node(List, pair);
1988 
1989  index->indexParams = lappend(index->indexParams, elem);
1990  index->excludeOpNames = lappend(index->excludeOpNames, opname);
1991  }
1992 
1993  return index;
1994  }
1995 
1996  /*
1997  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1998  *
1999  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2000  * also make sure they are NOT NULL, if possible. (Although we could leave
2001  * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
2002  * get it right the first time.)
2003  */
2004  foreach(lc, constraint->keys)
2005  {
2006  char *key = strVal(lfirst(lc));
2007  bool found = false;
2008  ColumnDef *column = NULL;
2009  ListCell *columns;
2010  IndexElem *iparam;
2011 
2012  foreach(columns, cxt->columns)
2013  {
2014  column = lfirst_node(ColumnDef, columns);
2015  if (strcmp(column->colname, key) == 0)
2016  {
2017  found = true;
2018  break;
2019  }
2020  }
2021  if (found)
2022  {
2023  /* found column in the new table; force it to be NOT NULL */
2024  if (constraint->contype == CONSTR_PRIMARY)
2025  column->is_not_null = true;
2026  }
2027  else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
2028  {
2029  /*
2030  * column will be a system column in the new table, so accept it.
2031  * System columns can't ever be null, so no need to worry about
2032  * PRIMARY/NOT NULL constraint.
2033  */
2034  found = true;
2035  }
2036  else if (cxt->inhRelations)
2037  {
2038  /* try inherited tables */
2039  ListCell *inher;
2040 
2041  foreach(inher, cxt->inhRelations)
2042  {
2043  RangeVar *inh = lfirst_node(RangeVar, inher);
2044  Relation rel;
2045  int count;
2046 
2047  rel = heap_openrv(inh, AccessShareLock);
2048  /* check user requested inheritance from valid relkind */
2049  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2050  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2051  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2052  ereport(ERROR,
2053  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2054  errmsg("inherited relation \"%s\" is not a table or foreign table",
2055  inh->relname)));
2056  for (count = 0; count < rel->rd_att->natts; count++)
2057  {
2058  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2059  count);
2060  char *inhname = NameStr(inhattr->attname);
2061 
2062  if (inhattr->attisdropped)
2063  continue;
2064  if (strcmp(key, inhname) == 0)
2065  {
2066  found = true;
2067 
2068  /*
2069  * We currently have no easy way to force an inherited
2070  * column to be NOT NULL at creation, if its parent
2071  * wasn't so already. We leave it to DefineIndex to
2072  * fix things up in this case.
2073  */
2074  break;
2075  }
2076  }
2077  heap_close(rel, NoLock);
2078  if (found)
2079  break;
2080  }
2081  }
2082 
2083  /*
2084  * In the ALTER TABLE case, don't complain about index keys not
2085  * created in the command; they may well exist already. DefineIndex
2086  * will complain about them if not, and will also take care of marking
2087  * them NOT NULL.
2088  */
2089  if (!found && !cxt->isalter)
2090  ereport(ERROR,
2091  (errcode(ERRCODE_UNDEFINED_COLUMN),
2092  errmsg("column \"%s\" named in key does not exist", key),
2093  parser_errposition(cxt->pstate, constraint->location)));
2094 
2095  /* Check for PRIMARY KEY(foo, foo) */
2096  foreach(columns, index->indexParams)
2097  {
2098  iparam = (IndexElem *) lfirst(columns);
2099  if (iparam->name && strcmp(key, iparam->name) == 0)
2100  {
2101  if (index->primary)
2102  ereport(ERROR,
2103  (errcode(ERRCODE_DUPLICATE_COLUMN),
2104  errmsg("column \"%s\" appears twice in primary key constraint",
2105  key),
2106  parser_errposition(cxt->pstate, constraint->location)));
2107  else
2108  ereport(ERROR,
2109  (errcode(ERRCODE_DUPLICATE_COLUMN),
2110  errmsg("column \"%s\" appears twice in unique constraint",
2111  key),
2112  parser_errposition(cxt->pstate, constraint->location)));
2113  }
2114  }
2115 
2116  /* OK, add it to the index definition */
2117  iparam = makeNode(IndexElem);
2118  iparam->name = pstrdup(key);
2119  iparam->expr = NULL;
2120  iparam->indexcolname = NULL;
2121  iparam->collation = NIL;
2122  iparam->opclass = NIL;
2123  iparam->ordering = SORTBY_DEFAULT;
2125  index->indexParams = lappend(index->indexParams, iparam);
2126  }
2127 
2128  return index;
2129 }
bool deferrable
Definition: parsenodes.h:2724
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:293
#define NIL
Definition: pg_list.h:69
Definition: c.h:536
bool primary
Definition: parsenodes.h:2722
List * keys
Definition: parsenodes.h:2107
List * exclusions
Definition: parsenodes.h:2110
int16 * rd_indoption
Definition: rel.h:186
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1407
SortByDir ordering
Definition: parsenodes.h:693
List * options
Definition: parsenodes.h:2715
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
char * tableSpace
Definition: parsenodes.h:2713
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
char * pstrdup(const char *in)
Definition: mcxt.c:1063
Node * whereClause
Definition: parsenodes.h:2716
#define Anum_pg_index_indclass
Definition: pg_index.h:89
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:214
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
bool initdeferred
Definition: parsenodes.h:2097
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2095
bool is_not_null
Definition: parsenodes.h:643
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
#define OidIsValid(objectId)
Definition: c.h:586
int natts
Definition: tupdesc.h:79
List * options
Definition: parsenodes.h:2113
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4782
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
Definition: type.h:89
ParseState * pstate
Definition: parse_utilcmd.c:75
char * relname
Definition: primnodes.h:68
Oid indexOid
Definition: parsenodes.h:2719
Node * expr
Definition: parsenodes.h:689
RangeVar * relation
Definition: parse_utilcmd.c:77
RangeVar * relation
Definition: parsenodes.h:2711
IndexStmt * pkey
Definition: parse_utilcmd.c:92
Form_pg_index rd_index
Definition: rel.h:159
SortByNulls nulls_ordering
Definition: parsenodes.h:694
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2096
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1702
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:183
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4719
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:544
bool transformed
Definition: parsenodes.h:2726
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:690
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:445
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:684
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
char * idxname
Definition: parsenodes.h:2710
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool if_not_exists
Definition: parsenodes.h:2728
#define lsecond_node(type, l)
Definition: pg_list.h:119
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
bool unique
Definition: parsenodes.h:2721
TupleDesc rd_att
Definition: rel.h:115
char * accessMethod
Definition: parsenodes.h:2712
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:692
Node * where_clause
Definition: parsenodes.h:2118
#define makeNode(_type_)
Definition: nodes.h:560
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2714
List * excludeOpNames
Definition: parsenodes.h:2717
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
bool initdeferred
Definition: parsenodes.h:2725
char * name
Definition: parsenodes.h:688
char * idxcomment
Definition: parsenodes.h:2718
#define DatumGetPointer(X)
Definition: postgres.h:555
bool concurrent
Definition: parsenodes.h:2727
bool isconstraint
Definition: parsenodes.h:2723
char * indexname
Definition: parsenodes.h:2114
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:557
ConstrType contype
Definition: parsenodes.h:2092
List * collation
Definition: parsenodes.h:691
char * colname
Definition: parsenodes.h:639
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:425
char * access_method
Definition: parsenodes.h:2117
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
char * indexspace
Definition: parsenodes.h:2115
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 1651 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1652 {
1653  IndexStmt *index;
1654  List *indexlist = NIL;
1655  ListCell *lc;
1656 
1657  /*
1658  * Run through the constraints that need to generate an index. For PRIMARY
1659  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1660  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1661  * NULL.
1662  */
1663  foreach(lc, cxt->ixconstraints)
1664  {
1665  Constraint *constraint = lfirst_node(Constraint, lc);
1666 
1667  Assert(constraint->contype == CONSTR_PRIMARY ||
1668  constraint->contype == CONSTR_UNIQUE ||
1669  constraint->contype == CONSTR_EXCLUSION);
1670 
1671  index = transformIndexConstraint(constraint, cxt);
1672 
1673  indexlist = lappend(indexlist, index);
1674  }
1675 
1676  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1677  foreach(lc, cxt->inh_indexes)
1678  {
1679  index = (IndexStmt *) lfirst(lc);
1680 
1681  if (index->primary)
1682  {
1683  if (cxt->pkey != NULL)
1684  ereport(ERROR,
1685  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1686  errmsg("multiple primary keys for table \"%s\" are not allowed",
1687  cxt->relation->relname)));
1688  cxt->pkey = index;
1689  }
1690 
1691  indexlist = lappend(indexlist, index);
1692  }
1693 
1694  /*
1695  * Scan the index list and remove any redundant index specifications. This
1696  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1697  * strict reading of SQL would suggest raising an error instead, but that
1698  * strikes me as too anal-retentive. - tgl 2001-02-14
1699  *
1700  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1701  * pre-existing indexes, too.
1702  */
1703  Assert(cxt->alist == NIL);
1704  if (cxt->pkey != NULL)
1705  {
1706  /* Make sure we keep the PKEY index in preference to others... */
1707  cxt->alist = list_make1(cxt->pkey);
1708  }
1709 
1710  foreach(lc, indexlist)
1711  {
1712  bool keep = true;
1713  ListCell *k;
1714 
1715  index = lfirst(lc);
1716 
1717  /* if it's pkey, it's already in cxt->alist */
1718  if (index == cxt->pkey)
1719  continue;
1720 
1721  foreach(k, cxt->alist)
1722  {
1723  IndexStmt *priorindex = lfirst(k);
1724 
1725  if (equal(index->indexParams, priorindex->indexParams) &&
1726  equal(index->whereClause, priorindex->whereClause) &&
1727  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1728  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1729  index->deferrable == priorindex->deferrable &&
1730  index->initdeferred == priorindex->initdeferred)
1731  {
1732  priorindex->unique |= index->unique;
1733 
1734  /*
1735  * If the prior index is as yet unnamed, and this one is
1736  * named, then transfer the name to the prior index. This
1737  * ensures that if we have named and unnamed constraints,
1738  * we'll use (at least one of) the names for the index.
1739  */
1740  if (priorindex->idxname == NULL)
1741  priorindex->idxname = index->idxname;
1742  keep = false;
1743  break;
1744  }
1745  }
1746 
1747  if (keep)
1748  cxt->alist = lappend(cxt->alist, index);
1749  }
1750 }
bool deferrable
Definition: parsenodes.h:2724
#define NIL
Definition: pg_list.h:69
bool primary
Definition: parsenodes.h:2722
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
Node * whereClause
Definition: parsenodes.h:2716
int errcode(int sqlerrcode)
Definition: elog.c:575
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:139
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
char * idxname
Definition: parsenodes.h:2710
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2721
char * accessMethod
Definition: parsenodes.h:2712
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2714
List * excludeOpNames
Definition: parsenodes.h:2717
bool initdeferred
Definition: parsenodes.h:2725
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConstrType contype
Definition: parsenodes.h:2092
Definition: pg_list.h:45

◆ transformIndexStmt()

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

Definition at line 2241 of file parse_utilcmd.c.

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

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

2242 {
2243  ParseState *pstate;
2244  RangeTblEntry *rte;
2245  ListCell *l;
2246  Relation rel;
2247 
2248  /* Nothing to do if statement already transformed. */
2249  if (stmt->transformed)
2250  return stmt;
2251 
2252  /*
2253  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2254  * overkill, but easy.)
2255  */
2256  stmt = copyObject(stmt);
2257 
2258  /* Set up pstate */
2259  pstate = make_parsestate(NULL);
2260  pstate->p_sourcetext = queryString;
2261 
2262  /*
2263  * Put the parent table into the rtable so that the expressions can refer
2264  * to its fields without qualification. Caller is responsible for locking
2265  * relation, but we still need to open it.
2266  */
2267  rel = relation_open(relid, NoLock);
2268  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2269 
2270  /* no to join list, yes to namespaces */
2271  addRTEtoQuery(pstate, rte, false, true, true);
2272 
2273  /* take care of the where clause */
2274  if (stmt->whereClause)
2275  {
2276  stmt->whereClause = transformWhereClause(pstate,
2277  stmt->whereClause,
2279  "WHERE");
2280  /* we have to fix its collations too */
2281  assign_expr_collations(pstate, stmt->whereClause);
2282  }
2283 
2284  /* take care of any index expressions */
2285  foreach(l, stmt->indexParams)
2286  {
2287  IndexElem *ielem = (IndexElem *) lfirst(l);
2288 
2289  if (ielem->expr)
2290  {
2291  /* Extract preliminary index col name before transforming expr */
2292  if (ielem->indexcolname == NULL)
2293  ielem->indexcolname = FigureIndexColname(ielem->expr);
2294 
2295  /* Now do parse transformation of the expression */
2296  ielem->expr = transformExpr(pstate, ielem->expr,
2298 
2299  /* We have to fix its collations too */
2300  assign_expr_collations(pstate, ielem->expr);
2301 
2302  /*
2303  * transformExpr() should have already rejected subqueries,
2304  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2305  * for an index expression.
2306  *
2307  * DefineIndex() will make more checks.
2308  */
2309  }
2310  }
2311 
2312  /*
2313  * Check that only the base rel is mentioned. (This should be dead code
2314  * now that add_missing_from is history.)
2315  */
2316  if (list_length(pstate->p_rtable) != 1)
2317  ereport(ERROR,
2318  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2319  errmsg("index expressions and predicates can refer only to the table being indexed")));
2320 
2321  free_parsestate(pstate);
2322 
2323  /* Close relation */
2324  heap_close(rel, NoLock);
2325 
2326  /* Mark statement as successfully transformed */
2327  stmt->transformed = true;
2328 
2329  return stmt;
2330 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Node * whereClause
Definition: parsenodes.h:2716
int errcode(int sqlerrcode)
Definition: elog.c:575
char * FigureIndexColname(Node *node)
#define heap_close(r, l)
Definition: heapam.h:97
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:689
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2726
char * indexcolname
Definition: parsenodes.h:690
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2714
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define copyObject(obj)
Definition: nodes.h:625
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:173

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1219 of file parse_utilcmd.c.

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

Referenced by transformCreateStmt().

1220 {
1221  HeapTuple tuple;
1222  TupleDesc tupdesc;
1223  int i;
1224  Oid ofTypeId;
1225 
1226  AssertArg(ofTypename);
1227 
1228  tuple = typenameType(NULL, ofTypename, NULL);
1229  check_of_type(tuple);
1230  ofTypeId = HeapTupleGetOid(tuple);
1231  ofTypename->typeOid = ofTypeId; /* cached for later */
1232 
1233  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1234  for (i = 0; i < tupdesc->natts; i++)
1235  {
1236  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1237  ColumnDef *n;
1238 
1239  if (attr->attisdropped)
1240  continue;
1241 
1242  n = makeNode(ColumnDef);
1243  n->colname = pstrdup(NameStr(attr->attname));
1244  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1245  n->inhcount = 0;
1246  n->is_local = true;
1247  n->is_not_null = false;
1248  n->is_from_type = true;
1249  n->is_from_parent = false;
1250  n->storage = 0;
1251  n->raw_default = NULL;
1252  n->cooked_default = NULL;
1253  n->collClause = NULL;
1254  n->collOid = attr->attcollation;
1255  n->constraints = NIL;
1256  n->location = -1;
1257  cxt->columns = lappend(cxt->columns, n);
1258  }
1259  DecrTupleDescRefCount(tupdesc);
1260 
1261  ReleaseSysCache(tuple);
1262 }
#define NIL
Definition: pg_list.h:69
Oid typeOid
Definition: parsenodes.h:209
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
char storage
Definition: parsenodes.h:646
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1618
bool is_local
Definition: parsenodes.h:642
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
List * constraints
Definition: parsenodes.h:652
char * pstrdup(const char *in)
Definition: mcxt.c:1063
bool is_from_parent
Definition: parsenodes.h:645
bool is_not_null
Definition: parsenodes.h:643
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:79
Node * cooked_default
Definition: parsenodes.h:648
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5109
Oid collOid
Definition: parsenodes.h:651
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int location
Definition: parsenodes.h:654
#define AssertArg(condition)
Definition: c.h:682
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
bool is_from_type
Definition: parsenodes.h:644
#define makeNode(_type_)
Definition: nodes.h:560
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:319
TypeName * typeName
Definition: parsenodes.h:640
CollateClause * collClause
Definition: parsenodes.h:650
int i
int inhcount
Definition: parsenodes.h:641
#define NameStr(name)
Definition: c.h:557
char * colname
Definition: parsenodes.h:639
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ transformPartitionBound()

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

Definition at line 3312 of file parse_utilcmd.c.

References Assert, castNode, Const::constisnull, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), forboth, get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), get_relid_attribute_name(), i, PartitionBoundSpec::is_default, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), PartitionBoundSpec::upperdatums, validateInfiniteBounds(), value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3314 {
3315  PartitionBoundSpec *result_spec;
3316  PartitionKey key = RelationGetPartitionKey(parent);
3317  char strategy = get_partition_strategy(key);
3318  int partnatts = get_partition_natts(key);
3319  List *partexprs = get_partition_exprs(key);
3320 
3321  /* Avoid scribbling on input */
3322  result_spec = copyObject(spec);
3323 
3324  if (spec->is_default)
3325  {
3326  if (strategy == PARTITION_STRATEGY_HASH)
3327  ereport(ERROR,
3328  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3329  errmsg("a hash-partitioned table may not have a default partition")));
3330 
3331  /*
3332  * In case of the default partition, parser had no way to identify the
3333  * partition strategy. Assign the parent's strategy to the default
3334  * partition bound spec.
3335  */
3336  result_spec->strategy = strategy;
3337 
3338  return result_spec;
3339  }
3340 
3341  if (strategy == PARTITION_STRATEGY_HASH)
3342  {
3343  if (spec->strategy != PARTITION_STRATEGY_HASH)
3344  ereport(ERROR,
3345  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3346  errmsg("invalid bound specification for a hash partition"),
3347  parser_errposition(pstate, exprLocation((Node *) spec))));
3348 
3349  if (spec->modulus <= 0)
3350  ereport(ERROR,
3351  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3352  errmsg("modulus for hash partition must be a positive integer")));
3353 
3354  Assert(spec->remainder >= 0);
3355 
3356  if (spec->remainder >= spec->modulus)
3357  ereport(ERROR,
3358  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3359  errmsg("remainder for hash partition must be less than modulus")));
3360  }
3361  else if (strategy == PARTITION_STRATEGY_LIST)
3362  {
3363  ListCell *cell;
3364  char *colname;
3365  Oid coltype;
3366  int32 coltypmod;
3367 
3368  if (spec->strategy != PARTITION_STRATEGY_LIST)
3369  ereport(ERROR,
3370  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3371  errmsg("invalid bound specification for a list partition"),
3372  parser_errposition(pstate, exprLocation((Node *) spec))));
3373 
3374  /* Get the only column's name in case we need to output an error */
3375  if (key->partattrs[0] != 0)
3376  colname = get_relid_attribute_name(RelationGetRelid(parent),
3377  key->partattrs[0]);
3378  else
3379  colname = deparse_expression((Node *) linitial(partexprs),
3381  RelationGetRelid(parent)),
3382  false, false);
3383  /* Need its type data too */
3384  coltype = get_partition_col_typid(key, 0);
3385  coltypmod = get_partition_col_typmod(key, 0);
3386 
3387  result_spec->listdatums = NIL;
3388  foreach(cell, spec->listdatums)
3389  {
3390  A_Const *con = castNode(A_Const, lfirst(cell));
3391  Const *value;
3392  ListCell *cell2;
3393  bool duplicate;
3394 
3395  value = transformPartitionBoundValue(pstate, con,
3396  colname, coltype, coltypmod);
3397 
3398  /* Don't add to the result if the value is a duplicate */
3399  duplicate = false;
3400  foreach(cell2, result_spec->listdatums)
3401  {
3402  Const *value2 = castNode(Const, lfirst(cell2));
3403 
3404  if (equal(value, value2))
3405  {
3406  duplicate = true;
3407  break;
3408  }
3409  }
3410  if (duplicate)
3411  continue;
3412 
3413  result_spec->listdatums = lappend(result_spec->listdatums,
3414  value);
3415  }
3416  }
3417  else if (strategy == PARTITION_STRATEGY_RANGE)
3418  {
3419  ListCell *cell1,
3420  *cell2;
3421  int i,
3422  j;
3423 
3424  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3425  ereport(ERROR,
3426  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3427  errmsg("invalid bound specification for a range partition"),
3428  parser_errposition(pstate, exprLocation((Node *) spec))));
3429 
3430  if (list_length(spec->lowerdatums) != partnatts)
3431  ereport(ERROR,
3432  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3433  errmsg("FROM must specify exactly one value per partitioning column")));
3434  if (list_length(spec->upperdatums) != partnatts)
3435  ereport(ERROR,
3436  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3437  errmsg("TO must specify exactly one value per partitioning column")));
3438 
3439  /*
3440  * Once we see MINVALUE or MAXVALUE for one column, the remaining
3441  * columns must be the same.
3442  */
3443  validateInfiniteBounds(pstate, spec->lowerdatums);
3444  validateInfiniteBounds(pstate, spec->upperdatums);
3445 
3446  /* Transform all the constants */
3447  i = j = 0;
3448  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3449  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3450  {
3451  PartitionRangeDatum *ldatum = (PartitionRangeDatum *) lfirst(cell1);
3452  PartitionRangeDatum *rdatum = (PartitionRangeDatum *) lfirst(cell2);
3453  char *colname;
3454  Oid coltype;
3455  int32 coltypmod;
3456  A_Const *con;
3457  Const *value;
3458 
3459  /* Get the column's name in case we need to output an error */
3460  if (key->partattrs[i] != 0)
3461  colname = get_relid_attribute_name(RelationGetRelid(parent),
3462  key->partattrs[i]);
3463  else
3464  {
3465  colname = deparse_expression((Node *) list_nth(partexprs, j),
3467  RelationGetRelid(parent)),
3468  false, false);
3469  ++j;
3470  }
3471  /* Need its type data too */
3472  coltype = get_partition_col_typid(key, i);
3473  coltypmod = get_partition_col_typmod(key, i);
3474 
3475  if (ldatum->value)
3476  {
3477  con = castNode(A_Const, ldatum->value);
3478  value = transformPartitionBoundValue(pstate, con,
3479  colname,
3480  coltype, coltypmod);
3481  if (value->constisnull)
3482  ereport(ERROR,
3483  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3484  errmsg("cannot specify NULL in range bound")));
3485  ldatum = copyObject(ldatum); /* don't scribble on input */
3486  ldatum->value = (Node *) value;
3487  }
3488 
3489  if (rdatum->value)
3490  {
3491  con = castNode(A_Const, rdatum->value);
3492  value = transformPartitionBoundValue(pstate, con,
3493  colname,
3494  coltype, coltypmod);
3495  if (value->constisnull)
3496  ereport(ERROR,
3497  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3498  errmsg("cannot specify NULL in range bound")));
3499  rdatum = copyObject(rdatum); /* don't scribble on input */
3500  rdatum->value = (Node *) value;
3501  }
3502 
3503  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3504  ldatum);
3505  result_spec->upperdatums = lappend(result_spec->upperdatums,
3506  rdatum);
3507 
3508  ++i;
3509  }
3510  }
3511  else
3512  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3513 
3514  return result_spec;
3515 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
static Const * transformPartitionBoundValue(ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:294
static int get_partition_natts(PartitionKey key)
Definition: rel.h:605
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static struct @121 value
static void validateInfiniteBounds(ParseState *pstate, List *blist)
void * list_nth(const List *list, int n)
Definition: list.c:410
static List * get_partition_exprs(PartitionKey key)
Definition: rel.h:611
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3067
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: rel.h:632
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
AttrNumber * partattrs
Definition: rel.h:56
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:626
static int get_partition_strategy(PartitionKey key)
Definition: rel.h:599
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:787
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3008
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:788
#define RelationGetPartitionKey(relation)
Definition: rel.h:593
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:789
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:425
bool constisnull
Definition: primnodes.h:197

◆ transformPartitionBoundValue()

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

Definition at line 3561 of file parse_utilcmd.c.

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, expression_planner(), exprType(), format_type_be(), IsA, A_Const::location, make_const(), parser_errposition(), A_Const::val, and value.

Referenced by transformPartitionBound().

3563 {
3564  Node *value;
3565 
3566  /* Make it into a Const */
3567  value = (Node *) make_const(pstate, &con->val, con->location);
3568 
3569  /* Coerce to correct type */
3570  value = coerce_to_target_type(pstate,
3571  value, exprType(value),
3572  colType,
3573  colTypmod,
3576  -1);
3577 
3578  if (value == NULL)
3579  ereport(ERROR,
3580  (errcode(ERRCODE_DATATYPE_MISMATCH),
3581  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3582  format_type_be(colType), colName),
3583  parser_errposition(pstate, con->location)));
3584 
3585  /* Simplify the expression, in case we had a coercion */
3586  if (!IsA(value, Const))
3587  value = (Node *) expression_planner((Expr *) value);
3588 
3589  /* Fail if we don't have a constant (i.e., non-immutable coercion) */
3590  if (!IsA(value, Const))
3591  ereport(ERROR,
3592  (errcode(ERRCODE_DATATYPE_MISMATCH),
3593  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3594  format_type_be(colType), colName),
3595  errdetail("The cast requires a non-immutable conversion."),
3596  errhint("Try putting the literal value in single quotes."),
3597  parser_errposition(pstate, con->location)));
3598 
3599  return (Const *) value;
3600 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int errhint(const char *fmt,...)
Definition: elog.c:987
Expr * expression_planner(Expr *expr)
Definition: planner.c:6026
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Const * make_const(ParseState *pstate, Value *value, int location)
Definition: parse_node.c:470
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
static struct @121 value
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int location
Definition: parsenodes.h:288
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
Value val
Definition: parsenodes.h:287

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 3288 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt().

3289 {
3290  Relation parentRel = cxt->rel;
3291 
3292  /* the table must be partitioned */
3293  if (parentRel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3294  ereport(ERROR,
3295  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3296  errmsg("\"%s\" is not partitioned",
3297  RelationGetRelationName(parentRel))));
3298 
3299  /* transform the partition bound, if any */
3300  Assert(RelationGetPartitionKey(parentRel) != NULL);
3301  if (cmd->bound != NULL)
3302  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3303  cmd->bound);
3304 }
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define Assert(condition)
Definition: c.h:680
PartitionBoundSpec * bound
Definition: parsenodes.h:848
#define RelationGetPartitionKey(relation)
Definition: rel.h:593
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ transformRuleStmt()

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

Definition at line 2346 of file parse_utilcmd.c.

References AccessExclusiveLock, generate_unaccent_rules::action, RuleStmt::actions, addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, copyObject, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), getInsertSelectQuery(), heap_close, heap_openrv(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_joinlist, ParseState::p_rtable, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RELKIND_MATVIEW, RangeTblEntry::requiredPerms, Query::rtable, Query::setOperations, transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2348 {
2349  Relation rel;
2350  ParseState *pstate;
2351  RangeTblEntry *oldrte;
2352  RangeTblEntry *newrte;
2353 
2354  /*
2355  * To avoid deadlock, make sure the first thing we do is grab
2356  * AccessExclusiveLock on the target relation. This will be needed by
2357  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2358  * beforehand.
2359  */
2361 
2362  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2363  ereport(ERROR,
2364  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2365  errmsg("rules on materialized views are not supported")));
2366 
2367  /* Set up pstate */
2368  pstate = make_parsestate(NULL);
2369  pstate->p_sourcetext = queryString;
2370 
2371  /*
2372  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2373  * Set up their RTEs in the main pstate for use in parsing the rule
2374  * qualification.
2375  */
2376  oldrte = addRangeTableEntryForRelation(pstate, rel,
2377  makeAlias("old", NIL),
2378  false, false);
2379  newrte = addRangeTableEntryForRelation(pstate, rel,
2380  makeAlias("new", NIL),
2381  false, false);
2382  /* Must override addRangeTableEntry's default access-check flags */
2383  oldrte->requiredPerms = 0;
2384  newrte->requiredPerms = 0;
2385 
2386  /*
2387  * They must be in the namespace too for lookup purposes, but only add the
2388  * one(s) that are relevant for the current kind of rule. In an UPDATE
2389  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2390  * there's no need to be so picky for INSERT & DELETE. We do not add them
2391  * to the joinlist.
2392  */
2393  switch (stmt->event)
2394  {
2395  case CMD_SELECT:
2396  addRTEtoQuery(pstate, oldrte, false, true, true);
2397  break;
2398  case CMD_UPDATE:
2399  addRTEtoQuery(pstate, oldrte, false, true, true);
2400  addRTEtoQuery(pstate, newrte, false, true, true);
2401  break;
2402  case CMD_INSERT:
2403  addRTEtoQuery(pstate, newrte, false, true, true);
2404  break;
2405  case CMD_DELETE:
2406  addRTEtoQuery(pstate, oldrte, false, true, true);
2407  break;
2408  default:
2409  elog(ERROR, "unrecognized event type: %d",
2410  (int) stmt->event);
2411  break;
2412  }
2413 
2414  /* take care of the where clause */
2415  *whereClause = transformWhereClause(pstate,
2416  (Node *) copyObject(stmt->whereClause),
2418  "WHERE");
2419  /* we have to fix its collations too */
2420  assign_expr_collations(pstate, *whereClause);
2421 
2422  /* this is probably dead code without add_missing_from: */
2423  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2424  ereport(ERROR,
2425  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2426  errmsg("rule WHERE condition cannot contain references to other relations")));
2427 
2428  /*
2429  * 'instead nothing' rules with a qualification need a query rangetable so
2430  * the rewrite handler can add the negated rule qualification to the
2431  * original query. We create a query with the new command type CMD_NOTHING
2432  * here that is treated specially by the rewrite system.
2433  */
2434  if (stmt->actions == NIL)
2435  {
2436  Query *nothing_qry = makeNode(Query);
2437 
2438  nothing_qry->commandType = CMD_NOTHING;
2439  nothing_qry->rtable = pstate->p_rtable;
2440  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2441 
2442  *actions = list_make1(nothing_qry);
2443  }
2444  else
2445  {
2446  ListCell *l;
2447  List *newactions = NIL;
2448 
2449  /*
2450  * transform each statement, like parse_sub_analyze()
2451  */
2452  foreach(l, stmt->actions)
2453  {
2454  Node *action = (Node *) lfirst(l);
2455  ParseState *sub_pstate = make_parsestate(NULL);
2456  Query *sub_qry,
2457  *top_subqry;
2458  bool has_old,
2459  has_new;
2460 
2461  /*
2462  * Since outer ParseState isn't parent of inner, have to pass down
2463  * the query text by hand.
2464  */
2465  sub_pstate->p_sourcetext = queryString;
2466 
2467  /*
2468  * Set up OLD/NEW in the rtable for this statement. The entries
2469  * are added only to relnamespace, not varnamespace, because we
2470  * don't want them to be referred to by unqualified field names
2471  * nor "*" in the rule actions. We decide later whether to put
2472  * them in the joinlist.
2473  */
2474  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2475  makeAlias("old", NIL),
2476  false, false);
2477  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2478  makeAlias("new", NIL),
2479  false, false);
2480  oldrte->requiredPerms = 0;
2481  newrte->requiredPerms = 0;
2482  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2483  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2484 
2485  /* Transform the rule action statement */
2486  top_subqry = transformStmt(sub_pstate,
2487  (Node *) copyObject(action));
2488 
2489  /*
2490  * We cannot support utility-statement actions (eg NOTIFY) with
2491  * nonempty rule WHERE conditions, because there's no way to make
2492  * the utility action execute conditionally.
2493  */
2494  if (top_subqry->commandType == CMD_UTILITY &&
2495  *whereClause != NULL)
2496  ereport(ERROR,
2497  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2498  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2499 
2500  /*
2501  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2502  * into the SELECT, and that's what we need to look at. (Ugly
2503  * kluge ... try to fix this when we redesign querytrees.)
2504  */
2505  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2506 
2507  /*
2508  * If the sub_qry is a setop, we cannot attach any qualifications
2509  * to it, because the planner won't notice them. This could
2510  * perhaps be relaxed someday, but for now, we may as well reject
2511  * such a rule immediately.
2512  */
2513  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2514  ereport(ERROR,
2515  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2516  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2517 
2518  /*
2519  * Validate action's use of OLD/NEW, qual too
2520  */
2521  has_old =
2522  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2523  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2524  has_new =
2525  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2526  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2527 
2528  switch (stmt->event)
2529  {
2530  case CMD_SELECT:
2531  if (has_old)
2532  ereport(ERROR,
2533  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2534  errmsg("ON SELECT rule cannot use OLD")));
2535  if (has_new)
2536  ereport(ERROR,
2537  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2538  errmsg("ON SELECT rule cannot use NEW")));
2539  break;
2540  case CMD_UPDATE:
2541  /* both are OK */
2542  break;
2543  case CMD_INSERT:
2544  if (has_old)
2545  ereport(ERROR,
2546  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2547  errmsg("ON INSERT rule cannot use OLD")));
2548  break;
2549  case CMD_DELETE:
2550  if (has_new)
2551  ereport(ERROR,
2552  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2553  errmsg("ON DELETE rule cannot use NEW")));
2554  break;
2555  default:
2556  elog(ERROR, "unrecognized event type: %d",
2557  (int) stmt->event);
2558  break;
2559  }
2560 
2561  /*
2562  * OLD/NEW are not allowed in WITH queries, because they would
2563  * amount to outer references for the WITH, which we disallow.
2564  * However, they were already in the outer rangetable when we
2565  * analyzed the query, so we have to check.
2566  *
2567  * Note that in the INSERT...SELECT case, we need to examine the
2568  * CTE lists of both top_subqry and sub_qry.
2569  *
2570  * Note that we aren't digging into the body of the query looking
2571  * for WITHs in nested sub-SELECTs. A WITH down there can
2572  * legitimately refer to OLD/NEW, because it'd be an
2573  * indirect-correlated outer reference.
2574  */
2575  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2576  PRS2_OLD_VARNO, 0) ||
2577  rangeTableEntry_used((Node *) sub_qry->cteList,
2578  PRS2_OLD_VARNO, 0))
2579  ereport(ERROR,
2580  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2581  errmsg("cannot refer to OLD within WITH query")));
2582  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2583  PRS2_NEW_VARNO, 0) ||
2584  rangeTableEntry_used((Node *) sub_qry->cteList,
2585  PRS2_NEW_VARNO, 0))
2586  ereport(ERROR,
2587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2588  errmsg("cannot refer to NEW within WITH query")));
2589 
2590  /*
2591  * For efficiency's sake, add OLD to the rule action's jointree
2592  * only if it was actually referenced in the statement or qual.
2593  *
2594  * For INSERT, NEW is not really a relation (only a reference to
2595  * the to-be-inserted tuple) and should never be added to the
2596  * jointree.
2597  *
2598  * For UPDATE, we treat NEW as being another kind of reference to
2599  * OLD, because it represents references to *transformed* tuples
2600  * of the existing relation. It would be wrong to enter NEW
2601  * separately in the jointree, since that would cause a double
2602  * join of the updated relation. It's also wrong to fail to make
2603  * a jointree entry if only NEW and not OLD is mentioned.
2604  */
2605  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2606  {
2607  /*
2608  * If sub_qry is a setop, manipulating its jointree will do no
2609  * good at all, because the jointree is dummy. (This should be
2610  * a can't-happen case because of prior tests.)
2611  */
2612  if (sub_qry->setOperations != NULL)
2613  ereport(ERROR,
2614  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2615  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2616  /* hack so we can use addRTEtoQuery() */
2617  sub_pstate->p_rtable = sub_qry->rtable;
2618  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2619  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2620  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2621  }
2622 
2623  newactions = lappend(newactions, top_subqry);
2624 
2625  free_parsestate(sub_pstate);
2626  }
2627 
2628  *actions = newactions;
2629  }
2630 
2631  free_parsestate(pstate);
2632 
2633  /* Close relation, but keep the exclusive lock */
2634  heap_close(rel, NoLock);
2635 }
#define NIL
Definition: pg_list.h:69
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:284
FromExpr * jointree
Definition: parsenodes.h:136
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
List * actions
Definition: parsenodes.h:2901
AclMode requiredPerms
Definition: parsenodes.h:1059
List * fromlist
Definition: primnodes.h:1478
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:386
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:250
List * lappend(List *list, void *datum)
Definition: list.c:128
#define PRS2_OLD_VARNO
Definition: primnodes.h:160
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:560
CmdType event
Definition: parsenodes.h:2899
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2898
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * p_joinlist
Definition: parse_node.h:175
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
RangeVar * relation
Definition: parsenodes.h:2896
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
#define PRS2_NEW_VARNO
Definition: primnodes.h:161
List * p_rtable
Definition: parse_node.h:173

◆ transformTableConstraint()

static void transformTableConstraint ( CreateStmtContext cxt,
Constraint constraint 
)
static

Definition at line 816 of file parse_utilcmd.c.

References CreateStmtContext::ckconstraints, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::fkconstraints, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), Constraint::location, parser_errposition(), and CreateStmtContext::pstate.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

817 {
818  switch (constraint->contype)
819  {
820  case CONSTR_PRIMARY:
821  if (cxt->isforeign)
822  ereport(ERROR,
823  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
824  errmsg("primary key constraints are not supported on foreign tables"),
826  constraint->location)));
827  if (cxt->ispartitioned)
828  ereport(ERROR,
829  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
830  errmsg("primary key constraints are not supported on partitioned tables"),
832  constraint->location)));
833  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
834  break;
835 
836  case CONSTR_UNIQUE:
837  if (cxt->isforeign)
838  ereport(ERROR,
839  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
840  errmsg("unique constraints are not supported on foreign tables"),
842  constraint->location)));
843  if (cxt->ispartitioned)
844  ereport(ERROR,
845  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
846  errmsg("unique constraints are not supported on partitioned tables"),
848  constraint->location)));
849  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
850  break;
851 
852  case CONSTR_EXCLUSION:
853  if (cxt->isforeign)
854  ereport(ERROR,
855  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
856  errmsg("exclusion constraints are not supported on foreign tables"),
858  constraint->location)));
859  if (cxt->ispartitioned)
860  ereport(ERROR,
861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
862  errmsg("exclusion constraints are not supported on partitioned tables"),
864  constraint->location)));
865  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
866  break;
867 
868  case CONSTR_CHECK:
869  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
870  break;
871 
872  case CONSTR_FOREIGN:
873  if (cxt->isforeign)
874  ereport(ERROR,
875  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
876  errmsg("foreign key constraints are not supported on foreign tables"),
878  constraint->location)));
879  if (cxt->ispartitioned)
880  ereport(ERROR,
881  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
882  errmsg("foreign key constraints are not supported on partitioned tables"),
884  constraint->location)));
885  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
886  break;
887 
888  case