PostgreSQL Source Code git master
Typedefs | Functions
parse_utilcmd.h File Reference
#include "parser/parse_node.h"
Include dependency graph for parse_utilcmd.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef struct AttrMap  AttrMap
 

Functions

ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
CreateStatsStmttransformStatsStmt (Oid relid, CreateStatsStmt *stmt, const char *queryString)
 
void  transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmtElements (List *schemaElts, const char *schemaName)
 
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 

Typedef Documentation

AttrMap

typedef struct AttrMap AttrMap

Definition at line 19 of file parse_utilcmd.h.

Function Documentation

expandTableLikeClause()

List * expandTableLikeClause ( RangeVarheapRel,
TableLikeClausetable_like_clause 
)

Definition at line 1344 of file parse_utilcmd.c.

1345{
1346 List *result = NIL;
1347 List *atsubcmds = NIL;
1348 AttrNumber parent_attno;
1349 Relation relation;
1350 Relation childrel;
1351 TupleDesc tupleDesc;
1352 TupleConstr *constr;
1353 AttrMap *attmap;
1354 char *comment;
1355
1356 /*
1357 * Open the relation referenced by the LIKE clause. We should still have
1358 * the table lock obtained by transformTableLikeClause (and this'll throw
1359 * an assertion failure if not). Hence, no need to recheck privileges
1360 * etc. We must open the rel by OID not name, to be sure we get the same
1361 * table.
1362 */
1363 if (!OidIsValid(table_like_clause->relationOid))
1364 elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1365
1366 relation = relation_open(table_like_clause->relationOid, NoLock);
1367
1368 tupleDesc = RelationGetDescr(relation);
1369 constr = tupleDesc->constr;
1370
1371 /*
1372 * Open the newly-created child relation; we have lock on that too.
1373 */
1374 childrel = relation_openrv(heapRel, NoLock);
1375
1376 /*
1377 * Construct a map from the LIKE relation's attnos to the child rel's.
1378 * This re-checks type match etc, although it shouldn't be possible to
1379 * have a failure since both tables are locked.
1380 */
1381 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1382 tupleDesc,
1383 false);
1384
1385 /*
1386 * Process defaults, if required.
1387 */
1388 if ((table_like_clause->options &
1390 constr != NULL)
1391 {
1392 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1393 parent_attno++)
1394 {
1395 Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1396 parent_attno - 1);
1397
1398 /*
1399 * Ignore dropped columns in the parent.
1400 */
1401 if (attribute->attisdropped)
1402 continue;
1403
1404 /*
1405 * Copy default, if present and it should be copied. We have
1406 * separate options for plain default expressions and GENERATED
1407 * defaults.
1408 */
1409 if (attribute->atthasdef &&
1410 (attribute->attgenerated ?
1411 (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1412 (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1413 {
1414 Node *this_default;
1415 AlterTableCmd *atsubcmd;
1416 bool found_whole_row;
1417
1418 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1419 if (this_default == NULL)
1420 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1421 parent_attno, RelationGetRelationName(relation));
1422
1423 atsubcmd = makeNode(AlterTableCmd);
1424 atsubcmd->subtype = AT_CookedColumnDefault;
1425 atsubcmd->num = attmap->attnums[parent_attno - 1];
1426 atsubcmd->def = map_variable_attnos(this_default,
1427 1, 0,
1428 attmap,
1429 InvalidOid,
1430 &found_whole_row);
1431
1432 /*
1433 * Prevent this for the same reason as for constraints below.
1434 * Note that defaults cannot contain any vars, so it's OK that
1435 * the error message refers to generated columns.
1436 */
1437 if (found_whole_row)
1438 ereport(ERROR,
1439 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1440 errmsg("cannot convert whole-row table reference"),
1441 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1442 NameStr(attribute->attname),
1443 RelationGetRelationName(relation))));
1444
1445 atsubcmds = lappend(atsubcmds, atsubcmd);
1446 }
1447 }
1448 }
1449
1450 /*
1451 * Copy CHECK constraints if requested, being careful to adjust attribute
1452 * numbers so they match the child.
1453 */
1454 if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1455 constr != NULL)
1456 {
1457 int ccnum;
1458
1459 for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1460 {
1461 char *ccname = constr->check[ccnum].ccname;
1462 char *ccbin = constr->check[ccnum].ccbin;
1463 bool ccenforced = constr->check[ccnum].ccenforced;
1464 bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1465 Node *ccbin_node;
1466 bool found_whole_row;
1467 Constraint *n;
1468 AlterTableCmd *atsubcmd;
1469
1470 ccbin_node = map_variable_attnos(stringToNode(ccbin),
1471 1, 0,
1472 attmap,
1473 InvalidOid, &found_whole_row);
1474
1475 /*
1476 * We reject whole-row variables because the whole point of LIKE
1477 * is that the new table's rowtype might later diverge from the
1478 * parent's. So, while translation might be possible right now,
1479 * it wouldn't be possible to guarantee it would work in future.
1480 */
1481 if (found_whole_row)
1482 ereport(ERROR,
1483 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1484 errmsg("cannot convert whole-row table reference"),
1485 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1486 ccname,
1487 RelationGetRelationName(relation))));
1488
1489 n = makeNode(Constraint);
1490 n->contype = CONSTR_CHECK;
1491 n->conname = pstrdup(ccname);
1492 n->location = -1;
1493 n->is_enforced = ccenforced;
1494 n->initially_valid = ccenforced; /* sic */
1495 n->is_no_inherit = ccnoinherit;
1496 n->raw_expr = NULL;
1497 n->cooked_expr = nodeToString(ccbin_node);
1498
1499 /* We can skip validation, since the new table should be empty. */
1500 n->skip_validation = true;
1501
1502 atsubcmd = makeNode(AlterTableCmd);
1503 atsubcmd->subtype = AT_AddConstraint;
1504 atsubcmd->def = (Node *) n;
1505 atsubcmds = lappend(atsubcmds, atsubcmd);
1506
1507 /* Copy comment on constraint */
1508 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1510 n->conname, false),
1511 ConstraintRelationId,
1512 0)) != NULL)
1513 {
1515
1516 stmt->objtype = OBJECT_TABCONSTRAINT;
1517 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1518 makeString(heapRel->relname),
1519 makeString(n->conname));
1520 stmt->comment = comment;
1521
1522 result = lappend(result, stmt);
1523 }
1524 }
1525 }
1526
1527 /*
1528 * If we generated any ALTER TABLE actions above, wrap them into a single
1529 * ALTER TABLE command. Stick it at the front of the result, so it runs
1530 * before any CommentStmts we made above.
1531 */
1532 if (atsubcmds)
1533 {
1535
1536 atcmd->relation = copyObject(heapRel);
1537 atcmd->cmds = atsubcmds;
1538 atcmd->objtype = OBJECT_TABLE;
1539 atcmd->missing_ok = false;
1540 result = lcons(atcmd, result);
1541 }
1542
1543 /*
1544 * Process indexes if required.
1545 */
1546 if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1547 relation->rd_rel->relhasindex &&
1548 childrel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1549 {
1550 List *parent_indexes;
1551 ListCell *l;
1552
1553 parent_indexes = RelationGetIndexList(relation);
1554
1555 foreach(l, parent_indexes)
1556 {
1557 Oid parent_index_oid = lfirst_oid(l);
1558 Relation parent_index;
1559 IndexStmt *index_stmt;
1560
1561 parent_index = index_open(parent_index_oid, AccessShareLock);
1562
1563 /* Build CREATE INDEX statement to recreate the parent_index */
1564 index_stmt = generateClonedIndexStmt(heapRel,
1565 parent_index,
1566 attmap,
1567 NULL);
1568
1569 /* Copy comment on index, if requested */
1570 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1571 {
1572 comment = GetComment(parent_index_oid, RelationRelationId, 0);
1573
1574 /*
1575 * We make use of IndexStmt's idxcomment option, so as not to
1576 * need to know now what name the index will have.
1577 */
1578 index_stmt->idxcomment = comment;
1579 }
1580
1581 result = lappend(result, index_stmt);
1582
1583 index_close(parent_index, AccessShareLock);
1584 }
1585 }
1586
1587 /*
1588 * Process extended statistics if required.
1589 */
1590 if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
1591 {
1592 List *parent_extstats;
1593 ListCell *l;
1594
1595 parent_extstats = RelationGetStatExtList(relation);
1596
1597 foreach(l, parent_extstats)
1598 {
1599 Oid parent_stat_oid = lfirst_oid(l);
1600 CreateStatsStmt *stats_stmt;
1601
1602 stats_stmt = generateClonedExtStatsStmt(heapRel,
1603 RelationGetRelid(childrel),
1604 parent_stat_oid,
1605 attmap);
1606
1607 /* Copy comment on statistics object, if requested */
1608 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1609 {
1610 comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
1611
1612 /*
1613 * We make use of CreateStatsStmt's stxcomment option, so as
1614 * not to need to know now what name the statistics will have.
1615 */
1616 stats_stmt->stxcomment = comment;
1617 }
1618
1619 result = lappend(result, stats_stmt);
1620 }
1621
1622 list_free(parent_extstats);
1623 }
1624
1625 /* Done with child rel */
1626 table_close(childrel, NoLock);
1627
1628 /*
1629 * Close the parent rel, but keep our AccessShareLock on it until xact
1630 * commit. That will prevent someone else from deleting or ALTERing the
1631 * parent before the child is committed.
1632 */
1633 table_close(relation, NoLock);
1634
1635 return result;
1636}
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:175
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:751
#define OidIsValid(objectId)
Definition: c.h:774
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1207
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lcons(void *datum, List *list)
Definition: list.c:495
void list_free(List *list)
Definition: list.c:1546
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1759
#define copyObject(obj)
Definition: nodes.h:232
#define makeNode(_type_)
Definition: nodes.h:161
char * nodeToString(const void *obj)
Definition: outfuncs.c:805
static CreateStatsStmt * generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid, Oid source_statsid, const AttrMap *attmap)
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2805
@ OBJECT_TABLE
Definition: parsenodes.h:2366
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2365
@ AT_AddConstraint
Definition: parsenodes.h:2433
@ AT_CookedColumnDefault
Definition: parsenodes.h:2420
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:789
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:793
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:795
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:792
@ CREATE_TABLE_LIKE_STATISTICS
Definition: parsenodes.h:796
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:791
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define NIL
Definition: pg_list.h:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:514
#define RelationGetDescr(relation)
Definition: rel.h:540
#define RelationGetRelationName(relation)
Definition: rel.h:548
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4836
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4977
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Definition: rewriteManip.c:1705
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:137
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
Node * def
Definition: parsenodes.h:2494
AlterTableType subtype
Definition: parsenodes.h:2488
bool missing_ok
Definition: parsenodes.h:2412
List * cmds
Definition: parsenodes.h:2410
RangeVar * relation
Definition: parsenodes.h:2409
ObjectType objtype
Definition: parsenodes.h:2411
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * ccname
Definition: tupdesc.h:30
bool ccenforced
Definition: tupdesc.h:32
bool ccnoinherit
Definition: tupdesc.h:34
char * ccbin
Definition: tupdesc.h:31
ParseLoc location
Definition: parsenodes.h:2877
ConstrType contype
Definition: parsenodes.h:2833
bool is_no_inherit
Definition: parsenodes.h:2840
bool is_enforced
Definition: parsenodes.h:2837
char * cooked_expr
Definition: parsenodes.h:2843
bool initially_valid
Definition: parsenodes.h:2839
bool skip_validation
Definition: parsenodes.h:2838
Node * raw_expr
Definition: parsenodes.h:2841
char * conname
Definition: parsenodes.h:2834
char * stxcomment
Definition: parsenodes.h:3526
char * idxcomment
Definition: parsenodes.h:3495
Definition: pg_list.h:54
Definition: nodes.h:135
char * relname
Definition: primnodes.h:83
char * schemaname
Definition: primnodes.h:80
Definition: rel.h:56
Form_pg_class rd_rel
Definition: rel.h:111
bits32 options
Definition: parsenodes.h:783
ConstrCheck * check
Definition: tupdesc.h:41
uint16 num_check
Definition: tupdesc.h:44
int natts
Definition: tupdesc.h:137
TupleConstr * constr
Definition: tupdesc.h:141
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:1092
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
Definition: pg_list.h:46
String * makeString(char *str)
Definition: value.c:63

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

Referenced by ProcessUtilitySlow().

generateClonedIndexStmt()

IndexStmt * generateClonedIndexStmt ( RangeVarheapRel,
Relation  source_idx,
const AttrMapattmap,
OidconstraintOid 
)

Definition at line 1692 of file parse_utilcmd.c.

1695{
1696 Oid source_relid = RelationGetRelid(source_idx);
1697 HeapTuple ht_idxrel;
1698 HeapTuple ht_idx;
1699 HeapTuple ht_am;
1700 Form_pg_class idxrelrec;
1701 Form_pg_index idxrec;
1702 Form_pg_am amrec;
1703 oidvector *indcollation;
1704 oidvector *indclass;
1706 List *indexprs;
1707 ListCell *indexpr_item;
1708 Oid indrelid;
1709 int keyno;
1710 Oid keycoltype;
1711 Datum datum;
1712 bool isnull;
1713
1714 if (constraintOid)
1715 *constraintOid = InvalidOid;
1716
1717 /*
1718 * Fetch pg_class tuple of source index. We can't use the copy in the
1719 * relcache entry because it doesn't include optional fields.
1720 */
1721 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1722 if (!HeapTupleIsValid(ht_idxrel))
1723 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1724 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1725
1726 /* Fetch pg_index tuple for source index from relcache entry */
1727 ht_idx = source_idx->rd_indextuple;
1728 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1729 indrelid = idxrec->indrelid;
1730
1731 /* Fetch the pg_am tuple of the index' access method */
1732 ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1733 if (!HeapTupleIsValid(ht_am))
1734 elog(ERROR, "cache lookup failed for access method %u",
1735 idxrelrec->relam);
1736 amrec = (Form_pg_am) GETSTRUCT(ht_am);
1737
1738 /* Extract indcollation from the pg_index tuple */
1739 datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1740 Anum_pg_index_indcollation);
1741 indcollation = (oidvector *) DatumGetPointer(datum);
1742
1743 /* Extract indclass from the pg_index tuple */
1744 datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
1745 indclass = (oidvector *) DatumGetPointer(datum);
1746
1747 /* Begin building the IndexStmt */
1749 index->relation = heapRel;
1750 index->accessMethod = pstrdup(NameStr(amrec->amname));
1751 if (OidIsValid(idxrelrec->reltablespace))
1752 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1753 else
1754 index->tableSpace = NULL;
1755 index->excludeOpNames = NIL;
1756 index->idxcomment = NULL;
1757 index->indexOid = InvalidOid;
1758 index->oldNumber = InvalidRelFileNumber;
1759 index->oldCreateSubid = InvalidSubTransactionId;
1760 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1761 index->unique = idxrec->indisunique;
1762 index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1763 index->primary = idxrec->indisprimary;
1764 index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
1765 index->transformed = true; /* don't need transformIndexStmt */
1766 index->concurrent = false;
1767 index->if_not_exists = false;
1768 index->reset_default_tblspc = false;
1769
1770 /*
1771 * We don't try to preserve the name of the source index; instead, just
1772 * let DefineIndex() choose a reasonable name. (If we tried to preserve
1773 * the name, we'd get duplicate-relation-name failures unless the source
1774 * table was in a different schema.)
1775 */
1776 index->idxname = NULL;
1777
1778 /*
1779 * If the index is marked PRIMARY or has an exclusion condition, it's
1780 * certainly from a constraint; else, if it's not marked UNIQUE, it
1781 * certainly isn't. If it is or might be from a constraint, we have to
1782 * fetch the pg_constraint record.
1783 */
1784 if (index->primary || index->unique || idxrec->indisexclusion)
1785 {
1786 Oid constraintId = get_index_constraint(source_relid);
1787
1788 if (OidIsValid(constraintId))
1789 {
1790 HeapTuple ht_constr;
1791 Form_pg_constraint conrec;
1792
1793 if (constraintOid)
1794 *constraintOid = constraintId;
1795
1796 ht_constr = SearchSysCache1(CONSTROID,
1797 ObjectIdGetDatum(constraintId));
1798 if (!HeapTupleIsValid(ht_constr))
1799 elog(ERROR, "cache lookup failed for constraint %u",
1800 constraintId);
1801 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1802
1803 index->isconstraint = true;
1804 index->deferrable = conrec->condeferrable;
1805 index->initdeferred = conrec->condeferred;
1806
1807 /* If it's an exclusion constraint, we need the operator names */
1808 if (idxrec->indisexclusion)
1809 {
1810 Datum *elems;
1811 int nElems;
1812 int i;
1813
1814 Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
1815 (index->iswithoutoverlaps &&
1816 (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
1817 /* Extract operator OIDs from the pg_constraint tuple */
1818 datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
1819 Anum_pg_constraint_conexclop);
1820 deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1821
1822 for (i = 0; i < nElems; i++)
1823 {
1824 Oid operid = DatumGetObjectId(elems[i]);
1825 HeapTuple opertup;
1826 Form_pg_operator operform;
1827 char *oprname;
1828 char *nspname;
1829 List *namelist;
1830
1831 opertup = SearchSysCache1(OPEROID,
1832 ObjectIdGetDatum(operid));
1833 if (!HeapTupleIsValid(opertup))
1834 elog(ERROR, "cache lookup failed for operator %u",
1835 operid);
1836 operform = (Form_pg_operator) GETSTRUCT(opertup);
1837 oprname = pstrdup(NameStr(operform->oprname));
1838 /* For simplicity we always schema-qualify the op name */
1839 nspname = get_namespace_name(operform->oprnamespace);
1840 namelist = list_make2(makeString(nspname),
1841 makeString(oprname));
1842 index->excludeOpNames = lappend(index->excludeOpNames,
1843 namelist);
1844 ReleaseSysCache(opertup);
1845 }
1846 }
1847
1848 ReleaseSysCache(ht_constr);
1849 }
1850 else
1851 index->isconstraint = false;
1852 }
1853 else
1854 index->isconstraint = false;
1855
1856 /* Get the index expressions, if any */
1857 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1858 Anum_pg_index_indexprs, &isnull);
1859 if (!isnull)
1860 {
1861 char *exprsString;
1862
1863 exprsString = TextDatumGetCString(datum);
1864 indexprs = (List *) stringToNode(exprsString);
1865 }
1866 else
1867 indexprs = NIL;
1868
1869 /* Build the list of IndexElem */
1870 index->indexParams = NIL;
1871 index->indexIncludingParams = NIL;
1872
1873 indexpr_item = list_head(indexprs);
1874 for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1875 {
1876 IndexElem *iparam;
1877 AttrNumber attnum = idxrec->indkey.values[keyno];
1879 keyno);
1880 int16 opt = source_idx->rd_indoption[keyno];
1881
1882 iparam = makeNode(IndexElem);
1883
1885 {
1886 /* Simple index column */
1887 char *attname;
1888
1889 attname = get_attname(indrelid, attnum, false);
1890 keycoltype = get_atttype(indrelid, attnum);
1891
1892 iparam->name = attname;
1893 iparam->expr = NULL;
1894 }
1895 else
1896 {
1897 /* Expressional index */
1898 Node *indexkey;
1899 bool found_whole_row;
1900
1901 if (indexpr_item == NULL)
1902 elog(ERROR, "too few entries in indexprs list");
1903 indexkey = (Node *) lfirst(indexpr_item);
1904 indexpr_item = lnext(indexprs, indexpr_item);
1905
1906 /* Adjust Vars to match new table's column numbering */
1907 indexkey = map_variable_attnos(indexkey,
1908 1, 0,
1909 attmap,
1910 InvalidOid, &found_whole_row);
1911
1912 /* As in expandTableLikeClause, reject whole-row variables */
1913 if (found_whole_row)
1914 ereport(ERROR,
1915 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1916 errmsg("cannot convert whole-row table reference"),
1917 errdetail("Index \"%s\" contains a whole-row table reference.",
1918 RelationGetRelationName(source_idx))));
1919
1920 iparam->name = NULL;
1921 iparam->expr = indexkey;
1922
1923 keycoltype = exprType(indexkey);
1924 }
1925
1926 /* Copy the original index column name */
1927 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1928
1929 /* Add the collation name, if non-default */
1930 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1931
1932 /* Add the operator class name, if non-default */
1933 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1934 iparam->opclassopts =
1935 untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1936
1937 iparam->ordering = SORTBY_DEFAULT;
1939
1940 /* Adjust options if necessary */
1941 if (source_idx->rd_indam->amcanorder)
1942 {
1943 /*
1944 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1945 * set non-default settings unnecessarily, though, so as to
1946 * improve the chance of recognizing equivalence to constraint
1947 * indexes.
1948 */
1949 if (opt & INDOPTION_DESC)
1950 {
1951 iparam->ordering = SORTBY_DESC;
1952 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1954 }
1955 else
1956 {
1957 if (opt & INDOPTION_NULLS_FIRST)
1959 }
1960 }
1961
1962 index->indexParams = lappend(index->indexParams, iparam);
1963 }
1964
1965 /* Handle included columns separately */
1966 for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1967 {
1968 IndexElem *iparam;
1969 AttrNumber attnum = idxrec->indkey.values[keyno];
1971 keyno);
1972
1973 iparam = makeNode(IndexElem);
1974
1976 {
1977 /* Simple index column */
1978 char *attname;
1979
1980 attname = get_attname(indrelid, attnum, false);
1981
1982 iparam->name = attname;
1983 iparam->expr = NULL;
1984 }
1985 else
1986 ereport(ERROR,
1987 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1988 errmsg("expressions are not supported in included columns")));
1989
1990 /* Copy the original index column name */
1991 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1992
1993 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1994 }
1995 /* Copy reloptions if any */
1996 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1997 Anum_pg_class_reloptions, &isnull);
1998 if (!isnull)
1999 index->options = untransformRelOptions(datum);
2000
2001 /* If it's a partial index, decompile and append the predicate */
2002 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
2003 Anum_pg_index_indpred, &isnull);
2004 if (!isnull)
2005 {
2006 char *pred_str;
2007 Node *pred_tree;
2008 bool found_whole_row;
2009
2010 /* Convert text string to node tree */
2011 pred_str = TextDatumGetCString(datum);
2012 pred_tree = (Node *) stringToNode(pred_str);
2013
2014 /* Adjust Vars to match new table's column numbering */
2015 pred_tree = map_variable_attnos(pred_tree,
2016 1, 0,
2017 attmap,
2018 InvalidOid, &found_whole_row);
2019
2020 /* As in expandTableLikeClause, reject whole-row variables */
2021 if (found_whole_row)
2022 ereport(ERROR,
2023 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2024 errmsg("cannot convert whole-row table reference"),
2025 errdetail("Index \"%s\" contains a whole-row table reference.",
2026 RelationGetRelationName(source_idx))));
2027
2028 index->whereClause = pred_tree;
2029 }
2030
2031 /* Clean up */
2032 ReleaseSysCache(ht_idxrel);
2033 ReleaseSysCache(ht_am);
2034
2035 return index;
2036}
#define DatumGetArrayTypeP(X)
Definition: array.h:261
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3698
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define InvalidSubTransactionId
Definition: c.h:663
int16_t int16
Definition: c.h:533
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
i
int i
Definition: isn.c:77
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1063
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:920
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:1006
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static List * get_collation(Oid collation, Oid actual_datatype)
static List * get_opclass(Oid opclass, Oid actual_datatype)
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
FormData_pg_constraint * Form_pg_constraint
Definition: pg_constraint.h:175
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:988
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define list_make2(x1, x2)
Definition: pg_list.h:214
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:252
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
uint64_t Datum
Definition: postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1351
#define InvalidRelFileNumber
Definition: relpath.h:26
bool amcanorder
Definition: amapi.h:246
Node * expr
Definition: parsenodes.h:812
SortByDir ordering
Definition: parsenodes.h:817
List * opclassopts
Definition: parsenodes.h:816
char * indexcolname
Definition: parsenodes.h:813
SortByNulls nulls_ordering
Definition: parsenodes.h:818
List * opclass
Definition: parsenodes.h:815
char * name
Definition: parsenodes.h:811
List * collation
Definition: parsenodes.h:814
struct IndexAmRoutine * rd_indam
Definition: rel.h:206
struct HeapTupleData * rd_indextuple
Definition: rel.h:194
int16 * rd_indoption
Definition: rel.h:211
Definition: type.h:96
Definition: c.h:731
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:738
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:625

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

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

transformAlterTableStmt()

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

Definition at line 3525 of file parse_utilcmd.c.

3528{
3529 Relation rel;
3530 TupleDesc tupdesc;
3531 ParseState *pstate;
3533 List *save_alist;
3534 ListCell *lcmd,
3535 *l;
3536 List *newcmds = NIL;
3537 bool skipValidation = true;
3538 AlterTableCmd *newcmd;
3539 ParseNamespaceItem *nsitem;
3540
3541 /* Caller is responsible for locking the relation */
3542 rel = relation_open(relid, NoLock);
3543 tupdesc = RelationGetDescr(rel);
3544
3545 /* Set up pstate */
3546 pstate = make_parsestate(NULL);
3547 pstate->p_sourcetext = queryString;
3548 nsitem = addRangeTableEntryForRelation(pstate,
3549 rel,
3551 NULL,
3552 false,
3553 true);
3554 addNSItemToQuery(pstate, nsitem, false, true, true);
3555
3556 /* Set up CreateStmtContext */
3557 cxt.pstate = pstate;
3558 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3559 {
3560 cxt.stmtType = "ALTER FOREIGN TABLE";
3561 cxt.isforeign = true;
3562 }
3563 else
3564 {
3565 cxt.stmtType = "ALTER TABLE";
3566 cxt.isforeign = false;
3567 }
3568 cxt.relation = stmt->relation;
3569 cxt.rel = rel;
3570 cxt.inhRelations = NIL;
3571 cxt.isalter = true;
3572 cxt.columns = NIL;
3573 cxt.ckconstraints = NIL;
3574 cxt.nnconstraints = NIL;
3575 cxt.fkconstraints = NIL;
3576 cxt.ixconstraints = NIL;
3577 cxt.likeclauses = NIL;
3578 cxt.blist = NIL;
3579 cxt.alist = NIL;
3580 cxt.pkey = NULL;
3581 cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3582 cxt.partbound = NULL;
3583 cxt.ofType = false;
3584
3585 /*
3586 * Transform ALTER subcommands that need it (most don't). These largely
3587 * re-use code from CREATE TABLE.
3588 */
3589 foreach(lcmd, stmt->cmds)
3590 {
3591 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3592
3593 switch (cmd->subtype)
3594 {
3595 case AT_AddColumn:
3596 {
3597 ColumnDef *def = castNode(ColumnDef, cmd->def);
3598
3599 transformColumnDefinition(&cxt, def);
3600
3601 /*
3602 * If the column has a non-null default, we can't skip
3603 * validation of foreign keys.
3604 */
3605 if (def->raw_default != NULL)
3606 skipValidation = false;
3607
3608 /*
3609 * All constraints are processed in other ways. Remove the
3610 * original list
3611 */
3612 def->constraints = NIL;
3613
3614 newcmds = lappend(newcmds, cmd);
3615 break;
3616 }
3617
3618 case AT_AddConstraint:
3619
3620 /*
3621 * The original AddConstraint cmd node doesn't go to newcmds
3622 */
3623 if (IsA(cmd->def, Constraint))
3624 {
3625 transformTableConstraint(&cxt, (Constraint *) cmd->def);
3626 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3627 skipValidation = false;
3628 }
3629 else
3630 elog(ERROR, "unrecognized node type: %d",
3631 (int) nodeTag(cmd->def));
3632 break;
3633
3634 case AT_AlterColumnType:
3635 {
3636 ColumnDef *def = castNode(ColumnDef, cmd->def);
3638
3639 /*
3640 * For ALTER COLUMN TYPE, transform the USING clause if
3641 * one was specified.
3642 */
3643 if (def->raw_default)
3644 {
3645 def->cooked_default =
3646 transformExpr(pstate, def->raw_default,
3648 }
3649
3650 /*
3651 * For identity column, create ALTER SEQUENCE command to
3652 * change the data type of the sequence. Identity sequence
3653 * is associated with the top level partitioned table.
3654 * Hence ignore partitions.
3655 */
3656 if (!RelationGetForm(rel)->relispartition)
3657 {
3658 attnum = get_attnum(relid, cmd->name);
3660 ereport(ERROR,
3661 (errcode(ERRCODE_UNDEFINED_COLUMN),
3662 errmsg("column \"%s\" of relation \"%s\" does not exist",
3663 cmd->name, RelationGetRelationName(rel))));
3664
3665 if (attnum > 0 &&
3666 TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3667 {
3668 Oid seq_relid = getIdentitySequence(rel, attnum, false);
3669 Oid typeOid = typenameTypeId(pstate, def->typeName);
3670 AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3671
3672 altseqstmt->sequence
3674 get_rel_name(seq_relid),
3675 -1);
3676 altseqstmt->options = list_make1(makeDefElem("as",
3677 (Node *) makeTypeNameFromOid(typeOid, -1),
3678 -1));
3679 altseqstmt->for_identity = true;
3680 cxt.blist = lappend(cxt.blist, altseqstmt);
3681 }
3682 }
3683
3684 newcmds = lappend(newcmds, cmd);
3685 break;
3686 }
3687
3688 case AT_AddIdentity:
3689 {
3690 Constraint *def = castNode(Constraint, cmd->def);
3691 ColumnDef *newdef = makeNode(ColumnDef);
3693
3694 newdef->colname = cmd->name;
3695 newdef->identity = def->generated_when;
3696 cmd->def = (Node *) newdef;
3697
3698 attnum = get_attnum(relid, cmd->name);
3700 ereport(ERROR,
3701 (errcode(ERRCODE_UNDEFINED_COLUMN),
3702 errmsg("column \"%s\" of relation \"%s\" does not exist",
3703 cmd->name, RelationGetRelationName(rel))));
3704
3705 generateSerialExtraStmts(&cxt, newdef,
3706 get_atttype(relid, attnum),
3707 def->options, true, true,
3708 NULL, NULL);
3709
3710 newcmds = lappend(newcmds, cmd);
3711 break;
3712 }
3713
3714 case AT_SetIdentity:
3715 {
3716 /*
3717 * Create an ALTER SEQUENCE statement for the internal
3718 * sequence of the identity column.
3719 */
3720 ListCell *lc;
3721 List *newseqopts = NIL;
3722 List *newdef = NIL;
3724 Oid seq_relid;
3725
3726 /*
3727 * Split options into those handled by ALTER SEQUENCE and
3728 * those for ALTER TABLE proper.
3729 */
3730 foreach(lc, castNode(List, cmd->def))
3731 {
3732 DefElem *def = lfirst_node(DefElem, lc);
3733
3734 if (strcmp(def->defname, "generated") == 0)
3735 newdef = lappend(newdef, def);
3736 else
3737 newseqopts = lappend(newseqopts, def);
3738 }
3739
3740 attnum = get_attnum(relid, cmd->name);
3742 ereport(ERROR,
3743 (errcode(ERRCODE_UNDEFINED_COLUMN),
3744 errmsg("column \"%s\" of relation \"%s\" does not exist",
3745 cmd->name, RelationGetRelationName(rel))));
3746
3747 seq_relid = getIdentitySequence(rel, attnum, true);
3748
3749 if (seq_relid)
3750 {
3751 AlterSeqStmt *seqstmt;
3752
3753 seqstmt = makeNode(AlterSeqStmt);
3755 get_rel_name(seq_relid), -1);
3756 seqstmt->options = newseqopts;
3757 seqstmt->for_identity = true;
3758 seqstmt->missing_ok = false;
3759
3760 cxt.blist = lappend(cxt.blist, seqstmt);
3761 }
3762
3763 /*
3764 * If column was not an identity column, we just let the
3765 * ALTER TABLE command error out later. (There are cases
3766 * this fails to cover, but we'll need to restructure
3767 * where creation of the sequence dependency linkage
3768 * happens before we can fix it.)
3769 */
3770
3771 cmd->def = (Node *) newdef;
3772 newcmds = lappend(newcmds, cmd);
3773 break;
3774 }
3775
3776 case AT_AttachPartition:
3777 case AT_DetachPartition:
3778 {
3779 PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3780
3781 transformPartitionCmd(&cxt, partcmd);
3782 /* assign transformed value of the partition bound */
3783 partcmd->bound = cxt.partbound;
3784 }
3785
3786 newcmds = lappend(newcmds, cmd);
3787 break;
3788
3789 default:
3790
3791 /*
3792 * Currently, we shouldn't actually get here for subcommand
3793 * types that don't require transformation; but if we do, just
3794 * emit them unchanged.
3795 */
3796 newcmds = lappend(newcmds, cmd);
3797 break;
3798 }
3799 }
3800
3801 /*
3802 * Transfer anything we already have in cxt.alist into save_alist, to keep
3803 * it separate from the output of transformIndexConstraints.
3804 */
3805 save_alist = cxt.alist;
3806 cxt.alist = NIL;
3807
3808 /* Postprocess constraints */
3810 transformFKConstraints(&cxt, skipValidation, true);
3811 transformCheckConstraints(&cxt, false);
3812
3813 /*
3814 * Push any index-creation commands into the ALTER, so that they can be
3815 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3816 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3817 * subcommand has already been through transformIndexStmt.
3818 */
3819 foreach(l, cxt.alist)
3820 {
3821 Node *istmt = (Node *) lfirst(l);
3822
3823 /*
3824 * We assume here that cxt.alist contains only IndexStmts generated
3825 * from primary key constraints.
3826 */
3827 if (IsA(istmt, IndexStmt))
3828 {
3829 IndexStmt *idxstmt = (IndexStmt *) istmt;
3830
3831 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3832 newcmd = makeNode(AlterTableCmd);
3834 newcmd->def = (Node *) idxstmt;
3835 newcmds = lappend(newcmds, newcmd);
3836 }
3837 else
3838 elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3839 }
3840 cxt.alist = NIL;
3841
3842 /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3844 {
3845 newcmd = makeNode(AlterTableCmd);
3846 newcmd->subtype = AT_AddConstraint;
3847 newcmd->def = (Node *) def;
3848 newcmds = lappend(newcmds, newcmd);
3849 }
3851 {
3852 newcmd = makeNode(AlterTableCmd);
3853 newcmd->subtype = AT_AddConstraint;
3854 newcmd->def = (Node *) def;
3855 newcmds = lappend(newcmds, newcmd);
3856 }
3858 {
3859 newcmd = makeNode(AlterTableCmd);
3860 newcmd->subtype = AT_AddConstraint;
3861 newcmd->def = (Node *) def;
3862 newcmds = lappend(newcmds, newcmd);
3863 }
3864
3865 /* Close rel */
3866 relation_close(rel, NoLock);
3867
3868 /*
3869 * Output results.
3870 */
3871 stmt->cmds = newcmds;
3872
3873 *beforeStmts = cxt.blist;
3874 *afterStmts = list_concat(cxt.alist, save_alist);
3875
3876 return stmt;
3877}
#define InvalidAttrNumber
Definition: attnum.h:23
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2095
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:951
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2119
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:637
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:473
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:547
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define nodeTag(nodeptr)
Definition: nodes.h:139
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:118
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:75
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
Definition: parse_utilcmd.c:390
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
Definition: parse_utilcmd.c:591
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ CONSTR_FOREIGN
Definition: parsenodes.h:2809
@ AT_AddIndexConstraint
Definition: parsenodes.h:2438
@ AT_SetIdentity
Definition: parsenodes.h:2480
@ AT_AddIndex
Definition: parsenodes.h:2431
@ AT_AddIdentity
Definition: parsenodes.h:2479
@ AT_AlterColumnType
Definition: parsenodes.h:2441
@ AT_DetachPartition
Definition: parsenodes.h:2477
@ AT_AttachPartition
Definition: parsenodes.h:2476
@ AT_AddColumn
Definition: parsenodes.h:2417
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:945
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define list_make1(x1)
Definition: pg_list.h:212
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
#define RelationGetForm(relation)
Definition: rel.h:508
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
List * options
Definition: parsenodes.h:3236
RangeVar * sequence
Definition: parsenodes.h:3235
bool for_identity
Definition: parsenodes.h:3237
bool missing_ok
Definition: parsenodes.h:3238
char * name
Definition: parsenodes.h:2489
char identity
Definition: parsenodes.h:765
List * constraints
Definition: parsenodes.h:771
Node * cooked_default
Definition: parsenodes.h:764
char * colname
Definition: parsenodes.h:754
TypeName * typeName
Definition: parsenodes.h:755
Node * raw_default
Definition: parsenodes.h:763
List * options
Definition: parsenodes.h:2855
char generated_when
Definition: parsenodes.h:2845
List * fkconstraints
Definition: parse_utilcmd.c:85
IndexStmt * pkey
Definition: parse_utilcmd.c:92
List * likeclauses
Definition: parse_utilcmd.c:87
List * ckconstraints
Definition: parse_utilcmd.c:83
const char * stmtType
Definition: parse_utilcmd.c:76
List * inhRelations
Definition: parse_utilcmd.c:79
List * ixconstraints
Definition: parse_utilcmd.c:86
RangeVar * relation
Definition: parse_utilcmd.c:77
ParseState * pstate
Definition: parse_utilcmd.c:75
List * nnconstraints
Definition: parse_utilcmd.c:84
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
char * defname
Definition: parsenodes.h:843
Oid indexOid
Definition: parsenodes.h:3496
const char * p_sourcetext
Definition: parse_node.h:195
PartitionBoundSpec * bound
Definition: parsenodes.h:975

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

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

transformCreateSchemaStmtElements()

List * transformCreateSchemaStmtElements ( ListschemaElts,
const char *  schemaName 
)

Definition at line 4102 of file parse_utilcmd.c.

4103{
4105 List *result;
4106 ListCell *elements;
4107
4108 cxt.schemaname = schemaName;
4109 cxt.sequences = NIL;
4110 cxt.tables = NIL;
4111 cxt.views = NIL;
4112 cxt.indexes = NIL;
4113 cxt.triggers = NIL;
4114 cxt.grants = NIL;
4115
4116 /*
4117 * Run through each schema element in the schema element list. Separate
4118 * statements by type, and do preliminary analysis.
4119 */
4120 foreach(elements, schemaElts)
4121 {
4122 Node *element = lfirst(elements);
4123
4124 switch (nodeTag(element))
4125 {
4126 case T_CreateSeqStmt:
4127 {
4129
4131 cxt.sequences = lappend(cxt.sequences, element);
4132 }
4133 break;
4134
4135 case T_CreateStmt:
4136 {
4137 CreateStmt *elp = (CreateStmt *) element;
4138
4140
4141 /*
4142 * XXX todo: deal with constraints
4143 */
4144 cxt.tables = lappend(cxt.tables, element);
4145 }
4146 break;
4147
4148 case T_ViewStmt:
4149 {
4150 ViewStmt *elp = (ViewStmt *) element;
4151
4153
4154 /*
4155 * XXX todo: deal with references between views
4156 */
4157 cxt.views = lappend(cxt.views, element);
4158 }
4159 break;
4160
4161 case T_IndexStmt:
4162 {
4163 IndexStmt *elp = (IndexStmt *) element;
4164
4166 cxt.indexes = lappend(cxt.indexes, element);
4167 }
4168 break;
4169
4170 case T_CreateTrigStmt:
4171 {
4173
4175 cxt.triggers = lappend(cxt.triggers, element);
4176 }
4177 break;
4178
4179 case T_GrantStmt:
4180 cxt.grants = lappend(cxt.grants, element);
4181 break;
4182
4183 default:
4184 elog(ERROR, "unrecognized node type: %d",
4185 (int) nodeTag(element));
4186 }
4187 }
4188
4189 result = NIL;
4190 result = list_concat(result, cxt.sequences);
4191 result = list_concat(result, cxt.tables);
4192 result = list_concat(result, cxt.views);
4193 result = list_concat(result, cxt.indexes);
4194 result = list_concat(result, cxt.triggers);
4195 result = list_concat(result, cxt.grants);
4196
4197 return result;
4198}
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
const char * schemaname
Definition: parse_utilcmd.c:101
RangeVar * sequence
Definition: parsenodes.h:3225
RangeVar * relation
Definition: parsenodes.h:2750
RangeVar * relation
Definition: parsenodes.h:3112
RangeVar * relation
Definition: parsenodes.h:3486
RangeVar * view
Definition: parsenodes.h:3879

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

Referenced by CreateSchemaCommand().

transformCreateStmt()

List * transformCreateStmt ( CreateStmtstmt,
const char *  queryString 
)

Definition at line 164 of file parse_utilcmd.c.

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

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

Referenced by ProcessUtilitySlow().

transformIndexStmt()

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

Definition at line 3049 of file parse_utilcmd.c.

3050{
3051 ParseState *pstate;
3052 ParseNamespaceItem *nsitem;
3053 ListCell *l;
3054 Relation rel;
3055
3056 /* Nothing to do if statement already transformed. */
3057 if (stmt->transformed)
3058 return stmt;
3059
3060 /* Set up pstate */
3061 pstate = make_parsestate(NULL);
3062 pstate->p_sourcetext = queryString;
3063
3064 /*
3065 * Put the parent table into the rtable so that the expressions can refer
3066 * to its fields without qualification. Caller is responsible for locking
3067 * relation, but we still need to open it.
3068 */
3069 rel = relation_open(relid, NoLock);
3070 nsitem = addRangeTableEntryForRelation(pstate, rel,
3072 NULL, false, true);
3073
3074 /* no to join list, yes to namespaces */
3075 addNSItemToQuery(pstate, nsitem, false, true, true);
3076
3077 /* take care of the where clause */
3078 if (stmt->whereClause)
3079 {
3080 stmt->whereClause = transformWhereClause(pstate,
3081 stmt->whereClause,
3083 "WHERE");
3084 /* we have to fix its collations too */
3085 assign_expr_collations(pstate, stmt->whereClause);
3086 }
3087
3088 /* take care of any index expressions */
3089 foreach(l, stmt->indexParams)
3090 {
3091 IndexElem *ielem = (IndexElem *) lfirst(l);
3092
3093 if (ielem->expr)
3094 {
3095 /* Extract preliminary index col name before transforming expr */
3096 if (ielem->indexcolname == NULL)
3097 ielem->indexcolname = FigureIndexColname(ielem->expr);
3098
3099 /* Now do parse transformation of the expression */
3100 ielem->expr = transformExpr(pstate, ielem->expr,
3102
3103 /* We have to fix its collations too */
3104 assign_expr_collations(pstate, ielem->expr);
3105
3106 /*
3107 * transformExpr() should have already rejected subqueries,
3108 * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3109 * for an index expression.
3110 *
3111 * DefineIndex() will make more checks.
3112 */
3113 }
3114 }
3115
3116 /*
3117 * Check that only the base rel is mentioned. (This should be dead code
3118 * now that add_missing_from is history.)
3119 */
3120 if (list_length(pstate->p_rtable) != 1)
3121 ereport(ERROR,
3122 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3123 errmsg("index expressions and predicates can refer only to the table being indexed")));
3124
3125 free_parsestate(pstate);
3126
3127 /* Close relation */
3128 table_close(rel, NoLock);
3129
3130 /* Mark statement as successfully transformed */
3131 stmt->transformed = true;
3132
3133 return stmt;
3134}
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Definition: parse_clause.c:1854
void assign_expr_collations(ParseState *pstate, Node *expr)
Definition: parse_collate.c:177
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:72
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
char * FigureIndexColname(Node *node)
Definition: parse_target.c:1731
static int list_length(const List *l)
Definition: pg_list.h:152
List * p_rtable
Definition: parse_node.h:196

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

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

transformPartitionBound()

PartitionBoundSpec * transformPartitionBound ( ParseStatepstate,
Relation  parent,
PartitionBoundSpecspec 
)

Definition at line 4278 of file parse_utilcmd.c.

4280{
4281 PartitionBoundSpec *result_spec;
4283 char strategy = get_partition_strategy(key);
4284 int partnatts = get_partition_natts(key);
4285 List *partexprs = get_partition_exprs(key);
4286
4287 /* Avoid scribbling on input */
4288 result_spec = copyObject(spec);
4289
4290 if (spec->is_default)
4291 {
4292 /*
4293 * Hash partitioning does not support a default partition; there's no
4294 * use case for it (since the set of partitions to create is perfectly
4295 * defined), and if users do get into it accidentally, it's hard to
4296 * back out from it afterwards.
4297 */
4298 if (strategy == PARTITION_STRATEGY_HASH)
4299 ereport(ERROR,
4300 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4301 errmsg("a hash-partitioned table may not have a default partition")));
4302
4303 /*
4304 * In case of the default partition, parser had no way to identify the
4305 * partition strategy. Assign the parent's strategy to the default
4306 * partition bound spec.
4307 */
4308 result_spec->strategy = strategy;
4309
4310 return result_spec;
4311 }
4312
4313 if (strategy == PARTITION_STRATEGY_HASH)
4314 {
4315 if (spec->strategy != PARTITION_STRATEGY_HASH)
4316 ereport(ERROR,
4317 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4318 errmsg("invalid bound specification for a hash partition"),
4319 parser_errposition(pstate, exprLocation((Node *) spec))));
4320
4321 if (spec->modulus <= 0)
4322 ereport(ERROR,
4323 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4324 errmsg("modulus for hash partition must be an integer value greater than zero")));
4325
4326 Assert(spec->remainder >= 0);
4327
4328 if (spec->remainder >= spec->modulus)
4329 ereport(ERROR,
4330 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4331 errmsg("remainder for hash partition must be less than modulus")));
4332 }
4333 else if (strategy == PARTITION_STRATEGY_LIST)
4334 {
4335 ListCell *cell;
4336 char *colname;
4337 Oid coltype;
4338 int32 coltypmod;
4339 Oid partcollation;
4340
4341 if (spec->strategy != PARTITION_STRATEGY_LIST)
4342 ereport(ERROR,
4343 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4344 errmsg("invalid bound specification for a list partition"),
4345 parser_errposition(pstate, exprLocation((Node *) spec))));
4346
4347 /* Get the only column's name in case we need to output an error */
4348 if (key->partattrs[0] != 0)
4349 colname = get_attname(RelationGetRelid(parent),
4350 key->partattrs[0], false);
4351 else
4352 colname = deparse_expression((Node *) linitial(partexprs),
4354 RelationGetRelid(parent)),
4355 false, false);
4356 /* Need its type data too */
4357 coltype = get_partition_col_typid(key, 0);
4358 coltypmod = get_partition_col_typmod(key, 0);
4359 partcollation = get_partition_col_collation(key, 0);
4360
4361 result_spec->listdatums = NIL;
4362 foreach(cell, spec->listdatums)
4363 {
4364 Node *expr = lfirst(cell);
4365 Const *value;
4366 ListCell *cell2;
4367 bool duplicate;
4368
4369 value = transformPartitionBoundValue(pstate, expr,
4370 colname, coltype, coltypmod,
4371 partcollation);
4372
4373 /* Don't add to the result if the value is a duplicate */
4374 duplicate = false;
4375 foreach(cell2, result_spec->listdatums)
4376 {
4377 Const *value2 = lfirst_node(Const, cell2);
4378
4379 if (equal(value, value2))
4380 {
4381 duplicate = true;
4382 break;
4383 }
4384 }
4385 if (duplicate)
4386 continue;
4387
4388 result_spec->listdatums = lappend(result_spec->listdatums,
4389 value);
4390 }
4391 }
4392 else if (strategy == PARTITION_STRATEGY_RANGE)
4393 {
4395 ereport(ERROR,
4396 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4397 errmsg("invalid bound specification for a range partition"),
4398 parser_errposition(pstate, exprLocation((Node *) spec))));
4399
4400 if (list_length(spec->lowerdatums) != partnatts)
4401 ereport(ERROR,
4402 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4403 errmsg("FROM must specify exactly one value per partitioning column")));
4404 if (list_length(spec->upperdatums) != partnatts)
4405 ereport(ERROR,
4406 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4407 errmsg("TO must specify exactly one value per partitioning column")));
4408
4409 /*
4410 * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4411 * any necessary validation.
4412 */
4413 result_spec->lowerdatums =
4415 parent);
4416 result_spec->upperdatums =
4418 parent);
4419 }
4420 else
4421 elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4422
4423 return result_spec;
4424}
int32_t int32
Definition: c.h:534
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static struct @169 value
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1388
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
static Const * transformPartitionBoundValue(ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:902
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:900
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:901
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:59
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:92
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:65
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:86
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:71
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:98
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3707
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3644
Definition: primnodes.h:324
List * lowerdatums
Definition: parsenodes.h:939
List * listdatums
Definition: parsenodes.h:936
List * upperdatums
Definition: parsenodes.h:940

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

Referenced by DefineRelation(), and transformPartitionCmd().

transformRuleStmt()

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

Definition at line 3219 of file parse_utilcmd.c.

3221{
3222 Relation rel;
3223 ParseState *pstate;
3224 ParseNamespaceItem *oldnsitem;
3225 ParseNamespaceItem *newnsitem;
3226
3227 /*
3228 * To avoid deadlock, make sure the first thing we do is grab
3229 * AccessExclusiveLock on the target relation. This will be needed by
3230 * DefineQueryRewrite(), and we don't want to grab a lesser lock
3231 * beforehand.
3232 */
3233 rel = table_openrv(stmt->relation, AccessExclusiveLock);
3234
3235 if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3236 ereport(ERROR,
3237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3238 errmsg("rules on materialized views are not supported")));
3239
3240 /* Set up pstate */
3241 pstate = make_parsestate(NULL);
3242 pstate->p_sourcetext = queryString;
3243
3244 /*
3245 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3246 * Set up their ParseNamespaceItems in the main pstate for use in parsing
3247 * the rule qualification.
3248 */
3249 oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3251 makeAlias("old", NIL),
3252 false, false);
3253 newnsitem = addRangeTableEntryForRelation(pstate, rel,
3255 makeAlias("new", NIL),
3256 false, false);
3257
3258 /*
3259 * They must be in the namespace too for lookup purposes, but only add the
3260 * one(s) that are relevant for the current kind of rule. In an UPDATE
3261 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3262 * there's no need to be so picky for INSERT & DELETE. We do not add them
3263 * to the joinlist.
3264 */
3265 switch (stmt->event)
3266 {
3267 case CMD_SELECT:
3268 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3269 break;
3270 case CMD_UPDATE:
3271 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3272 addNSItemToQuery(pstate, newnsitem, false, true, true);
3273 break;
3274 case CMD_INSERT:
3275 addNSItemToQuery(pstate, newnsitem, false, true, true);
3276 break;
3277 case CMD_DELETE:
3278 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3279 break;
3280 default:
3281 elog(ERROR, "unrecognized event type: %d",
3282 (int) stmt->event);
3283 break;
3284 }
3285
3286 /* take care of the where clause */
3287 *whereClause = transformWhereClause(pstate,
3288 stmt->whereClause,
3290 "WHERE");
3291 /* we have to fix its collations too */
3292 assign_expr_collations(pstate, *whereClause);
3293
3294 /* this is probably dead code without add_missing_from: */
3295 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3296 ereport(ERROR,
3297 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3298 errmsg("rule WHERE condition cannot contain references to other relations")));
3299
3300 /*
3301 * 'instead nothing' rules with a qualification need a query rangetable so
3302 * the rewrite handler can add the negated rule qualification to the
3303 * original query. We create a query with the new command type CMD_NOTHING
3304 * here that is treated specially by the rewrite system.
3305 */
3306 if (stmt->actions == NIL)
3307 {
3308 Query *nothing_qry = makeNode(Query);
3309
3310 nothing_qry->commandType = CMD_NOTHING;
3311 nothing_qry->rtable = pstate->p_rtable;
3312 nothing_qry->rteperminfos = pstate->p_rteperminfos;
3313 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3314
3315 *actions = list_make1(nothing_qry);
3316 }
3317 else
3318 {
3319 ListCell *l;
3320 List *newactions = NIL;
3321
3322 /*
3323 * transform each statement, like parse_sub_analyze()
3324 */
3325 foreach(l, stmt->actions)
3326 {
3327 Node *action = (Node *) lfirst(l);
3328 ParseState *sub_pstate = make_parsestate(NULL);
3329 Query *sub_qry,
3330 *top_subqry;
3331 bool has_old,
3332 has_new;
3333
3334 /*
3335 * Since outer ParseState isn't parent of inner, have to pass down
3336 * the query text by hand.
3337 */
3338 sub_pstate->p_sourcetext = queryString;
3339
3340 /*
3341 * Set up OLD/NEW in the rtable for this statement. The entries
3342 * are added only to relnamespace, not varnamespace, because we
3343 * don't want them to be referred to by unqualified field names
3344 * nor "*" in the rule actions. We decide later whether to put
3345 * them in the joinlist.
3346 */
3347 oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3349 makeAlias("old", NIL),
3350 false, false);
3351 newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3353 makeAlias("new", NIL),
3354 false, false);
3355 addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3356 addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3357
3358 /* Transform the rule action statement */
3359 top_subqry = transformStmt(sub_pstate, action);
3360
3361 /*
3362 * We cannot support utility-statement actions (eg NOTIFY) with
3363 * nonempty rule WHERE conditions, because there's no way to make
3364 * the utility action execute conditionally.
3365 */
3366 if (top_subqry->commandType == CMD_UTILITY &&
3367 *whereClause != NULL)
3368 ereport(ERROR,
3369 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3370 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3371
3372 /*
3373 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3374 * into the SELECT, and that's what we need to look at. (Ugly
3375 * kluge ... try to fix this when we redesign querytrees.)
3376 */
3377 sub_qry = getInsertSelectQuery(top_subqry, NULL);
3378
3379 /*
3380 * If the sub_qry is a setop, we cannot attach any qualifications
3381 * to it, because the planner won't notice them. This could
3382 * perhaps be relaxed someday, but for now, we may as well reject
3383 * such a rule immediately.
3384 */
3385 if (sub_qry->setOperations != NULL && *whereClause != NULL)
3386 ereport(ERROR,
3387 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3388 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3389
3390 /*
3391 * Validate action's use of OLD/NEW, qual too
3392 */
3393 has_old =
3394 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3395 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3396 has_new =
3397 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3398 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3399
3400 switch (stmt->event)
3401 {
3402 case CMD_SELECT:
3403 if (has_old)
3404 ereport(ERROR,
3405 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3406 errmsg("ON SELECT rule cannot use OLD")));
3407 if (has_new)
3408 ereport(ERROR,
3409 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3410 errmsg("ON SELECT rule cannot use NEW")));
3411 break;
3412 case CMD_UPDATE:
3413 /* both are OK */
3414 break;
3415 case CMD_INSERT:
3416 if (has_old)
3417 ereport(ERROR,
3418 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3419 errmsg("ON INSERT rule cannot use OLD")));
3420 break;
3421 case CMD_DELETE:
3422 if (has_new)
3423 ereport(ERROR,
3424 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3425 errmsg("ON DELETE rule cannot use NEW")));
3426 break;
3427 default:
3428 elog(ERROR, "unrecognized event type: %d",
3429 (int) stmt->event);
3430 break;
3431 }
3432
3433 /*
3434 * OLD/NEW are not allowed in WITH queries, because they would
3435 * amount to outer references for the WITH, which we disallow.
3436 * However, they were already in the outer rangetable when we
3437 * analyzed the query, so we have to check.
3438 *
3439 * Note that in the INSERT...SELECT case, we need to examine the
3440 * CTE lists of both top_subqry and sub_qry.
3441 *
3442 * Note that we aren't digging into the body of the query looking
3443 * for WITHs in nested sub-SELECTs. A WITH down there can
3444 * legitimately refer to OLD/NEW, because it'd be an
3445 * indirect-correlated outer reference.
3446 */
3447 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3448 PRS2_OLD_VARNO, 0) ||
3449 rangeTableEntry_used((Node *) sub_qry->cteList,
3450 PRS2_OLD_VARNO, 0))
3451 ereport(ERROR,
3452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3453 errmsg("cannot refer to OLD within WITH query")));
3454 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3455 PRS2_NEW_VARNO, 0) ||
3456 rangeTableEntry_used((Node *) sub_qry->cteList,
3457 PRS2_NEW_VARNO, 0))
3458 ereport(ERROR,
3459 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3460 errmsg("cannot refer to NEW within WITH query")));
3461
3462 /*
3463 * For efficiency's sake, add OLD to the rule action's jointree
3464 * only if it was actually referenced in the statement or qual.
3465 *
3466 * For INSERT, NEW is not really a relation (only a reference to
3467 * the to-be-inserted tuple) and should never be added to the
3468 * jointree.
3469 *
3470 * For UPDATE, we treat NEW as being another kind of reference to
3471 * OLD, because it represents references to *transformed* tuples
3472 * of the existing relation. It would be wrong to enter NEW
3473 * separately in the jointree, since that would cause a double
3474 * join of the updated relation. It's also wrong to fail to make
3475 * a jointree entry if only NEW and not OLD is mentioned.
3476 */
3477 if (has_old || (has_new && stmt->event == CMD_UPDATE))
3478 {
3479 RangeTblRef *rtr;
3480
3481 /*
3482 * If sub_qry is a setop, manipulating its jointree will do no
3483 * good at all, because the jointree is dummy. (This should be
3484 * a can't-happen case because of prior tests.)
3485 */
3486 if (sub_qry->setOperations != NULL)
3487 ereport(ERROR,
3488 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3489 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3490 /* hackishly add OLD to the already-built FROM clause */
3491 rtr = makeNode(RangeTblRef);
3492 rtr->rtindex = oldnsitem->p_rtindex;
3493 sub_qry->jointree->fromlist =
3494 lappend(sub_qry->jointree->fromlist, rtr);
3495 }
3496
3497 newactions = lappend(newactions, top_subqry);
3498
3499 free_parsestate(sub_pstate);
3500 }
3501
3502 *actions = newactions;
3503 }
3504
3505 free_parsestate(pstate);
3506
3507 /* Close relation, but keep the exclusive lock */
3508 table_close(rel, NoLock);
3509}
#define AccessExclusiveLock
Definition: lockdefs.h:43
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:438
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:336
@ CMD_UTILITY
Definition: nodes.h:280
@ CMD_INSERT
Definition: nodes.h:277
@ CMD_DELETE
Definition: nodes.h:278
@ CMD_UPDATE
Definition: nodes.h:276
@ CMD_SELECT
Definition: nodes.h:275
@ CMD_NOTHING
Definition: nodes.h:282
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:323
#define PRS2_OLD_VARNO
Definition: primnodes.h:250
#define PRS2_NEW_VARNO
Definition: primnodes.h:251
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:1061
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:1093
List * fromlist
Definition: primnodes.h:2356
List * p_rteperminfos
Definition: parse_node.h:197
Definition: parsenodes.h:118
FromExpr * jointree
Definition: parsenodes.h:182
Node * setOperations
Definition: parsenodes.h:236
List * cteList
Definition: parsenodes.h:173
List * rtable
Definition: parsenodes.h:175
CmdType commandType
Definition: parsenodes.h:121
int rtindex
Definition: primnodes.h:2294
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

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

Referenced by DefineRule().

transformStatsStmt()

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

Definition at line 3144 of file parse_utilcmd.c.

3145{
3146 ParseState *pstate;
3147 ParseNamespaceItem *nsitem;
3148 ListCell *l;
3149 Relation rel;
3150
3151 /* Nothing to do if statement already transformed. */
3152 if (stmt->transformed)
3153 return stmt;
3154
3155 /* Set up pstate */
3156 pstate = make_parsestate(NULL);
3157 pstate->p_sourcetext = queryString;
3158
3159 /*
3160 * Put the parent table into the rtable so that the expressions can refer
3161 * to its fields without qualification. Caller is responsible for locking
3162 * relation, but we still need to open it.
3163 */
3164 rel = relation_open(relid, NoLock);
3165 nsitem = addRangeTableEntryForRelation(pstate, rel,
3167 NULL, false, true);
3168
3169 /* no to join list, yes to namespaces */
3170 addNSItemToQuery(pstate, nsitem, false, true, true);
3171
3172 /* take care of any expressions */
3173 foreach(l, stmt->exprs)
3174 {
3175 StatsElem *selem = (StatsElem *) lfirst(l);
3176
3177 if (selem->expr)
3178 {
3179 /* Now do parse transformation of the expression */
3180 selem->expr = transformExpr(pstate, selem->expr,
3182
3183 /* We have to fix its collations too */
3184 assign_expr_collations(pstate, selem->expr);
3185 }
3186 }
3187
3188 /*
3189 * Check that only the base rel is mentioned. (This should be dead code
3190 * now that add_missing_from is history.)
3191 */
3192 if (list_length(pstate->p_rtable) != 1)
3193 ereport(ERROR,
3194 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3195 errmsg("statistics expressions can refer only to the table being referenced")));
3196
3197 free_parsestate(pstate);
3198
3199 /* Close relation */
3200 table_close(rel, NoLock);
3201
3202 /* Mark statement as successfully transformed */
3203 stmt->transformed = true;
3204
3205 return stmt;
3206}
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:74
Node * expr
Definition: parsenodes.h:3542

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, StatsElem::expr, EXPR_KIND_STATS_EXPRESSION, free_parsestate(), lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), and transformExpr().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

AltStyle によって変換されたページ (->オリジナル) /