PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 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

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

Referenced by transformConstraintAttrs().

Function Documentation

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

Definition at line 1254 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, NULL, 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, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

Referenced by transformTableLikeClause().

1256 {
1257  Oid source_relid = RelationGetRelid(source_idx);
1258  Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
1259  HeapTuple ht_idxrel;
1260  HeapTuple ht_idx;
1261  HeapTuple ht_am;
1262  Form_pg_class idxrelrec;
1263  Form_pg_index idxrec;
1264  Form_pg_am amrec;
1265  oidvector *indcollation;
1266  oidvector *indclass;
1267  IndexStmt *index;
1268  List *indexprs;
1269  ListCell *indexpr_item;
1270  Oid indrelid;
1271  int keyno;
1272  Oid keycoltype;
1273  Datum datum;
1274  bool isnull;
1275 
1276  /*
1277  * Fetch pg_class tuple of source index. We can't use the copy in the
1278  * relcache entry because it doesn't include optional fields.
1279  */
1280  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1281  if (!HeapTupleIsValid(ht_idxrel))
1282  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1283  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1284 
1285  /* Fetch pg_index tuple for source index from relcache entry */
1286  ht_idx = source_idx->rd_indextuple;
1287  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1288  indrelid = idxrec->indrelid;
1289 
1290  /* Fetch the pg_am tuple of the index' access method */
1291  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1292  if (!HeapTupleIsValid(ht_am))
1293  elog(ERROR, "cache lookup failed for access method %u",
1294  idxrelrec->relam);
1295  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1296 
1297  /* Extract indcollation from the pg_index tuple */
1298  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1299  Anum_pg_index_indcollation, &isnull);
1300  Assert(!isnull);
1301  indcollation = (oidvector *) DatumGetPointer(datum);
1302 
1303  /* Extract indclass from the pg_index tuple */
1304  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1305  Anum_pg_index_indclass, &isnull);
1306  Assert(!isnull);
1307  indclass = (oidvector *) DatumGetPointer(datum);
1308 
1309  /* Begin building the IndexStmt */
1310  index = makeNode(IndexStmt);
1311  index->relation = cxt->relation;
1312  index->accessMethod = pstrdup(NameStr(amrec->amname));
1313  if (OidIsValid(idxrelrec->reltablespace))
1314  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1315  else
1316  index->tableSpace = NULL;
1317  index->excludeOpNames = NIL;
1318  index->idxcomment = NULL;
1319  index->indexOid = InvalidOid;
1320  index->oldNode = InvalidOid;
1321  index->unique = idxrec->indisunique;
1322  index->primary = idxrec->indisprimary;
1323  index->transformed = true; /* don't need transformIndexStmt */
1324  index->concurrent = false;
1325  index->if_not_exists = false;
1326 
1327  /*
1328  * We don't try to preserve the name of the source index; instead, just
1329  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1330  * the name, we'd get duplicate-relation-name failures unless the source
1331  * table was in a different schema.)
1332  */
1333  index->idxname = NULL;
1334 
1335  /*
1336  * If the index is marked PRIMARY or has an exclusion condition, it's
1337  * certainly from a constraint; else, if it's not marked UNIQUE, it
1338  * certainly isn't. If it is or might be from a constraint, we have to
1339  * fetch the pg_constraint record.
1340  */
1341  if (index->primary || index->unique || idxrec->indisexclusion)
1342  {
1343  Oid constraintId = get_index_constraint(source_relid);
1344 
1345  if (OidIsValid(constraintId))
1346  {
1347  HeapTuple ht_constr;
1348  Form_pg_constraint conrec;
1349 
1350  ht_constr = SearchSysCache1(CONSTROID,
1351  ObjectIdGetDatum(constraintId));
1352  if (!HeapTupleIsValid(ht_constr))
1353  elog(ERROR, "cache lookup failed for constraint %u",
1354  constraintId);
1355  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1356 
1357  index->isconstraint = true;
1358  index->deferrable = conrec->condeferrable;
1359  index->initdeferred = conrec->condeferred;
1360 
1361  /* If it's an exclusion constraint, we need the operator names */
1362  if (idxrec->indisexclusion)
1363  {
1364  Datum *elems;
1365  int nElems;
1366  int i;
1367 
1368  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1369  /* Extract operator OIDs from the pg_constraint tuple */
1370  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1372  &isnull);
1373  if (isnull)
1374  elog(ERROR, "null conexclop for constraint %u",
1375  constraintId);
1376 
1378  OIDOID, sizeof(Oid), true, 'i',
1379  &elems, NULL, &nElems);
1380 
1381  for (i = 0; i < nElems; i++)
1382  {
1383  Oid operid = DatumGetObjectId(elems[i]);
1384  HeapTuple opertup;
1385  Form_pg_operator operform;
1386  char *oprname;
1387  char *nspname;
1388  List *namelist;
1389 
1390  opertup = SearchSysCache1(OPEROID,
1391  ObjectIdGetDatum(operid));
1392  if (!HeapTupleIsValid(opertup))
1393  elog(ERROR, "cache lookup failed for operator %u",
1394  operid);
1395  operform = (Form_pg_operator) GETSTRUCT(opertup);
1396  oprname = pstrdup(NameStr(operform->oprname));
1397  /* For simplicity we always schema-qualify the op name */
1398  nspname = get_namespace_name(operform->oprnamespace);
1399  namelist = list_make2(makeString(nspname),
1400  makeString(oprname));
1401  index->excludeOpNames = lappend(index->excludeOpNames,
1402  namelist);
1403  ReleaseSysCache(opertup);
1404  }
1405  }
1406 
1407  ReleaseSysCache(ht_constr);
1408  }
1409  else
1410  index->isconstraint = false;
1411  }
1412  else
1413  index->isconstraint = false;
1414 
1415  /* Get the index expressions, if any */
1416  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1417  Anum_pg_index_indexprs, &isnull);
1418  if (!isnull)
1419  {
1420  char *exprsString;
1421 
1422  exprsString = TextDatumGetCString(datum);
1423  indexprs = (List *) stringToNode(exprsString);
1424  }
1425  else
1426  indexprs = NIL;
1427 
1428  /* Build the list of IndexElem */
1429  index->indexParams = NIL;
1430 
1431  indexpr_item = list_head(indexprs);
1432  for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1433  {
1434  IndexElem *iparam;
1435  AttrNumber attnum = idxrec->indkey.values[keyno];
1436  int16 opt = source_idx->rd_indoption[keyno];
1437 
1438  iparam = makeNode(IndexElem);
1439 
1440  if (AttributeNumberIsValid(attnum))
1441  {
1442  /* Simple index column */
1443  char *attname;
1444 
1445  attname = get_relid_attribute_name(indrelid, attnum);
1446  keycoltype = get_atttype(indrelid, attnum);
1447 
1448  iparam->name = attname;
1449  iparam->expr = NULL;
1450  }
1451  else
1452  {
1453  /* Expressional index */
1454  Node *indexkey;
1455  bool found_whole_row;
1456 
1457  if (indexpr_item == NULL)
1458  elog(ERROR, "too few entries in indexprs list");
1459  indexkey = (Node *) lfirst(indexpr_item);
1460  indexpr_item = lnext(indexpr_item);
1461 
1462  /* Adjust Vars to match new table's column numbering */
1463  indexkey = map_variable_attnos(indexkey,
1464  1, 0,
1465  attmap, attmap_length,
1466  &found_whole_row);
1467 
1468  /* As in transformTableLikeClause, reject whole-row variables */
1469  if (found_whole_row)
1470  ereport(ERROR,
1471  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1472  errmsg("cannot convert whole-row table reference"),
1473  errdetail("Index \"%s\" contains a whole-row table reference.",
1474  RelationGetRelationName(source_idx))));
1475 
1476  iparam->name = NULL;
1477  iparam->expr = indexkey;
1478 
1479  keycoltype = exprType(indexkey);
1480  }
1481 
1482  /* Copy the original index column name */
1483  iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1484 
1485  /* Add the collation name, if non-default */
1486  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1487 
1488  /* Add the operator class name, if non-default */
1489  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1490 
1491  iparam->ordering = SORTBY_DEFAULT;
1493 
1494  /* Adjust options if necessary */
1495  if (source_idx->rd_amroutine->amcanorder)
1496  {
1497  /*
1498  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1499  * set non-default settings unnecessarily, though, so as to
1500  * improve the chance of recognizing equivalence to constraint
1501  * indexes.
1502  */
1503  if (opt & INDOPTION_DESC)
1504  {
1505  iparam->ordering = SORTBY_DESC;
1506  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1508  }
1509  else
1510  {
1511  if (opt & INDOPTION_NULLS_FIRST)
1513  }
1514  }
1515 
1516  index->indexParams = lappend(index->indexParams, iparam);
1517  }
1518 
1519  /* Copy reloptions if any */
1520  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1521  Anum_pg_class_reloptions, &isnull);
1522  if (!isnull)
1523  index->options = untransformRelOptions(datum);
1524 
1525  /* If it's a partial index, decompile and append the predicate */
1526  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1527  Anum_pg_index_indpred, &isnull);
1528  if (!isnull)
1529  {
1530  char *pred_str;
1531  Node *pred_tree;
1532  bool found_whole_row;
1533 
1534  /* Convert text string to node tree */
1535  pred_str = TextDatumGetCString(datum);
1536  pred_tree = (Node *) stringToNode(pred_str);
1537 
1538  /* Adjust Vars to match new table's column numbering */
1539  pred_tree = map_variable_attnos(pred_tree,
1540  1, 0,
1541  attmap, attmap_length,
1542  &found_whole_row);
1543 
1544  /* As in transformTableLikeClause, reject whole-row variables */
1545  if (found_whole_row)
1546  ereport(ERROR,
1547  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1548  errmsg("cannot convert whole-row table reference"),
1549  errdetail("Index \"%s\" contains a whole-row table reference.",
1550  RelationGetRelationName(source_idx))));
1551 
1552  index->whereClause = pred_tree;
1553  }
1554 
1555  /* Clean up */
1556  ReleaseSysCache(ht_idxrel);
1557  ReleaseSysCache(ht_am);
1558 
1559  return index;
1560 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
bool deferrable
Definition: parsenodes.h:2697
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, bool *found_whole_row)
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:478
bool primary
Definition: parsenodes.h:2695
#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:656
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2688
#define RelationGetDescr(relation)
Definition: rel.h:428
#define OIDOID
Definition: pg_type.h:328
char * tableSpace
Definition: parsenodes.h:2686
#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:1077
Node * whereClause
Definition: parsenodes.h:2689
#define Anum_pg_index_indclass
Definition: pg_index.h:89
Definition: nodes.h:509
#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:538
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2692
Node * expr
Definition: parsenodes.h:689
RangeVar * relation
Definition: parse_utilcmd.c:77
RangeVar * relation
Definition: parsenodes.h:2684
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:3033
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:486
bool transformed
Definition: parsenodes.h:2699
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:690
#define RelationGetRelationName(relation)
Definition: rel.h:436
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
List * lappend(List *list, void *datum)
Definition: list.c:128
char * idxname
Definition: parsenodes.h:2683
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:92
bool if_not_exists
Definition: parsenodes.h:2701
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
bool unique
Definition: parsenodes.h:2694
List * untransformRelOptions(Datum options)
Definition: reloptions.c:907
char * accessMethod
Definition: parsenodes.h:2685
#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:557
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define INDOPTION_DESC
Definition: pg_index.h:99
List * indexParams
Definition: parsenodes.h:2687
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
List * excludeOpNames
Definition: parsenodes.h:2690
bool initdeferred
Definition: parsenodes.h:2698
bool amcanorder
Definition: amapi.h:171
char * name
Definition: parsenodes.h:688
char * idxcomment
Definition: parsenodes.h:2691
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:3475
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
bool concurrent
Definition: parsenodes.h:2700
bool isconstraint
Definition: parsenodes.h:2696
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:499
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:416
#define Anum_pg_constraint_conexclop
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
#define DatumGetArrayTypeP(X)
Definition: array.h:242
static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
char **  snamespace_p,
char **  sname_p 
)
static

Definition at line 358 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(), NULL, 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().

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

Definition at line 1569 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(), result, and SearchSysCache1.

Referenced by generateClonedIndexStmt().

1570 {
1571  List *result;
1572  HeapTuple ht_coll;
1573  Form_pg_collation coll_rec;
1574  char *nsp_name;
1575  char *coll_name;
1576 
1577  if (!OidIsValid(collation))
1578  return NIL; /* easy case */
1579  if (collation == get_typcollation(actual_datatype))
1580  return NIL; /* just let it default */
1581 
1582  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1583  if (!HeapTupleIsValid(ht_coll))
1584  elog(ERROR, "cache lookup failed for collation %u", collation);
1585  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1586 
1587  /* For simplicity, we always schema-qualify the name */
1588  nsp_name = get_namespace_name(coll_rec->collnamespace);
1589  coll_name = pstrdup(NameStr(coll_rec->collname));
1590  result = list_make2(makeString(nsp_name), makeString(coll_name));
1591 
1592  ReleaseSysCache(ht_coll);
1593  return result;
1594 }
#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:656
char * pstrdup(const char *in)
Definition: mcxt.c:1077
return result
Definition: formatting.c:1633
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:52
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
static List * get_opclass ( Oid  opclass,
Oid  actual_datatype 
)
static

Definition at line 1603 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1604 {
1605  List *result = NIL;
1606  HeapTuple ht_opc;
1607  Form_pg_opclass opc_rec;
1608 
1609  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1610  if (!HeapTupleIsValid(ht_opc))
1611  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1612  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1613 
1614  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1615  {
1616  /* For simplicity, we always schema-qualify the name */
1617  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1618  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1619 
1620  result = list_make2(makeString(nsp_name), makeString(opc_name));
1621  }
1622 
1623  ReleaseSysCache(ht_opc);
1624  return result;
1625 }
#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:1391
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1077
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
Definition: pg_list.h:45
static void setSchemaName ( char *  context_schema,
char **  stmt_schema_name 
)
static

Definition at line 3250 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3251 {
3252  if (*stmt_schema_name == NULL)
3253  *stmt_schema_name = context_schema;
3254  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3255  ereport(ERROR,
3256  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3257  errmsg("CREATE specifies a schema (%s) "
3258  "different from the one being created (%s)",
3259  *stmt_schema_name, context_schema)));
3260 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
List* transformAlterTableStmt ( Oid  relid,
AlterTableStmt stmt,
const char *  queryString 
)

Definition at line 2634 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, NULL, OBJECT_FOREIGN_TABLE, 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, result, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), ColumnDef::typeName, and typenameTypeId().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

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

Definition at line 2124 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2125 {
2126  ListCell *ckclist;
2127 
2128  if (cxt->ckconstraints == NIL)
2129  return;
2130 
2131  /*
2132  * If creating a new table, we can safely skip validation of check
2133  * constraints, and nonetheless mark them valid. (This will override any
2134  * user-supplied NOT VALID flag.)
2135  */
2136  if (skipValidation)
2137  {
2138  foreach(ckclist, cxt->ckconstraints)
2139  {
2140  Constraint *constraint = (Constraint *) lfirst(ckclist);
2141 
2142  constraint->skip_validation = true;
2143  constraint->initially_valid = true;
2144  }
2145  }
2146 }
#define NIL
Definition: pg_list.h:69
bool initially_valid
Definition: parsenodes.h:2106
#define lfirst(lc)
Definition: pg_list.h:106
bool skip_validation
Definition: parsenodes.h:2105
static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 501 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_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, FALSE, 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, NULL, OBJECT_FOREIGN_TABLE, Constraint::options, parser_errposition(), 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(), TRUE, Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

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

Definition at line 3092 of file parse_utilcmd.c.

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

Referenced by transformColumnDefinition().

3093 {
3094  /*
3095  * All we really need to do here is verify that the type is valid,
3096  * including any collation spec that might be present.
3097  */
3098  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3099 
3100  if (column->collClause)
3101  {
3102  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3103 
3104  LookupCollation(cxt->pstate,
3105  column->collClause->collname,
3106  column->collClause->location);
3107  /* Complain if COLLATE is applied to an uncollatable type */
3108  if (!OidIsValid(typtup->typcollation))
3109  ereport(ERROR,
3110  (errcode(ERRCODE_DATATYPE_MISMATCH),
3111  errmsg("collations are not supported by type %s",
3114  column->collClause->location)));
3115  }
3116 
3117  ReleaseSysCache(ctype);
3118 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
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:538
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:1117
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
#define NULL
Definition: c.h:229
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:695
static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 2977 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, NULL, parser_errposition(), CreateStmtContext::pstate, and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition().

2978 {
2979  Constraint *lastprimarycon = NULL;
2980  bool saw_deferrability = false;
2981  bool saw_initially = false;
2982  ListCell *clist;
2983 
2984 #define SUPPORTS_ATTRS(node) \
2985  ((node) != NULL && \
2986  ((node)->contype == CONSTR_PRIMARY || \
2987  (node)->contype == CONSTR_UNIQUE || \
2988  (node)->contype == CONSTR_EXCLUSION || \
2989  (node)->contype == CONSTR_FOREIGN))
2990 
2991  foreach(clist, constraintList)
2992  {
2993  Constraint *con = (Constraint *) lfirst(clist);
2994 
2995  if (!IsA(con, Constraint))
2996  elog(ERROR, "unrecognized node type: %d",
2997  (int) nodeTag(con));
2998  switch (con->contype)
2999  {
3001  if (!SUPPORTS_ATTRS(lastprimarycon))
3002  ereport(ERROR,
3003  (errcode(ERRCODE_SYNTAX_ERROR),
3004  errmsg("misplaced DEFERRABLE clause"),
3005  parser_errposition(cxt->pstate, con->location)));
3006  if (saw_deferrability)
3007  ereport(ERROR,
3008  (errcode(ERRCODE_SYNTAX_ERROR),
3009  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3010  parser_errposition(cxt->pstate, con->location)));
3011  saw_deferrability = true;
3012  lastprimarycon->deferrable = true;
3013  break;
3014 
3016  if (!SUPPORTS_ATTRS(lastprimarycon))
3017  ereport(ERROR,
3018  (errcode(ERRCODE_SYNTAX_ERROR),
3019  errmsg("misplaced NOT DEFERRABLE clause"),
3020  parser_errposition(cxt->pstate, con->location)));
3021  if (saw_deferrability)
3022  ereport(ERROR,
3023  (errcode(ERRCODE_SYNTAX_ERROR),
3024  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3025  parser_errposition(cxt->pstate, con->location)));
3026  saw_deferrability = true;
3027  lastprimarycon->deferrable = false;
3028  if (saw_initially &&
3029  lastprimarycon->initdeferred)
3030  ereport(ERROR,
3031  (errcode(ERRCODE_SYNTAX_ERROR),
3032  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3033  parser_errposition(cxt->pstate, con->location)));
3034  break;
3035 
3036  case CONSTR_ATTR_DEFERRED:
3037  if (!SUPPORTS_ATTRS(lastprimarycon))
3038  ereport(ERROR,
3039  (errcode(ERRCODE_SYNTAX_ERROR),
3040  errmsg("misplaced INITIALLY DEFERRED clause"),
3041  parser_errposition(cxt->pstate, con->location)));
3042  if (saw_initially)
3043  ereport(ERROR,
3044  (errcode(ERRCODE_SYNTAX_ERROR),
3045  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3046  parser_errposition(cxt->pstate, con->location)));
3047  saw_initially = true;
3048  lastprimarycon->initdeferred = true;
3049 
3050  /*
3051  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3052  */
3053  if (!saw_deferrability)
3054  lastprimarycon->deferrable = true;
3055  else if (!lastprimarycon->deferrable)
3056  ereport(ERROR,
3057  (errcode(ERRCODE_SYNTAX_ERROR),
3058  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3059  parser_errposition(cxt->pstate, con->location)));
3060  break;
3061 
3062  case CONSTR_ATTR_IMMEDIATE:
3063  if (!SUPPORTS_ATTRS(lastprimarycon))
3064  ereport(ERROR,
3065  (errcode(ERRCODE_SYNTAX_ERROR),
3066  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3067  parser_errposition(cxt->pstate, con->location)));
3068  if (saw_initially)
3069  ereport(ERROR,
3070  (errcode(ERRCODE_SYNTAX_ERROR),
3071  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3072  parser_errposition(cxt->pstate, con->location)));
3073  saw_initially = true;
3074  lastprimarycon->initdeferred = false;
3075  break;
3076 
3077  default:
3078  /* Otherwise it's not an attribute */
3079  lastprimarycon = con;
3080  /* reset flags for new primary node */
3081  saw_deferrability = false;
3082  saw_initially = false;
3083  break;
3084  }
3085  }
3086 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:2070
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2069
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
#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:514
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SUPPORTS_ATTRS(node)
ConstrType contype
Definition: parsenodes.h:2065
#define elog
Definition: elog.h:219
List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3145 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, result, 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().

3146 {
3148  List *result;
3149  ListCell *elements;
3150 
3151  cxt.stmtType = "CREATE SCHEMA";
3152  cxt.schemaname = stmt->schemaname;
3153  cxt.authrole = (RoleSpec *) stmt->authrole;
3154  cxt.sequences = NIL;
3155  cxt.tables = NIL;
3156  cxt.views = NIL;
3157  cxt.indexes = NIL;
3158  cxt.triggers = NIL;
3159  cxt.grants = NIL;
3160 
3161  /*
3162  * Run through each schema element in the schema element list. Separate
3163  * statements by type, and do preliminary analysis.
3164  */
3165  foreach(elements, stmt->schemaElts)
3166  {
3167  Node *element = lfirst(elements);
3168 
3169  switch (nodeTag(element))
3170  {
3171  case T_CreateSeqStmt:
3172  {
3173  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3174 
3176  cxt.sequences = lappend(cxt.sequences, element);
3177  }
3178  break;
3179 
3180  case T_CreateStmt:
3181  {
3182  CreateStmt *elp = (CreateStmt *) element;
3183 
3185 
3186  /*
3187  * XXX todo: deal with constraints
3188  */
3189  cxt.tables = lappend(cxt.tables, element);
3190  }
3191  break;
3192 
3193  case T_ViewStmt:
3194  {
3195  ViewStmt *elp = (ViewStmt *) element;
3196 
3197  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3198 
3199  /*
3200  * XXX todo: deal with references between views
3201  */
3202  cxt.views = lappend(cxt.views, element);
3203  }
3204  break;
3205 
3206  case T_IndexStmt:
3207  {
3208  IndexStmt *elp = (IndexStmt *) element;
3209 
3211  cxt.indexes = lappend(cxt.indexes, element);
3212  }
3213  break;
3214 
3215  case T_CreateTrigStmt:
3216  {
3217  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3218 
3220  cxt.triggers = lappend(cxt.triggers, element);
3221  }
3222  break;
3223 
3224  case T_GrantStmt:
3225  cxt.grants = lappend(cxt.grants, element);
3226  break;
3227 
3228  default:
3229  elog(ERROR, "unrecognized node type: %d",
3230  (int) nodeTag(element));
3231  }
3232  }
3233 
3234  result = NIL;
3235  result = list_concat(result, cxt.sequences);
3236  result = list_concat(result, cxt.tables);
3237  result = list_concat(result, cxt.views);
3238  result = list_concat(result, cxt.indexes);
3239  result = list_concat(result, cxt.triggers);
3240  result = list_concat(result, cxt.grants);
3241 
3242  return result;
3243 }
RangeVar * relation
Definition: parsenodes.h:1987
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:509
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1633
RangeVar * view
Definition: parsenodes.h:2985
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2684
RoleSpec * authrole
Definition: parsenodes.h:1659
#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:2454
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:514
RangeVar * relation
Definition: parsenodes.h:2339
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 157 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, NULL, CreateStmt::ofTypename, OidIsValid, CreateStmt::options, ParseState::p_sourcetext, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RELPERSISTENCE_TEMP, result, 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().

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

Definition at line 2153 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, NULL, OBJECT_TABLE, CreateStmtContext::relation, AlterTableStmt::relation, AlterTableStmt::relkind, Constraint::skip_validation, and AlterTableCmd::subtype.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2155 {
2156  ListCell *fkclist;
2157 
2158  if (cxt->fkconstraints == NIL)
2159  return;
2160 
2161  /*
2162  * If CREATE TABLE or adding a column with NULL default, we can safely
2163  * skip validation of FK constraints, and nonetheless mark them valid.
2164  * (This will override any user-supplied NOT VALID flag.)
2165  */
2166  if (skipValidation)
2167  {
2168  foreach(fkclist, cxt->fkconstraints)
2169  {
2170  Constraint *constraint = (Constraint *) lfirst(fkclist);
2171 
2172  constraint->skip_validation = true;
2173  constraint->initially_valid = true;
2174  }
2175  }
2176 
2177  /*
2178  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2179  * CONSTRAINT command to execute after the basic command is complete. (If
2180  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2181  * its own subcommand list.)
2182  *
2183  * Note: the ADD CONSTRAINT command must also execute after any index
2184  * creation commands. Thus, this should run after
2185  * transformIndexConstraints, so that the CREATE INDEX commands are
2186  * already in cxt->alist.
2187  */
2188  if (!isAddConstraint)
2189  {
2190  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2191 
2192  alterstmt->relation = cxt->relation;
2193  alterstmt->cmds = NIL;
2194  alterstmt->relkind = OBJECT_TABLE;
2195 
2196  foreach(fkclist, cxt->fkconstraints)
2197  {
2198  Constraint *constraint = (Constraint *) lfirst(fkclist);
2199  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2200 
2201  altercmd->subtype = AT_ProcessedConstraint;
2202  altercmd->name = NULL;
2203  altercmd->def = (Node *) constraint;
2204  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2205  }
2206 
2207  cxt->alist = lappend(cxt->alist, alterstmt);
2208  }
2209 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:509
AlterTableType subtype
Definition: parsenodes.h:1764
RangeVar * relation
Definition: parse_utilcmd.c:77
ObjectType relkind
Definition: parsenodes.h:1679
List * lappend(List *list, void *datum)
Definition: list.c:128
bool initially_valid
Definition: parsenodes.h:2106
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
RangeVar * relation
Definition: parsenodes.h:1677
bool skip_validation
Definition: parsenodes.h:2105
static IndexStmt * transformIndexConstraint ( Constraint constraint,
CreateStmtContext cxt 
)
static

Definition at line 1742 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, Anum_pg_index_indclass, Assert, tupleDesc::attrs, 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, NULL, 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, TRUE, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

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

Definition at line 1635 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, NULL, CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::relation, RangeVar::relname, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1636 {
1637  IndexStmt *index;
1638  List *indexlist = NIL;
1639  ListCell *lc;
1640 
1641  /*
1642  * Run through the constraints that need to generate an index. For PRIMARY
1643  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1644  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1645  * NULL.
1646  */
1647  foreach(lc, cxt->ixconstraints)
1648  {
1649  Constraint *constraint = lfirst_node(Constraint, lc);
1650 
1651  Assert(constraint->contype == CONSTR_PRIMARY ||
1652  constraint->contype == CONSTR_UNIQUE ||
1653  constraint->contype == CONSTR_EXCLUSION);
1654 
1655  index = transformIndexConstraint(constraint, cxt);
1656 
1657  indexlist = lappend(indexlist, index);
1658  }
1659 
1660  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1661  foreach(lc, cxt->inh_indexes)
1662  {
1663  index = (IndexStmt *) lfirst(lc);
1664 
1665  if (index->primary)
1666  {
1667  if (cxt->pkey != NULL)
1668  ereport(ERROR,
1669  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1670  errmsg("multiple primary keys for table \"%s\" are not allowed",
1671  cxt->relation->relname)));
1672  cxt->pkey = index;
1673  }
1674 
1675  indexlist = lappend(indexlist, index);
1676  }
1677 
1678  /*
1679  * Scan the index list and remove any redundant index specifications. This
1680  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1681  * strict reading of SQL would suggest raising an error instead, but that
1682  * strikes me as too anal-retentive. - tgl 2001-02-14
1683  *
1684  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1685  * pre-existing indexes, too.
1686  */
1687  Assert(cxt->alist == NIL);
1688  if (cxt->pkey != NULL)
1689  {
1690  /* Make sure we keep the PKEY index in preference to others... */
1691  cxt->alist = list_make1(cxt->pkey);
1692  }
1693 
1694  foreach(lc, indexlist)
1695  {
1696  bool keep = true;
1697  ListCell *k;
1698 
1699  index = lfirst(lc);
1700 
1701  /* if it's pkey, it's already in cxt->alist */
1702  if (index == cxt->pkey)
1703  continue;
1704 
1705  foreach(k, cxt->alist)
1706  {
1707  IndexStmt *priorindex = lfirst(k);
1708 
1709  if (equal(index->indexParams, priorindex->indexParams) &&
1710  equal(index->whereClause, priorindex->whereClause) &&
1711  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1712  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1713  index->deferrable == priorindex->deferrable &&
1714  index->initdeferred == priorindex->initdeferred)
1715  {
1716  priorindex->unique |= index->unique;
1717 
1718  /*
1719  * If the prior index is as yet unnamed, and this one is
1720  * named, then transfer the name to the prior index. This
1721  * ensures that if we have named and unnamed constraints,
1722  * we'll use (at least one of) the names for the index.
1723  */
1724  if (priorindex->idxname == NULL)
1725  priorindex->idxname = index->idxname;
1726  keep = false;
1727  break;
1728  }
1729  }
1730 
1731  if (keep)
1732  cxt->alist = lappend(cxt->alist, index);
1733  }
1734 }
bool deferrable
Definition: parsenodes.h:2697
#define NIL
Definition: pg_list.h:69
bool primary
Definition: parsenodes.h:2695
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
Node * whereClause
Definition: parsenodes.h:2689
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:2683
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2694
char * accessMethod
Definition: parsenodes.h:2685
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2687
List * excludeOpNames
Definition: parsenodes.h:2690
bool initdeferred
Definition: parsenodes.h:2698
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConstrType contype
Definition: parsenodes.h:2065
Definition: pg_list.h:45
IndexStmt* transformIndexStmt ( Oid  relid,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 2224 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, NULL, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), IndexStmt::transformed, transformExpr(), transformWhereClause(), and IndexStmt::whereClause.

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

2225 {
2226  ParseState *pstate;
2227  RangeTblEntry *rte;
2228  ListCell *l;
2229  Relation rel;
2230 
2231  /* Nothing to do if statement already transformed. */
2232  if (stmt->transformed)
2233  return stmt;
2234 
2235  /*
2236  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2237  * overkill, but easy.)
2238  */
2239  stmt = copyObject(stmt);
2240 
2241  /* Set up pstate */
2242  pstate = make_parsestate(NULL);
2243  pstate->p_sourcetext = queryString;
2244 
2245  /*
2246  * Put the parent table into the rtable so that the expressions can refer
2247  * to its fields without qualification. Caller is responsible for locking
2248  * relation, but we still need to open it.
2249  */
2250  rel = relation_open(relid, NoLock);
2251  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2252 
2253  /* no to join list, yes to namespaces */
2254  addRTEtoQuery(pstate, rte, false, true, true);
2255 
2256  /* take care of the where clause */
2257  if (stmt->whereClause)
2258  {
2259  stmt->whereClause = transformWhereClause(pstate,
2260  stmt->whereClause,
2262  "WHERE");
2263  /* we have to fix its collations too */
2264  assign_expr_collations(pstate, stmt->whereClause);
2265  }
2266 
2267  /* take care of any index expressions */
2268  foreach(l, stmt->indexParams)
2269  {
2270  IndexElem *ielem = (IndexElem *) lfirst(l);
2271 
2272  if (ielem->expr)
2273  {
2274  /* Extract preliminary index col name before transforming expr */
2275  if (ielem->indexcolname == NULL)
2276  ielem->indexcolname = FigureIndexColname(ielem->expr);
2277 
2278  /* Now do parse transformation of the expression */
2279  ielem->expr = transformExpr(pstate, ielem->expr,
2281 
2282  /* We have to fix its collations too */
2283  assign_expr_collations(pstate, ielem->expr);
2284 
2285  /*
2286  * transformExpr() should have already rejected subqueries,
2287  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2288  * for an index expression.
2289  *
2290  * DefineIndex() will make more checks.
2291  */
2292  }
2293  }
2294 
2295  /*
2296  * Check that only the base rel is mentioned. (This should be dead code
2297  * now that add_missing_from is history.)
2298  */
2299  if (list_length(pstate->p_rtable) != 1)
2300  ereport(ERROR,
2301  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2302  errmsg("index expressions and predicates can refer only to the table being indexed")));
2303 
2304  free_parsestate(pstate);
2305 
2306  /* Close relation */
2307  heap_close(rel, NoLock);
2308 
2309  /* Mark statement as successfully transformed */
2310  stmt->transformed = true;
2311 
2312  return stmt;
2313 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Node * whereClause
Definition: parsenodes.h:2689
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:2699
char * indexcolname
Definition: parsenodes.h:690
const char * p_sourcetext
Definition: parse_node.h:171
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2687
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:1114
#define copyObject(obj)
Definition: nodes.h:622
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:172
static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1204 of file parse_utilcmd.c.

References AssertArg, tupleDesc::attrs, 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, NULL, pstrdup(), ColumnDef::raw_default, ReleaseSysCache(), ColumnDef::storage, ColumnDef::typeName, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

1205 {
1206  HeapTuple tuple;
1207  TupleDesc tupdesc;
1208  int i;
1209  Oid ofTypeId;
1210 
1211  AssertArg(ofTypename);
1212 
1213  tuple = typenameType(NULL, ofTypename, NULL);
1214  check_of_type(tuple);
1215  ofTypeId = HeapTupleGetOid(tuple);
1216  ofTypename->typeOid = ofTypeId; /* cached for later */
1217 
1218  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1219  for (i = 0; i < tupdesc->natts; i++)
1220  {
1221  Form_pg_attribute attr = tupdesc->attrs[i];
1222  ColumnDef *n;
1223 
1224  if (attr->attisdropped)
1225  continue;
1226 
1227  n = makeNode(ColumnDef);
1228  n->colname = pstrdup(NameStr(attr->attname));
1229  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1230  n->inhcount = 0;
1231  n->is_local = true;
1232  n->is_not_null = false;
1233  n->is_from_type = true;
1234  n->is_from_parent = false;
1235  n->storage = 0;
1236  n->raw_default = NULL;
1237  n->cooked_default = NULL;
1238  n->collClause = NULL;
1239  n->collOid = attr->attcollation;
1240  n->constraints = NIL;
1241  n->location = -1;
1242  cxt->columns = lappend(cxt->columns, n);
1243  }
1244  DecrTupleDescRefCount(tupdesc);
1245 
1246  ReleaseSysCache(tuple);
1247 }
#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:1257
bool is_local
Definition: parsenodes.h:642
List * constraints
Definition: parsenodes.h:652
char * pstrdup(const char *in)
Definition: mcxt.c:1077
bool is_from_parent
Definition: parsenodes.h:645
Form_pg_attribute * attrs
Definition: tupdesc.h:74
bool is_not_null
Definition: parsenodes.h:643
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
Node * cooked_default
Definition: parsenodes.h:648
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5019
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:677
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:469
bool is_from_type
Definition: parsenodes.h:644
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:336
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:499
char * colname
Definition: parsenodes.h:639
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
PartitionBoundSpec* transformPartitionBound ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 3294 of file parse_utilcmd.c.

References 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, PartitionRangeDatum::infinite, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), PartitionBoundSpec::upperdatums, value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3296 {
3297  PartitionBoundSpec *result_spec;
3298  PartitionKey key = RelationGetPartitionKey(parent);
3299  char strategy = get_partition_strategy(key);
3300  int partnatts = get_partition_natts(key);
3301  List *partexprs = get_partition_exprs(key);
3302 
3303  /* Avoid scribbling on input */
3304  result_spec = copyObject(spec);
3305 
3306  if (strategy == PARTITION_STRATEGY_LIST)
3307  {
3308  ListCell *cell;
3309  char *colname;
3310  Oid coltype;
3311  int32 coltypmod;
3312 
3313  if (spec->strategy != PARTITION_STRATEGY_LIST)
3314  ereport(ERROR,
3315  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3316  errmsg("invalid bound specification for a list partition"),
3317  parser_errposition(pstate, exprLocation((Node *) spec))));
3318 
3319  /* Get the only column's name in case we need to output an error */
3320  if (key->partattrs[0] != 0)
3321  colname = get_relid_attribute_name(RelationGetRelid(parent),
3322  key->partattrs[0]);
3323  else
3324  colname = deparse_expression((Node *) linitial(partexprs),
3326  RelationGetRelid(parent)),
3327  false, false);
3328  /* Need its type data too */
3329  coltype = get_partition_col_typid(key, 0);
3330  coltypmod = get_partition_col_typmod(key, 0);
3331 
3332  result_spec->listdatums = NIL;
3333  foreach(cell, spec->listdatums)
3334  {
3335  A_Const *con = castNode(A_Const, lfirst(cell));
3336  Const *value;
3337  ListCell *cell2;
3338  bool duplicate;
3339 
3340  value = transformPartitionBoundValue(pstate, con,
3341  colname, coltype, coltypmod);
3342 
3343  /* Don't add to the result if the value is a duplicate */
3344  duplicate = false;
3345  foreach(cell2, result_spec->listdatums)
3346  {
3347  Const *value2 = castNode(Const, lfirst(cell2));
3348 
3349  if (equal(value, value2))
3350  {
3351  duplicate = true;
3352  break;
3353  }
3354  }
3355  if (duplicate)
3356  continue;
3357 
3358  result_spec->listdatums = lappend(result_spec->listdatums,
3359  value);
3360  }
3361  }
3362  else if (strategy == PARTITION_STRATEGY_RANGE)
3363  {
3364  ListCell *cell1,
3365  *cell2;
3366  int i,
3367  j;
3368  bool seen_unbounded;
3369 
3370  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3371  ereport(ERROR,
3372  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3373  errmsg("invalid bound specification for a range partition"),
3374  parser_errposition(pstate, exprLocation((Node *) spec))));
3375 
3376  if (list_length(spec->lowerdatums) != partnatts)
3377  ereport(ERROR,
3378  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3379  errmsg("FROM must specify exactly one value per partitioning column")));
3380  if (list_length(spec->upperdatums) != partnatts)
3381  ereport(ERROR,
3382  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3383  errmsg("TO must specify exactly one value per partitioning column")));
3384 
3385  /*
3386  * Check that no finite value follows an UNBOUNDED item in either of
3387  * lower and upper bound lists.
3388  */
3389  seen_unbounded = false;
3390  foreach(cell1, spec->lowerdatums)
3391  {
3393  lfirst(cell1));
3394 
3395  if (ldatum->infinite)
3396  seen_unbounded = true;
3397  else if (seen_unbounded)
3398  ereport(ERROR,
3399  (errcode(ERRCODE_DATATYPE_MISMATCH),
3400  errmsg("cannot specify finite value after UNBOUNDED"),
3401  parser_errposition(pstate, exprLocation((Node *) ldatum))));
3402  }
3403  seen_unbounded = false;
3404  foreach(cell1, spec->upperdatums)
3405  {
3407  lfirst(cell1));
3408 
3409  if (rdatum->infinite)
3410  seen_unbounded = true;
3411  else if (seen_unbounded)
3412  ereport(ERROR,
3413  (errcode(ERRCODE_DATATYPE_MISMATCH),
3414  errmsg("cannot specify finite value after UNBOUNDED"),
3415  parser_errposition(pstate, exprLocation((Node *) rdatum))));
3416  }
3417 
3418  /* Transform all the constants */
3419  i = j = 0;
3420  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3421  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3422  {
3423  PartitionRangeDatum *ldatum = (PartitionRangeDatum *) lfirst(cell1);
3424  PartitionRangeDatum *rdatum = (PartitionRangeDatum *) lfirst(cell2);
3425  char *colname;
3426  Oid coltype;
3427  int32 coltypmod;
3428  A_Const *con;
3429  Const *value;
3430 
3431  /* Get the column's name in case we need to output an error */
3432  if (key->partattrs[i] != 0)
3433  colname = get_relid_attribute_name(RelationGetRelid(parent),
3434  key->partattrs[i]);
3435  else
3436  {
3437  colname = deparse_expression((Node *) list_nth(partexprs, j),
3439  RelationGetRelid(parent)),
3440  false, false);
3441  ++j;
3442  }
3443  /* Need its type data too */
3444  coltype = get_partition_col_typid(key, i);
3445  coltypmod = get_partition_col_typmod(key, i);
3446 
3447  if (ldatum->value)
3448  {
3449  con = castNode(A_Const, ldatum->value);
3450  value = transformPartitionBoundValue(pstate, con,
3451  colname,
3452  coltype, coltypmod);
3453  if (value->constisnull)
3454  ereport(ERROR,
3455  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3456  errmsg("cannot specify NULL in range bound")));
3457  ldatum = copyObject(ldatum); /* don't scribble on input */
3458  ldatum->value = (Node *) value;
3459  }
3460 
3461  if (rdatum->value)
3462  {
3463  con = castNode(A_Const, rdatum->value);
3464  value = transformPartitionBoundValue(pstate, con,
3465  colname,
3466  coltype, coltypmod);
3467  if (value->constisnull)
3468  ereport(ERROR,
3469  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3470  errmsg("cannot specify NULL in range bound")));
3471  rdatum = copyObject(rdatum); /* don't scribble on input */
3472  rdatum->value = (Node *) value;
3473  }
3474 
3475  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3476  ldatum);
3477  result_spec->upperdatums = lappend(result_spec->upperdatums,
3478  rdatum);
3479 
3480  ++i;
3481  }
3482  }
3483  else
3484  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3485 
3486  return result_spec;
3487 }
#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:2962
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
Definition: nodes.h:509
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:256
static int get_partition_natts(PartitionKey key)
Definition: rel.h:596
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static struct @121 value
void * list_nth(const List *list, int n)
Definition: list.c:410
static List * get_partition_exprs(PartitionKey key)
Definition: rel.h:602
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3036
#define RelationGetRelationName(relation)
Definition: rel.h:436
#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:623
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:617
static int get_partition_strategy(PartitionKey key)
Definition: rel.h:590
#define lfirst(lc)
Definition: pg_list.h:106
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:2977
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:786
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:787
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:622
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
bool constisnull
Definition: primnodes.h:197
static Const * transformPartitionBoundValue ( ParseState pstate,
A_Const con,
const char *  colName,
Oid  colType,
int32  colTypmod 
)
static

Definition at line 3493 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(), NULL, parser_errposition(), A_Const::val, and value.

Referenced by transformPartitionBound().

3495 {
3496  Node *value;
3497 
3498  /* Make it into a Const */
3499  value = (Node *) make_const(pstate, &con->val, con->location);
3500 
3501  /* Coerce to correct type */
3502  value = coerce_to_target_type(pstate,
3503  value, exprType(value),
3504  colType,
3505  colTypmod,
3508  -1);
3509 
3510  if (value == NULL)
3511  ereport(ERROR,
3512  (errcode(ERRCODE_DATATYPE_MISMATCH),
3513  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3514  format_type_be(colType), colName),
3515  parser_errposition(pstate, con->location)));
3516 
3517  /* Simplify the expression, in case we had a coercion */
3518  if (!IsA(value, Const))
3519  value = (Node *) expression_planner((Expr *) value);
3520 
3521  /* Fail if we don't have a constant (i.e., non-immutable coercion) */
3522  if (!IsA(value, Const))
3523  ereport(ERROR,
3524  (errcode(ERRCODE_DATATYPE_MISMATCH),
3525  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3526  format_type_be(colType), colName),
3527  errdetail("The cast requires a non-immutable conversion."),
3528  errhint("Try putting the literal value in single quotes."),
3529  parser_errposition(pstate, con->location)));
3530 
3531  return (Const *) value;
3532 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int errhint(const char *fmt,...)
Definition: elog.c:987
Expr * expression_planner(Expr *expr)
Definition: planner.c:5931
Definition: nodes.h:509
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:77
static struct @121 value
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
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
static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 3270 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt().

3271 {
3272  Relation parentRel = cxt->rel;
3273 
3274  /* the table must be partitioned */
3275  if (parentRel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3276  ereport(ERROR,
3277  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3278  errmsg("\"%s\" is not partitioned",
3279  RelationGetRelationName(parentRel))));
3280 
3281  /* transform the partition bound, if any */
3282  Assert(RelationGetPartitionKey(parentRel) != NULL);
3283  if (cmd->bound != NULL)
3284  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3285  cmd->bound);
3286 }
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:436
#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 NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
PartitionBoundSpec * bound
Definition: parsenodes.h:833
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
int errmsg(const char *fmt,...)
Definition: elog.c:797
void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 2329 of file parse_utilcmd.c.

References AccessExclusiveLock, 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(), FromExpr::fromlist, getInsertSelectQuery(), heap_close, heap_openrv(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, NULL, 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().

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

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

803 {
804  switch (constraint->contype)
805  {
806  case CONSTR_PRIMARY:
807  if (cxt->isforeign)
808  ereport(ERROR,
809  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
810  errmsg("primary key constraints are not supported on foreign tables"),
812  constraint->location)));
813  if (cxt->ispartitioned)
814  ereport(ERROR,
815  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
816  errmsg("primary key constraints are not supported on partitioned tables"),
818  constraint->location)));
819  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
820  break;
821 
822  case CONSTR_UNIQUE:
823  if (cxt->isforeign)
824  ereport(ERROR,
825  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
826  errmsg("unique constraints are not supported on foreign tables"),
828  constraint->location)));
829  if (cxt->ispartitioned)
830  ereport(ERROR,
831  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
832  errmsg("unique constraints are not supported on partitioned tables"),
834  constraint->location)));
835  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
836  break;
837 
838  case CONSTR_EXCLUSION:
839  if (cxt->isforeign)
840  ereport(ERROR,
841  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
842  errmsg("exclusion constraints are not supported on foreign tables"),
844  constraint->location)));
845  if (cxt->ispartitioned)
846  ereport(ERROR,
847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
848  errmsg("exclusion constraints are not supported on partitioned tables"),
850  constraint->location)));
851  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
852  break;
853 
854  case CONSTR_CHECK:
855  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
856  break;
857 
858  case CONSTR_FOREIGN:
859  if (cxt->