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

1245 {
1246  Oid source_relid = RelationGetRelid(source_idx);
1247  Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
1248  HeapTuple ht_idxrel;
1249  HeapTuple ht_idx;
1250  HeapTuple ht_am;
1251  Form_pg_class idxrelrec;
1252  Form_pg_index idxrec;
1253  Form_pg_am amrec;
1254  oidvector *indcollation;
1255  oidvector *indclass;
1256  IndexStmt *index;
1257  List *indexprs;
1258  ListCell *indexpr_item;
1259  Oid indrelid;
1260  int keyno;
1261  Oid keycoltype;
1262  Datum datum;
1263  bool isnull;
1264 
1265  /*
1266  * Fetch pg_class tuple of source index. We can't use the copy in the
1267  * relcache entry because it doesn't include optional fields.
1268  */
1269  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1270  if (!HeapTupleIsValid(ht_idxrel))
1271  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1272  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1273 
1274  /* Fetch pg_index tuple for source index from relcache entry */
1275  ht_idx = source_idx->rd_indextuple;
1276  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1277  indrelid = idxrec->indrelid;
1278 
1279  /* Fetch the pg_am tuple of the index' access method */
1280  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1281  if (!HeapTupleIsValid(ht_am))
1282  elog(ERROR, "cache lookup failed for access method %u",
1283  idxrelrec->relam);
1284  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1285 
1286  /* Extract indcollation from the pg_index tuple */
1287  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1288  Anum_pg_index_indcollation, &isnull);
1289  Assert(!isnull);
1290  indcollation = (oidvector *) DatumGetPointer(datum);
1291 
1292  /* Extract indclass from the pg_index tuple */
1293  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1294  Anum_pg_index_indclass, &isnull);
1295  Assert(!isnull);
1296  indclass = (oidvector *) DatumGetPointer(datum);
1297 
1298  /* Begin building the IndexStmt */
1299  index = makeNode(IndexStmt);
1300  index->relation = cxt->relation;
1301  index->accessMethod = pstrdup(NameStr(amrec->amname));
1302  if (OidIsValid(idxrelrec->reltablespace))
1303  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1304  else
1305  index->tableSpace = NULL;
1306  index->excludeOpNames = NIL;
1307  index->idxcomment = NULL;
1308  index->indexOid = InvalidOid;
1309  index->oldNode = InvalidOid;
1310  index->unique = idxrec->indisunique;
1311  index->primary = idxrec->indisprimary;
1312  index->transformed = true; /* don't need transformIndexStmt */
1313  index->concurrent = false;
1314  index->if_not_exists = false;
1315 
1316  /*
1317  * We don't try to preserve the name of the source index; instead, just
1318  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1319  * the name, we'd get duplicate-relation-name failures unless the source
1320  * table was in a different schema.)
1321  */
1322  index->idxname = NULL;
1323 
1324  /*
1325  * If the index is marked PRIMARY or has an exclusion condition, it's
1326  * certainly from a constraint; else, if it's not marked UNIQUE, it
1327  * certainly isn't. If it is or might be from a constraint, we have to
1328  * fetch the pg_constraint record.
1329  */
1330  if (index->primary || index->unique || idxrec->indisexclusion)
1331  {
1332  Oid constraintId = get_index_constraint(source_relid);
1333 
1334  if (OidIsValid(constraintId))
1335  {
1336  HeapTuple ht_constr;
1337  Form_pg_constraint conrec;
1338 
1339  ht_constr = SearchSysCache1(CONSTROID,
1340  ObjectIdGetDatum(constraintId));
1341  if (!HeapTupleIsValid(ht_constr))
1342  elog(ERROR, "cache lookup failed for constraint %u",
1343  constraintId);
1344  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1345 
1346  index->isconstraint = true;
1347  index->deferrable = conrec->condeferrable;
1348  index->initdeferred = conrec->condeferred;
1349 
1350  /* If it's an exclusion constraint, we need the operator names */
1351  if (idxrec->indisexclusion)
1352  {
1353  Datum *elems;
1354  int nElems;
1355  int i;
1356 
1357  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1358  /* Extract operator OIDs from the pg_constraint tuple */
1359  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1361  &isnull);
1362  if (isnull)
1363  elog(ERROR, "null conexclop for constraint %u",
1364  constraintId);
1365 
1367  OIDOID, sizeof(Oid), true, 'i',
1368  &elems, NULL, &nElems);
1369 
1370  for (i = 0; i < nElems; i++)
1371  {
1372  Oid operid = DatumGetObjectId(elems[i]);
1373  HeapTuple opertup;
1374  Form_pg_operator operform;
1375  char *oprname;
1376  char *nspname;
1377  List *namelist;
1378 
1379  opertup = SearchSysCache1(OPEROID,
1380  ObjectIdGetDatum(operid));
1381  if (!HeapTupleIsValid(opertup))
1382  elog(ERROR, "cache lookup failed for operator %u",
1383  operid);
1384  operform = (Form_pg_operator) GETSTRUCT(opertup);
1385  oprname = pstrdup(NameStr(operform->oprname));
1386  /* For simplicity we always schema-qualify the op name */
1387  nspname = get_namespace_name(operform->oprnamespace);
1388  namelist = list_make2(makeString(nspname),
1389  makeString(oprname));
1390  index->excludeOpNames = lappend(index->excludeOpNames,
1391  namelist);
1392  ReleaseSysCache(opertup);
1393  }
1394  }
1395 
1396  ReleaseSysCache(ht_constr);
1397  }
1398  else
1399  index->isconstraint = false;
1400  }
1401  else
1402  index->isconstraint = false;
1403 
1404  /* Get the index expressions, if any */
1405  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1406  Anum_pg_index_indexprs, &isnull);
1407  if (!isnull)
1408  {
1409  char *exprsString;
1410 
1411  exprsString = TextDatumGetCString(datum);
1412  indexprs = (List *) stringToNode(exprsString);
1413  }
1414  else
1415  indexprs = NIL;
1416 
1417  /* Build the list of IndexElem */
1418  index->indexParams = NIL;
1419 
1420  indexpr_item = list_head(indexprs);
1421  for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1422  {
1423  IndexElem *iparam;
1424  AttrNumber attnum = idxrec->indkey.values[keyno];
1425  int16 opt = source_idx->rd_indoption[keyno];
1426 
1427  iparam = makeNode(IndexElem);
1428 
1429  if (AttributeNumberIsValid(attnum))
1430  {
1431  /* Simple index column */
1432  char *attname;
1433 
1434  attname = get_relid_attribute_name(indrelid, attnum);
1435  keycoltype = get_atttype(indrelid, attnum);
1436 
1437  iparam->name = attname;
1438  iparam->expr = NULL;
1439  }
1440  else
1441  {
1442  /* Expressional index */
1443  Node *indexkey;
1444  bool found_whole_row;
1445 
1446  if (indexpr_item == NULL)
1447  elog(ERROR, "too few entries in indexprs list");
1448  indexkey = (Node *) lfirst(indexpr_item);
1449  indexpr_item = lnext(indexpr_item);
1450 
1451  /* Adjust Vars to match new table's column numbering */
1452  indexkey = map_variable_attnos(indexkey,
1453  1, 0,
1454  attmap, attmap_length,
1455  &found_whole_row);
1456 
1457  /* As in transformTableLikeClause, reject whole-row variables */
1458  if (found_whole_row)
1459  ereport(ERROR,
1460  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1461  errmsg("cannot convert whole-row table reference"),
1462  errdetail("Index \"%s\" contains a whole-row table reference.",
1463  RelationGetRelationName(source_idx))));
1464 
1465  iparam->name = NULL;
1466  iparam->expr = indexkey;
1467 
1468  keycoltype = exprType(indexkey);
1469  }
1470 
1471  /* Copy the original index column name */
1472  iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1473 
1474  /* Add the collation name, if non-default */
1475  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1476 
1477  /* Add the operator class name, if non-default */
1478  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1479 
1480  iparam->ordering = SORTBY_DEFAULT;
1482 
1483  /* Adjust options if necessary */
1484  if (source_idx->rd_amroutine->amcanorder)
1485  {
1486  /*
1487  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1488  * set non-default settings unnecessarily, though, so as to
1489  * improve the chance of recognizing equivalence to constraint
1490  * indexes.
1491  */
1492  if (opt & INDOPTION_DESC)
1493  {
1494  iparam->ordering = SORTBY_DESC;
1495  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1497  }
1498  else
1499  {
1500  if (opt & INDOPTION_NULLS_FIRST)
1502  }
1503  }
1504 
1505  index->indexParams = lappend(index->indexParams, iparam);
1506  }
1507 
1508  /* Copy reloptions if any */
1509  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1510  Anum_pg_class_reloptions, &isnull);
1511  if (!isnull)
1512  index->options = untransformRelOptions(datum);
1513 
1514  /* If it's a partial index, decompile and append the predicate */
1515  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1516  Anum_pg_index_indpred, &isnull);
1517  if (!isnull)
1518  {
1519  char *pred_str;
1520  Node *pred_tree;
1521  bool found_whole_row;
1522 
1523  /* Convert text string to node tree */
1524  pred_str = TextDatumGetCString(datum);
1525  pred_tree = (Node *) stringToNode(pred_str);
1526 
1527  /* Adjust Vars to match new table's column numbering */
1528  pred_tree = map_variable_attnos(pred_tree,
1529  1, 0,
1530  attmap, attmap_length,
1531  &found_whole_row);
1532 
1533  /* As in transformTableLikeClause, reject whole-row variables */
1534  if (found_whole_row)
1535  ereport(ERROR,
1536  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1537  errmsg("cannot convert whole-row table reference"),
1538  errdetail("Index \"%s\" contains a whole-row table reference.",
1539  RelationGetRelationName(source_idx))));
1540 
1541  index->whereClause = pred_tree;
1542  }
1543 
1544  /* Clean up */
1545  ReleaseSysCache(ht_idxrel);
1546  ReleaseSysCache(ht_am);
1547 
1548  return index;
1549 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
bool deferrable
Definition: parsenodes.h:2676
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:2674
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
void * stringToNode(char *str)
Definition: read.c:38
int16 * rd_indoption
Definition: rel.h:186
SortByDir ordering
Definition: parsenodes.h:693
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2667
#define RelationGetDescr(relation)
Definition: rel.h:429
#define OIDOID
Definition: pg_type.h:328
char * tableSpace
Definition: parsenodes.h:2665
#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:2668
#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:152
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
Definition: type.h:90
Oid indexOid
Definition: parsenodes.h:2671
Node * expr
Definition: parsenodes.h:689
RangeVar * relation
Definition: parse_utilcmd.c:77
RangeVar * relation
Definition: parsenodes.h:2663
SortByNulls nulls_ordering
Definition: parsenodes.h:694
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:486
bool transformed
Definition: parsenodes.h:2678
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:690
#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:2662
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:2680
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1278
bool unique
Definition: parsenodes.h:2673
List * untransformRelOptions(Datum options)
Definition: reloptions.c:907
char * accessMethod
Definition: parsenodes.h:2664
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:692
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:557
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define INDOPTION_DESC
Definition: pg_index.h:99
List * indexParams
Definition: parsenodes.h:2666
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
List * excludeOpNames
Definition: parsenodes.h:2669
bool initdeferred
Definition: parsenodes.h:2677
bool amcanorder
Definition: amapi.h:171
char * name
Definition: parsenodes.h:688
char * idxcomment
Definition: parsenodes.h:2670
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:2679
bool isconstraint
Definition: parsenodes.h:2675
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
int i
#define NameStr(name)
Definition: c.h:499
List * collation
Definition: parsenodes.h:691
#define elog
Definition: elog.h:219
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h: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
382  * field names, two different serial columns in the same table could
383  * be assigned the same sequence name, and we'd not notice since we
384  * aren't creating the sequence quite yet. In practice this seems
385  * quite unlikely to be a problem, especially since few people would
386  * need two serial columns in 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  snamespace = rv->schemaname;
407  sname = rv->relname;
408  seqoptions = list_delete_ptr(seqoptions, nameEl);
409  }
410  else
411  {
412  if (cxt->rel)
413  snamespaceid = RelationGetNamespace(cxt->rel);
414  else
415  {
416  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
417  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
418  }
419  snamespace = get_namespace_name(snamespaceid);
420  sname = ChooseRelationName(cxt->relation->relname,
421  column->colname,
422  "seq",
423  snamespaceid);
424  }
425 
426  ereport(DEBUG1,
427  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
428  cxt->stmtType, sname,
429  cxt->relation->relname, column->colname)));
430 
431  /*
432  * Build a CREATE SEQUENCE command to create the sequence object, and
433  * add it to the list of things to be done before this CREATE/ALTER
434  * 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  * If a sequence data type was specified, add it to the options. Prepend
442  * to the list rather than append; in case a user supplied their own AS
443  * clause, the "redundant options" error will point to their occurrence,
444  * not our synthetic one.
445  */
446  if (seqtypid)
447  seqstmt->options = lcons(makeDefElem("as", (Node *) makeTypeNameFromOid(seqtypid, -1), -1),
448  seqstmt->options);
449 
450  /*
451  * If this is ALTER ADD COLUMN, make sure the sequence will be owned
452  * by the table's owner. The current user might be someone else
453  * (perhaps a superuser, or someone who's only a member of the owning
454  * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
455  * and sequence have exactly the same owning role.
456  */
457  if (cxt->rel)
458  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
459  else
460  seqstmt->ownerId = InvalidOid;
461 
462  cxt->blist = lappend(cxt->blist, seqstmt);
463 
464  /*
465  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
466  * as owned by this column, and add it to the list of things to be
467  * done after this CREATE/ALTER TABLE.
468  */
469  altseqstmt = makeNode(AlterSeqStmt);
470  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
471  attnamelist = list_make3(makeString(snamespace),
472  makeString(cxt->relation->relname),
473  makeString(column->colname));
474  altseqstmt->options = list_make1(makeDefElem("owned_by",
475  (Node *) attnamelist, -1));
476  altseqstmt->for_identity = for_identity;
477 
478  cxt->alist = lappend(cxt->alist, altseqstmt);
479 
480  if (snamespace_p)
481  *snamespace_p = snamespace;
482  if (sname_p)
483  *sname_p = sname;
484 }
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:2913
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:543
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:614
List * options
Definition: parsenodes.h:2444
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:3038
#define ereport(elevel, rest)
Definition: elog.h:122
Node * arg
Definition: parsenodes.h:720
List * lappend(List *list, void *datum)
Definition: list.c:128
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:469
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2443
RangeVar * sequence
Definition: parsenodes.h:2433
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:2445
char * defname
Definition: parsenodes.h:719
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:420
List * options
Definition: parsenodes.h:2434
#define RelationGetNamespace(relation)
Definition: rel.h:444
static List * get_collation ( Oid  collation,
Oid  actual_datatype 
)
static

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

1559 {
1560  List *result;
1561  HeapTuple ht_coll;
1562  Form_pg_collation coll_rec;
1563  char *nsp_name;
1564  char *coll_name;
1565 
1566  if (!OidIsValid(collation))
1567  return NIL; /* easy case */
1568  if (collation == get_typcollation(actual_datatype))
1569  return NIL; /* just let it default */
1570 
1571  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1572  if (!HeapTupleIsValid(ht_coll))
1573  elog(ERROR, "cache lookup failed for collation %u", collation);
1574  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1575 
1576  /* For simplicity, we always schema-qualify the name */
1577  nsp_name = get_namespace_name(coll_rec->collnamespace);
1578  coll_name = pstrdup(NameStr(coll_rec->collname));
1579  result = list_make2(makeString(nsp_name), makeString(coll_name));
1580 
1581  ReleaseSysCache(ht_coll);
1582  return result;
1583 }
#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:1618
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
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:51
#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 1592 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().

1593 {
1594  List *result = NIL;
1595  HeapTuple ht_opc;
1596  Form_pg_opclass opc_rec;
1597 
1598  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1599  if (!HeapTupleIsValid(ht_opc))
1600  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1601  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1602 
1603  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1604  {
1605  /* For simplicity, we always schema-qualify the name */
1606  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1607  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1608 
1609  result = list_make2(makeString(nsp_name), makeString(opc_name));
1610  }
1611 
1612  ReleaseSysCache(ht_opc);
1613  return result;
1614 }
#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:1618
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#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 3228 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3229 {
3230  if (*stmt_schema_name == NULL)
3231  *stmt_schema_name = context_schema;
3232  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3233  ereport(ERROR,
3234  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3235  errmsg("CREATE specifies a schema (%s) "
3236  "different from the one being created (%s)",
3237  *stmt_schema_name, context_schema)));
3238 }
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 2623 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().

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

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

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

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

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

3071 {
3072  /*
3073  * All we really need to do here is verify that the type is valid,
3074  * including any collation spec that might be present.
3075  */
3076  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3077 
3078  if (column->collClause)
3079  {
3080  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3081 
3082  LookupCollation(cxt->pstate,
3083  column->collClause->collname,
3084  column->collClause->location);
3085  /* Complain if COLLATE is applied to an uncollatable type */
3086  if (!OidIsValid(typtup->typcollation))
3087  ereport(ERROR,
3088  (errcode(ERRCODE_DATATYPE_MISMATCH),
3089  errmsg("collations are not supported by type %s",
3092  column->collClause->location)));
3093  }
3094 
3095  ReleaseSysCache(ctype);
3096 }
#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:1116
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:650
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 2955 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().

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

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

3124 {
3126  List *result;
3127  ListCell *elements;
3128 
3129  cxt.stmtType = "CREATE SCHEMA";
3130  cxt.schemaname = stmt->schemaname;
3131  cxt.authrole = (RoleSpec *) stmt->authrole;
3132  cxt.sequences = NIL;
3133  cxt.tables = NIL;
3134  cxt.views = NIL;
3135  cxt.indexes = NIL;
3136  cxt.triggers = NIL;
3137  cxt.grants = NIL;
3138 
3139  /*
3140  * Run through each schema element in the schema element list. Separate
3141  * statements by type, and do preliminary analysis.
3142  */
3143  foreach(elements, stmt->schemaElts)
3144  {
3145  Node *element = lfirst(elements);
3146 
3147  switch (nodeTag(element))
3148  {
3149  case T_CreateSeqStmt:
3150  {
3151  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3152 
3154  cxt.sequences = lappend(cxt.sequences, element);
3155  }
3156  break;
3157 
3158  case T_CreateStmt:
3159  {
3160  CreateStmt *elp = (CreateStmt *) element;
3161 
3163 
3164  /*
3165  * XXX todo: deal with constraints
3166  */
3167  cxt.tables = lappend(cxt.tables, element);
3168  }
3169  break;
3170 
3171  case T_ViewStmt:
3172  {
3173  ViewStmt *elp = (ViewStmt *) element;
3174 
3175  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3176 
3177  /*
3178  * XXX todo: deal with references between views
3179  */
3180  cxt.views = lappend(cxt.views, element);
3181  }
3182  break;
3183 
3184  case T_IndexStmt:
3185  {
3186  IndexStmt *elp = (IndexStmt *) element;
3187 
3189  cxt.indexes = lappend(cxt.indexes, element);
3190  }
3191  break;
3192 
3193  case T_CreateTrigStmt:
3194  {
3195  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3196 
3198  cxt.triggers = lappend(cxt.triggers, element);
3199  }
3200  break;
3201 
3202  case T_GrantStmt:
3203  cxt.grants = lappend(cxt.grants, element);
3204  break;
3205 
3206  default:
3207  elog(ERROR, "unrecognized node type: %d",
3208  (int) nodeTag(element));
3209  }
3210  }
3211 
3212  result = NIL;
3213  result = list_concat(result, cxt.sequences);
3214  result = list_concat(result, cxt.tables);
3215  result = list_concat(result, cxt.views);
3216  result = list_concat(result, cxt.indexes);
3217  result = list_concat(result, cxt.triggers);
3218  result = list_concat(result, cxt.grants);
3219 
3220  return result;
3221 }
RangeVar * relation
Definition: parsenodes.h:1967
#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:1618
RangeVar * view
Definition: parsenodes.h:2964
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2663
RoleSpec * authrole
Definition: parsenodes.h:1639
#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:2433
#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:2318
#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:1967
#define NIL
Definition: pg_list.h:69
List * inhRelations
Definition: parsenodes.h:1969
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * partParams
Definition: parsenodes.h:776
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:1618
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:543
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:1974
bool if_not_exists
Definition: parsenodes.h:1978
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:3038
#define NoLock
Definition: lockdefs.h:34
List * options
Definition: parsenodes.h:1975
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:507
Node * partbound
Definition: parsenodes.h:1971
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:1968
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:775
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:1972
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:1973
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints ( CreateStmtContext cxt,
bool  skipValidation,
bool  isAddConstraint 
)
static

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

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

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

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

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

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

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

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

1195 {
1196  HeapTuple tuple;
1197  TupleDesc tupdesc;
1198  int i;
1199  Oid ofTypeId;
1200 
1201  AssertArg(ofTypename);
1202 
1203  tuple = typenameType(NULL, ofTypename, NULL);
1204  check_of_type(tuple);
1205  ofTypeId = HeapTupleGetOid(tuple);
1206  ofTypename->typeOid = ofTypeId; /* cached for later */
1207 
1208  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1209  for (i = 0; i < tupdesc->natts; i++)
1210  {
1211  Form_pg_attribute attr = tupdesc->attrs[i];
1212  ColumnDef *n;
1213 
1214  if (attr->attisdropped)
1215  continue;
1216 
1217  n = makeNode(ColumnDef);
1218  n->colname = pstrdup(NameStr(attr->attname));
1219  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1220  n->inhcount = 0;
1221  n->is_local = true;
1222  n->is_not_null = false;
1223  n->is_from_type = true;
1224  n->storage = 0;
1225  n->raw_default = NULL;
1226  n->cooked_default = NULL;
1227  n->collClause = NULL;
1228  n->collOid = attr->attcollation;
1229  n->constraints = NIL;
1230  n->location = -1;
1231  cxt->columns = lappend(cxt->columns, n);
1232  }
1233  DecrTupleDescRefCount(tupdesc);
1234 
1235  ReleaseSysCache(tuple);
1236 }
#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:646
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:652
char * pstrdup(const char *in)
Definition: mcxt.c:1077
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:648
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5027
Oid collOid
Definition: parsenodes.h:651
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int location
Definition: parsenodes.h:654
#define AssertArg(condition)
Definition: c.h:677
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
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:650
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 3272 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().

3273 {
3274  PartitionBoundSpec *spec = (PartitionBoundSpec *) bound,
3275  *result_spec;
3276  PartitionKey key = RelationGetPartitionKey(parent);
3277  char strategy = get_partition_strategy(key);
3278  int partnatts = get_partition_natts(key);
3279  List *partexprs = get_partition_exprs(key);
3280 
3281  result_spec = copyObject(spec);
3282 
3283  if (strategy == PARTITION_STRATEGY_LIST)
3284  {
3285  ListCell *cell;
3286  char *colname;
3287 
3288  /* Get the only column's name in case we need to output an error */
3289  if (key->partattrs[0] != 0)
3290  colname = get_relid_attribute_name(RelationGetRelid(parent),
3291  key->partattrs[0]);
3292  else
3293  colname = deparse_expression((Node *) linitial(partexprs),
3295  RelationGetRelid(parent)),
3296  false, false);
3297 
3298  if (spec->strategy != PARTITION_STRATEGY_LIST)
3299  ereport(ERROR,
3300  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3301  errmsg("invalid bound specification for a list partition"),
3302  parser_errposition(pstate, exprLocation(bound))));
3303 
3304  result_spec->listdatums = NIL;
3305  foreach(cell, spec->listdatums)
3306  {
3307  A_Const *con = (A_Const *) lfirst(cell);
3308  Node *value;
3309  ListCell *cell2;
3310  bool duplicate;
3311 
3312  value = (Node *) make_const(pstate, &con->val, con->location);
3313  value = coerce_to_target_type(pstate,
3314  value, exprType(value),
3315  get_partition_col_typid(key, 0),
3316  get_partition_col_typmod(key, 0),
3319  -1);
3320 
3321  if (value == NULL)
3322  ereport(ERROR,
3323  (errcode(ERRCODE_DATATYPE_MISMATCH),
3324  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3326  colname),
3327  parser_errposition(pstate,
3328  exprLocation((Node *) con))));
3329 
3330  /* Simplify the expression */
3331  value = (Node *) expression_planner((Expr *) value);
3332 
3333  /* Don't add to the result if the value is a duplicate */
3334  duplicate = false;
3335  foreach(cell2, result_spec->listdatums)
3336  {
3337  Const *value2 = (Const *) lfirst(cell2);
3338 
3339  if (equal(value, value2))
3340  {
3341  duplicate = true;
3342  break;
3343  }
3344  }
3345  if (duplicate)
3346  continue;
3347 
3348  result_spec->listdatums = lappend(result_spec->listdatums,
3349  value);
3350  }
3351  }
3352  else if (strategy == PARTITION_STRATEGY_RANGE)
3353  {
3354  ListCell *cell1,
3355  *cell2;
3356  int i,
3357  j;
3358  char *colname;
3359 
3360  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3361  ereport(ERROR,
3362  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3363  errmsg("invalid bound specification for a range partition"),
3364  parser_errposition(pstate, exprLocation(bound))));
3365 
3366  Assert(spec->lowerdatums != NIL && spec->upperdatums != NIL);
3367 
3368  if (list_length(spec->lowerdatums) != partnatts)
3369  ereport(ERROR,
3370  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3371  errmsg("FROM must specify exactly one value per partitioning column")));
3372  if (list_length(spec->upperdatums) != partnatts)
3373  ereport(ERROR,
3374  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3375  errmsg("TO must specify exactly one value per partitioning column")));
3376 
3377  i = j = 0;
3378  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3379  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3380  {
3381  PartitionRangeDatum *ldatum,
3382  *rdatum;
3383  Node *value;
3384  A_Const *lcon = NULL,
3385  *rcon = NULL;
3386 
3387  ldatum = (PartitionRangeDatum *) lfirst(cell1);
3388  rdatum = (PartitionRangeDatum *) lfirst(cell2);
3389  /* Get the column's name in case we need to output an error */
3390  if (key->partattrs[i] != 0)
3391  colname = get_relid_attribute_name(RelationGetRelid(parent),
3392  key->partattrs[i]);
3393  else
3394  {
3395  colname = deparse_expression((Node *) list_nth(partexprs, j),
3397  RelationGetRelid(parent)),
3398  false, false);
3399  ++j;
3400  }
3401 
3402  if (!ldatum->infinite)
3403  lcon = (A_Const *) ldatum->value;
3404  if (!rdatum->infinite)
3405  rcon = (A_Const *) rdatum->value;
3406 
3407  if (lcon)
3408  {
3409  value = (Node *) make_const(pstate, &lcon->val, lcon->location);
3410  if (((Const *) value)->constisnull)
3411  ereport(ERROR,
3412  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3413  errmsg("cannot specify NULL in range bound")));
3414  value = coerce_to_target_type(pstate,
3415  value, exprType(value),
3416  get_partition_col_typid(key, i),
3417  get_partition_col_typmod(key, i),
3420  -1);
3421  if (value == NULL)
3422  ereport(ERROR,
3423  (errcode(ERRCODE_DATATYPE_MISMATCH),
3424  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3426  colname),
3427  parser_errposition(pstate, exprLocation((Node *) ldatum))));
3428 
3429  /* Simplify the expression */
3430  value = (Node *) expression_planner((Expr *) value);
3431  ldatum->value = value;
3432  }
3433 
3434  if (rcon)
3435  {
3436  value = (Node *) make_const(pstate, &rcon->val, rcon->location);
3437  if (((Const *) value)->constisnull)
3438  ereport(ERROR,
3439  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3440  errmsg("cannot specify NULL in range bound")));
3441  value = coerce_to_target_type(pstate,
3442  value, exprType(value),
3443  get_partition_col_typid(key, i),
3444  get_partition_col_typmod(key, i),
3447  -1);
3448  if (value == NULL)
3449  ereport(ERROR,
3450  (errcode(ERRCODE_DATATYPE_MISMATCH),
3451  errmsg("specified value cannot be cast to type \"%s\" of column \"%s\"",
3453  colname),
3454  parser_errposition(pstate, exprLocation((Node *) rdatum))));
3455 
3456  /* Simplify the expression */
3457  value = (Node *) expression_planner((Expr *) value);
3458  rdatum->value = value;
3459  }
3460 
3461  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3462  copyObject(ldatum));
3463  result_spec->upperdatums = lappend(result_spec->upperdatums,
3464  copyObject(rdatum));
3465 
3466  ++i;
3467  }
3468  }
3469  else
3470  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3471 
3472  return (Node *) result_spec;
3473 }
#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:1213
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2961
Expr * expression_planner(Expr *expr)
Definition: planner.c:5928
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:2998
#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:2939
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:780
#define RelationGetPartitionKey(relation)
Definition: rel.h:585
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:781
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 3248 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().

3249 {
3250  Relation parentRel = cxt->rel;
3251 
3252  /* the table must be partitioned */
3253  if (parentRel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3254  ereport(ERROR,
3255  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3256  errmsg("\"%s\" is not partitioned",
3257  RelationGetRelationName(parentRel))));
3258 
3259  /* transform the partition bound, if any */
3260  Assert(RelationGetPartitionKey(parentRel) != NULL);
3261  if (cmd->bound != NULL)
3262  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3263  cmd->bound);
3264 }
Node * transformPartitionBound(ParseState *pstate, Relation parent, Node *bound)
Node * bound
Definition: parsenodes.h:825
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 2318 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().

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

794 {
795  switch (constraint->contype)
796  {
797  case CONSTR_PRIMARY:
798  if (cxt->isforeign)
799  ereport(ERROR,
800  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
801  errmsg("primary key constraints are not supported on foreign tables"),
803  constraint->location)));
804  if (cxt->ispartitioned)
805  ereport(ERROR,
806  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
807  errmsg("primary key constraints are not supported on partitioned tables"),
809  constraint->location)));
810  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
811  break;
812 
813  case CONSTR_UNIQUE:
814  if (cxt->isforeign)
815  ereport(ERROR,
816  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
817  errmsg("unique constraints are not supported on foreign tables"),
819  constraint->location)));
820  if (cxt->ispartitioned)
821  ereport(ERROR,
822  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
823  errmsg("unique constraints are not supported on partitioned tables"),
825  constraint->location)));
826  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
827  break;
828 
829  case CONSTR_EXCLUSION:
830  if (cxt->isforeign)
831  ereport(ERROR,
832  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
833  errmsg("exclusion constraints are not supported on foreign tables"),
835  constraint->location)));
836  if (cxt->ispartitioned)
837  ereport(ERROR,
838  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
839  errmsg("exclusion constraints are not supported on partitioned tables"),
841  constraint->location)));
842  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
843  break;
844 
845  case CONSTR_CHECK:
846  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
847  break;
848 
849  case CONSTR_FOREIGN:
850  if (cxt->isforeign)
851  ereport(ERROR,
852  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
853  errmsg("foreign key constraints are not supported on foreign tables"),
855  constraint->location)));
856  if (cxt->ispartitioned)
857  ereport(ERROR,
858  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
859  errmsg("foreign key constraints are not supported on partitioned tables"),
861  constraint->location)));
862  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
863  break;
864 
865  case CONSTR_NULL:
866  case CONSTR_NOTNULL:
867  case CONSTR_DEFAULT:
872  elog(ERROR, "invalid context for constraint type %d",
873  constraint->contype);
874  break;
875 
876  default:
877  elog(ERROR, "unrecognized constraint type: %d",
878  constraint->contype);
879  break;
880  }
881 }
int errcode(int sqlerrcode)
Definition: elog.c:575
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:43