PostgreSQL Source Code git master
parse_utilcmd.h File Reference
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.

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)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const struct AttrMap *attmap, Oid *constraintOid)
 

Function Documentation

◆ expandTableLikeClause()

List * expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1322 of file parse_utilcmd.c.

1323{
1324 List *result = NIL;
1325 List *atsubcmds = NIL;
1326 AttrNumber parent_attno;
1327 Relation relation;
1328 Relation childrel;
1329 TupleDesc tupleDesc;
1330 TupleConstr *constr;
1331 AttrMap *attmap;
1332 char *comment;
1333
1334 /*
1335 * Open the relation referenced by the LIKE clause. We should still have
1336 * the table lock obtained by transformTableLikeClause (and this'll throw
1337 * an assertion failure if not). Hence, no need to recheck privileges
1338 * etc. We must open the rel by OID not name, to be sure we get the same
1339 * table.
1340 */
1341 if (!OidIsValid(table_like_clause->relationOid))
1342 elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1343
1344 relation = relation_open(table_like_clause->relationOid, NoLock);
1345
1346 tupleDesc = RelationGetDescr(relation);
1347 constr = tupleDesc->constr;
1348
1349 /*
1350 * Open the newly-created child relation; we have lock on that too.
1351 */
1352 childrel = relation_openrv(heapRel, NoLock);
1353
1354 /*
1355 * Construct a map from the LIKE relation's attnos to the child rel's.
1356 * This re-checks type match etc, although it shouldn't be possible to
1357 * have a failure since both tables are locked.
1358 */
1359 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1360 tupleDesc,
1361 false);
1362
1363 /*
1364 * Process defaults, if required.
1365 */
1366 if ((table_like_clause->options &
1368 constr != NULL)
1369 {
1370 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1371 parent_attno++)
1372 {
1373 Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1374 parent_attno - 1);
1375
1376 /*
1377 * Ignore dropped columns in the parent.
1378 */
1379 if (attribute->attisdropped)
1380 continue;
1381
1382 /*
1383 * Copy default, if present and it should be copied. We have
1384 * separate options for plain default expressions and GENERATED
1385 * defaults.
1386 */
1387 if (attribute->atthasdef &&
1388 (attribute->attgenerated ?
1389 (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1390 (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1391 {
1392 Node *this_default;
1393 AlterTableCmd *atsubcmd;
1394 bool found_whole_row;
1395
1396 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1397 if (this_default == NULL)
1398 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1399 parent_attno, RelationGetRelationName(relation));
1400
1401 atsubcmd = makeNode(AlterTableCmd);
1402 atsubcmd->subtype = AT_CookedColumnDefault;
1403 atsubcmd->num = attmap->attnums[parent_attno - 1];
1404 atsubcmd->def = map_variable_attnos(this_default,
1405 1, 0,
1406 attmap,
1407 InvalidOid,
1408 &found_whole_row);
1409
1410 /*
1411 * Prevent this for the same reason as for constraints below.
1412 * Note that defaults cannot contain any vars, so it's OK that
1413 * the error message refers to generated columns.
1414 */
1415 if (found_whole_row)
1416 ereport(ERROR,
1417 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1418 errmsg("cannot convert whole-row table reference"),
1419 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1420 NameStr(attribute->attname),
1421 RelationGetRelationName(relation))));
1422
1423 atsubcmds = lappend(atsubcmds, atsubcmd);
1424 }
1425 }
1426 }
1427
1428 /*
1429 * Copy CHECK constraints if requested, being careful to adjust attribute
1430 * numbers so they match the child.
1431 */
1432 if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1433 constr != NULL)
1434 {
1435 int ccnum;
1436
1437 for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1438 {
1439 char *ccname = constr->check[ccnum].ccname;
1440 char *ccbin = constr->check[ccnum].ccbin;
1441 bool ccenforced = constr->check[ccnum].ccenforced;
1442 bool ccvalid = constr->check[ccnum].ccvalid;
1443 bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1444 Node *ccbin_node;
1445 bool found_whole_row;
1446 Constraint *n;
1447 AlterTableCmd *atsubcmd;
1448
1449 ccbin_node = map_variable_attnos(stringToNode(ccbin),
1450 1, 0,
1451 attmap,
1452 InvalidOid, &found_whole_row);
1453
1454 /*
1455 * We reject whole-row variables because the whole point of LIKE
1456 * is that the new table's rowtype might later diverge from the
1457 * parent's. So, while translation might be possible right now,
1458 * it wouldn't be possible to guarantee it would work in future.
1459 */
1460 if (found_whole_row)
1461 ereport(ERROR,
1462 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1463 errmsg("cannot convert whole-row table reference"),
1464 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1465 ccname,
1466 RelationGetRelationName(relation))));
1467
1468 n = makeNode(Constraint);
1469 n->contype = CONSTR_CHECK;
1470 n->conname = pstrdup(ccname);
1471 n->location = -1;
1472 n->is_enforced = ccenforced;
1473 n->initially_valid = ccvalid;
1474 n->is_no_inherit = ccnoinherit;
1475 n->raw_expr = NULL;
1476 n->cooked_expr = nodeToString(ccbin_node);
1477
1478 /* We can skip validation, since the new table should be empty. */
1479 n->skip_validation = true;
1480
1481 atsubcmd = makeNode(AlterTableCmd);
1482 atsubcmd->subtype = AT_AddConstraint;
1483 atsubcmd->def = (Node *) n;
1484 atsubcmds = lappend(atsubcmds, atsubcmd);
1485
1486 /* Copy comment on constraint */
1487 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1489 n->conname, false),
1490 ConstraintRelationId,
1491 0)) != NULL)
1492 {
1494
1495 stmt->objtype = OBJECT_TABCONSTRAINT;
1496 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1497 makeString(heapRel->relname),
1498 makeString(n->conname));
1499 stmt->comment = comment;
1500
1501 result = lappend(result, stmt);
1502 }
1503 }
1504 }
1505
1506 /*
1507 * If we generated any ALTER TABLE actions above, wrap them into a single
1508 * ALTER TABLE command. Stick it at the front of the result, so it runs
1509 * before any CommentStmts we made above.
1510 */
1511 if (atsubcmds)
1512 {
1514
1515 atcmd->relation = copyObject(heapRel);
1516 atcmd->cmds = atsubcmds;
1517 atcmd->objtype = OBJECT_TABLE;
1518 atcmd->missing_ok = false;
1519 result = lcons(atcmd, result);
1520 }
1521
1522 /*
1523 * Process indexes if required.
1524 */
1525 if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1526 relation->rd_rel->relhasindex &&
1527 childrel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1528 {
1529 List *parent_indexes;
1530 ListCell *l;
1531
1532 parent_indexes = RelationGetIndexList(relation);
1533
1534 foreach(l, parent_indexes)
1535 {
1536 Oid parent_index_oid = lfirst_oid(l);
1537 Relation parent_index;
1538 IndexStmt *index_stmt;
1539
1540 parent_index = index_open(parent_index_oid, AccessShareLock);
1541
1542 /* Build CREATE INDEX statement to recreate the parent_index */
1543 index_stmt = generateClonedIndexStmt(heapRel,
1544 parent_index,
1545 attmap,
1546 NULL);
1547
1548 /* Copy comment on index, if requested */
1549 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1550 {
1551 comment = GetComment(parent_index_oid, RelationRelationId, 0);
1552
1553 /*
1554 * We make use of IndexStmt's idxcomment option, so as not to
1555 * need to know now what name the index will have.
1556 */
1557 index_stmt->idxcomment = comment;
1558 }
1559
1560 result = lappend(result, index_stmt);
1561
1562 index_close(parent_index, AccessShareLock);
1563 }
1564 }
1565
1566 /*
1567 * Process extended statistics if required.
1568 */
1569 if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
1570 {
1571 List *parent_extstats;
1572 ListCell *l;
1573
1574 parent_extstats = RelationGetStatExtList(relation);
1575
1576 foreach(l, parent_extstats)
1577 {
1578 Oid parent_stat_oid = lfirst_oid(l);
1579 CreateStatsStmt *stats_stmt;
1580
1581 stats_stmt = generateClonedExtStatsStmt(heapRel,
1582 RelationGetRelid(childrel),
1583 parent_stat_oid,
1584 attmap);
1585
1586 /* Copy comment on statistics object, if requested */
1587 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1588 {
1589 comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
1590
1591 /*
1592 * We make use of CreateStatsStmt's stxcomment option, so as
1593 * not to need to know now what name the statistics will have.
1594 */
1595 stats_stmt->stxcomment = comment;
1596 }
1597
1598 result = lappend(result, stats_stmt);
1599 }
1600
1601 list_free(parent_extstats);
1602 }
1603
1604 /* Done with child rel */
1605 table_close(childrel, NoLock);
1606
1607 /*
1608 * Close the parent rel, but keep our AccessShareLock on it until xact
1609 * commit. That will prevent someone else from deleting or ALTERing the
1610 * parent before the child is committed.
1611 */
1612 table_close(relation, NoLock);
1613
1614 return result;
1615}
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:717
#define OidIsValid(objectId)
Definition: c.h:746
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1204
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:225
#define ereport(elevel,...)
Definition: elog.h:149
#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:2327
#define copyObject(obj)
Definition: nodes.h:230
#define makeNode(_type_)
Definition: nodes.h:161
char * nodeToString(const void *obj)
Definition: outfuncs.c:797
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:2794
@ OBJECT_TABLE
Definition: parsenodes.h:2358
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2357
@ AT_AddConstraint
Definition: parsenodes.h:2425
@ AT_CookedColumnDefault
Definition: parsenodes.h:2412
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:772
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:776
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:778
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:775
@ CREATE_TABLE_LIKE_STATISTICS
Definition: parsenodes.h:779
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:774
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:35
unsigned int Oid
Definition: postgres_ext.h:30
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:516
#define RelationGetDescr(relation)
Definition: rel.h:542
#define RelationGetRelationName(relation)
Definition: rel.h:550
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4833
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4974
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:137
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
AlterTableType subtype
Definition: parsenodes.h:2480
RangeVar * relation
Definition: parsenodes.h:2401
ObjectType objtype
Definition: parsenodes.h:2403
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
bool ccvalid
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ParseLoc location
Definition: parsenodes.h:2866
ConstrType contype
Definition: parsenodes.h:2822
bool is_no_inherit
Definition: parsenodes.h:2829
bool is_enforced
Definition: parsenodes.h:2826
char * cooked_expr
Definition: parsenodes.h:2832
bool initially_valid
Definition: parsenodes.h:2828
bool skip_validation
Definition: parsenodes.h:2827
Node * raw_expr
Definition: parsenodes.h:2830
char * conname
Definition: parsenodes.h:2823
char * idxcomment
Definition: parsenodes.h:3455
Definition: pg_list.h:54
Definition: nodes.h:135
char * relname
Definition: primnodes.h:83
char * schemaname
Definition: primnodes.h:80
Form_pg_class rd_rel
Definition: rel.h:111
ConstrCheck * check
Definition: tupdesc.h:41
uint16 num_check
Definition: tupdesc.h:44
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:1085
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
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, ConstrCheck::ccvalid, 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 ( RangeVar heapRel,
Relation  source_idx,
const struct AttrMap attmap,
Oid constraintOid 
)

◆ transformAlterTableStmt()

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

Definition at line 3504 of file parse_utilcmd.c.

3507{
3508 Relation rel;
3509 TupleDesc tupdesc;
3510 ParseState *pstate;
3512 List *save_alist;
3513 ListCell *lcmd,
3514 *l;
3515 List *newcmds = NIL;
3516 bool skipValidation = true;
3517 AlterTableCmd *newcmd;
3518 ParseNamespaceItem *nsitem;
3519
3520 /* Caller is responsible for locking the relation */
3521 rel = relation_open(relid, NoLock);
3522 tupdesc = RelationGetDescr(rel);
3523
3524 /* Set up pstate */
3525 pstate = make_parsestate(NULL);
3526 pstate->p_sourcetext = queryString;
3527 nsitem = addRangeTableEntryForRelation(pstate,
3528 rel,
3530 NULL,
3531 false,
3532 true);
3533 addNSItemToQuery(pstate, nsitem, false, true, true);
3534
3535 /* Set up CreateStmtContext */
3536 cxt.pstate = pstate;
3537 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3538 {
3539 cxt.stmtType = "ALTER FOREIGN TABLE";
3540 cxt.isforeign = true;
3541 }
3542 else
3543 {
3544 cxt.stmtType = "ALTER TABLE";
3545 cxt.isforeign = false;
3546 }
3547 cxt.relation = stmt->relation;
3548 cxt.rel = rel;
3549 cxt.inhRelations = NIL;
3550 cxt.isalter = true;
3551 cxt.columns = NIL;
3552 cxt.ckconstraints = NIL;
3553 cxt.nnconstraints = NIL;
3554 cxt.fkconstraints = NIL;
3555 cxt.ixconstraints = NIL;
3556 cxt.likeclauses = NIL;
3557 cxt.blist = NIL;
3558 cxt.alist = NIL;
3559 cxt.pkey = NULL;
3560 cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3561 cxt.partbound = NULL;
3562 cxt.ofType = false;
3563
3564 /*
3565 * Transform ALTER subcommands that need it (most don't). These largely
3566 * re-use code from CREATE TABLE.
3567 */
3568 foreach(lcmd, stmt->cmds)
3569 {
3570 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3571
3572 switch (cmd->subtype)
3573 {
3574 case AT_AddColumn:
3575 {
3576 ColumnDef *def = castNode(ColumnDef, cmd->def);
3577
3578 transformColumnDefinition(&cxt, def);
3579
3580 /*
3581 * If the column has a non-null default, we can't skip
3582 * validation of foreign keys.
3583 */
3584 if (def->raw_default != NULL)
3585 skipValidation = false;
3586
3587 /*
3588 * All constraints are processed in other ways. Remove the
3589 * original list
3590 */
3591 def->constraints = NIL;
3592
3593 newcmds = lappend(newcmds, cmd);
3594 break;
3595 }
3596
3597 case AT_AddConstraint:
3598
3599 /*
3600 * The original AddConstraint cmd node doesn't go to newcmds
3601 */
3602 if (IsA(cmd->def, Constraint))
3603 {
3604 transformTableConstraint(&cxt, (Constraint *) cmd->def);
3605 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3606 skipValidation = false;
3607 }
3608 else
3609 elog(ERROR, "unrecognized node type: %d",
3610 (int) nodeTag(cmd->def));
3611 break;
3612
3613 case AT_AlterColumnType:
3614 {
3615 ColumnDef *def = castNode(ColumnDef, cmd->def);
3617
3618 /*
3619 * For ALTER COLUMN TYPE, transform the USING clause if
3620 * one was specified.
3621 */
3622 if (def->raw_default)
3623 {
3624 def->cooked_default =
3625 transformExpr(pstate, def->raw_default,
3627 }
3628
3629 /*
3630 * For identity column, create ALTER SEQUENCE command to
3631 * change the data type of the sequence. Identity sequence
3632 * is associated with the top level partitioned table.
3633 * Hence ignore partitions.
3634 */
3635 if (!RelationGetForm(rel)->relispartition)
3636 {
3637 attnum = get_attnum(relid, cmd->name);
3639 ereport(ERROR,
3640 (errcode(ERRCODE_UNDEFINED_COLUMN),
3641 errmsg("column \"%s\" of relation \"%s\" does not exist",
3642 cmd->name, RelationGetRelationName(rel))));
3643
3644 if (attnum > 0 &&
3645 TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3646 {
3647 Oid seq_relid = getIdentitySequence(rel, attnum, false);
3648 Oid typeOid = typenameTypeId(pstate, def->typeName);
3649 AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3650
3651 altseqstmt->sequence
3653 get_rel_name(seq_relid),
3654 -1);
3655 altseqstmt->options = list_make1(makeDefElem("as",
3656 (Node *) makeTypeNameFromOid(typeOid, -1),
3657 -1));
3658 altseqstmt->for_identity = true;
3659 cxt.blist = lappend(cxt.blist, altseqstmt);
3660 }
3661 }
3662
3663 newcmds = lappend(newcmds, cmd);
3664 break;
3665 }
3666
3667 case AT_AddIdentity:
3668 {
3669 Constraint *def = castNode(Constraint, cmd->def);
3670 ColumnDef *newdef = makeNode(ColumnDef);
3672
3673 newdef->colname = cmd->name;
3674 newdef->identity = def->generated_when;
3675 cmd->def = (Node *) newdef;
3676
3677 attnum = get_attnum(relid, cmd->name);
3679 ereport(ERROR,
3680 (errcode(ERRCODE_UNDEFINED_COLUMN),
3681 errmsg("column \"%s\" of relation \"%s\" does not exist",
3682 cmd->name, RelationGetRelationName(rel))));
3683
3684 generateSerialExtraStmts(&cxt, newdef,
3685 get_atttype(relid, attnum),
3686 def->options, true, true,
3687 NULL, NULL);
3688
3689 newcmds = lappend(newcmds, cmd);
3690 break;
3691 }
3692
3693 case AT_SetIdentity:
3694 {
3695 /*
3696 * Create an ALTER SEQUENCE statement for the internal
3697 * sequence of the identity column.
3698 */
3699 ListCell *lc;
3700 List *newseqopts = NIL;
3701 List *newdef = NIL;
3703 Oid seq_relid;
3704
3705 /*
3706 * Split options into those handled by ALTER SEQUENCE and
3707 * those for ALTER TABLE proper.
3708 */
3709 foreach(lc, castNode(List, cmd->def))
3710 {
3711 DefElem *def = lfirst_node(DefElem, lc);
3712
3713 if (strcmp(def->defname, "generated") == 0)
3714 newdef = lappend(newdef, def);
3715 else
3716 newseqopts = lappend(newseqopts, def);
3717 }
3718
3719 attnum = get_attnum(relid, cmd->name);
3721 ereport(ERROR,
3722 (errcode(ERRCODE_UNDEFINED_COLUMN),
3723 errmsg("column \"%s\" of relation \"%s\" does not exist",
3724 cmd->name, RelationGetRelationName(rel))));
3725
3726 seq_relid = getIdentitySequence(rel, attnum, true);
3727
3728 if (seq_relid)
3729 {
3730 AlterSeqStmt *seqstmt;
3731
3732 seqstmt = makeNode(AlterSeqStmt);
3734 get_rel_name(seq_relid), -1);
3735 seqstmt->options = newseqopts;
3736 seqstmt->for_identity = true;
3737 seqstmt->missing_ok = false;
3738
3739 cxt.blist = lappend(cxt.blist, seqstmt);
3740 }
3741
3742 /*
3743 * If column was not an identity column, we just let the
3744 * ALTER TABLE command error out later. (There are cases
3745 * this fails to cover, but we'll need to restructure
3746 * where creation of the sequence dependency linkage
3747 * happens before we can fix it.)
3748 */
3749
3750 cmd->def = (Node *) newdef;
3751 newcmds = lappend(newcmds, cmd);
3752 break;
3753 }
3754
3755 case AT_AttachPartition:
3756 case AT_DetachPartition:
3757 {
3758 PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3759
3760 transformPartitionCmd(&cxt, partcmd);
3761 /* assign transformed value of the partition bound */
3762 partcmd->bound = cxt.partbound;
3763 }
3764
3765 newcmds = lappend(newcmds, cmd);
3766 break;
3767
3768 default:
3769
3770 /*
3771 * Currently, we shouldn't actually get here for subcommand
3772 * types that don't require transformation; but if we do, just
3773 * emit them unchanged.
3774 */
3775 newcmds = lappend(newcmds, cmd);
3776 break;
3777 }
3778 }
3779
3780 /*
3781 * Transfer anything we already have in cxt.alist into save_alist, to keep
3782 * it separate from the output of transformIndexConstraints.
3783 */
3784 save_alist = cxt.alist;
3785 cxt.alist = NIL;
3786
3787 /* Postprocess constraints */
3789 transformFKConstraints(&cxt, skipValidation, true);
3790 transformCheckConstraints(&cxt, false);
3791
3792 /*
3793 * Push any index-creation commands into the ALTER, so that they can be
3794 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3795 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3796 * subcommand has already been through transformIndexStmt.
3797 */
3798 foreach(l, cxt.alist)
3799 {
3800 Node *istmt = (Node *) lfirst(l);
3801
3802 /*
3803 * We assume here that cxt.alist contains only IndexStmts generated
3804 * from primary key constraints.
3805 */
3806 if (IsA(istmt, IndexStmt))
3807 {
3808 IndexStmt *idxstmt = (IndexStmt *) istmt;
3809
3810 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3811 newcmd = makeNode(AlterTableCmd);
3813 newcmd->def = (Node *) idxstmt;
3814 newcmds = lappend(newcmds, newcmd);
3815 }
3816 else
3817 elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3818 }
3819 cxt.alist = NIL;
3820
3821 /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3823 {
3824 newcmd = makeNode(AlterTableCmd);
3825 newcmd->subtype = AT_AddConstraint;
3826 newcmd->def = (Node *) def;
3827 newcmds = lappend(newcmds, newcmd);
3828 }
3830 {
3831 newcmd = makeNode(AlterTableCmd);
3832 newcmd->subtype = AT_AddConstraint;
3833 newcmd->def = (Node *) def;
3834 newcmds = lappend(newcmds, newcmd);
3835 }
3837 {
3838 newcmd = makeNode(AlterTableCmd);
3839 newcmd->subtype = AT_AddConstraint;
3840 newcmd->def = (Node *) def;
3841 newcmds = lappend(newcmds, newcmd);
3842 }
3843
3844 /* Close rel */
3845 relation_close(rel, NoLock);
3846
3847 /*
3848 * Output results.
3849 */
3850 stmt->cmds = newcmds;
3851
3852 *beforeStmts = cxt.blist;
3853 *afterStmts = list_concat(cxt.alist, save_alist);
3854
3855 return stmt;
3856}
#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:2068
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:950
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2092
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3506
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:1005
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)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
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:2798
@ AT_AddIndexConstraint
Definition: parsenodes.h:2430
@ AT_SetIdentity
Definition: parsenodes.h:2472
@ AT_AddIndex
Definition: parsenodes.h:2423
@ AT_AddIdentity
Definition: parsenodes.h:2471
@ AT_AlterColumnType
Definition: parsenodes.h:2433
@ AT_DetachPartition
Definition: parsenodes.h:2469
@ AT_AttachPartition
Definition: parsenodes.h:2468
@ AT_AddColumn
Definition: parsenodes.h:2409
int16 attnum
Definition: pg_attribute.h:74
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:945
#define lfirst(lc)
Definition: pg_list.h:172
#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:510
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
List * options
Definition: parsenodes.h:3225
RangeVar * sequence
Definition: parsenodes.h:3224
bool for_identity
Definition: parsenodes.h:3226
char identity
Definition: parsenodes.h:748
List * constraints
Definition: parsenodes.h:754
Node * cooked_default
Definition: parsenodes.h:747
char * colname
Definition: parsenodes.h:737
TypeName * typeName
Definition: parsenodes.h:738
Node * raw_default
Definition: parsenodes.h:746
List * options
Definition: parsenodes.h:2844
char generated_when
Definition: parsenodes.h:2834
IndexStmt * pkey
Definition: parse_utilcmd.c:92
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parse_utilcmd.c:77
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
char * defname
Definition: parsenodes.h:826
Oid indexOid
Definition: parsenodes.h:3456
const char * p_sourcetext
Definition: parse_node.h:209
PartitionBoundSpec * bound
Definition: parsenodes.h:958

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 ( List schemaElts,
const char *  schemaName 
)

Definition at line 4081 of file parse_utilcmd.c.

4082{
4084 List *result;
4085 ListCell *elements;
4086
4087 cxt.schemaname = schemaName;
4088 cxt.sequences = NIL;
4089 cxt.tables = NIL;
4090 cxt.views = NIL;
4091 cxt.indexes = NIL;
4092 cxt.triggers = NIL;
4093 cxt.grants = NIL;
4094
4095 /*
4096 * Run through each schema element in the schema element list. Separate
4097 * statements by type, and do preliminary analysis.
4098 */
4099 foreach(elements, schemaElts)
4100 {
4101 Node *element = lfirst(elements);
4102
4103 switch (nodeTag(element))
4104 {
4105 case T_CreateSeqStmt:
4106 {
4108
4110 cxt.sequences = lappend(cxt.sequences, element);
4111 }
4112 break;
4113
4114 case T_CreateStmt:
4115 {
4116 CreateStmt *elp = (CreateStmt *) element;
4117
4119
4120 /*
4121 * XXX todo: deal with constraints
4122 */
4123 cxt.tables = lappend(cxt.tables, element);
4124 }
4125 break;
4126
4127 case T_ViewStmt:
4128 {
4129 ViewStmt *elp = (ViewStmt *) element;
4130
4132
4133 /*
4134 * XXX todo: deal with references between views
4135 */
4136 cxt.views = lappend(cxt.views, element);
4137 }
4138 break;
4139
4140 case T_IndexStmt:
4141 {
4142 IndexStmt *elp = (IndexStmt *) element;
4143
4145 cxt.indexes = lappend(cxt.indexes, element);
4146 }
4147 break;
4148
4149 case T_CreateTrigStmt:
4150 {
4152
4154 cxt.triggers = lappend(cxt.triggers, element);
4155 }
4156 break;
4157
4158 case T_GrantStmt:
4159 cxt.grants = lappend(cxt.grants, element);
4160 break;
4161
4162 default:
4163 elog(ERROR, "unrecognized node type: %d",
4164 (int) nodeTag(element));
4165 }
4166 }
4167
4168 result = NIL;
4169 result = list_concat(result, cxt.sequences);
4170 result = list_concat(result, cxt.tables);
4171 result = list_concat(result, cxt.views);
4172 result = list_concat(result, cxt.indexes);
4173 result = list_concat(result, cxt.triggers);
4174 result = list_concat(result, cxt.grants);
4175
4176 return result;
4177}
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
RangeVar * sequence
Definition: parsenodes.h:3214
RangeVar * relation
Definition: parsenodes.h:2739
RangeVar * relation
Definition: parsenodes.h:3101
RangeVar * relation
Definition: parsenodes.h:3446
RangeVar * view
Definition: parsenodes.h:3839

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 ( CreateStmt stmt,
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
Assert(PointerIsAligned(start, uint64))
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:739
#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,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 3028 of file parse_utilcmd.c.

3029{
3030 ParseState *pstate;
3031 ParseNamespaceItem *nsitem;
3032 ListCell *l;
3033 Relation rel;
3034
3035 /* Nothing to do if statement already transformed. */
3036 if (stmt->transformed)
3037 return stmt;
3038
3039 /* Set up pstate */
3040 pstate = make_parsestate(NULL);
3041 pstate->p_sourcetext = queryString;
3042
3043 /*
3044 * Put the parent table into the rtable so that the expressions can refer
3045 * to its fields without qualification. Caller is responsible for locking
3046 * relation, but we still need to open it.
3047 */
3048 rel = relation_open(relid, NoLock);
3049 nsitem = addRangeTableEntryForRelation(pstate, rel,
3051 NULL, false, true);
3052
3053 /* no to join list, yes to namespaces */
3054 addNSItemToQuery(pstate, nsitem, false, true, true);
3055
3056 /* take care of the where clause */
3057 if (stmt->whereClause)
3058 {
3059 stmt->whereClause = transformWhereClause(pstate,
3060 stmt->whereClause,
3062 "WHERE");
3063 /* we have to fix its collations too */
3064 assign_expr_collations(pstate, stmt->whereClause);
3065 }
3066
3067 /* take care of any index expressions */
3068 foreach(l, stmt->indexParams)
3069 {
3070 IndexElem *ielem = (IndexElem *) lfirst(l);
3071
3072 if (ielem->expr)
3073 {
3074 /* Extract preliminary index col name before transforming expr */
3075 if (ielem->indexcolname == NULL)
3076 ielem->indexcolname = FigureIndexColname(ielem->expr);
3077
3078 /* Now do parse transformation of the expression */
3079 ielem->expr = transformExpr(pstate, ielem->expr,
3081
3082 /* We have to fix its collations too */
3083 assign_expr_collations(pstate, ielem->expr);
3084
3085 /*
3086 * transformExpr() should have already rejected subqueries,
3087 * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3088 * for an index expression.
3089 *
3090 * DefineIndex() will make more checks.
3091 */
3092 }
3093 }
3094
3095 /*
3096 * Check that only the base rel is mentioned. (This should be dead code
3097 * now that add_missing_from is history.)
3098 */
3099 if (list_length(pstate->p_rtable) != 1)
3100 ereport(ERROR,
3101 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3102 errmsg("index expressions and predicates can refer only to the table being indexed")));
3103
3104 free_parsestate(pstate);
3105
3106 /* Close relation */
3107 table_close(rel, NoLock);
3108
3109 /* Mark statement as successfully transformed */
3110 stmt->transformed = true;
3111
3112 return stmt;
3113}
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
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)
static int list_length(const List *l)
Definition: pg_list.h:152
Node * expr
Definition: parsenodes.h:795
char * indexcolname
Definition: parsenodes.h:796
List * p_rtable
Definition: parse_node.h:212

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 ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 4257 of file parse_utilcmd.c.

4259{
4260 PartitionBoundSpec *result_spec;
4262 char strategy = get_partition_strategy(key);
4263 int partnatts = get_partition_natts(key);
4264 List *partexprs = get_partition_exprs(key);
4265
4266 /* Avoid scribbling on input */
4267 result_spec = copyObject(spec);
4268
4269 if (spec->is_default)
4270 {
4271 /*
4272 * Hash partitioning does not support a default partition; there's no
4273 * use case for it (since the set of partitions to create is perfectly
4274 * defined), and if users do get into it accidentally, it's hard to
4275 * back out from it afterwards.
4276 */
4277 if (strategy == PARTITION_STRATEGY_HASH)
4278 ereport(ERROR,
4279 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4280 errmsg("a hash-partitioned table may not have a default partition")));
4281
4282 /*
4283 * In case of the default partition, parser had no way to identify the
4284 * partition strategy. Assign the parent's strategy to the default
4285 * partition bound spec.
4286 */
4287 result_spec->strategy = strategy;
4288
4289 return result_spec;
4290 }
4291
4292 if (strategy == PARTITION_STRATEGY_HASH)
4293 {
4294 if (spec->strategy != PARTITION_STRATEGY_HASH)
4295 ereport(ERROR,
4296 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4297 errmsg("invalid bound specification for a hash partition"),
4298 parser_errposition(pstate, exprLocation((Node *) spec))));
4299
4300 if (spec->modulus <= 0)
4301 ereport(ERROR,
4302 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4303 errmsg("modulus for hash partition must be an integer value greater than zero")));
4304
4305 Assert(spec->remainder >= 0);
4306
4307 if (spec->remainder >= spec->modulus)
4308 ereport(ERROR,
4309 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4310 errmsg("remainder for hash partition must be less than modulus")));
4311 }
4312 else if (strategy == PARTITION_STRATEGY_LIST)
4313 {
4314 ListCell *cell;
4315 char *colname;
4316 Oid coltype;
4317 int32 coltypmod;
4318 Oid partcollation;
4319
4320 if (spec->strategy != PARTITION_STRATEGY_LIST)
4321 ereport(ERROR,
4322 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4323 errmsg("invalid bound specification for a list partition"),
4324 parser_errposition(pstate, exprLocation((Node *) spec))));
4325
4326 /* Get the only column's name in case we need to output an error */
4327 if (key->partattrs[0] != 0)
4328 colname = get_attname(RelationGetRelid(parent),
4329 key->partattrs[0], false);
4330 else
4331 colname = deparse_expression((Node *) linitial(partexprs),
4333 RelationGetRelid(parent)),
4334 false, false);
4335 /* Need its type data too */
4336 coltype = get_partition_col_typid(key, 0);
4337 coltypmod = get_partition_col_typmod(key, 0);
4338 partcollation = get_partition_col_collation(key, 0);
4339
4340 result_spec->listdatums = NIL;
4341 foreach(cell, spec->listdatums)
4342 {
4343 Node *expr = lfirst(cell);
4344 Const *value;
4345 ListCell *cell2;
4346 bool duplicate;
4347
4348 value = transformPartitionBoundValue(pstate, expr,
4349 colname, coltype, coltypmod,
4350 partcollation);
4351
4352 /* Don't add to the result if the value is a duplicate */
4353 duplicate = false;
4354 foreach(cell2, result_spec->listdatums)
4355 {
4356 Const *value2 = lfirst_node(Const, cell2);
4357
4358 if (equal(value, value2))
4359 {
4360 duplicate = true;
4361 break;
4362 }
4363 }
4364 if (duplicate)
4365 continue;
4366
4367 result_spec->listdatums = lappend(result_spec->listdatums,
4368 value);
4369 }
4370 }
4371 else if (strategy == PARTITION_STRATEGY_RANGE)
4372 {
4374 ereport(ERROR,
4375 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4376 errmsg("invalid bound specification for a range partition"),
4377 parser_errposition(pstate, exprLocation((Node *) spec))));
4378
4379 if (list_length(spec->lowerdatums) != partnatts)
4380 ereport(ERROR,
4381 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4382 errmsg("FROM must specify exactly one value per partitioning column")));
4383 if (list_length(spec->upperdatums) != partnatts)
4384 ereport(ERROR,
4385 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4386 errmsg("TO must specify exactly one value per partitioning column")));
4387
4388 /*
4389 * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4390 * any necessary validation.
4391 */
4392 result_spec->lowerdatums =
4394 parent);
4395 result_spec->upperdatums =
4397 parent);
4398 }
4399 else
4400 elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4401
4402 return result_spec;
4403}
int32_t int32
Definition: c.h:498
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static struct @165 value
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:919
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:885
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:883
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:884
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:3708
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3645

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 ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 3198 of file parse_utilcmd.c.

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

Definition at line 3123 of file parse_utilcmd.c.

3124{
3125 ParseState *pstate;
3126 ParseNamespaceItem *nsitem;
3127 ListCell *l;
3128 Relation rel;
3129
3130 /* Nothing to do if statement already transformed. */
3131 if (stmt->transformed)
3132 return stmt;
3133
3134 /* Set up pstate */
3135 pstate = make_parsestate(NULL);
3136 pstate->p_sourcetext = queryString;
3137
3138 /*
3139 * Put the parent table into the rtable so that the expressions can refer
3140 * to its fields without qualification. Caller is responsible for locking
3141 * relation, but we still need to open it.
3142 */
3143 rel = relation_open(relid, NoLock);
3144 nsitem = addRangeTableEntryForRelation(pstate, rel,
3146 NULL, false, true);
3147
3148 /* no to join list, yes to namespaces */
3149 addNSItemToQuery(pstate, nsitem, false, true, true);
3150
3151 /* take care of any expressions */
3152 foreach(l, stmt->exprs)
3153 {
3154 StatsElem *selem = (StatsElem *) lfirst(l);
3155
3156 if (selem->expr)
3157 {
3158 /* Now do parse transformation of the expression */
3159 selem->expr = transformExpr(pstate, selem->expr,
3161
3162 /* We have to fix its collations too */
3163 assign_expr_collations(pstate, selem->expr);
3164 }
3165 }
3166
3167 /*
3168 * Check that only the base rel is mentioned. (This should be dead code
3169 * now that add_missing_from is history.)
3170 */
3171 if (list_length(pstate->p_rtable) != 1)
3172 ereport(ERROR,
3173 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3174 errmsg("statistics expressions can refer only to the table being referenced")));
3175
3176 free_parsestate(pstate);
3177
3178 /* Close relation */
3179 table_close(rel, NoLock);
3180
3181 /* Mark statement as successfully transformed */
3182 stmt->transformed = true;
3183
3184 return stmt;
3185}
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:74
Node * expr
Definition: parsenodes.h:3502

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