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)
 
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)
 
NodetransformPartitionBound (ParseState *pstate, Relation parent, Node *bound)
 

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

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

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

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

1562 {
1563  List *result;
1564  HeapTuple ht_coll;
1565  Form_pg_collation coll_rec;
1566  char *nsp_name;
1567  char *coll_name;
1568 
1569  if (!OidIsValid(collation))
1570  return NIL; /* easy case */
1571  if (collation == get_typcollation(actual_datatype))
1572  return NIL; /* just let it default */
1573 
1574  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1575  if (!HeapTupleIsValid(ht_coll))
1576  elog(ERROR, "cache lookup failed for collation %u", collation);
1577  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1578 
1579  /* For simplicity, we always schema-qualify the name */
1580  nsp_name = get_namespace_name(coll_rec->collnamespace);
1581  coll_name = pstrdup(NameStr(coll_rec->collname));
1582  result = list_make2(makeString(nsp_name), makeString(coll_name));
1583 
1584  ReleaseSysCache(ht_coll);
1585  return result;
1586 }
#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:1632
#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 1595 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().

1596 {
1597  List *result = NIL;
1598  HeapTuple ht_opc;
1599  Form_pg_opclass opc_rec;
1600 
1601  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1602  if (!HeapTupleIsValid(ht_opc))
1603  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1604  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1605 
1606  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1607  {
1608  /* For simplicity, we always schema-qualify the name */
1609  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1610  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1611 
1612  result = list_make2(makeString(nsp_name), makeString(opc_name));
1613  }
1614 
1615  ReleaseSysCache(ht_opc);
1616  return result;
1617 }
#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:1378
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1077
return result
Definition: formatting.c:1632
#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 3242 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3243 {
3244  if (*stmt_schema_name == NULL)
3245  *stmt_schema_name = context_schema;
3246  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3247  ereport(ERROR,
3248  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3249  errmsg("CREATE specifies a schema (%s) "
3250  "different from the one being created (%s)",
3251  *stmt_schema_name, context_schema)));
3252 }
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 2626 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().

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

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

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

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

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

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

3085 {
3086  /*
3087  * All we really need to do here is verify that the type is valid,
3088  * including any collation spec that might be present.
3089  */
3090  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3091 
3092  if (column->collClause)
3093  {
3094  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3095 
3096  LookupCollation(cxt->pstate,
3097  column->collClause->collname,
3098  column->collClause->location);
3099  /* Complain if COLLATE is applied to an uncollatable type */
3100  if (!OidIsValid(typtup->typcollation))
3101  ereport(ERROR,
3102  (errcode(ERRCODE_DATATYPE_MISMATCH),
3103  errmsg("collations are not supported by type %s",
3106  column->collClause->location)));
3107  }
3108 
3109  ReleaseSysCache(ctype);
3110 }
#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:641
CollateClause * collClause
Definition: parsenodes.h:651
List * collname
Definition: parsenodes.h:310
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 2969 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().

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

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

3138 {
3140  List *result;
3141  ListCell *elements;
3142 
3143  cxt.stmtType = "CREATE SCHEMA";
3144  cxt.schemaname = stmt->schemaname;
3145  cxt.authrole = (RoleSpec *) stmt->authrole;
3146  cxt.sequences = NIL;
3147  cxt.tables = NIL;
3148  cxt.views = NIL;
3149  cxt.indexes = NIL;
3150  cxt.triggers = NIL;
3151  cxt.grants = NIL;
3152 
3153  /*
3154  * Run through each schema element in the schema element list. Separate
3155  * statements by type, and do preliminary analysis.
3156  */
3157  foreach(elements, stmt->schemaElts)
3158  {
3159  Node *element = lfirst(elements);
3160 
3161  switch (nodeTag(element))
3162  {
3163  case T_CreateSeqStmt:
3164  {
3165  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3166 
3168  cxt.sequences = lappend(cxt.sequences, element);
3169  }
3170  break;
3171 
3172  case T_CreateStmt:
3173  {
3174  CreateStmt *elp = (CreateStmt *) element;
3175 
3177 
3178  /*
3179  * XXX todo: deal with constraints
3180  */
3181  cxt.tables = lappend(cxt.tables, element);
3182  }
3183  break;
3184 
3185  case T_ViewStmt:
3186  {
3187  ViewStmt *elp = (ViewStmt *) element;
3188 
3189  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3190 
3191  /*
3192  * XXX todo: deal with references between views
3193  */
3194  cxt.views = lappend(cxt.views, element);
3195  }
3196  break;
3197 
3198  case T_IndexStmt:
3199  {
3200  IndexStmt *elp = (IndexStmt *) element;
3201 
3203  cxt.indexes = lappend(cxt.indexes, element);
3204  }
3205  break;
3206 
3207  case T_CreateTrigStmt:
3208  {
3209  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3210 
3212  cxt.triggers = lappend(cxt.triggers, element);
3213  }
3214  break;
3215 
3216  case T_GrantStmt:
3217  cxt.grants = lappend(cxt.grants, element);
3218  break;
3219 
3220  default:
3221  elog(ERROR, "unrecognized node type: %d",
3222  (int) nodeTag(element));
3223  }
3224  }
3225 
3226  result = NIL;
3227  result = list_concat(result, cxt.sequences);
3228  result = list_concat(result, cxt.tables);
3229  result = list_concat(result, cxt.views);
3230  result = list_concat(result, cxt.indexes);
3231  result = list_concat(result, cxt.triggers);
3232  result = list_concat(result, cxt.grants);
3233 
3234  return result;
3235 }
RangeVar * relation
Definition: parsenodes.h:1968
#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:1632
RangeVar * view
Definition: parsenodes.h:2965
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2664
RoleSpec * authrole
Definition: parsenodes.h:1640
#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:2434
#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:2319
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 155 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(), list_length(), RangeVar::location, make_parsestate(), makeDefElem(), makeInteger(), NIL, nodeTag, NoLock, NOTICE, NULL, CreateStmt::ofTypename, OidIsValid, CreateStmt::options, ParseState::p_sourcetext, CreateStmt::partbound, PARTITION_MAX_KEYS, PartitionSpec::partParams, CreateStmt::partspec, pg_strcasecmp(), 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, PartitionSpec::strategy, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

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

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

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

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

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

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

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

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

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

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

1197 {
1198  HeapTuple tuple;
1199  TupleDesc tupdesc;
1200  int i;
1201  Oid ofTypeId;
1202 
1203  AssertArg(ofTypename);
1204 
1205  tuple = typenameType(NULL, ofTypename, NULL);
1206  check_of_type(tuple);
1207  ofTypeId = HeapTupleGetOid(tuple);
1208  ofTypename->typeOid = ofTypeId; /* cached for later */
1209 
1210  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1211  for (i = 0; i < tupdesc->natts; i++)
1212  {
1213  Form_pg_attribute attr = tupdesc->attrs[i];
1214  ColumnDef *n;
1215 
1216  if (attr->attisdropped)
1217  continue;
1218 
1219  n = makeNode(ColumnDef);
1220  n->colname = pstrdup(NameStr(attr->attname));
1221  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1222  n->inhcount = 0;
1223  n->is_local = true;
1224  n->is_not_null = false;
1225  n->is_from_type = true;
1226  n->is_from_parent = false;
1227  n->storage = 0;
1228  n->raw_default = NULL;
1229  n->cooked_default = NULL;
1230  n->collClause = NULL;
1231  n->collOid = attr->attcollation;
1232  n->constraints = NIL;
1233  n->location = -1;
1234  cxt->columns = lappend(cxt->columns, n);
1235  }
1236  DecrTupleDescRefCount(tupdesc);
1237 
1238  ReleaseSysCache(tuple);
1239 }
#define NIL
Definition: pg_list.h:69
Oid typeOid
Definition: parsenodes.h:210
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
char storage
Definition: parsenodes.h:647
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1257
bool is_local
Definition: parsenodes.h:643
List * constraints
Definition: parsenodes.h:653
char * pstrdup(const char *in)
Definition: mcxt.c:1077
bool is_from_parent
Definition: parsenodes.h:646
Form_pg_attribute * attrs
Definition: tupdesc.h:74
bool is_not_null
Definition: parsenodes.h:644
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
Node * cooked_default
Definition: parsenodes.h:649
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5010
Oid collOid
Definition: parsenodes.h:652
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int location
Definition: parsenodes.h:655
#define AssertArg(condition)
Definition: c.h:677
Node * raw_default
Definition: parsenodes.h:648
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:645
#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:641
CollateClause * collClause
Definition: parsenodes.h:651
int i
int inhcount
Definition: parsenodes.h:642
#define NameStr(name)
Definition: c.h:499
char * colname
Definition: parsenodes.h:640
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
Node* transformPartitionBound ( ParseState pstate,
Relation  parent,
Node bound 
)

Definition at line 3286 of file parse_utilcmd.c.

References Assert, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, expression_planner(), exprLocation(), exprType(), forboth, format_type_be(), 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, A_Const::location, PartitionBoundSpec::lowerdatums, make_const(), NIL, NULL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, PartitionBoundSpec::upperdatums, A_Const::val, value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3287 {
3288  PartitionBoundSpec *spec = (PartitionBoundSpec *) bound,
3289  *result_spec;
3290  PartitionKey key = RelationGetPartitionKey(parent);
3291  char strategy = get_partition_strategy(key);
3292  int partnatts = get_partition_natts(key);
3293  List *partexprs = get_partition_exprs(key);
3294 
3295  result_spec = copyObject(spec);
3296 
3297  if (strategy == PARTITION_STRATEGY_LIST)
3298  {
3299  ListCell *cell;
3300  char *colname;
3301 
3302  /* Get the only column's name in case we need to output an error */
3303  if (key->partattrs[0] != 0)
3304  colname = get_relid_attribute_name(RelationGetRelid(parent),
3305  key->partattrs[0]);
3306  else
3307  colname = deparse_expression((Node *) linitial(partexprs),
3309  RelationGetRelid(parent)),
3310  false, false);
3311 
3312  if (spec->strategy != PARTITION_STRATEGY_LIST)
3313  ereport(ERROR,
3314  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3315  errmsg("invalid bound specification for a list partition"),
3316  parser_errposition(pstate, exprLocation(bound))));
3317 
3318  result_spec->listdatums = NIL;
3319  foreach(cell, spec->listdatums)
3320  {
3321  A_Const *con = (A_Const *) lfirst(cell);
3322  Node *value;
3323  ListCell *cell2;
3324  bool duplicate;
3325 
3326  value = (Node *) make_const(pstate, &con->val, con->location);
3327  value = coerce_to_target_type(pstate,
3328  value, exprType(value),
3329  get_partition_col_typid(key, 0),
3330  get_partition_col_typmod(key, 0),
3333  -1);
3334 
3335  if (value == NULL)
3336  ereport(ERROR,
3337  (errcode(ERRCODE_DATATYPE_MISMATCH),
3338  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3340  colname),
3341  parser_errposition(pstate,
3342  exprLocation((Node *) con))));
3343 
3344  /* Simplify the expression */
3345  value = (Node *) expression_planner((Expr *) value);
3346 
3347  /* Don't add to the result if the value is a duplicate */
3348  duplicate = false;
3349  foreach(cell2, result_spec->listdatums)
3350  {
3351  Const *value2 = (Const *) lfirst(cell2);
3352 
3353  if (equal(value, value2))
3354  {
3355  duplicate = true;
3356  break;
3357  }
3358  }
3359  if (duplicate)
3360  continue;
3361 
3362  result_spec->listdatums = lappend(result_spec->listdatums,
3363  value);
3364  }
3365  }
3366  else if (strategy == PARTITION_STRATEGY_RANGE)
3367  {
3368  ListCell *cell1,
3369  *cell2;
3370  int i,
3371  j;
3372  char *colname;
3373  bool seen_unbounded;
3374 
3375  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3376  ereport(ERROR,
3377  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3378  errmsg("invalid bound specification for a range partition"),
3379  parser_errposition(pstate, exprLocation(bound))));
3380 
3381  Assert(spec->lowerdatums != NIL && spec->upperdatums != NIL);
3382 
3383  if (list_length(spec->lowerdatums) != partnatts)
3384  ereport(ERROR,
3385  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3386  errmsg("FROM must specify exactly one value per partitioning column")));
3387  if (list_length(spec->upperdatums) != partnatts)
3388  ereport(ERROR,
3389  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3390  errmsg("TO must specify exactly one value per partitioning column")));
3391 
3392  /*
3393  * Check that no finite value follows a UNBOUNDED literal in either of
3394  * lower and upper bound lists.
3395  */
3396  seen_unbounded = false;
3397  foreach(cell1, spec->lowerdatums)
3398  {
3399  PartitionRangeDatum *ldatum;
3400 
3401  ldatum = (PartitionRangeDatum *) lfirst(cell1);
3402  if (ldatum->infinite)
3403  seen_unbounded = true;
3404  else if (seen_unbounded)
3405  ereport(ERROR,
3406  (errcode(ERRCODE_DATATYPE_MISMATCH),
3407  errmsg("cannot specify finite value after UNBOUNDED"),
3408  parser_errposition(pstate, exprLocation((Node *) ldatum))));
3409  }
3410  seen_unbounded = false;
3411  foreach(cell1, spec->upperdatums)
3412  {
3413  PartitionRangeDatum *rdatum;
3414 
3415  rdatum = (PartitionRangeDatum *) lfirst(cell1);
3416  if (rdatum->infinite)
3417  seen_unbounded = true;
3418  else if (seen_unbounded)
3419  ereport(ERROR,
3420  (errcode(ERRCODE_DATATYPE_MISMATCH),
3421  errmsg("cannot specify finite value after UNBOUNDED"),
3422  parser_errposition(pstate, exprLocation((Node *) rdatum))));
3423  }
3424 
3425  i = j = 0;
3426  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3427  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3428  {
3429  PartitionRangeDatum *ldatum,
3430  *rdatum;
3431  Node *value;
3432  A_Const *lcon = NULL,
3433  *rcon = NULL;
3434 
3435  ldatum = (PartitionRangeDatum *) lfirst(cell1);
3436  rdatum = (PartitionRangeDatum *) lfirst(cell2);
3437  /* Get the column's name in case we need to output an error */
3438  if (key->partattrs[i] != 0)
3439  colname = get_relid_attribute_name(RelationGetRelid(parent),
3440  key->partattrs[i]);
3441  else
3442  {
3443  colname = deparse_expression((Node *) list_nth(partexprs, j),
3445  RelationGetRelid(parent)),
3446  false, false);
3447  ++j;
3448  }
3449 
3450  if (!ldatum->infinite)
3451  lcon = (A_Const *) ldatum->value;
3452  if (!rdatum->infinite)
3453  rcon = (A_Const *) rdatum->value;
3454 
3455  if (lcon)
3456  {
3457  value = (Node *) make_const(pstate, &lcon->val, lcon->location);
3458  if (((Const *) value)->constisnull)
3459  ereport(ERROR,
3460  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3461  errmsg("cannot specify NULL in range bound")));
3462  value = coerce_to_target_type(pstate,
3463  value, exprType(value),
3464  get_partition_col_typid(key, i),
3465  get_partition_col_typmod(key, i),
3468  -1);
3469  if (value == NULL)
3470  ereport(ERROR,
3471  (errcode(ERRCODE_DATATYPE_MISMATCH),
3472  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3474  colname),
3475  parser_errposition(pstate, exprLocation((Node *) ldatum))));
3476 
3477  /* Simplify the expression */
3478  value = (Node *) expression_planner((Expr *) value);
3479  ldatum->value = value;
3480  }
3481 
3482  if (rcon)
3483  {
3484  value = (Node *) make_const(pstate, &rcon->val, rcon->location);
3485  if (((Const *) value)->constisnull)
3486  ereport(ERROR,
3487  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3488  errmsg("cannot specify NULL in range bound")));
3489  value = coerce_to_target_type(pstate,
3490  value, exprType(value),
3491  get_partition_col_typid(key, i),
3492  get_partition_col_typmod(key, i),
3495  -1);
3496  if (value == NULL)
3497  ereport(ERROR,
3498  (errcode(ERRCODE_DATATYPE_MISMATCH),
3499  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3501  colname),
3502  parser_errposition(pstate, exprLocation((Node *) rdatum))));
3503 
3504  /* Simplify the expression */
3505  value = (Node *) expression_planner((Expr *) value);
3506  rdatum->value = value;
3507  }
3508 
3509  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3510  copyObject(ldatum));
3511  result_spec->upperdatums = lappend(result_spec->upperdatums,
3512  copyObject(rdatum));
3513 
3514  ++i;
3515  }
3516  }
3517  else
3518  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3519 
3520  return (Node *) result_spec;
3521 }
#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:1214
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
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
static int get_partition_natts(PartitionKey key)
Definition: rel.h:597
#define linitial(l)
Definition: pg_list.h:111
#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
void * list_nth(const List *list, int n)
Definition: list.c:410
static List * get_partition_exprs(PartitionKey key)
Definition: rel.h:603
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3036
#define RelationGetRelationName(relation)
Definition: rel.h:437
#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:624
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:618
static int get_partition_strategy(PartitionKey key)
Definition: rel.h:591
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
int location
Definition: parsenodes.h:289
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:2977
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
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:781
#define RelationGetPartitionKey(relation)
Definition: rel.h:585
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:782
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
static struct @121 value
#define copyObject(obj)
Definition: nodes.h:621
Value val
Definition: parsenodes.h:288
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

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

3263 {
3264  Relation parentRel = cxt->rel;
3265 
3266  /* the table must be partitioned */
3267  if (parentRel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3268  ereport(ERROR,
3269  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3270  errmsg("\"%s\" is not partitioned",
3271  RelationGetRelationName(parentRel))));
3272 
3273  /* transform the partition bound, if any */
3274  Assert(RelationGetPartitionKey(parentRel) != NULL);
3275  if (cmd->bound != NULL)
3276  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3277  cmd->bound);
3278 }
Node * transformPartitionBound(ParseState *pstate, Relation parent, Node *bound)
Node * bound
Definition: parsenodes.h:826
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define RelationGetPartitionKey(relation)
Definition: rel.h:585
int errmsg(const char *fmt,...)
Definition: elog.c:797
void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

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

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

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

795 {
796  switch (constraint->contype)
797  {
798  case CONSTR_PRIMARY:
799  if (cxt->isforeign)
800  ereport(ERROR,
801  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
802  errmsg("primary key constraints are not supported on foreign tables"),
804  constraint->location)));
805  if (cxt->ispartitioned)
806  ereport(ERROR,
807  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
808  errmsg("primary key constraints are not supported on partitioned tables"),
810  constraint->location)));
811  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
812  break;
813 
814  case CONSTR_UNIQUE:
815  if (cxt->isforeign)
816  ereport(ERROR,
817  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
818  errmsg("unique constraints are not supported on foreign tables"),
820  constraint->location)));
821  if (cxt->ispartitioned)
822  ereport(ERROR,
823  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
824  errmsg("unique constraints are not supported on partitioned tables"),
826  constraint->location)));
827  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
828  break;
829 
830  case CONSTR_EXCLUSION:
831  if (cxt->isforeign)
832  ereport(ERROR,
833  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
834  errmsg("exclusion constraints are not supported on foreign tables"),
836  constraint->location)));
837  if (cxt->ispartitioned)
838  ereport(ERROR,
839  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
840  errmsg("exclusion constraints are not supported on partitioned tables"),
842  constraint->location)));
843  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
844  break;
845 
846  case CONSTR_CHECK:
847  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
848  break;
849 
850  case CONSTR_FOREIGN:
851  if (cxt->isforeign)
852  ereport(ERROR,
853  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
854  errmsg("foreign key constraints are not supported on foreign tables"),
856  constraint->location)));
857  if (cxt->ispartitioned)
858  ereport(ERROR,
859  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
860  errmsg("foreign key constraints are not supported on partitioned tables"),
862  constraint->location)));
863  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
864