PostgreSQL Source Code git master
Loading...
Searching...
No Matches
parse_utilcmd.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/attmap.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "access/toast_compression.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for parse_utilcmd.c:

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

static void transformColumnDefinition (CreateStmtContext *cxt, ColumnDef *column)
 
static void transformTableConstraint (CreateStmtContext *cxt, Constraint *constraint)
 
static void transformTableLikeClause (CreateStmtContext *cxt, TableLikeClause *table_like_clause)
 
static void transformOfType (CreateStmtContext *cxt, TypeName *ofTypename)
 
static CreateStatsStmtgenerateClonedExtStatsStmt (RangeVar *heapRel, Oid heapRelid, Oid source_statsid, const AttrMap *attmap)
 
static Listget_collation (Oid collation, Oid actual_datatype)
 
static Listget_opclass (Oid opclass, Oid actual_datatype)
 
static void transformIndexConstraints (CreateStmtContext *cxt)
 
static IndexStmttransformIndexConstraint (Constraint *constraint, CreateStmtContext *cxt)
 
static void transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (ParseState *pstate, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void checkSchemaNameRV (ParseState *pstate, const char *context_schema, RangeVar *relation)
 
static void checkSchemaNameList (const char *context_schema, List *qualified_name)
 
static CreateStmttransformCreateSchemaCreateTable (ParseState *pstate, CreateStmt *stmt, List **fk_elements)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionBoundSpec *bound)
 
static ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 
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)
 
static void checkPartition (Relation rel, Oid partRelOid, bool isMerge)
 
static void transformPartitionCmdForSplit (CreateStmtContext *cxt, PartitionCmd *partcmd)
 
static void transformPartitionCmdForMerge (CreateStmtContext *cxt, PartitionCmd *partcmd)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
ListtransformCreateSchemaStmtElements (ParseState *pstate, List *schemaElts, const char *schemaName)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))
@ CONSTR_FOREIGN
@ CONSTR_UNIQUE
@ CONSTR_EXCLUSION
@ CONSTR_PRIMARY
static int fb(int x)

Function Documentation

◆ checkPartition()

static void checkPartition ( Relation  rel,
Oid  partRelOid,
bool  isMerge 
)
static

Definition at line 3532 of file parse_utilcmd.c.

3533{
3534 Relation partRel;
3535
3536 partRel = table_open(partRelOid, NoLock);
3537
3538 if (partRel->rd_rel->relkind != RELKIND_RELATION)
3539 ereport(ERROR,
3541 errmsg("\"%s\" is not a table", RelationGetRelationName(partRel)),
3542 isMerge
3543 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions that don't have sub-partitions.")
3544 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions that don't have sub-partitions."));
3545
3546 if (!partRel->rd_rel->relispartition)
3547 ereport(ERROR,
3549 errmsg("\"%s\" is not a partition of partitioned table \"%s\"",
3551 isMerge
3552 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions that don't have sub-partitions.")
3553 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions that don't have sub-partitions."));
3554
3556 ereport(ERROR,
3558 errmsg("relation \"%s\" is not a partition of relation \"%s\"",
3560 isMerge
3561 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions that don't have sub-partitions.")
3562 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions that don't have sub-partitions."));
3563
3564 table_close(partRel, NoLock);
3565}
int errcode(int sqlerrcode)
Definition elog.c:875
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
#define NoLock
Definition lockdefs.h:34
static char * errmsg
Oid get_partition_parent(Oid relid, bool even_if_detached)
Definition partition.c:53
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetRelationName(relation)
Definition rel.h:550
Form_pg_class rd_rel
Definition rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References ereport, errcode(), errhint(), errmsg, ERROR, fb(), get_partition_parent(), NoLock, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, table_close(), and table_open().

Referenced by transformPartitionCmdForMerge(), and transformPartitionCmdForSplit().

◆ checkSchemaNameList()

static void checkSchemaNameList ( const char context_schema,
List qualified_name 
)
static

Definition at line 4612 of file parse_utilcmd.c.

4613{
4614 char *obj_schema;
4615 char *obj_name;
4616
4618 if (obj_schema != NULL &&
4620 ereport(ERROR,
4622 errmsg("CREATE specifies a schema (%s) "
4623 "different from the one being created (%s)",
4625}
void DeconstructQualifiedName(const List *names, char **nspname_p, char **objname_p)
Definition namespace.c:3373

References DeconstructQualifiedName(), ereport, errcode(), errmsg, ERROR, and fb().

Referenced by transformCreateSchemaStmtElements().

◆ checkSchemaNameRV()

static void checkSchemaNameRV ( ParseState pstate,
const char context_schema,
RangeVar relation 
)
static

Definition at line 4581 of file parse_utilcmd.c.

4583{
4584 if (relation->schemaname != NULL &&
4585 strcmp(context_schema, relation->schemaname) != 0)
4586 ereport(ERROR,
4588 errmsg("CREATE specifies a schema (%s) "
4589 "different from the one being created (%s)",
4590 relation->schemaname, context_schema),
4591 parser_errposition(pstate, relation->location)));
4592
4593 if (relation->relpersistence == RELPERSISTENCE_TEMP)
4594 {
4595 /* spell this error the same as in RangeVarAdjustRelationPersistence */
4596 ereport(ERROR,
4598 errmsg("cannot create temporary relation in non-temporary schema"),
4599 parser_errposition(pstate, relation->location)));
4600 }
4601}
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
char relpersistence
Definition primnodes.h:90
ParseLoc location
Definition primnodes.h:96
char * schemaname
Definition primnodes.h:81

References ereport, errcode(), errmsg, ERROR, fb(), RangeVar::location, parser_errposition(), RangeVar::relpersistence, and RangeVar::schemaname.

Referenced by transformCreateSchemaStmtElements().

◆ expandTableLikeClause()

List * expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1342 of file parse_utilcmd.c.

1343{
1344 List *result = NIL;
1345 List *atsubcmds = NIL;
1347 Relation relation;
1350 TupleConstr *constr;
1351 AttrMap *attmap;
1352 char *comment;
1353
1354 /*
1355 * Open the relation referenced by the LIKE clause. We should still have
1356 * the table lock obtained by transformTableLikeClause (and this'll throw
1357 * an assertion failure if not). Hence, no need to recheck privileges
1358 * etc. We must open the rel by OID not name, to be sure we get the same
1359 * table.
1360 */
1361 if (!OidIsValid(table_like_clause->relationOid))
1362 elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1363
1364 relation = relation_open(table_like_clause->relationOid, NoLock);
1365
1366 tupleDesc = RelationGetDescr(relation);
1367 constr = tupleDesc->constr;
1368
1369 /*
1370 * Open the newly-created child relation; we have lock on that too.
1371 */
1372 childrel = relation_openrv(heapRel, NoLock);
1373
1374 /*
1375 * Construct a map from the LIKE relation's attnos to the child rel's.
1376 * This re-checks type match etc, although it shouldn't be possible to
1377 * have a failure since both tables are locked.
1378 */
1380 tupleDesc,
1381 false);
1382
1383 /*
1384 * Process defaults, if required.
1385 */
1386 if ((table_like_clause->options &
1388 constr != NULL)
1389 {
1390 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1391 parent_attno++)
1392 {
1394 parent_attno - 1);
1395
1396 /*
1397 * Ignore dropped columns in the parent.
1398 */
1399 if (attribute->attisdropped)
1400 continue;
1401
1402 /*
1403 * Copy default, if present and it should be copied. We have
1404 * separate options for plain default expressions and GENERATED
1405 * defaults.
1406 */
1407 if (attribute->atthasdef &&
1408 (attribute->attgenerated ?
1411 {
1414 bool found_whole_row;
1415
1417 if (this_default == NULL)
1418 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1420
1423 atsubcmd->num = attmap->attnums[parent_attno - 1];
1425 1, 0,
1426 attmap,
1427 InvalidOid,
1428 &found_whole_row);
1429
1430 /*
1431 * Prevent this for the same reason as for constraints below.
1432 * Note that defaults cannot contain any vars, so it's OK that
1433 * the error message refers to generated columns.
1434 */
1435 if (found_whole_row)
1436 ereport(ERROR,
1438 errmsg("cannot convert whole-row table reference"),
1439 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1440 NameStr(attribute->attname),
1441 RelationGetRelationName(relation))));
1442
1444 }
1445 }
1446 }
1447
1448 /*
1449 * Copy CHECK constraints if requested, being careful to adjust attribute
1450 * numbers so they match the child.
1451 */
1453 constr != NULL)
1454 {
1455 int ccnum;
1456
1457 for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1458 {
1459 char *ccname = constr->check[ccnum].ccname;
1460 char *ccbin = constr->check[ccnum].ccbin;
1461 bool ccenforced = constr->check[ccnum].ccenforced;
1462 bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1464 bool found_whole_row;
1465 Constraint *n;
1467
1469 1, 0,
1470 attmap,
1471 InvalidOid, &found_whole_row);
1472
1473 /*
1474 * We reject whole-row variables because the whole point of LIKE
1475 * is that the new table's rowtype might later diverge from the
1476 * parent's. So, while translation might be possible right now,
1477 * it wouldn't be possible to guarantee it would work in future.
1478 */
1479 if (found_whole_row)
1480 ereport(ERROR,
1482 errmsg("cannot convert whole-row table reference"),
1483 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1484 ccname,
1485 RelationGetRelationName(relation))));
1486
1487 n = makeNode(Constraint);
1488 n->contype = CONSTR_CHECK;
1489 n->conname = pstrdup(ccname);
1490 n->location = -1;
1491 n->is_enforced = ccenforced;
1492 n->initially_valid = ccenforced; /* sic */
1493 n->is_no_inherit = ccnoinherit;
1494 n->raw_expr = NULL;
1496
1497 /* We can skip validation, since the new table should be empty. */
1498 n->skip_validation = true;
1499
1501 atsubcmd->subtype = AT_AddConstraint;
1502 atsubcmd->def = (Node *) n;
1504
1505 /* Copy comment on constraint */
1508 n->conname, false),
1510 0)) != NULL)
1511 {
1513
1514 stmt->objtype = OBJECT_TABCONSTRAINT;
1515 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1516 makeString(heapRel->relname),
1517 makeString(n->conname));
1518 stmt->comment = comment;
1519
1521 }
1522 }
1523 }
1524
1525 /*
1526 * If we generated any ALTER TABLE actions above, wrap them into a single
1527 * ALTER TABLE command. Stick it at the front of the result, so it runs
1528 * before any CommentStmts we made above.
1529 */
1530 if (atsubcmds)
1531 {
1533
1534 atcmd->relation = copyObject(heapRel);
1535 atcmd->cmds = atsubcmds;
1536 atcmd->objtype = OBJECT_TABLE;
1537 atcmd->missing_ok = false;
1539 }
1540
1541 /*
1542 * Process indexes if required.
1543 */
1545 relation->rd_rel->relhasindex &&
1546 childrel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1547 {
1549 ListCell *l;
1550
1552
1553 foreach(l, parent_indexes)
1554 {
1558
1560
1561 /* Build CREATE INDEX statement to recreate the parent_index */
1564 attmap,
1565 NULL);
1566
1567 /* Copy comment on index, if requested */
1569 {
1571
1572 /*
1573 * We make use of IndexStmt's idxcomment option, so as not to
1574 * need to know now what name the index will have.
1575 */
1576 index_stmt->idxcomment = comment;
1577 }
1578
1580
1582 }
1583 }
1584
1585 /*
1586 * Process extended statistics if required.
1587 */
1589 {
1591 ListCell *l;
1592
1594
1595 foreach(l, parent_extstats)
1596 {
1599
1603 attmap);
1604
1605 /* Copy comment on statistics object, if requested */
1607 {
1609
1610 /*
1611 * We make use of CreateStatsStmt's stxcomment option, so as
1612 * not to need to know now what name the statistics will have.
1613 */
1614 stats_stmt->stxcomment = comment;
1615 }
1616
1618 }
1619
1621 }
1622
1623 /* Done with child rel */
1625
1626 /*
1627 * Close the parent rel, but keep our AccessShareLock on it until xact
1628 * commit. That will prevent someone else from deleting or ALTERing the
1629 * parent before the child is committed.
1630 */
1631 table_close(relation, NoLock);
1632
1633 return result;
1634}
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:835
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition comment.c:420
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define elog(elevel,...)
Definition elog.h:228
#define stmt
#define comment
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
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 AccessShareLock
Definition lockdefs.h:36
char * pstrdup(const char *in)
Definition mcxt.c:1910
#define copyObject(obj)
Definition nodes.h:232
#define makeNode(_type_)
Definition nodes.h:161
char * nodeToString(const void *obj)
Definition outfuncs.c:811
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
@ OBJECT_TABLE
@ OBJECT_TABCONSTRAINT
@ AT_AddConstraint
@ AT_CookedColumnDefault
@ CREATE_TABLE_LIKE_COMMENTS
Definition parsenodes.h:805
@ CREATE_TABLE_LIKE_GENERATED
Definition parsenodes.h:809
@ CREATE_TABLE_LIKE_INDEXES
Definition parsenodes.h:811
@ CREATE_TABLE_LIKE_DEFAULTS
Definition parsenodes.h:808
@ CREATE_TABLE_LIKE_STATISTICS
Definition parsenodes.h:812
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition parsenodes.h:807
FormData_pg_attribute * Form_pg_attribute
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:248
#define lfirst_oid(lc)
Definition pg_list.h:174
#define InvalidOid
unsigned int Oid
void * stringToNode(const char *str)
Definition read.c:90
#define RelationGetDescr(relation)
Definition rel.h:542
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4837
List * RelationGetStatExtList(Relation relation)
Definition relcache.c:4978
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:138
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:48
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
ConstrType contype
bool is_no_inherit
bool is_enforced
char * cooked_expr
bool initially_valid
bool skip_validation
Node * raw_expr
char * conname
Definition pg_list.h:54
Definition nodes.h:135
char * relname
Definition primnodes.h:84
ConstrCheck * check
Definition tupdesc.h:41
uint16 num_check
Definition tupdesc.h:44
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition tupdesc.c:1152
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
String * makeString(char *str)
Definition value.c:63

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccenforced, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, comment, Constraint::conname, 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, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), generateClonedExtStatsStmt(), generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), 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(), NameStr, NIL, nodeToString(), NoLock, TupleConstr::num_check, OBJECT_TABCONSTRAINT, OBJECT_TABLE, OidIsValid, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, RelationGetStatExtList(), RangeVar::relname, result, RangeVar::schemaname, Constraint::skip_validation, stmt, stringToNode(), table_close(), TupleDescAttr(), and TupleDescGetDefault().

Referenced by ProcessUtilitySlow().

◆ generateClonedExtStatsStmt()

static CreateStatsStmt * generateClonedExtStatsStmt ( RangeVar heapRel,
Oid  heapRelid,
Oid  source_statsid,
const AttrMap attmap 
)
static

Definition at line 2051 of file parse_utilcmd.c.

2053{
2056 CreateStatsStmt *stats;
2057 List *stat_types = NIL;
2058 List *def_names = NIL;
2059 bool isnull;
2060 Datum datum;
2061 ArrayType *arr;
2062 char *enabled;
2063 int i;
2064
2066 Assert(heapRel != NULL);
2067
2068 /*
2069 * Fetch pg_statistic_ext tuple of source statistics object.
2070 */
2073 elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
2075
2076 /* Determine which statistics types exist */
2079 arr = DatumGetArrayTypeP(datum);
2080 if (ARR_NDIM(arr) != 1 ||
2081 ARR_HASNULL(arr) ||
2082 ARR_ELEMTYPE(arr) != CHAROID)
2083 elog(ERROR, "stxkind is not a 1-D char array");
2084 enabled = (char *) ARR_DATA_PTR(arr);
2085 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
2086 {
2087 if (enabled[i] == STATS_EXT_NDISTINCT)
2088 stat_types = lappend(stat_types, makeString("ndistinct"));
2089 else if (enabled[i] == STATS_EXT_DEPENDENCIES)
2090 stat_types = lappend(stat_types, makeString("dependencies"));
2091 else if (enabled[i] == STATS_EXT_MCV)
2092 stat_types = lappend(stat_types, makeString("mcv"));
2093 else if (enabled[i] == STATS_EXT_EXPRESSIONS)
2094 /* expression stats are not exposed to users */
2095 continue;
2096 else
2097 elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
2098 }
2099
2100 /* Determine which columns the statistics are on */
2101 for (i = 0; i < statsrec->stxkeys.dim1; i++)
2102 {
2104 AttrNumber attnum = statsrec->stxkeys.values[i];
2105
2106 selem->name =
2107 get_attname(heapRelid, attmap->attnums[attnum - 1], false);
2108 selem->expr = NULL;
2109
2111 }
2112
2113 /*
2114 * Now handle expressions, if there are any. The order (with respect to
2115 * regular attributes) does not really matter for extended stats, so we
2116 * simply append them after simple column references.
2117 *
2118 * XXX Some places during build/estimation treat expressions as if they
2119 * are before attributes, but for the CREATE command that's entirely
2120 * irrelevant.
2121 */
2124
2125 if (!isnull)
2126 {
2127 ListCell *lc;
2128 List *exprs = NIL;
2129 char *exprsString;
2130
2132 exprs = (List *) stringToNode(exprsString);
2133
2134 foreach(lc, exprs)
2135 {
2136 Node *expr = (Node *) lfirst(lc);
2138 bool found_whole_row;
2139
2140 /* Adjust Vars to match new table's column numbering */
2141 expr = map_variable_attnos(expr,
2142 1, 0,
2143 attmap,
2144 InvalidOid,
2145 &found_whole_row);
2146
2147 selem->name = NULL;
2148 selem->expr = expr;
2149
2151 }
2152
2154 }
2155
2156 /* finally, build the output node */
2157 stats = makeNode(CreateStatsStmt);
2158 stats->defnames = NULL;
2159 stats->stat_types = stat_types;
2160 stats->exprs = def_names;
2161 stats->relations = list_make1(heapRel);
2162 stats->stxcomment = NULL;
2163 stats->transformed = true; /* don't need transformStatsStmt again */
2164 stats->if_not_exists = false;
2165
2166 /* Clean up */
2168
2169 return stats;
2170}
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define DatumGetArrayTypeP(X)
Definition array.h:261
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
#define ARR_HASNULL(a)
Definition array.h:291
#define TextDatumGetCString(d)
Definition builtins.h:99
#define Assert(condition)
Definition c.h:943
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
int i
Definition isn.c:77
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition lsyscache.c:984
void pfree(void *pointer)
Definition mcxt.c:1619
int16 attnum
#define lfirst(lc)
Definition pg_list.h:172
#define list_make1(x1)
Definition pg_list.h:244
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext * Form_pg_statistic_ext
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog, ERROR, CreateStatsStmt::exprs, fb(), Form_pg_statistic_ext, get_attname(), GETSTRUCT(), HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, InvalidOid, lappend(), lfirst, list_make1, makeNode, makeString(), map_variable_attnos(), NIL, ObjectIdGetDatum(), OidIsValid, pfree(), CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, stringToNode(), CreateStatsStmt::stxcomment, SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and CreateStatsStmt::transformed.

Referenced by expandTableLikeClause().

◆ generateClonedIndexStmt()

IndexStmt * generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const AttrMap attmap,
Oid constraintOid 
)

Definition at line 1690 of file parse_utilcmd.c.

1693{
1704 List *indexprs;
1706 Oid indrelid;
1707 int keyno;
1709 Datum datum;
1710 bool isnull;
1711
1712 if (constraintOid)
1714
1715 /*
1716 * Fetch pg_class tuple of source index. We can't use the copy in the
1717 * relcache entry because it doesn't include optional fields.
1718 */
1721 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1723
1724 /* Fetch pg_index tuple for source index from relcache entry */
1725 ht_idx = source_idx->rd_indextuple;
1727 indrelid = idxrec->indrelid;
1728
1729 /* Fetch the pg_am tuple of the index' access method */
1731 if (!HeapTupleIsValid(ht_am))
1732 elog(ERROR, "cache lookup failed for access method %u",
1733 idxrelrec->relam);
1735
1736 /* Extract indcollation from the pg_index tuple */
1740
1741 /* Extract indclass from the pg_index tuple */
1743 indclass = (oidvector *) DatumGetPointer(datum);
1744
1745 /* Begin building the IndexStmt */
1747 index->relation = heapRel;
1748 index->accessMethod = pstrdup(NameStr(amrec->amname));
1749 if (OidIsValid(idxrelrec->reltablespace))
1750 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1751 else
1752 index->tableSpace = NULL;
1753 index->excludeOpNames = NIL;
1754 index->idxcomment = NULL;
1755 index->indexOid = InvalidOid;
1756 index->oldNumber = InvalidRelFileNumber;
1757 index->oldCreateSubid = InvalidSubTransactionId;
1758 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1759 index->unique = idxrec->indisunique;
1760 index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1761 index->primary = idxrec->indisprimary;
1762 index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
1763 index->transformed = true; /* don't need transformIndexStmt */
1764 index->concurrent = false;
1765 index->if_not_exists = false;
1766 index->reset_default_tblspc = false;
1767
1768 /*
1769 * We don't try to preserve the name of the source index; instead, just
1770 * let DefineIndex() choose a reasonable name. (If we tried to preserve
1771 * the name, we'd get duplicate-relation-name failures unless the source
1772 * table was in a different schema.)
1773 */
1774 index->idxname = NULL;
1775
1776 /*
1777 * If the index is marked PRIMARY or has an exclusion condition, it's
1778 * certainly from a constraint; else, if it's not marked UNIQUE, it
1779 * certainly isn't. If it is or might be from a constraint, we have to
1780 * fetch the pg_constraint record.
1781 */
1782 if (index->primary || index->unique || idxrec->indisexclusion)
1783 {
1785
1787 {
1790
1791 if (constraintOid)
1793
1797 elog(ERROR, "cache lookup failed for constraint %u",
1798 constraintId);
1800
1801 index->isconstraint = true;
1802 index->deferrable = conrec->condeferrable;
1803 index->initdeferred = conrec->condeferred;
1804
1805 /* If it's an exclusion constraint, we need the operator names */
1806 if (idxrec->indisexclusion)
1807 {
1808 Datum *elems;
1809 int nElems;
1810 int i;
1811
1812 Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
1813 (index->iswithoutoverlaps &&
1814 (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
1815 /* Extract operator OIDs from the pg_constraint tuple */
1818 deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1819
1820 for (i = 0; i < nElems; i++)
1821 {
1822 Oid operid = DatumGetObjectId(elems[i]);
1825 char *oprname;
1826 char *nspname;
1827 List *namelist;
1828
1832 elog(ERROR, "cache lookup failed for operator %u",
1833 operid);
1835 oprname = pstrdup(NameStr(operform->oprname));
1836 /* For simplicity we always schema-qualify the op name */
1837 nspname = get_namespace_name(operform->oprnamespace);
1838 namelist = list_make2(makeString(nspname),
1839 makeString(oprname));
1840 index->excludeOpNames = lappend(index->excludeOpNames,
1841 namelist);
1843 }
1844 }
1845
1847 }
1848 else
1849 index->isconstraint = false;
1850 }
1851 else
1852 index->isconstraint = false;
1853
1854 /* Get the index expressions, if any */
1856 Anum_pg_index_indexprs, &isnull);
1857 if (!isnull)
1858 {
1859 char *exprsString;
1860
1863 }
1864 else
1865 indexprs = NIL;
1866
1867 /* Build the list of IndexElem */
1868 index->indexParams = NIL;
1869 index->indexIncludingParams = NIL;
1870
1872 for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1873 {
1875 AttrNumber attnum = idxrec->indkey.values[keyno];
1877 keyno);
1878 int16 opt = source_idx->rd_indoption[keyno];
1879
1881
1883 {
1884 /* Simple index column */
1885 char *attname;
1886
1889
1890 iparam->name = attname;
1891 iparam->expr = NULL;
1892 }
1893 else
1894 {
1895 /* Expressional index */
1896 Node *indexkey;
1897 bool found_whole_row;
1898
1899 if (indexpr_item == NULL)
1900 elog(ERROR, "too few entries in indexprs list");
1903
1904 /* Adjust Vars to match new table's column numbering */
1906 1, 0,
1907 attmap,
1908 InvalidOid, &found_whole_row);
1909
1910 /* As in expandTableLikeClause, reject whole-row variables */
1911 if (found_whole_row)
1912 ereport(ERROR,
1914 errmsg("cannot convert whole-row table reference"),
1915 errdetail("Index \"%s\" contains a whole-row table reference.",
1917
1918 iparam->name = NULL;
1919 iparam->expr = indexkey;
1920
1922 }
1923
1924 /* Copy the original index column name */
1925 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1926
1927 /* Add the collation name, if non-default */
1928 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1929
1930 /* Add the operator class name, if non-default */
1931 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1932 iparam->opclassopts =
1934
1935 iparam->ordering = SORTBY_DEFAULT;
1936 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1937
1938 /* Adjust options if necessary */
1939 if (source_idx->rd_indam->amcanorder)
1940 {
1941 /*
1942 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1943 * set non-default settings unnecessarily, though, so as to
1944 * improve the chance of recognizing equivalence to constraint
1945 * indexes.
1946 */
1947 if (opt & INDOPTION_DESC)
1948 {
1949 iparam->ordering = SORTBY_DESC;
1950 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1951 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1952 }
1953 else
1954 {
1955 if (opt & INDOPTION_NULLS_FIRST)
1956 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1957 }
1958 }
1959
1960 iparam->location = -1;
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 {
1969 AttrNumber attnum = idxrec->indkey.values[keyno];
1971 keyno);
1972
1974
1976 {
1977 /* Simple index column */
1978 char *attname;
1979
1981
1982 iparam->name = attname;
1983 iparam->expr = NULL;
1984 }
1985 else
1986 ereport(ERROR,
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 iparam->location = -1;
1994
1995 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1996 }
1997 /* Copy reloptions if any */
1999 Anum_pg_class_reloptions, &isnull);
2000 if (!isnull)
2001 index->options = untransformRelOptions(datum);
2002
2003 /* If it's a partial index, decompile and append the predicate */
2005 Anum_pg_index_indpred, &isnull);
2006 if (!isnull)
2007 {
2008 char *pred_str;
2009 Node *pred_tree;
2010 bool found_whole_row;
2011
2012 /* Convert text string to node tree */
2015
2016 /* Adjust Vars to match new table's column numbering */
2018 1, 0,
2019 attmap,
2020 InvalidOid, &found_whole_row);
2021
2022 /* As in expandTableLikeClause, reject whole-row variables */
2023 if (found_whole_row)
2024 ereport(ERROR,
2026 errmsg("cannot convert whole-row table reference"),
2027 errdetail("Index \"%s\" contains a whole-row table reference.",
2029
2030 index->whereClause = pred_tree;
2031 }
2032
2033 /* Clean up */
2036
2037 return index;
2038}
void deconstruct_array_builtin(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
char * get_tablespace_name(Oid spc_oid)
#define InvalidSubTransactionId
Definition c.h:742
int16_t int16
Definition c.h:619
Datum get_attoptions(Oid relid, int16 attnum)
Definition lsyscache.c:1127
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3599
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition lsyscache.c:1070
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
END_CATALOG_STRUCT typedef FormData_pg_am * Form_pg_am
Definition pg_am.h:52
NameData attname
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
Oid get_index_constraint(Oid indexId)
Definition pg_depend.c:1061
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
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:375
#define list_make2(x1, x2)
Definition pg_list.h:246
END_CATALOG_STRUCT typedef FormData_pg_operator * Form_pg_operator
Definition pg_operator.h:87
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
List * untransformRelOptions(Datum options)
#define InvalidRelFileNumber
Definition relpath.h:26
Definition type.h:97
Definition c.h:815

References Assert, attname, attnum, AttributeNumberIsValid, DatumGetArrayTypeP, DatumGetObjectId(), DatumGetPointer(), deconstruct_array_builtin(), elog, ereport, errcode(), errdetail(), errmsg, ERROR, exprType(), fb(), Form_pg_am, Form_pg_constraint, Form_pg_index, Form_pg_operator, get_attname(), get_attoptions(), get_atttype(), get_collation(), get_index_constraint(), get_namespace_name(), get_opclass(), get_tablespace_name(), GETSTRUCT(), HeapTupleIsValid, i, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), NameStr, NIL, ObjectIdGetDatum(), OidIsValid, pstrdup(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TupleDescAttr(), and untransformRelOptions().

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

◆ generateSerialExtraStmts()

static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
bool  col_exists,
char **  snamespace_p,
char **  sname_p 
)
static

Definition at line 388 of file parse_utilcmd.c.

392{
397 char *snamespace;
398 char *sname;
399 char seqpersistence;
403
404 /* Make a copy of this as we may end up modifying it in the code below */
406
407 /*
408 * Check for non-SQL-standard options (not supported within CREATE
409 * SEQUENCE, because they'd be redundant), and remove them from the
410 * seqoptions list if found.
411 */
412 foreach(option, seqoptions)
413 {
415
416 if (strcmp(defel->defname, "sequence_name") == 0)
417 {
418 if (nameEl)
420 nameEl = defel;
422 }
423 else if (strcmp(defel->defname, "logged") == 0 ||
424 strcmp(defel->defname, "unlogged") == 0)
425 {
426 if (loggedEl)
428 loggedEl = defel;
430 }
431 }
432
433 /*
434 * Determine namespace and name to use for the sequence.
435 */
436 if (nameEl)
437 {
438 /* Use specified name */
440
442 if (!snamespace)
443 {
444 /* Given unqualified SEQUENCE NAME, select namespace */
445 if (cxt->rel)
447 else
450 }
451 sname = rv->relname;
452 }
453 else
454 {
455 /*
456 * Generate a name.
457 *
458 * Although we use ChooseRelationName, it's not guaranteed that the
459 * selected sequence name won't conflict; given sufficiently long
460 * field names, two different serial columns in the same table could
461 * be assigned the same sequence name, and we'd not notice since we
462 * aren't creating the sequence quite yet. In practice this seems
463 * quite unlikely to be a problem, especially since few people would
464 * need two serial columns in one table.
465 */
466 if (cxt->rel)
468 else
469 {
472 }
475 column->colname,
476 "seq",
478 false);
479 }
480
482 (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
483 cxt->stmtType, sname,
484 cxt->relation->relname, column->colname)));
485
486 /*
487 * Determine the persistence of the sequence. By default we copy the
488 * persistence of the table, but if LOGGED or UNLOGGED was specified, use
489 * that (as long as the table isn't TEMP).
490 *
491 * For CREATE TABLE, we get the persistence from cxt->relation, which
492 * comes from the CreateStmt in progress. For ALTER TABLE, the parser
493 * won't set cxt->relation->relpersistence, but we have cxt->rel as the
494 * existing table, so we copy the persistence from there.
495 */
496 seqpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
497 if (loggedEl)
498 {
502 errmsg("cannot set logged status of a temporary sequence"),
503 parser_errposition(cxt->pstate, loggedEl->location)));
504 else if (strcmp(loggedEl->defname, "logged") == 0)
506 else
508 }
509
510 /*
511 * Build a CREATE SEQUENCE command to create the sequence object, and add
512 * it to the list of things to be done before this CREATE/ALTER TABLE.
513 */
515 seqstmt->for_identity = for_identity;
516 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
517 seqstmt->sequence->relpersistence = seqpersistence;
518 seqstmt->options = seqoptions;
519
520 /*
521 * If a sequence data type was specified, add it to the options. Prepend
522 * to the list rather than append; in case a user supplied their own AS
523 * clause, the "redundant options" error will point to their occurrence,
524 * not our synthetic one.
525 */
526 if (seqtypid)
527 seqstmt->options = lcons(makeDefElem("as",
528 (Node *) makeTypeNameFromOid(seqtypid, -1),
529 -1),
530 seqstmt->options);
531
532 /*
533 * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
534 * the table's owner. The current user might be someone else (perhaps a
535 * superuser, or someone who's only a member of the owning role), but the
536 * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
537 * exactly the same owning role.
538 */
539 if (cxt->rel)
540 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
541 else
542 seqstmt->ownerId = InvalidOid;
543
544 cxt->blist = lappend(cxt->blist, seqstmt);
545
546 /*
547 * Store the identity sequence name that we decided on. ALTER TABLE ...
548 * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
549 * with values from the sequence, while the association of the sequence
550 * with the table is not set until after the ALTER TABLE.
551 */
552 column->identitySequence = seqstmt->sequence;
553
554 /*
555 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
556 * owned by this column, and add it to the appropriate list of things to
557 * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
558 * COLUMN, it must be done after the statement because we don't know the
559 * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
560 * we can do the marking immediately, which improves some ALTER TABLE
561 * behaviors.
562 */
564 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
567 makeString(column->colname));
568 altseqstmt->options = list_make1(makeDefElem("owned_by",
569 (Node *) attnamelist, -1));
570 altseqstmt->for_identity = for_identity;
571
572 if (col_exists)
573 cxt->blist = lappend(cxt->blist, altseqstmt);
574 else
575 cxt->alist = lappend(cxt->alist, altseqstmt);
576
577 if (snamespace_p)
579 if (sname_p)
580 *sname_p = sname;
581}
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG1
Definition elog.h:31
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition indexcmds.c:2634
List * list_copy(const List *oldlist)
Definition list.c:1573
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
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition namespace.c:847
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition namespace.c:655
RangeVar * makeRangeVarFromNameList(const List *names)
Definition namespace.c:3626
#define castNode(_type_, nodeptr)
Definition nodes.h:182
#define lfirst_node(type, lc)
Definition pg_list.h:176
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:423
#define RelationGetNamespace(relation)
Definition rel.h:557
const char * stmtType
RangeVar * relation
ParseState * pstate

References CreateStmtContext::alist, CreateStmtContext::blist, castNode, ChooseRelationName(), DEBUG1, ereport, errcode(), errmsg, errmsg_internal(), ERROR, errorConflictingDefElem(), fb(), foreach_delete_current, get_namespace_name(), InvalidOid, lappend(), lcons(), lfirst_node, list_copy(), list_make1, list_make3, makeDefElem(), makeNode, makeRangeVar(), makeRangeVarFromNameList(), makeString(), makeTypeNameFromOid(), parser_errposition(), CreateStmtContext::pstate, RangeVarAdjustRelationPersistence(), RangeVarGetCreationNamespace(), RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetNamespace, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, and CreateStmtContext::stmtType.

Referenced by transformAlterTableStmt(), transformColumnDefinition(), and transformTableLikeClause().

◆ get_collation()

static List * get_collation ( Oid  collation,
Oid  actual_datatype 
)
static

Definition at line 2179 of file parse_utilcmd.c.

2180{
2181 List *result;
2184 char *nsp_name;
2185 char *coll_name;
2186
2187 if (!OidIsValid(collation))
2188 return NIL; /* easy case */
2189 if (collation == get_typcollation(actual_datatype))
2190 return NIL; /* just let it default */
2191
2194 elog(ERROR, "cache lookup failed for collation %u", collation);
2196
2197 /* For simplicity, we always schema-qualify the name */
2198 nsp_name = get_namespace_name(coll_rec->collnamespace);
2199 coll_name = pstrdup(NameStr(coll_rec->collname));
2201
2203 return result;
2204}
Oid get_typcollation(Oid typid)
Definition lsyscache.c:3289
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation

References elog, ERROR, fb(), Form_pg_collation, get_namespace_name(), get_typcollation(), GETSTRUCT(), HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum(), OidIsValid, pstrdup(), ReleaseSysCache(), result, and SearchSysCache1().

Referenced by generateClonedIndexStmt().

◆ get_opclass()

static List * get_opclass ( Oid  opclass,
Oid  actual_datatype 
)
static

Definition at line 2213 of file parse_utilcmd.c.

2214{
2215 List *result = NIL;
2218
2221 elog(ERROR, "cache lookup failed for opclass %u", opclass);
2223
2224 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2225 {
2226 /* For simplicity, we always schema-qualify the name */
2227 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2228 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2229
2231 }
2232
2234 return result;
2235}
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition indexcmds.c:2371
END_CATALOG_STRUCT typedef FormData_pg_opclass * Form_pg_opclass
Definition pg_opclass.h:87

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

Referenced by generateClonedIndexStmt().

◆ transformAlterTableStmt()

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

Definition at line 3819 of file parse_utilcmd.c.

3822{
3823 Relation rel;
3824 TupleDesc tupdesc;
3825 ParseState *pstate;
3828 ListCell *lcmd,
3829 *l;
3830 List *newcmds = NIL;
3831 bool skipValidation = true;
3834
3835 /* Caller is responsible for locking the relation */
3836 rel = relation_open(relid, NoLock);
3837 tupdesc = RelationGetDescr(rel);
3838
3839 /* Set up pstate */
3840 pstate = make_parsestate(NULL);
3841 pstate->p_sourcetext = queryString;
3843 rel,
3845 NULL,
3846 false,
3847 true);
3848 addNSItemToQuery(pstate, nsitem, false, true, true);
3849
3850 /* Set up CreateStmtContext */
3851 cxt.pstate = pstate;
3852 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3853 {
3854 cxt.stmtType = "ALTER FOREIGN TABLE";
3855 cxt.isforeign = true;
3856 }
3857 else
3858 {
3859 cxt.stmtType = "ALTER TABLE";
3860 cxt.isforeign = false;
3861 }
3862 cxt.relation = stmt->relation;
3863 cxt.rel = rel;
3864 cxt.inhRelations = NIL;
3865 cxt.isalter = true;
3866 cxt.columns = NIL;
3867 cxt.ckconstraints = NIL;
3868 cxt.nnconstraints = NIL;
3869 cxt.fkconstraints = NIL;
3870 cxt.ixconstraints = NIL;
3871 cxt.likeclauses = NIL;
3872 cxt.blist = NIL;
3873 cxt.alist = NIL;
3874 cxt.pkey = NULL;
3875 cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3876 cxt.partbound = NULL;
3877 cxt.ofType = false;
3878
3879 /*
3880 * Transform ALTER subcommands that need it (most don't). These largely
3881 * re-use code from CREATE TABLE.
3882 */
3883 foreach(lcmd, stmt->cmds)
3884 {
3886
3887 switch (cmd->subtype)
3888 {
3889 case AT_AddColumn:
3890 {
3891 ColumnDef *def = castNode(ColumnDef, cmd->def);
3892
3893 transformColumnDefinition(&cxt, def);
3894
3895 /*
3896 * If the column has a non-null default, we can't skip
3897 * validation of foreign keys.
3898 */
3899 if (def->raw_default != NULL)
3900 skipValidation = false;
3901
3902 /*
3903 * All constraints are processed in other ways. Remove the
3904 * original list
3905 */
3906 def->constraints = NIL;
3907
3908 newcmds = lappend(newcmds, cmd);
3909 break;
3910 }
3911
3912 case AT_AddConstraint:
3913
3914 /*
3915 * The original AddConstraint cmd node doesn't go to newcmds
3916 */
3917 if (IsA(cmd->def, Constraint))
3918 {
3919 transformTableConstraint(&cxt, (Constraint *) cmd->def);
3920 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3921 skipValidation = false;
3922 }
3923 else
3924 elog(ERROR, "unrecognized node type: %d",
3925 (int) nodeTag(cmd->def));
3926 break;
3927
3928 case AT_AlterColumnType:
3929 {
3930 ColumnDef *def = castNode(ColumnDef, cmd->def);
3932
3933 /*
3934 * For ALTER COLUMN TYPE, transform the USING clause if
3935 * one was specified.
3936 */
3937 if (def->raw_default)
3938 {
3939 def->cooked_default =
3940 transformExpr(pstate, def->raw_default,
3942 }
3943
3944 /*
3945 * For identity column, create ALTER SEQUENCE command to
3946 * change the data type of the sequence. Identity sequence
3947 * is associated with the top level partitioned table.
3948 * Hence ignore partitions.
3949 */
3951 {
3952 attnum = get_attnum(relid, cmd->name);
3954 ereport(ERROR,
3956 errmsg("column \"%s\" of relation \"%s\" does not exist",
3957 cmd->name, RelationGetRelationName(rel))));
3958
3959 if (attnum > 0 &&
3960 TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3961 {
3962 Oid seq_relid = getIdentitySequence(rel, attnum, false);
3963 Oid typeOid = typenameTypeId(pstate, def->typeName);
3965
3966 altseqstmt->sequence
3969 -1);
3970 altseqstmt->options = list_make1(makeDefElem("as",
3971 (Node *) makeTypeNameFromOid(typeOid, -1),
3972 -1));
3973 altseqstmt->for_identity = true;
3974 cxt.blist = lappend(cxt.blist, altseqstmt);
3975 }
3976 }
3977
3978 newcmds = lappend(newcmds, cmd);
3979 break;
3980 }
3981
3982 case AT_AddIdentity:
3983 {
3984 Constraint *def = castNode(Constraint, cmd->def);
3987
3988 newdef->colname = cmd->name;
3989 newdef->identity = def->generated_when;
3990 cmd->def = (Node *) newdef;
3991
3992 attnum = get_attnum(relid, cmd->name);
3994 ereport(ERROR,
3996 errmsg("column \"%s\" of relation \"%s\" does not exist",
3997 cmd->name, RelationGetRelationName(rel))));
3998
4000 get_atttype(relid, attnum),
4001 def->options, true, true,
4002 NULL, NULL);
4003
4004 newcmds = lappend(newcmds, cmd);
4005 break;
4006 }
4007
4008 case AT_SetIdentity:
4009 {
4010 /*
4011 * Create an ALTER SEQUENCE statement for the internal
4012 * sequence of the identity column.
4013 */
4014 ListCell *lc;
4015 List *newseqopts = NIL;
4016 List *newdef = NIL;
4018 Oid seq_relid;
4019
4020 /*
4021 * Split options into those handled by ALTER SEQUENCE and
4022 * those for ALTER TABLE proper.
4023 */
4024 foreach(lc, castNode(List, cmd->def))
4025 {
4026 DefElem *def = lfirst_node(DefElem, lc);
4027
4028 if (strcmp(def->defname, "generated") == 0)
4029 newdef = lappend(newdef, def);
4030 else
4032 }
4033
4034 attnum = get_attnum(relid, cmd->name);
4036 ereport(ERROR,
4038 errmsg("column \"%s\" of relation \"%s\" does not exist",
4039 cmd->name, RelationGetRelationName(rel))));
4040
4041 seq_relid = getIdentitySequence(rel, attnum, true);
4042
4043 if (seq_relid)
4044 {
4046
4049 get_rel_name(seq_relid), -1);
4050 seqstmt->options = newseqopts;
4051 seqstmt->for_identity = true;
4052 seqstmt->missing_ok = false;
4053
4054 cxt.blist = lappend(cxt.blist, seqstmt);
4055 }
4056
4057 /*
4058 * If column was not an identity column, we just let the
4059 * ALTER TABLE command error out later. (There are cases
4060 * this fails to cover, but we'll need to restructure
4061 * where creation of the sequence dependency linkage
4062 * happens before we can fix it.)
4063 */
4064
4065 cmd->def = (Node *) newdef;
4066 newcmds = lappend(newcmds, cmd);
4067 break;
4068 }
4069
4070 case AT_AttachPartition:
4071 case AT_DetachPartition:
4072 {
4074
4075 transformPartitionCmd(&cxt, partcmd->bound);
4076 /* assign the transformed value of the partition bound */
4077 partcmd->bound = cxt.partbound;
4078 }
4079
4080 newcmds = lappend(newcmds, cmd);
4081 break;
4082
4083 case AT_MergePartitions:
4084 {
4086
4087 if (list_length(partcmd->partlist) < 2)
4088 ereport(ERROR,
4090 errmsg("list of partitions to be merged should include at least two partitions"));
4091
4093 newcmds = lappend(newcmds, cmd);
4094 break;
4095 }
4096
4097 case AT_SplitPartition:
4098 {
4100
4101 if (list_length(partcmd->partlist) < 2)
4102 ereport(ERROR,
4104 errmsg("list of new partitions should contain at least two partitions"));
4105
4107 newcmds = lappend(newcmds, cmd);
4108 break;
4109 }
4110
4111 default:
4112
4113 /*
4114 * Currently, we shouldn't actually get here for the
4115 * subcommand types that don't require transformation; but if
4116 * we do, just emit them unchanged.
4117 */
4118 newcmds = lappend(newcmds, cmd);
4119 break;
4120 }
4121 }
4122
4123 /*
4124 * Transfer anything we already have in cxt.alist into save_alist, to keep
4125 * it separate from the output of transformIndexConstraints.
4126 */
4127 save_alist = cxt.alist;
4128 cxt.alist = NIL;
4129
4130 /* Postprocess constraints */
4133 transformCheckConstraints(&cxt, false);
4134
4135 /*
4136 * Push any index-creation commands into the ALTER, so that they can be
4137 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
4138 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
4139 * subcommand has already been through transformIndexStmt.
4140 */
4141 foreach(l, cxt.alist)
4142 {
4143 Node *istmt = (Node *) lfirst(l);
4144
4145 /*
4146 * We assume here that cxt.alist contains only IndexStmts generated
4147 * from primary key constraints.
4148 */
4149 if (IsA(istmt, IndexStmt))
4150 {
4151 IndexStmt *idxstmt = (IndexStmt *) istmt;
4152
4153 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
4155 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
4156 newcmd->def = (Node *) idxstmt;
4158 }
4159 else
4160 elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
4161 }
4162 cxt.alist = NIL;
4163
4164 /* Append any CHECK, NOT NULL or FK constraints to the commands list */
4166 {
4168 newcmd->subtype = AT_AddConstraint;
4169 newcmd->def = (Node *) def;
4171 }
4173 {
4175 newcmd->subtype = AT_AddConstraint;
4176 newcmd->def = (Node *) def;
4178 }
4180 {
4182 newcmd->subtype = AT_AddConstraint;
4183 newcmd->def = (Node *) def;
4185 }
4186
4187 /* Close rel */
4188 relation_close(rel, NoLock);
4189
4190 /*
4191 * Output results.
4192 */
4193 stmt->cmds = newcmds;
4194
4195 *beforeStmts = cxt.blist;
4196 *afterStmts = list_concat(cxt.alist, save_alist);
4197
4198 return stmt;
4199}
#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:2159
AttrNumber get_attnum(Oid relid, const char *attname)
Definition lsyscache.c:1015
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2183
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define nodeTag(nodeptr)
Definition nodes.h:139
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:121
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition parse_node.h:76
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, LOCKMODE lockmode, Alias *alias, bool inh, bool inFromCl)
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 transformPartitionCmdForSplit(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformPartitionCmdForMerge(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionBoundSpec *bound)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ AT_AddIndexConstraint
@ AT_MergePartitions
@ AT_SetIdentity
@ AT_AddIndex
@ AT_AddIdentity
@ AT_AlterColumnType
@ AT_DetachPartition
@ AT_AttachPartition
@ AT_SplitPartition
@ AT_AddColumn
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition pg_depend.c:1018
static int list_length(const List *l)
Definition pg_list.h:152
#define foreach_node(type, var, lst)
Definition pg_list.h:528
#define RelationGetForm(relation)
Definition rel.h:510
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:206
AlterTableType subtype
List * constraints
Definition parsenodes.h:787
Node * cooked_default
Definition parsenodes.h:780
TypeName * typeName
Definition parsenodes.h:771
Node * raw_default
Definition parsenodes.h:779
List * options
char generated_when
PartitionBoundSpec * partbound
char * defname
Definition parsenodes.h:860
const char * p_sourcetext
Definition parse_node.h:214

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_MergePartitions, AT_SetIdentity, AT_SplitPartition, attnum, CreateStmtContext::blist, castNode, CreateStmtContext::ckconstraints, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg, ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, fb(), CreateStmtContext::fkconstraints, foreach_node, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_length(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterTableCmd::name, NIL, CreateStmtContext::nnconstraints, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::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, stmt, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformPartitionCmdForMerge(), transformPartitionCmdForSplit(), transformTableConstraint(), TupleDescAttr(), ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2958 of file parse_utilcmd.c.

2959{
2961
2962 if (cxt->ckconstraints == NIL)
2963 return;
2964
2965 /*
2966 * When creating a new table (but not a foreign table), we can safely skip
2967 * the validation of check constraints and mark them as valid based on the
2968 * constraint enforcement flag, since NOT ENFORCED constraints must always
2969 * be marked as NOT VALID. (This will override any user-supplied NOT VALID
2970 * flag.)
2971 */
2972 if (skipValidation)
2973 {
2974 foreach(ckclist, cxt->ckconstraints)
2975 {
2976 Constraint *constraint = (Constraint *) lfirst(ckclist);
2977
2978 constraint->skip_validation = true;
2979 constraint->initially_valid = constraint->is_enforced;
2980 }
2981 }
2982}

References CreateStmtContext::ckconstraints, fb(), Constraint::initially_valid, Constraint::is_enforced, lfirst, NIL, and Constraint::skip_validation.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 589 of file parse_utilcmd.c.

590{
591 bool is_serial;
592 bool saw_nullable;
593 bool saw_default;
594 bool saw_identity;
595 bool saw_generated;
596 bool need_notnull = false;
597 bool disallow_noinherit_notnull = false;
599
600 cxt->columns = lappend(cxt->columns, column);
601
602 /* Check for SERIAL pseudo-types */
603 is_serial = false;
604 if (column->typeName
605 && list_length(column->typeName->names) == 1
606 && !column->typeName->pct_type)
607 {
608 char *typname = strVal(linitial(column->typeName->names));
609
610 if (strcmp(typname, "smallserial") == 0 ||
611 strcmp(typname, "serial2") == 0)
612 {
613 is_serial = true;
614 column->typeName->names = NIL;
615 column->typeName->typeOid = INT2OID;
616 }
617 else if (strcmp(typname, "serial") == 0 ||
618 strcmp(typname, "serial4") == 0)
619 {
620 is_serial = true;
621 column->typeName->names = NIL;
622 column->typeName->typeOid = INT4OID;
623 }
624 else if (strcmp(typname, "bigserial") == 0 ||
625 strcmp(typname, "serial8") == 0)
626 {
627 is_serial = true;
628 column->typeName->names = NIL;
629 column->typeName->typeOid = INT8OID;
630 }
631
632 /*
633 * We have to reject "serial[]" explicitly, because once we've set
634 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
635 * special coding for serial(typmod) though.
636 */
637 if (is_serial && column->typeName->arrayBounds != NIL)
640 errmsg("array of serial is not implemented"),
642 column->typeName->location)));
643 }
644
645 /* Do necessary work on the column type declaration */
646 if (column->typeName)
648
649 /* Special actions for SERIAL pseudo-types */
650 if (is_serial)
651 {
652 char *snamespace;
653 char *sname;
654 char *qstring;
658 Constraint *constraint;
659
661 column->typeName->typeOid, NIL,
662 false, false,
663 &snamespace, &sname);
664
665 /*
666 * Create appropriate constraints for SERIAL. We do this in full,
667 * rather than shortcutting, so that we will detect any conflicting
668 * constraints the user wrote (like a different DEFAULT).
669 *
670 * Create an expression tree representing the function call
671 * nextval('sequencename'). We cannot reduce the raw tree to cooked
672 * form until after the sequence is created, but there's no need to do
673 * so.
674 */
677 snamenode->val.node.type = T_String;
678 snamenode->val.sval.sval = qstring;
679 snamenode->location = -1;
681 castnode->typeName = SystemTypeName("regclass");
682 castnode->arg = (Node *) snamenode;
683 castnode->location = -1;
687 -1);
688 constraint = makeNode(Constraint);
689 constraint->contype = CONSTR_DEFAULT;
690 constraint->location = -1;
691 constraint->raw_expr = (Node *) funccallnode;
692 constraint->cooked_expr = NULL;
693 column->constraints = lappend(column->constraints, constraint);
694
695 /* have a not-null constraint added later */
696 need_notnull = true;
698 }
699
700 /* Process column constraints, if any... */
701 transformConstraintAttrs(cxt->pstate, column->constraints);
702
703 /*
704 * First, scan the column's constraints to see if a not-null constraint
705 * that we add must be prevented from being NO INHERIT. This should be
706 * enforced only for PRIMARY KEY, not IDENTITY or SERIAL. However, if the
707 * not-null constraint is specified as a table constraint rather than as a
708 * column constraint, AddRelationNotNullConstraints would raise an error
709 * if a NO INHERIT mismatch is found. To avoid inconsistently disallowing
710 * it in the table constraint case but not the column constraint case, we
711 * disallow it here as well. Maybe AddRelationNotNullConstraints can be
712 * improved someday, so that it doesn't complain, and then we can remove
713 * the restriction for SERIAL and IDENTITY here as well.
714 */
716 {
717 foreach_node(Constraint, constraint, column->constraints)
718 {
719 switch (constraint->contype)
720 {
721 case CONSTR_IDENTITY:
722 case CONSTR_PRIMARY:
724 break;
725 default:
726 break;
727 }
728 }
729 }
730
731 /* Now scan them again to do full processing */
732 saw_nullable = false;
733 saw_default = false;
734 saw_identity = false;
735 saw_generated = false;
736
737 foreach_node(Constraint, constraint, column->constraints)
738 {
739 switch (constraint->contype)
740 {
741 case CONSTR_NULL:
742 if ((saw_nullable && column->is_not_null) || need_notnull)
745 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
746 column->colname, cxt->relation->relname),
748 constraint->location)));
749 column->is_not_null = false;
750 saw_nullable = true;
751 break;
752
753 case CONSTR_NOTNULL:
754 if (cxt->ispartitioned && constraint->is_no_inherit)
757 errmsg("not-null constraints on partitioned tables cannot be NO INHERIT"));
758
759 /* Disallow conflicting [NOT] NULL markings */
760 if (saw_nullable && !column->is_not_null)
763 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
764 column->colname, cxt->relation->relname),
766 constraint->location)));
767
768 if (disallow_noinherit_notnull && constraint->is_no_inherit)
771 errmsg("conflicting NO INHERIT declarations for not-null constraints on column \"%s\"",
772 column->colname));
773
774 /*
775 * If this is the first time we see this column being marked
776 * not-null, add the constraint entry and keep track of it.
777 * Also, remove previous markings that we need one.
778 *
779 * If this is a redundant not-null specification, just check
780 * that it doesn't conflict with what was specified earlier.
781 *
782 * Any conflicts with table constraints will be further
783 * checked in AddRelationNotNullConstraints().
784 */
785 if (!column->is_not_null)
786 {
787 column->is_not_null = true;
788 saw_nullable = true;
789 need_notnull = false;
790
791 constraint->keys = list_make1(makeString(column->colname));
792 notnull_constraint = constraint;
793 cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
794 }
795 else if (notnull_constraint)
796 {
797 if (constraint->conname &&
798 notnull_constraint->conname &&
799 strcmp(notnull_constraint->conname, constraint->conname) != 0)
800 elog(ERROR, "conflicting not-null constraint names \"%s\" and \"%s\"",
801 notnull_constraint->conname, constraint->conname);
802
803 if (notnull_constraint->is_no_inherit != constraint->is_no_inherit)
806 errmsg("conflicting NO INHERIT declarations for not-null constraints on column \"%s\"",
807 column->colname));
808
809 if (!notnull_constraint->conname && constraint->conname)
810 notnull_constraint->conname = constraint->conname;
811 }
812
813 break;
814
815 case CONSTR_DEFAULT:
816 if (saw_default)
819 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
820 column->colname, cxt->relation->relname),
822 constraint->location)));
823 column->raw_default = constraint->raw_expr;
824 Assert(constraint->cooked_expr == NULL);
825 saw_default = true;
826 break;
827
828 case CONSTR_IDENTITY:
829 {
830 Type ctype;
831 Oid typeOid;
832
833 if (cxt->ofType)
836 errmsg("identity columns are not supported on typed tables")));
837 if (cxt->partbound)
840 errmsg("identity columns are not supported on partitions")));
841
842 ctype = typenameType(cxt->pstate, column->typeName, NULL);
843 typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
844 ReleaseSysCache(ctype);
845
846 if (saw_identity)
849 errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
850 column->colname, cxt->relation->relname),
852 constraint->location)));
853
855 typeOid, constraint->options,
856 true, false,
857 NULL, NULL);
858
859 column->identity = constraint->generated_when;
860 saw_identity = true;
861
862 /*
863 * Identity columns are always NOT NULL, but we may have a
864 * constraint already.
865 */
866 if (!saw_nullable)
867 need_notnull = true;
868 else if (!column->is_not_null)
871 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
872 column->colname, cxt->relation->relname),
874 constraint->location)));
875 break;
876 }
877
878 case CONSTR_GENERATED:
879 if (cxt->ofType)
882 errmsg("generated columns are not supported on typed tables")));
883 if (saw_generated)
886 errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
887 column->colname, cxt->relation->relname),
889 constraint->location)));
890 column->generated = constraint->generated_kind;
891 column->raw_default = constraint->raw_expr;
892 Assert(constraint->cooked_expr == NULL);
893 saw_generated = true;
894 break;
895
896 case CONSTR_CHECK:
897 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
898 break;
899
900 case CONSTR_PRIMARY:
901 if (saw_nullable && !column->is_not_null)
904 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
905 column->colname, cxt->relation->relname),
907 constraint->location)));
908 need_notnull = true;
909
910 if (cxt->isforeign)
913 errmsg("primary key constraints are not supported on foreign tables"),
915 constraint->location)));
917
918 case CONSTR_UNIQUE:
919 if (cxt->isforeign)
922 errmsg("unique constraints are not supported on foreign tables"),
924 constraint->location)));
925 if (constraint->keys == NIL)
926 constraint->keys = list_make1(makeString(column->colname));
927 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
928 break;
929
930 case CONSTR_EXCLUSION:
931 /* grammar does not allow EXCLUDE as a column constraint */
932 elog(ERROR, "column exclusion constraints are not supported");
933 break;
934
935 case CONSTR_FOREIGN:
936 if (cxt->isforeign)
939 errmsg("foreign key constraints are not supported on foreign tables"),
941 constraint->location)));
942
943 /*
944 * Fill in the current attribute's name and throw it into the
945 * list of FK constraints to be processed later.
946 */
947 constraint->fk_attrs = list_make1(makeString(column->colname));
948 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
949 break;
950
957 /* transformConstraintAttrs took care of these */
958 break;
959
960 default:
961 elog(ERROR, "unrecognized constraint type: %d",
962 constraint->contype);
963 break;
964 }
965
969 errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
970 column->colname, cxt->relation->relname),
972 constraint->location)));
973
977 errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
978 column->colname, cxt->relation->relname),
980 constraint->location)));
981
985 errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
986 column->colname, cxt->relation->relname),
988 constraint->location)));
989 }
990
991 /*
992 * If we need a not-null constraint for PRIMARY KEY, SERIAL or IDENTITY,
993 * and one was not explicitly specified, add one now.
994 */
995 if (need_notnull && !(saw_nullable && column->is_not_null))
996 {
997 column->is_not_null = true;
1000 }
1001
1002 /*
1003 * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
1004 * per-column foreign data wrapper options to this column after creation.
1005 */
1006 if (column->fdwoptions != NIL)
1007 {
1009 AlterTableCmd *cmd;
1010
1011 cmd = makeNode(AlterTableCmd);
1013 cmd->name = column->colname;
1014 cmd->def = (Node *) column->fdwoptions;
1015 cmd->behavior = DROP_RESTRICT;
1016 cmd->missing_ok = false;
1017
1019 stmt->relation = cxt->relation;
1020 stmt->cmds = NIL;
1021 stmt->objtype = OBJECT_FOREIGN_TABLE;
1022 stmt->cmds = lappend(stmt->cmds, cmd);
1023
1024 cxt->alist = lappend(cxt->alist, stmt);
1025 }
1026}
#define pg_fallthrough
Definition c.h:161
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition makefuncs.c:676
Constraint * makeNotNullConstraint(String *colname)
Definition makefuncs.c:493
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition parse_type.c:264
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
static void transformConstraintAttrs(ParseState *pstate, List *constraintList)
@ CONSTR_ATTR_ENFORCED
@ CONSTR_ATTR_DEFERRED
@ CONSTR_IDENTITY
@ CONSTR_ATTR_NOT_DEFERRABLE
@ CONSTR_DEFAULT
@ CONSTR_NOTNULL
@ CONSTR_ATTR_IMMEDIATE
@ CONSTR_NULL
@ CONSTR_GENERATED
@ CONSTR_ATTR_DEFERRABLE
@ CONSTR_ATTR_NOT_ENFORCED
@ DROP_RESTRICT
@ OBJECT_FOREIGN_TABLE
@ AT_AlterColumnGenericOptions
List * SystemFuncName(char *name)
TypeName * SystemTypeName(char *name)
#define linitial(l)
Definition pg_list.h:178
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
NameData typname
Definition pg_type.h:43
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
char * quote_qualified_identifier(const char *qualifier, const char *ident)
List * keys
char generated_kind
List * fk_attrs
#define strVal(v)
Definition value.h:82

References CreateStmtContext::alist, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, COERCE_EXPLICIT_CALL, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_ENFORCED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_ATTR_NOT_ENFORCED, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg, ERROR, fb(), CreateStmtContext::fkconstraints, foreach_node, Form_pg_type, generateSerialExtraStmts(), GETSTRUCT(), CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), linitial, list_length(), list_make1, Constraint::location, makeFuncCall(), makeNode, makeNotNullConstraint(), makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, NIL, CreateStmtContext::nnconstraints, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, parser_errposition(), CreateStmtContext::partbound, pg_fallthrough, CreateStmtContext::pstate, quote_qualified_identifier(), Constraint::raw_expr, CreateStmtContext::relation, ReleaseSysCache(), RangeVar::relname, stmt, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), transformColumnType(), transformConstraintAttrs(), typenameType(), and typname.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 4370 of file parse_utilcmd.c.

4371{
4372 /*
4373 * All we really need to do here is verify that the type is valid,
4374 * including any collation spec that might be present.
4375 */
4376 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
4377
4378 if (column->collClause)
4379 {
4381
4383 column->collClause->collname,
4384 column->collClause->location);
4385 /* Complain if COLLATE is applied to an uncollatable type */
4386 if (!OidIsValid(typtup->typcollation))
4387 ereport(ERROR,
4389 errmsg("collations are not supported by type %s",
4390 format_type_be(typtup->oid)),
4392 column->collClause->location)));
4393 }
4394
4395 ReleaseSysCache(ctype);
4396}
char * format_type_be(Oid type_oid)
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition parse_type.c:515

References ereport, errcode(), errmsg, ERROR, fb(), Form_pg_type, format_type_be(), GETSTRUCT(), LookupCollation(), OidIsValid, parser_errposition(), CreateStmtContext::pstate, ReleaseSysCache(), and typenameType().

Referenced by transformColumnDefinition().

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( ParseState pstate,
List constraintList 
)
static

Definition at line 4215 of file parse_utilcmd.c.

4216{
4218 bool saw_deferrability = false;
4219 bool saw_initially = false;
4220 bool saw_enforced = false;
4221 ListCell *clist;
4222
4223#define SUPPORTS_ATTRS(node) \
4224 ((node) != NULL && \
4225 ((node)->contype == CONSTR_PRIMARY || \
4226 (node)->contype == CONSTR_UNIQUE || \
4227 (node)->contype == CONSTR_EXCLUSION || \
4228 (node)->contype == CONSTR_FOREIGN))
4229
4230 foreach(clist, constraintList)
4231 {
4232 Constraint *con = (Constraint *) lfirst(clist);
4233
4234 if (!IsA(con, Constraint))
4235 elog(ERROR, "unrecognized node type: %d",
4236 (int) nodeTag(con));
4237 switch (con->contype)
4238 {
4241 ereport(ERROR,
4243 errmsg("misplaced DEFERRABLE clause"),
4244 parser_errposition(pstate, con->location)));
4246 ereport(ERROR,
4248 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
4249 parser_errposition(pstate, con->location)));
4250 saw_deferrability = true;
4251 lastprimarycon->deferrable = true;
4252 break;
4253
4256 ereport(ERROR,
4258 errmsg("misplaced NOT DEFERRABLE clause"),
4259 parser_errposition(pstate, con->location)));
4261 ereport(ERROR,
4263 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
4264 parser_errposition(pstate, con->location)));
4265 saw_deferrability = true;
4266 lastprimarycon->deferrable = false;
4267 if (saw_initially &&
4268 lastprimarycon->initdeferred)
4269 ereport(ERROR,
4271 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
4272 parser_errposition(pstate, con->location)));
4273 break;
4274
4277 ereport(ERROR,
4279 errmsg("misplaced INITIALLY DEFERRED clause"),
4280 parser_errposition(pstate, con->location)));
4281 if (saw_initially)
4282 ereport(ERROR,
4284 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
4285 parser_errposition(pstate, con->location)));
4286 saw_initially = true;
4287 lastprimarycon->initdeferred = true;
4288
4289 /*
4290 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
4291 */
4292 if (!saw_deferrability)
4293 lastprimarycon->deferrable = true;
4294 else if (!lastprimarycon->deferrable)
4295 ereport(ERROR,
4297 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
4298 parser_errposition(pstate, con->location)));
4299 break;
4300
4303 ereport(ERROR,
4305 errmsg("misplaced INITIALLY IMMEDIATE clause"),
4306 parser_errposition(pstate, con->location)));
4307 if (saw_initially)
4308 ereport(ERROR,
4310 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
4311 parser_errposition(pstate, con->location)));
4312 saw_initially = true;
4313 lastprimarycon->initdeferred = false;
4314 break;
4315
4317 if (lastprimarycon == NULL ||
4318 (lastprimarycon->contype != CONSTR_CHECK &&
4319 lastprimarycon->contype != CONSTR_FOREIGN))
4320 ereport(ERROR,
4322 errmsg("misplaced ENFORCED clause"),
4323 parser_errposition(pstate, con->location)));
4324 if (saw_enforced)
4325 ereport(ERROR,
4327 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
4328 parser_errposition(pstate, con->location)));
4329 saw_enforced = true;
4330 lastprimarycon->is_enforced = true;
4331 break;
4332
4334 if (lastprimarycon == NULL ||
4335 (lastprimarycon->contype != CONSTR_CHECK &&
4336 lastprimarycon->contype != CONSTR_FOREIGN))
4337 ereport(ERROR,
4339 errmsg("misplaced NOT ENFORCED clause"),
4340 parser_errposition(pstate, con->location)));
4341 if (saw_enforced)
4342 ereport(ERROR,
4344 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
4345 parser_errposition(pstate, con->location)));
4346 saw_enforced = true;
4347 lastprimarycon->is_enforced = false;
4348
4349 /* A NOT ENFORCED constraint must be marked as invalid. */
4350 lastprimarycon->skip_validation = true;
4351 lastprimarycon->initially_valid = false;
4352 break;
4353
4354 default:
4355 /* Otherwise it's not an attribute */
4356 lastprimarycon = con;
4357 /* reset flags for new primary node */
4358 saw_deferrability = false;
4359 saw_initially = false;
4360 saw_enforced = false;
4361 break;
4362 }
4363 }
4364}
#define SUPPORTS_ATTRS(node)

References CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_ENFORCED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_ATTR_NOT_ENFORCED, CONSTR_CHECK, CONSTR_FOREIGN, Constraint::contype, elog, ereport, errcode(), errmsg, ERROR, fb(), IsA, lfirst, Constraint::location, nodeTag, parser_errposition(), and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition(), and transformCreateSchemaCreateTable().

◆ transformCreateSchemaCreateTable()

static CreateStmt * transformCreateSchemaCreateTable ( ParseState pstate,
CreateStmt stmt,
List **  fk_elements 
)
static

Definition at line 4635 of file parse_utilcmd.c.

4638{
4640 List *newElts = NIL;
4641 ListCell *lc;
4642
4643 /*
4644 * Flat-copy the CreateStmt node, allowing us to replace its tableElts
4645 * list without damaging the input data structure. Most sub-nodes will be
4646 * shared with the input, though.
4647 */
4649 memcpy(newstmt, stmt, sizeof(CreateStmt));
4650
4651 /* Scan for foreign-key constraints */
4652 foreach(lc, stmt->tableElts)
4653 {
4654 Node *element = lfirst(lc);
4657
4658 if (IsA(element, Constraint))
4659 {
4660 Constraint *constr = (Constraint *) element;
4661
4662 if (constr->contype != CONSTR_FOREIGN)
4663 {
4664 /* Other constraint types pass through unchanged */
4665 newElts = lappend(newElts, constr);
4666 continue;
4667 }
4668
4669 /* Make it into an ALTER TABLE ADD CONSTRAINT command */
4671 altercmd->subtype = AT_AddConstraint;
4672 altercmd->name = NULL;
4673 altercmd->def = (Node *) copyObject(constr);
4674
4676 alterstmt->relation = copyObject(stmt->relation);
4677 alterstmt->cmds = list_make1(altercmd);
4678 alterstmt->objtype = OBJECT_TABLE;
4679
4681 }
4682 else if (IsA(element, ColumnDef))
4683 {
4684 ColumnDef *entry = (ColumnDef *) element;
4687 bool afterFK = false;
4688
4689 /*
4690 * We must preprocess the list of column constraints to attach
4691 * attributes such as DEFERRED to the appropriate constraint node.
4692 * Do this on a copy. (But execution of the CreateStmt will run
4693 * transformConstraintAttrs on the copy, so we are nonetheless
4694 * relying on transformConstraintAttrs to be idempotent.)
4695 */
4698
4699 /* Scan the column constraints ... */
4701 {
4702 switch (colconstr->contype)
4703 {
4704 case CONSTR_FOREIGN:
4705 /* colconstr is already a copy, OK to modify */
4706 colconstr->fk_attrs = list_make1(makeString(entry->colname));
4707
4708 /* Make it into an ALTER TABLE ADD CONSTRAINT command */
4710 altercmd->subtype = AT_AddConstraint;
4711 altercmd->name = NULL;
4712 altercmd->def = (Node *) colconstr;
4713
4715 alterstmt->relation = copyObject(stmt->relation);
4716 alterstmt->cmds = list_make1(altercmd);
4717 alterstmt->objtype = OBJECT_TABLE;
4718
4720
4721 /* Remove the Constraint node from entryconstraints */
4724
4725 /*
4726 * Immediately-following attribute constraints should
4727 * be dropped, too.
4728 */
4729 afterFK = true;
4730 break;
4731
4732 /*
4733 * Column constraint lists separate a Constraint node
4734 * from its attributes (e.g. NOT ENFORCED); so a
4735 * column-level foreign key constraint may be
4736 * represented by multiple Constraint nodes. After
4737 * transformConstraintAttrs, the foreign key
4738 * Constraint node contains all required information,
4739 * making it okay to put into *fk_elements as a
4740 * stand-alone Constraint. But since we removed the
4741 * foreign key Constraint node from entryconstraints,
4742 * we must remove any dependent attribute nodes too,
4743 * else the later re-execution of
4744 * transformConstraintAttrs will misbehave.
4745 */
4752 if (afterFK)
4755 colconstr);
4756 break;
4757
4758 default:
4759 /* Any following constraint attributes are unrelated */
4760 afterFK = false;
4761 break;
4762 }
4763 }
4764
4765 /* Now make a modified ColumnDef to put into newElts */
4767 memcpy(newentry, entry, sizeof(ColumnDef));
4768 newentry->constraints = entryconstraints;
4770 }
4771 else
4772 {
4773 /* Other node types pass through unchanged */
4775 }
4776 }
4777
4778 newstmt->tableElts = newElts;
4779 return newstmt;
4780}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
static chr element(struct vars *v, const chr *startp, const chr *endp)
char * colname
Definition parsenodes.h:770

References AT_AddConstraint, ColumnDef::colname, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_ENFORCED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_ATTR_NOT_ENFORCED, CONSTR_FOREIGN, ColumnDef::constraints, Constraint::contype, copyObject, element(), fb(), foreach_delete_current, foreach_node, IsA, lappend(), lfirst, list_make1, makeNode, makeString(), memcpy(), NIL, OBJECT_TABLE, stmt, and transformConstraintAttrs().

Referenced by transformCreateSchemaStmtElements().

◆ transformCreateSchemaStmtElements()

List * transformCreateSchemaStmtElements ( ParseState pstate,
List schemaElts,
const char schemaName 
)

Definition at line 4428 of file parse_utilcmd.c.

4430{
4431 List *elements = NIL;
4432 List *fk_elements = NIL;
4433 ListCell *lc;
4434
4435 /*
4436 * Run through each schema element in the schema element list. Check
4437 * target schema names, and collect the list of actions to be done.
4438 */
4439 foreach(lc, schemaElts)
4440 {
4441 Node *element = lfirst(lc);
4442
4443 switch (nodeTag(element))
4444 {
4445 case T_CreateSeqStmt:
4446 {
4448
4449 checkSchemaNameRV(pstate, schemaName, elp->sequence);
4450 elements = lappend(elements, element);
4451 }
4452 break;
4453
4454 case T_CreateStmt:
4455 {
4457
4458 checkSchemaNameRV(pstate, schemaName, elp->relation);
4459 /* Pull out any foreign key clauses, add to fk_elements */
4461 elp,
4462 &fk_elements);
4463 elements = lappend(elements, elp);
4464 }
4465 break;
4466
4467 case T_ViewStmt:
4468 {
4470
4471 checkSchemaNameRV(pstate, schemaName, elp->view);
4472 elements = lappend(elements, element);
4473 }
4474 break;
4475
4476 case T_IndexStmt:
4477 {
4479
4480 checkSchemaNameRV(pstate, schemaName, elp->relation);
4481 elements = lappend(elements, element);
4482 }
4483 break;
4484
4485 case T_CreateTrigStmt:
4486 {
4488
4489 checkSchemaNameRV(pstate, schemaName, elp->relation);
4490 elements = lappend(elements, element);
4491 }
4492 break;
4493
4494 case T_CreateDomainStmt:
4495 {
4497
4498 checkSchemaNameList(schemaName, elp->domainname);
4499 elements = lappend(elements, element);
4500 }
4501 break;
4502
4504 {
4506
4508 elements = lappend(elements, element);
4509 }
4510 break;
4511
4512 /*
4513 * CREATE TYPE can produce a DefineStmt, but also
4514 * CreateEnumStmt, CreateRangeStmt, and CompositeTypeStmt.
4515 * Allowing DefineStmt also provides support for several other
4516 * commands: currently, CREATE AGGREGATE, CREATE COLLATION,
4517 * CREATE OPERATOR, and text search objects.
4518 */
4519
4520 case T_DefineStmt:
4521 {
4523
4525 elements = lappend(elements, element);
4526 }
4527 break;
4528
4529 case T_CreateEnumStmt:
4530 {
4532
4534 elements = lappend(elements, element);
4535 }
4536 break;
4537
4538 case T_CreateRangeStmt:
4539 {
4541
4543 elements = lappend(elements, element);
4544 }
4545 break;
4546
4548 {
4550
4551 checkSchemaNameRV(pstate, schemaName, elp->typevar);
4552 elements = lappend(elements, element);
4553 }
4554 break;
4555
4556 case T_GrantStmt:
4557 elements = lappend(elements, element);
4558 break;
4559
4560 default:
4561 elog(ERROR, "unrecognized node type: %d",
4562 (int) nodeTag(element));
4563 }
4564 }
4565
4566 return list_concat(elements, fk_elements);
4567}
static CreateStmt * transformCreateSchemaCreateTable(ParseState *pstate, CreateStmt *stmt, List **fk_elements)
static void checkSchemaNameRV(ParseState *pstate, const char *context_schema, RangeVar *relation)
static void checkSchemaNameList(const char *context_schema, List *qualified_name)

References checkSchemaNameList(), checkSchemaNameRV(), element(), elog, ERROR, fb(), lappend(), lfirst, list_concat(), NIL, nodeTag, and transformCreateSchemaCreateTable().

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

List * transformCreateStmt ( CreateStmt stmt,
const char queryString 
)

Definition at line 162 of file parse_utilcmd.c.

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

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), checkMembershipInCurrentExtension(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, element(), elog, ereport, errcode(), errmsg, ERROR, fb(), 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, result, setup_parser_errposition_callback(), stmt, CreateStmtContext::stmtType, strVal, transformCheckConstraints(), transformColumnDefinition(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

◆ transformFKConstraints()

static void transformFKConstraints ( CreateStmtContext cxt,
bool  skipValidation,
bool  isAddConstraint 
)
static

Definition at line 2989 of file parse_utilcmd.c.

2991{
2993
2994 if (cxt->fkconstraints == NIL)
2995 return;
2996
2997 /*
2998 * If CREATE TABLE or adding a column with NULL default, we can safely
2999 * skip validation of FK constraints, and mark them as valid based on the
3000 * constraint enforcement flag, since NOT ENFORCED constraints must always
3001 * be marked as NOT VALID. (This will override any user-supplied NOT VALID
3002 * flag.)
3003 */
3004 if (skipValidation)
3005 {
3006 foreach(fkclist, cxt->fkconstraints)
3007 {
3008 Constraint *constraint = (Constraint *) lfirst(fkclist);
3009
3010 constraint->skip_validation = true;
3011 constraint->initially_valid = constraint->is_enforced;
3012 }
3013 }
3014
3015 /*
3016 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
3017 * CONSTRAINT command to execute after the basic command is complete. (If
3018 * called from ADD CONSTRAINT, that routine will add the FK constraints to
3019 * its own subcommand list.)
3020 *
3021 * Note: the ADD CONSTRAINT command must also execute after any index
3022 * creation commands. Thus, this should run after
3023 * transformIndexConstraints, so that the CREATE INDEX commands are
3024 * already in cxt->alist. See also the handling of cxt->likeclauses.
3025 */
3026 if (!isAddConstraint)
3027 {
3029
3030 alterstmt->relation = cxt->relation;
3031 alterstmt->cmds = NIL;
3032 alterstmt->objtype = OBJECT_TABLE;
3033
3034 foreach(fkclist, cxt->fkconstraints)
3035 {
3036 Constraint *constraint = (Constraint *) lfirst(fkclist);
3038
3039 altercmd->subtype = AT_AddConstraint;
3040 altercmd->name = NULL;
3041 altercmd->def = (Node *) constraint;
3042 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
3043 }
3044
3045 cxt->alist = lappend(cxt->alist, alterstmt);
3046 }
3047}

References CreateStmtContext::alist, AT_AddConstraint, fb(), CreateStmtContext::fkconstraints, Constraint::initially_valid, Constraint::is_enforced, lappend(), lfirst, makeNode, NIL, OBJECT_TABLE, CreateStmtContext::relation, and Constraint::skip_validation.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexConstraint()

static IndexStmt * transformIndexConstraint ( Constraint constraint,
CreateStmtContext cxt 
)
static

Definition at line 2344 of file parse_utilcmd.c.

2345{
2347 ListCell *lc;
2348
2350
2351 index->unique = (constraint->contype != CONSTR_EXCLUSION);
2352 index->primary = (constraint->contype == CONSTR_PRIMARY);
2353 if (index->primary)
2354 {
2355 if (cxt->pkey != NULL)
2356 ereport(ERROR,
2358 errmsg("multiple primary keys for table \"%s\" are not allowed",
2359 cxt->relation->relname),
2360 parser_errposition(cxt->pstate, constraint->location)));
2361 cxt->pkey = index;
2362
2363 /*
2364 * In ALTER TABLE case, a primary index might already exist, but
2365 * DefineIndex will check for it.
2366 */
2367 }
2368 index->nulls_not_distinct = constraint->nulls_not_distinct;
2369 index->isconstraint = true;
2370 index->iswithoutoverlaps = constraint->without_overlaps;
2371 index->deferrable = constraint->deferrable;
2372 index->initdeferred = constraint->initdeferred;
2373
2374 if (constraint->conname != NULL)
2375 index->idxname = pstrdup(constraint->conname);
2376 else
2377 index->idxname = NULL; /* DefineIndex will choose name */
2378
2379 index->relation = cxt->relation;
2380 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2381 index->options = constraint->options;
2382 index->tableSpace = constraint->indexspace;
2383 index->whereClause = constraint->where_clause;
2384 index->indexParams = NIL;
2385 index->indexIncludingParams = NIL;
2386 index->excludeOpNames = NIL;
2387 index->idxcomment = NULL;
2388 index->indexOid = InvalidOid;
2389 index->oldNumber = InvalidRelFileNumber;
2390 index->oldCreateSubid = InvalidSubTransactionId;
2391 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2392 index->transformed = false;
2393 index->concurrent = false;
2394 index->if_not_exists = false;
2395 index->reset_default_tblspc = constraint->reset_default_tblspc;
2396
2397 /*
2398 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2399 * verify it's usable, then extract the implied column name list. (We
2400 * will not actually need the column name list at runtime, but we need it
2401 * now to check for duplicate column entries below.)
2402 */
2403 if (constraint->indexname != NULL)
2404 {
2405 char *index_name = constraint->indexname;
2406 Relation heap_rel = cxt->rel;
2407 Oid index_oid;
2412 int i;
2413
2414 /* Grammar should not allow this with explicit column list */
2415 Assert(constraint->keys == NIL);
2416
2417 /* Grammar should only allow PRIMARY and UNIQUE constraints */
2418 Assert(constraint->contype == CONSTR_PRIMARY ||
2419 constraint->contype == CONSTR_UNIQUE);
2420
2421 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2422 if (!cxt->isalter)
2423 ereport(ERROR,
2425 errmsg("cannot use an existing index in CREATE TABLE"),
2426 parser_errposition(cxt->pstate, constraint->location)));
2427
2428 /* Look for the index in the same schema as the table */
2430
2431 if (!OidIsValid(index_oid))
2432 ereport(ERROR,
2434 errmsg("index \"%s\" does not exist", index_name),
2435 parser_errposition(cxt->pstate, constraint->location)));
2436
2437 /* Open the index (this will throw an error if it is not an index) */
2439 index_form = index_rel->rd_index;
2440
2441 /* Check that it does not have an associated constraint already */
2443 ereport(ERROR,
2445 errmsg("index \"%s\" is already associated with a constraint",
2446 index_name),
2447 parser_errposition(cxt->pstate, constraint->location)));
2448
2449 /* Perform validity checks on the index */
2450 if (index_form->indrelid != RelationGetRelid(heap_rel))
2451 ereport(ERROR,
2453 errmsg("index \"%s\" does not belong to table \"%s\"",
2455 parser_errposition(cxt->pstate, constraint->location)));
2456
2457 if (!index_form->indisvalid)
2458 ereport(ERROR,
2460 errmsg("index \"%s\" is not valid", index_name),
2461 parser_errposition(cxt->pstate, constraint->location)));
2462
2463 /*
2464 * Today we forbid non-unique indexes, but we could permit GiST
2465 * indexes whose last entry is a range type and use that to create a
2466 * WITHOUT OVERLAPS constraint (i.e. a temporal constraint).
2467 */
2468 if (!index_form->indisunique)
2469 ereport(ERROR,
2471 errmsg("\"%s\" is not a unique index", index_name),
2472 errdetail("Cannot create a primary key or unique constraint using such an index."),
2473 parser_errposition(cxt->pstate, constraint->location)));
2474
2476 ereport(ERROR,
2478 errmsg("index \"%s\" contains expressions", index_name),
2479 errdetail("Cannot create a primary key or unique constraint using such an index."),
2480 parser_errposition(cxt->pstate, constraint->location)));
2481
2483 ereport(ERROR,
2485 errmsg("\"%s\" is a partial index", index_name),
2486 errdetail("Cannot create a primary key or unique constraint using such an index."),
2487 parser_errposition(cxt->pstate, constraint->location)));
2488
2489 /*
2490 * It's probably unsafe to change a deferred index to non-deferred. (A
2491 * non-constraint index couldn't be deferred anyway, so this case
2492 * should never occur; no need to sweat, but let's check it.)
2493 */
2494 if (!index_form->indimmediate && !constraint->deferrable)
2495 ereport(ERROR,
2497 errmsg("\"%s\" is a deferrable index", index_name),
2498 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2499 parser_errposition(cxt->pstate, constraint->location)));
2500
2501 /*
2502 * Insist on it being a btree. We must have an index that exactly
2503 * matches what you'd get from plain ADD CONSTRAINT syntax, else dump
2504 * and reload will produce a different index (breaking pg_upgrade in
2505 * particular).
2506 */
2507 if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2508 ereport(ERROR,
2510 errmsg("index \"%s\" is not a btree", index_name),
2511 parser_errposition(cxt->pstate, constraint->location)));
2512
2513 /* Must get indclass the hard way */
2515 index_rel->rd_indextuple,
2518
2519 for (i = 0; i < index_form->indnatts; i++)
2520 {
2521 int16 attnum = index_form->indkey.values[i];
2523 char *attname;
2525
2526 /*
2527 * We shouldn't see attnum == 0 here, since we already rejected
2528 * expression indexes. If we do, SystemAttributeDefinition will
2529 * throw an error.
2530 */
2531 if (attnum > 0)
2532 {
2533 Assert(attnum <= heap_rel->rd_att->natts);
2534 attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2535 }
2536 else
2538 attname = pstrdup(NameStr(attform->attname));
2539
2541 {
2542 /*
2543 * Insist on default opclass, collation, and sort options.
2544 * While the index would still work as a constraint with
2545 * non-default settings, it might not provide exactly the same
2546 * uniqueness semantics as you'd get from a normally-created
2547 * constraint; and there's also the dump/reload problem
2548 * mentioned above.
2549 */
2550 Datum attoptions =
2552
2554 index_rel->rd_rel->relam);
2555 if (indclass->values[i] != defopclass ||
2556 attform->attcollation != index_rel->rd_indcollation[i] ||
2557 attoptions != (Datum) 0 ||
2558 index_rel->rd_indoption[i] != 0)
2559 ereport(ERROR,
2561 errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2562 errdetail("Cannot create a primary key or unique constraint using such an index."),
2563 parser_errposition(cxt->pstate, constraint->location)));
2564
2565 /* If a PK, ensure the columns get not null constraints */
2566 if (constraint->contype == CONSTR_PRIMARY)
2567 cxt->nnconstraints =
2570
2571 constraint->keys = lappend(constraint->keys, makeString(attname));
2572 }
2573 else
2574 constraint->including = lappend(constraint->including, makeString(attname));
2575 }
2576
2577 /* Close the index relation but keep the lock */
2579
2580 index->indexOid = index_oid;
2581 }
2582
2583 /*
2584 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2585 * IndexElems and operator names. We have to break that apart into
2586 * separate lists.
2587 */
2588 if (constraint->contype == CONSTR_EXCLUSION)
2589 {
2590 foreach(lc, constraint->exclusions)
2591 {
2592 List *pair = (List *) lfirst(lc);
2593 IndexElem *elem;
2594 List *opname;
2595
2596 Assert(list_length(pair) == 2);
2597 elem = linitial_node(IndexElem, pair);
2599
2600 index->indexParams = lappend(index->indexParams, elem);
2601 index->excludeOpNames = lappend(index->excludeOpNames, opname);
2602 }
2603 }
2604
2605 /*
2606 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2607 *
2608 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2609 * also make sure they are not-null. For WITHOUT OVERLAPS constraints, we
2610 * make sure the last part is a range or multirange.
2611 */
2612 else
2613 {
2614 foreach(lc, constraint->keys)
2615 {
2616 char *key = strVal(lfirst(lc));
2617 bool found = false;
2619 ListCell *columns;
2621 Oid typid = InvalidOid;
2622
2623 /* Make sure referenced column exists. */
2624 foreach(columns, cxt->columns)
2625 {
2626 column = lfirst_node(ColumnDef, columns);
2627 if (strcmp(column->colname, key) == 0)
2628 {
2629 found = true;
2630 break;
2631 }
2632 }
2633 if (!found)
2634 column = NULL;
2635
2636 if (found)
2637 {
2638 /*
2639 * column is defined in the new table. For CREATE TABLE with
2640 * a PRIMARY KEY, we can apply the not-null constraint cheaply
2641 * here. If the not-null constraint already exists, we can
2642 * (albeit not so cheaply) verify that it's not a NO INHERIT
2643 * constraint.
2644 *
2645 * Note that ALTER TABLE never needs either check, because
2646 * those constraints have already been added by
2647 * ATPrepAddPrimaryKey.
2648 */
2649 if (constraint->contype == CONSTR_PRIMARY &&
2650 !cxt->isalter)
2651 {
2652 if (column->is_not_null)
2653 {
2655 {
2656 if (strcmp(strVal(linitial(nn->keys)), key) == 0)
2657 {
2658 if (nn->is_no_inherit)
2659 ereport(ERROR,
2661 errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
2662 key));
2663 break;
2664 }
2665 }
2666 }
2667 else
2668 {
2669 column->is_not_null = true;
2670 cxt->nnconstraints =
2673 }
2674 }
2675 else if (constraint->contype == CONSTR_PRIMARY)
2676 Assert(column->is_not_null);
2677 }
2678 else if (SystemAttributeByName(key) != NULL)
2679 {
2680 /*
2681 * column will be a system column in the new table, so accept
2682 * it. System columns can't ever be null, so no need to worry
2683 * about PRIMARY/NOT NULL constraint.
2684 */
2685 found = true;
2686 }
2687 else if (cxt->inhRelations)
2688 {
2689 /* try inherited tables */
2690 ListCell *inher;
2691
2692 foreach(inher, cxt->inhRelations)
2693 {
2695 Relation rel;
2696 int count;
2697
2698 rel = table_openrv(inh, AccessShareLock);
2699 /* check user requested inheritance from valid relkind */
2700 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2701 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2702 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2703 ereport(ERROR,
2705 errmsg("inherited relation \"%s\" is not a table or foreign table",
2706 inh->relname)));
2707 for (count = 0; count < rel->rd_att->natts; count++)
2708 {
2710 count);
2711 char *inhname = NameStr(inhattr->attname);
2712
2713 if (inhattr->attisdropped)
2714 continue;
2715 if (strcmp(key, inhname) == 0)
2716 {
2717 found = true;
2718 typid = inhattr->atttypid;
2719
2720 if (constraint->contype == CONSTR_PRIMARY)
2721 cxt->nnconstraints =
2724 break;
2725 }
2726 }
2727 table_close(rel, NoLock);
2728 if (found)
2729 break;
2730 }
2731 }
2732
2733 /*
2734 * In the ALTER TABLE case, don't complain about index keys not
2735 * created in the command; they may well exist already.
2736 * DefineIndex will complain about them if not.
2737 */
2738 if (!found && !cxt->isalter)
2739 ereport(ERROR,
2741 errmsg("column \"%s\" named in key does not exist", key),
2742 parser_errposition(cxt->pstate, constraint->location)));
2743
2744 /* Check for PRIMARY KEY(foo, foo) */
2745 foreach(columns, index->indexParams)
2746 {
2747 iparam = (IndexElem *) lfirst(columns);
2748 if (iparam->name && strcmp(key, iparam->name) == 0)
2749 {
2750 if (index->primary)
2751 ereport(ERROR,
2753 errmsg("column \"%s\" appears twice in primary key constraint",
2754 key),
2755 parser_errposition(cxt->pstate, constraint->location)));
2756 else
2757 ereport(ERROR,
2759 errmsg("column \"%s\" appears twice in unique constraint",
2760 key),
2761 parser_errposition(cxt->pstate, constraint->location)));
2762 }
2763 }
2764
2765 /*
2766 * The WITHOUT OVERLAPS part (if any) must be a range or
2767 * multirange type, or a domain over such a type.
2768 */
2769 if (constraint->without_overlaps && lc == list_last_cell(constraint->keys))
2770 {
2771 if (!found && cxt->isalter)
2772 {
2773 /*
2774 * Look up the column type on existing table. If we can't
2775 * find it, let things fail in DefineIndex.
2776 */
2777 Relation rel = cxt->rel;
2778
2779 for (int i = 0; i < rel->rd_att->natts; i++)
2780 {
2782 const char *attname;
2783
2784 if (attr->attisdropped)
2785 continue;
2786 attname = NameStr(attr->attname);
2787 if (strcmp(attname, key) == 0)
2788 {
2789 found = true;
2790 typid = attr->atttypid;
2791 break;
2792 }
2793 }
2794 }
2795 if (found)
2796 {
2797 /* Look up column type if we didn't already */
2798 if (!OidIsValid(typid) && column)
2799 typid = typenameTypeId(cxt->pstate,
2800 column->typeName);
2801 /* Look through any domain */
2802 if (OidIsValid(typid))
2803 typid = getBaseType(typid);
2804 /* Complain if not range/multirange */
2805 if (!OidIsValid(typid) ||
2806 !(type_is_range(typid) || type_is_multirange(typid)))
2807 ereport(ERROR,
2809 errmsg("column \"%s\" in WITHOUT OVERLAPS is not a range or multirange type", key),
2810 parser_errposition(cxt->pstate, constraint->location)));
2811 }
2812 }
2813
2814 /* OK, add it to the index definition */
2816 iparam->name = pstrdup(key);
2817 iparam->expr = NULL;
2818 iparam->indexcolname = NULL;
2819 iparam->collation = NIL;
2820 iparam->opclass = NIL;
2821 iparam->opclassopts = NIL;
2822 iparam->ordering = SORTBY_DEFAULT;
2823 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
2824 iparam->location = -1;
2825 index->indexParams = lappend(index->indexParams, iparam);
2826 }
2827
2828 if (constraint->without_overlaps)
2829 {
2830 /*
2831 * This enforces that there is at least one equality column
2832 * besides the WITHOUT OVERLAPS columns. This is per SQL
2833 * standard. XXX Do we need this?
2834 */
2835 if (list_length(constraint->keys) < 2)
2836 ereport(ERROR,
2838 errmsg("constraint using WITHOUT OVERLAPS needs at least two columns"));
2839
2840 /* WITHOUT OVERLAPS requires a GiST index */
2841 index->accessMethod = "gist";
2842 }
2843
2844 }
2845
2846 /*
2847 * Add included columns to index definition. This is much like the
2848 * simple-column-name-list code above, except that we don't worry about
2849 * NOT NULL marking; included columns in a primary key should not be
2850 * forced NOT NULL. We don't complain about duplicate columns, either,
2851 * though maybe we should?
2852 */
2853 foreach(lc, constraint->including)
2854 {
2855 char *key = strVal(lfirst(lc));
2856 bool found = false;
2858 ListCell *columns;
2860
2861 foreach(columns, cxt->columns)
2862 {
2863 column = lfirst_node(ColumnDef, columns);
2864 if (strcmp(column->colname, key) == 0)
2865 {
2866 found = true;
2867 break;
2868 }
2869 }
2870
2871 if (!found)
2872 {
2873 if (SystemAttributeByName(key) != NULL)
2874 {
2875 /*
2876 * column will be a system column in the new table, so accept
2877 * it.
2878 */
2879 found = true;
2880 }
2881 else if (cxt->inhRelations)
2882 {
2883 /* try inherited tables */
2884 ListCell *inher;
2885
2886 foreach(inher, cxt->inhRelations)
2887 {
2889 Relation rel;
2890 int count;
2891
2892 rel = table_openrv(inh, AccessShareLock);
2893 /* check user requested inheritance from valid relkind */
2894 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2895 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2896 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2897 ereport(ERROR,
2899 errmsg("inherited relation \"%s\" is not a table or foreign table",
2900 inh->relname)));
2901 for (count = 0; count < rel->rd_att->natts; count++)
2902 {
2904 count);
2905 char *inhname = NameStr(inhattr->attname);
2906
2907 if (inhattr->attisdropped)
2908 continue;
2909 if (strcmp(key, inhname) == 0)
2910 {
2911 found = true;
2912 break;
2913 }
2914 }
2915 table_close(rel, NoLock);
2916 if (found)
2917 break;
2918 }
2919 }
2920 }
2921
2922 /*
2923 * In the ALTER TABLE case, don't complain about index keys not
2924 * created in the command; they may well exist already. DefineIndex
2925 * will complain about them if not.
2926 */
2927 if (!found && !cxt->isalter)
2928 ereport(ERROR,
2930 errmsg("column \"%s\" named in key does not exist", key),
2931 parser_errposition(cxt->pstate, constraint->location)));
2932
2933 /* OK, add it to the index definition */
2935 iparam->name = pstrdup(key);
2936 iparam->expr = NULL;
2937 iparam->indexcolname = NULL;
2938 iparam->collation = NIL;
2939 iparam->opclass = NIL;
2940 iparam->opclassopts = NIL;
2941 iparam->location = -1;
2942 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2943 }
2944
2945 return index;
2946}
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition amcmds.c:163
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition heap.c:248
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition heap.c:236
#define DEFAULT_INDEX_TYPE
Definition index.h:27
bool type_is_range(Oid typid)
Definition lsyscache.c:2921
Oid getBaseType(Oid typid)
Definition lsyscache.c:2754
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2116
bool type_is_multirange(Oid typid)
Definition lsyscache.c:2931
FormData_pg_attribute
#define linitial_node(type, l)
Definition pg_list.h:181
#define lsecond_node(type, l)
Definition pg_list.h:186
static ListCell * list_last_cell(const List *list)
Definition pg_list.h:320
List * RelationGetIndexPredicate(Relation relation)
Definition relcache.c:5211
List * RelationGetIndexExpressions(Relation relation)
Definition relcache.c:5098
bool initdeferred
List * exclusions
bool reset_default_tblspc
Node * where_clause
char * indexname
char * indexspace
char * access_method
bool nulls_not_distinct
bool without_overlaps
bool deferrable
List * including
TupleDesc rd_att
Definition rel.h:112
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition table.c:83

References Constraint::access_method, AccessShareLock, Assert, attname, attnum, CreateStmtContext::columns, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, DatumGetPointer(), DEFAULT_INDEX_TYPE, Constraint::deferrable, ereport, errcode(), errdetail(), errmsg, ERROR, Constraint::exclusions, fb(), foreach_node, Form_pg_index, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), getBaseType(), GetDefaultOpClass(), i, Constraint::including, index_close(), index_open(), Constraint::indexname, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, CreateStmtContext::isalter, Constraint::keys, lappend(), lfirst, lfirst_node, linitial, linitial_node, list_last_cell(), list_length(), Constraint::location, lsecond_node, makeNode, makeNotNullConstraint(), makeString(), NameStr, TupleDescData::natts, NIL, CreateStmtContext::nnconstraints, NoLock, Constraint::nulls_not_distinct, OidIsValid, Constraint::options, parser_errposition(), CreateStmtContext::pkey, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, SysCacheGetAttrNotNull(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), TupleDescAttr(), type_is_multirange(), type_is_range(), typenameTypeId(), Constraint::where_clause, and Constraint::without_overlaps.

Referenced by transformIndexConstraints().

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2245 of file parse_utilcmd.c.

2246{
2248 List *indexlist = NIL;
2250 ListCell *lc;
2251
2252 /*
2253 * Run through the constraints that need to generate an index, and do so.
2254 *
2255 * For PRIMARY KEY, this queues not-null constraints for each column, if
2256 * needed.
2257 */
2258 foreach(lc, cxt->ixconstraints)
2259 {
2260 Constraint *constraint = lfirst_node(Constraint, lc);
2261
2262 Assert(constraint->contype == CONSTR_PRIMARY ||
2263 constraint->contype == CONSTR_UNIQUE ||
2264 constraint->contype == CONSTR_EXCLUSION);
2265
2266 index = transformIndexConstraint(constraint, cxt);
2267
2268 indexlist = lappend(indexlist, index);
2269 }
2270
2271 /*
2272 * Scan the index list and remove any redundant index specifications. This
2273 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2274 * strict reading of SQL would suggest raising an error instead, but that
2275 * strikes me as too anal-retentive. - tgl 2001-02-14
2276 *
2277 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2278 * pre-existing indexes, too.
2279 */
2280 if (cxt->pkey != NULL)
2281 {
2282 /* Make sure we keep the PKEY index in preference to others... */
2284 }
2285
2286 foreach(lc, indexlist)
2287 {
2288 bool keep = true;
2289 ListCell *k;
2290
2291 index = lfirst(lc);
2292
2293 /* if it's pkey, it's already in finalindexlist */
2294 if (index == cxt->pkey)
2295 continue;
2296
2297 foreach(k, finalindexlist)
2298 {
2300
2301 if (equal(index->indexParams, priorindex->indexParams) &&
2302 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2303 equal(index->whereClause, priorindex->whereClause) &&
2304 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2305 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2306 index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2307 index->deferrable == priorindex->deferrable &&
2308 index->initdeferred == priorindex->initdeferred)
2309 {
2310 priorindex->unique |= index->unique;
2311
2312 /*
2313 * If the prior index is as yet unnamed, and this one is
2314 * named, then transfer the name to the prior index. This
2315 * ensures that if we have named and unnamed constraints,
2316 * we'll use (at least one of) the names for the index.
2317 */
2318 if (priorindex->idxname == NULL)
2319 priorindex->idxname = index->idxname;
2320 keep = false;
2321 break;
2322 }
2323 }
2324
2325 if (keep)
2327 }
2328
2329 /*
2330 * Now append all the IndexStmts to cxt->alist.
2331 */
2332 cxt->alist = list_concat(cxt->alist, finalindexlist);
2333}
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)

References CreateStmtContext::alist, Assert, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, equal(), fb(), CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, NIL, CreateStmtContext::pkey, and transformIndexConstraint().

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexStmt()

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

Definition at line 3062 of file parse_utilcmd.c.

3063{
3064 ParseState *pstate;
3066 ListCell *l;
3067 Relation rel;
3068
3069 /* Nothing to do if statement already transformed. */
3070 if (stmt->transformed)
3071 return stmt;
3072
3073 /* Set up pstate */
3074 pstate = make_parsestate(NULL);
3075 pstate->p_sourcetext = queryString;
3076
3077 /*
3078 * Put the parent table into the rtable so that the expressions can refer
3079 * to its fields without qualification. Caller is responsible for locking
3080 * relation, but we still need to open it.
3081 */
3082 rel = relation_open(relid, NoLock);
3085 NULL, false, true);
3086
3087 /* no to join list, yes to namespaces */
3088 addNSItemToQuery(pstate, nsitem, false, true, true);
3089
3090 /* take care of the where clause */
3091 if (stmt->whereClause)
3092 {
3093 stmt->whereClause = transformWhereClause(pstate,
3094 stmt->whereClause,
3096 "WHERE");
3097 /* we have to fix its collations too */
3098 assign_expr_collations(pstate, stmt->whereClause);
3099 }
3100
3101 /* take care of any index expressions */
3102 foreach(l, stmt->indexParams)
3103 {
3104 IndexElem *ielem = (IndexElem *) lfirst(l);
3105
3106 if (ielem->expr)
3107 {
3108 /* Extract preliminary index col name before transforming expr */
3109 if (ielem->indexcolname == NULL)
3111
3112 /* Now do parse transformation of the expression */
3113 ielem->expr = transformExpr(pstate, ielem->expr,
3115
3116 /* We have to fix its collations too */
3117 assign_expr_collations(pstate, ielem->expr);
3118
3119 /*
3120 * transformExpr() should have already rejected subqueries,
3121 * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3122 * for an index expression.
3123 *
3124 * DefineIndex() will make more checks.
3125 */
3126 }
3127 }
3128
3129 /*
3130 * Check that only the base rel is mentioned. (This should be dead code
3131 * now that add_missing_from is history.)
3132 */
3133 if (list_length(pstate->p_rtable) != 1)
3134 ereport(ERROR,
3136 errmsg("index expressions and predicates can refer only to the table being indexed")));
3137
3138 free_parsestate(pstate);
3139
3140 /* Close relation */
3141 table_close(rel, NoLock);
3142
3143 /* Mark statement as successfully transformed */
3144 stmt->transformed = true;
3145
3146 return stmt;
3147}
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:73
@ EXPR_KIND_INDEX_PREDICATE
Definition parse_node.h:74
char * FigureIndexColname(Node *node)
char * indexcolname
Definition parsenodes.h:829
List * p_rtable
Definition parse_node.h:215

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg, ERROR, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, fb(), 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().

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1637 of file parse_utilcmd.c.

1638{
1639 HeapTuple tuple;
1640 TupleDesc tupdesc;
1641 int i;
1642 Oid ofTypeId;
1643
1644 Assert(ofTypename);
1645
1646 tuple = typenameType(cxt->pstate, ofTypename, NULL);
1647 check_of_type(tuple);
1648 ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1649 ofTypename->typeOid = ofTypeId; /* cached for later */
1650
1651 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1652 for (i = 0; i < tupdesc->natts; i++)
1653 {
1654 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1655 ColumnDef *n;
1656
1657 if (attr->attisdropped)
1658 continue;
1659
1660 n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1661 attr->atttypmod, attr->attcollation);
1662 n->is_from_type = true;
1663
1664 cxt->columns = lappend(cxt->columns, n);
1665 }
1666 ReleaseTupleDesc(tupdesc);
1667
1668 ReleaseSysCache(tuple);
1669}
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition makefuncs.c:565
bool is_from_type
Definition parsenodes.h:776
Oid typeOid
Definition parsenodes.h:289
void check_of_type(HeapTuple typetuple)
Definition tablecmds.c:7233
#define ReleaseTupleDesc(tupdesc)
Definition tupdesc.h:240
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition typcache.c:1947

References Assert, check_of_type(), CreateStmtContext::columns, fb(), Form_pg_type, GETSTRUCT(), i, ColumnDef::is_from_type, lappend(), lookup_rowtype_tupdesc(), makeColumnDef(), NameStr, TupleDescData::natts, CreateStmtContext::pstate, ReleaseSysCache(), ReleaseTupleDesc, TupleDescAttr(), typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

◆ transformPartitionBound()

PartitionBoundSpec * transformPartitionBound ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 4843 of file parse_utilcmd.c.

4845{
4848 char strategy = get_partition_strategy(key);
4849 int partnatts = get_partition_natts(key);
4850 List *partexprs = get_partition_exprs(key);
4851
4852 /* Avoid scribbling on input */
4854
4855 if (spec->is_default)
4856 {
4857 /*
4858 * Hash partitioning does not support a default partition; there's no
4859 * use case for it (since the set of partitions to create is perfectly
4860 * defined), and if users do get into it accidentally, it's hard to
4861 * back out from it afterwards.
4862 */
4863 if (strategy == PARTITION_STRATEGY_HASH)
4864 ereport(ERROR,
4866 errmsg("a hash-partitioned table may not have a default partition")));
4867
4868 /*
4869 * In case of the default partition, parser had no way to identify the
4870 * partition strategy. Assign the parent's strategy to the default
4871 * partition bound spec.
4872 */
4873 result_spec->strategy = strategy;
4874
4875 return result_spec;
4876 }
4877
4878 if (strategy == PARTITION_STRATEGY_HASH)
4879 {
4880 if (spec->strategy != PARTITION_STRATEGY_HASH)
4881 ereport(ERROR,
4883 errmsg("invalid bound specification for a hash partition"),
4884 parser_errposition(pstate, exprLocation((Node *) spec))));
4885
4886 if (spec->modulus <= 0)
4887 ereport(ERROR,
4889 errmsg("modulus for hash partition must be an integer value greater than zero")));
4890
4891 Assert(spec->remainder >= 0);
4892
4893 if (spec->remainder >= spec->modulus)
4894 ereport(ERROR,
4896 errmsg("remainder for hash partition must be less than modulus")));
4897 }
4898 else if (strategy == PARTITION_STRATEGY_LIST)
4899 {
4900 ListCell *cell;
4901 char *colname;
4902 Oid coltype;
4904 Oid partcollation;
4905
4906 if (spec->strategy != PARTITION_STRATEGY_LIST)
4907 ereport(ERROR,
4909 errmsg("invalid bound specification for a list partition"),
4910 parser_errposition(pstate, exprLocation((Node *) spec))));
4911
4912 /* Get the only column's name in case we need to output an error */
4913 if (key->partattrs[0] != 0)
4914 colname = get_attname(RelationGetRelid(parent),
4915 key->partattrs[0], false);
4916 else
4917 colname = deparse_expression((Node *) linitial(partexprs),
4919 RelationGetRelid(parent)),
4920 false, false);
4921 /* Need its type data too */
4922 coltype = get_partition_col_typid(key, 0);
4924 partcollation = get_partition_col_collation(key, 0);
4925
4926 result_spec->listdatums = NIL;
4927 foreach(cell, spec->listdatums)
4928 {
4929 Node *expr = lfirst(cell);
4930 Const *value;
4931 ListCell *cell2;
4932 bool duplicate;
4933
4934 value = transformPartitionBoundValue(pstate, expr,
4935 colname, coltype, coltypmod,
4936 partcollation);
4937
4938 /* Don't add to the result if the value is a duplicate */
4939 duplicate = false;
4940 foreach(cell2, result_spec->listdatums)
4941 {
4943
4944 if (equal(value, value2))
4945 {
4946 duplicate = true;
4947 break;
4948 }
4949 }
4950 if (duplicate)
4951 continue;
4952
4953 result_spec->listdatums = lappend(result_spec->listdatums,
4954 value);
4955 }
4956 }
4957 else if (strategy == PARTITION_STRATEGY_RANGE)
4958 {
4959 if (spec->strategy != PARTITION_STRATEGY_RANGE)
4960 ereport(ERROR,
4962 errmsg("invalid bound specification for a range partition"),
4963 parser_errposition(pstate, exprLocation((Node *) spec))));
4964
4965 if (list_length(spec->lowerdatums) != partnatts)
4966 ereport(ERROR,
4968 errmsg("FROM must specify exactly one value per partitioning column")));
4969 if (list_length(spec->upperdatums) != partnatts)
4970 ereport(ERROR,
4972 errmsg("TO must specify exactly one value per partitioning column")));
4973
4974 /*
4975 * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4976 * any necessary validation.
4977 */
4978 result_spec->lowerdatums =
4979 transformPartitionRangeBounds(pstate, spec->lowerdatums,
4980 parent);
4981 result_spec->upperdatums =
4982 transformPartitionRangeBounds(pstate, spec->upperdatums,
4983 parent);
4984 }
4985 else
4986 elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4987
4988 return result_spec;
4989}
int32_t int32
Definition c.h:620
static struct @177 value
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1403
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:919
@ PARTITION_STRATEGY_LIST
Definition parsenodes.h:917
@ PARTITION_STRATEGY_RANGE
Definition parsenodes.h:918
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:4070
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition ruleutils.c:4007

References Assert, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg, ERROR, exprLocation(), fb(), get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), lappend(), lfirst, lfirst_node, linitial, list_length(), NIL, parser_errposition(), PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, transformPartitionBoundValue(), transformPartitionRangeBounds(), and value.

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformPartitionBoundValue()

static Const * transformPartitionBoundValue ( ParseState pstate,
Node val,
const char colName,
Oid  colType,
int32  colTypmod,
Oid  partCollation 
)
static

Definition at line 5154 of file parse_utilcmd.c.

5157{
5158 Node *value;
5159
5160 /* Transform raw parsetree */
5162
5163 /*
5164 * transformExpr() should have already rejected column references,
5165 * subqueries, aggregates, window functions, and SRFs, based on the
5166 * EXPR_KIND_ of a partition bound expression.
5167 */
5169
5170 /*
5171 * Coerce to the correct type. This might cause an explicit coercion step
5172 * to be added on top of the expression, which must be evaluated before
5173 * returning the result to the caller.
5174 */
5177 colType,
5178 colTypmod,
5181 -1);
5182
5183 if (value == NULL)
5184 ereport(ERROR,
5186 errmsg("specified value cannot be cast to type %s for column \"%s\"",
5189
5190 /*
5191 * Evaluate the expression, if needed, assigning the partition key's data
5192 * type and collation to the resulting Const node.
5193 */
5194 if (!IsA(value, Const))
5195 {
5200 if (!IsA(value, Const))
5201 elog(ERROR, "could not evaluate partition bound expression");
5202 }
5203 else
5204 {
5205 /*
5206 * If the expression is already a Const, as is often the case, we can
5207 * skip the rather expensive steps above. But we still have to insert
5208 * the right collation, since coerce_to_target_type doesn't handle
5209 * that.
5210 */
5211 ((Const *) value)->constcollid = partCollation;
5212 }
5213
5214 /*
5215 * Attach original expression's parse location to the Const, so that
5216 * that's what will be reported for any later errors related to this
5217 * partition bound.
5218 */
5219 ((Const *) value)->location = exprLocation(val);
5220
5221 return (Const *) value;
5222}
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition clauses.c:5724
long val
Definition informix.c:689
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
@ EXPR_KIND_PARTITION_BOUND
Definition parse_node.h:80
Expr * expression_planner(Expr *expr)
Definition planner.c:7081
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCION_ASSIGNMENT
Definition primnodes.h:748
bool contain_var_clause(Node *node)
Definition var.c:406

References Assert, assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, contain_var_clause(), elog, ereport, errcode(), errmsg, ERROR, evaluate_expr(), EXPR_KIND_PARTITION_BOUND, expression_planner(), exprLocation(), exprType(), fb(), format_type_be(), IsA, parser_errposition(), transformExpr(), val, and value.

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionBoundSpec bound 
)
static

Definition at line 4790 of file parse_utilcmd.c.

4791{
4792 Relation parentRel = cxt->rel;
4793
4794 switch (parentRel->rd_rel->relkind)
4795 {
4797 /* transform the partition bound, if any */
4799 if (bound != NULL)
4801 bound);
4802 break;
4804
4805 /*
4806 * A partitioned index cannot have a partition bound set. ALTER
4807 * INDEX prevents that with its grammar, but not ALTER TABLE.
4808 */
4809 if (bound != NULL)
4810 ereport(ERROR,
4812 errmsg("\"%s\" is not a partitioned table",
4814 break;
4815 case RELKIND_RELATION:
4816 /* the table must be partitioned */
4817 ereport(ERROR,
4819 errmsg("table \"%s\" is not partitioned",
4821 break;
4822 case RELKIND_INDEX:
4823 /* the index must be partitioned */
4824 ereport(ERROR,
4826 errmsg("index \"%s\" is not partitioned",
4828 break;
4829 default:
4830 /* parser shouldn't let this case through */
4831 elog(ERROR, "\"%s\" is not a partitioned table or index",
4833 break;
4834 }
4835}
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)

References Assert, elog, ereport, errcode(), errmsg, ERROR, fb(), CreateStmtContext::partbound, CreateStmtContext::pstate, CreateStmtContext::rel, RelationGetPartitionKey(), RelationGetRelationName, and transformPartitionBound().

Referenced by transformAlterTableStmt(), and transformPartitionCmdForSplit().

◆ transformPartitionCmdForMerge()

static void transformPartitionCmdForMerge ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3719 of file parse_utilcmd.c.

3720{
3722 Oid partOid;
3723 Relation parent = cxt->rel;
3725 char strategy;
3727 *listptr2;
3728 bool isDefaultPart = false;
3729 List *partOids = NIL;
3730
3731 key = RelationGetPartitionKey(parent);
3732 strategy = get_partition_strategy(key);
3733
3734 if (strategy == PARTITION_STRATEGY_HASH)
3735 ereport(ERROR,
3737 errmsg("partition of hash-partitioned table cannot be merged"));
3738
3739 /* Does the partitioned table (parent) have a default partition? */
3741
3742 foreach(listptr, partcmd->partlist)
3743 {
3745
3746 /* Partitions in the list should have different names. */
3747 for_each_cell(listptr2, partcmd->partlist, lnext(partcmd->partlist, listptr))
3748 {
3750
3751 if (equal(name, name2))
3752 ereport(ERROR,
3754 errmsg("partition with name \"%s\" is already used", name->relname),
3755 parser_errposition(cxt->pstate, name2->location));
3756 }
3757
3758 /*
3759 * Search the DEFAULT partition in the list. Open and lock partitions
3760 * before calculating the boundary for resulting partition, we also
3761 * check for ownership along the way. We need to use
3762 * AccessExclusiveLock here, because these merged partitions will be
3763 * detached and then dropped in ATExecMergePartitions.
3764 */
3767 NULL);
3768 /* Is the current partition a DEFAULT partition? */
3769 if (partOid == defaultPartOid)
3770 isDefaultPart = true;
3771
3772 /*
3773 * Extended check because the same partition can have different names
3774 * (for example, "part_name" and "public.part_name").
3775 */
3776 foreach(listptr2, partOids)
3777 {
3779
3780 if (curOid == partOid)
3781 ereport(ERROR,
3783 errmsg("partition with name \"%s\" is already used", name->relname),
3784 parser_errposition(cxt->pstate, name->location));
3785 }
3786
3787 checkPartition(parent, partOid, true);
3788
3790 }
3791
3792 /* Allocate the bound of the resulting partition. */
3793 Assert(partcmd->bound == NULL);
3795
3796 /* Fill the partition bound. */
3797 partcmd->bound->strategy = strategy;
3798 partcmd->bound->location = -1;
3799 partcmd->bound->is_default = isDefaultPart;
3800 if (!isDefaultPart)
3802 partOids, partcmd->bound,
3803 cxt->pstate);
3804}
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
#define AccessExclusiveLock
Definition lockdefs.h:43
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
static void checkPartition(Relation rel, Oid partRelOid, bool isMerge)
void calculate_partition_bound_for_merge(Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition partdesc.c:501
#define for_each_cell(cell, lst, initcell)
Definition pg_list.h:470
void RangeVarCallbackOwnsRelation(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
const char * name

References AccessExclusiveLock, Assert, calculate_partition_bound_for_merge(), checkPartition(), equal(), ereport, errcode(), errmsg, ERROR, fb(), for_each_cell, get_default_oid_from_partdesc(), get_partition_strategy(), lappend_oid(), lfirst, lfirst_oid, lnext(), makeNode, name, NIL, parser_errposition(), PARTITION_STRATEGY_HASH, CreateStmtContext::pstate, RangeVarCallbackOwnsRelation(), RangeVarGetRelidExtended(), CreateStmtContext::rel, RelationGetPartitionDesc(), and RelationGetPartitionKey().

Referenced by transformAlterTableStmt().

◆ transformPartitionCmdForSplit()

static void transformPartitionCmdForSplit ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3575 of file parse_utilcmd.c.

3576{
3577 Relation parent = cxt->rel;
3579 char strategy;
3582 int default_index = -1;
3583 bool isSplitPartDefault;
3585 *listptr2;
3586 List *splitlist;
3587
3588 splitlist = partcmd->partlist;
3589 key = RelationGetPartitionKey(parent);
3590 strategy = get_partition_strategy(key);
3592
3593 /* Transform partition bounds for all partitions in the list: */
3595 {
3596 cxt->partbound = NULL;
3597 transformPartitionCmd(cxt, sps->bound);
3598 /* Assign the transformed value of the partition bound. */
3599 sps->bound = cxt->partbound;
3600 }
3601
3602 /*
3603 * Open and lock the partition, check ownership along the way. We need to
3604 * use AccessExclusiveLock here because this split partition will be
3605 * detached, then dropped in ATExecSplitPartition.
3606 */
3609 NULL);
3610
3611 checkPartition(parent, splitPartOid, false);
3612
3613 switch (strategy)
3614 {
3617 {
3619 {
3620 if (sps->bound->is_default)
3621 {
3622 if (default_index != -1)
3623 ereport(ERROR,
3625 errmsg("cannot specify more than one DEFAULT partition"),
3626 parser_errposition(cxt->pstate, sps->name->location));
3627
3628 default_index = foreach_current_index(sps);
3629 }
3630 }
3631 }
3632 break;
3633
3635 ereport(ERROR,
3637 errmsg("partition of hash-partitioned table cannot be split"));
3638 break;
3639
3640 default:
3641 elog(ERROR, "unexpected partition strategy: %d",
3642 (int) key->strategy);
3643 break;
3644 }
3645
3646 /* isSplitPartDefault: is the being split partition a DEFAULT partition? */
3648
3649 if (isSplitPartDefault && default_index == -1)
3650 ereport(ERROR,
3652 errmsg("cannot split DEFAULT partition \"%s\"",
3654 errhint("To split a DEFAULT partition, one of the new partitions must be DEFAULT."));
3655
3656 /*
3657 * If the partition being split is not the DEFAULT partition, but the
3658 * DEFAULT partition exists, then none of the resulting split partitions
3659 * can be the DEFAULT.
3660 */
3661 if (!isSplitPartDefault && (default_index != -1) && OidIsValid(defaultPartOid))
3662 {
3664 (SinglePartitionSpec *) list_nth(splitlist, default_index);
3665
3666 ereport(ERROR,
3668 errmsg("cannot split non-DEFAULT partition \"%s\"",
3670 errdetail("New partition cannot be DEFAULT because DEFAULT partition \"%s\" already exists.",
3672 parser_errposition(cxt->pstate, spsDef->name->location));
3673 }
3674
3675 foreach(listptr, splitlist)
3676 {
3677 Oid nspid;
3679 RangeVar *name = sps->name;
3680
3682
3683 /* Partitions in the list should have different names. */
3685 {
3686 Oid nspid2;
3688 RangeVar *name2 = sps2->name;
3689
3690 if (equal(name, name2))
3691 ereport(ERROR,
3693 errmsg("partition with name \"%s\" is already used", name->relname),
3694 parser_errposition(cxt->pstate, name2->location));
3695
3697
3698 if (nspid2 == nspid && strcmp(name->relname, name2->relname) == 0)
3699 ereport(ERROR,
3701 errmsg("partition with name \"%s\" is already used", name->relname),
3702 parser_errposition(cxt->pstate, name2->location));
3703 }
3704 }
3705
3706 /* Then we should check partitions with transformed bounds. */
3708}
int nspid
void check_partitions_for_split(Relation parent, Oid splitPartOid, List *partlist, ParseState *pstate)
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
static void * list_nth(const List *list, int n)
Definition pg_list.h:331

References AccessExclusiveLock, check_partitions_for_split(), checkPartition(), elog, equal(), ereport, errcode(), errdetail(), errhint(), errmsg, ERROR, fb(), for_each_cell, foreach_current_index, foreach_node, get_default_oid_from_partdesc(), get_partition_strategy(), get_rel_name(), lfirst, list_nth(), lnext(), name, nspid, OidIsValid, parser_errposition(), CreateStmtContext::partbound, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, CreateStmtContext::pstate, RangeVarCallbackOwnsRelation(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), CreateStmtContext::rel, RelationGetPartitionDesc(), RelationGetPartitionKey(), and transformPartitionCmd().

Referenced by transformAlterTableStmt().

◆ transformPartitionRangeBounds()

static List * transformPartitionRangeBounds ( ParseState pstate,
List blist,
Relation  parent 
)
static

Definition at line 4997 of file parse_utilcmd.c.

4999{
5000 List *result = NIL;
5002 List *partexprs = get_partition_exprs(key);
5003 ListCell *lc;
5004 int i,
5005 j;
5006
5007 j = 0;
5008 foreach(lc, blist)
5009 {
5010 Node *expr = lfirst(lc);
5012
5014
5015 /*
5016 * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
5017 * as ColumnRefs.
5018 */
5019 if (IsA(expr, ColumnRef))
5020 {
5021 ColumnRef *cref = (ColumnRef *) expr;
5022 char *cname = NULL;
5023
5024 /*
5025 * There should be a single field named either "minvalue" or
5026 * "maxvalue".
5027 */
5028 if (list_length(cref->fields) == 1 &&
5029 IsA(linitial(cref->fields), String))
5030 cname = strVal(linitial(cref->fields));
5031
5032 if (cname == NULL)
5033 {
5034 /*
5035 * ColumnRef is not in the desired single-field-name form. For
5036 * consistency between all partition strategies, let the
5037 * expression transformation report any errors rather than
5038 * doing it ourselves.
5039 */
5040 }
5041 else if (strcmp("minvalue", cname) == 0)
5042 {
5045 prd->value = NULL;
5046 }
5047 else if (strcmp("maxvalue", cname) == 0)
5048 {
5051 prd->value = NULL;
5052 }
5053 }
5054
5055 if (prd == NULL)
5056 {
5057 char *colname;
5058 Oid coltype;
5060 Oid partcollation;
5061 Const *value;
5062
5063 /* Get the column's name in case we need to output an error */
5064 if (key->partattrs[i] != 0)
5065 colname = get_attname(RelationGetRelid(parent),
5066 key->partattrs[i], false);
5067 else
5068 {
5069 colname = deparse_expression((Node *) list_nth(partexprs, j),
5071 RelationGetRelid(parent)),
5072 false, false);
5073 ++j;
5074 }
5075
5076 /* Need its type data too */
5077 coltype = get_partition_col_typid(key, i);
5079 partcollation = get_partition_col_collation(key, i);
5080
5081 value = transformPartitionBoundValue(pstate, expr,
5082 colname,
5083 coltype, coltypmod,
5084 partcollation);
5085 if (value->constisnull)
5086 ereport(ERROR,
5088 errmsg("cannot specify NULL in range bound")));
5091 prd->value = (Node *) value;
5092 }
5093
5094 prd->location = exprLocation(expr);
5095
5097 }
5098
5099 /*
5100 * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
5101 * must be the same.
5102 */
5104
5105 return result;
5106}
int j
Definition isn.c:78
static void validateInfiniteBounds(ParseState *pstate, List *blist)
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition parsenodes.h:971
@ PARTITION_RANGE_DATUM_VALUE
Definition parsenodes.h:970
@ PARTITION_RANGE_DATUM_MINVALUE
Definition parsenodes.h:969
Definition value.h:64

References deparse_context_for(), deparse_expression(), ereport, errcode(), errmsg, ERROR, exprLocation(), fb(), foreach_current_index, get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), i, IsA, j, lappend(), lfirst, linitial, list_length(), list_nth(), makeNode, NIL, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, result, strVal, transformPartitionBoundValue(), validateInfiniteBounds(), and value.

Referenced by transformPartitionBound().

◆ transformRuleStmt()

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

Definition at line 3232 of file parse_utilcmd.c.

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

References AccessExclusiveLock, AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, elog, ereport, errcode(), errmsg, ERROR, EXPR_KIND_WHERE, fb(), free_parsestate(), getInsertSelectQuery(), lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, stmt, table_close(), table_openrv(), transformStmt(), and transformWhereClause().

Referenced by DefineRule().

◆ transformStatsStmt()

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

Definition at line 3157 of file parse_utilcmd.c.

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

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg, ERROR, StatsElem::expr, EXPR_KIND_STATS_EXPRESSION, fb(), 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().

◆ transformTableConstraint()

static void transformTableConstraint ( CreateStmtContext cxt,
Constraint constraint 
)
static

Definition at line 1033 of file parse_utilcmd.c.

1034{
1035 switch (constraint->contype)
1036 {
1037 case CONSTR_PRIMARY:
1038 if (cxt->isforeign)
1039 ereport(ERROR,
1041 errmsg("primary key constraints are not supported on foreign tables"),
1043 constraint->location)));
1044 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1045 break;
1046
1047 case CONSTR_UNIQUE:
1048 if (cxt->isforeign)
1049 ereport(ERROR,
1051 errmsg("unique constraints are not supported on foreign tables"),
1053 constraint->location)));
1054 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1055 break;
1056
1057 case CONSTR_EXCLUSION:
1058 if (cxt->isforeign)
1059 ereport(ERROR,
1061 errmsg("exclusion constraints are not supported on foreign tables"),
1063 constraint->location)));
1064 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1065 break;
1066
1067 case CONSTR_CHECK:
1068 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1069 break;
1070
1071 case CONSTR_NOTNULL:
1072 if (cxt->ispartitioned && constraint->is_no_inherit)
1073 ereport(ERROR,
1075 errmsg("not-null constraints on partitioned tables cannot be NO INHERIT"));
1076
1077 cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
1078 break;
1079
1080 case CONSTR_FOREIGN:
1081 if (cxt->isforeign)
1082 ereport(ERROR,
1084 errmsg("foreign key constraints are not supported on foreign tables"),
1086 constraint->location)));
1087 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
1088 break;
1089
1090 case CONSTR_NULL:
1091 case CONSTR_DEFAULT:
1098 elog(ERROR, "invalid context for constraint type %d",
1099 constraint->contype);
1100 break;
1101
1102 default:
1103 elog(ERROR, "unrecognized constraint type: %d",
1104 constraint->contype);
1105 break;
1106 }
1107}

References CreateStmtContext::ckconstraints, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_ENFORCED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_ATTR_NOT_ENFORCED, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, elog, ereport, errcode(), errmsg, ERROR, fb(), CreateStmtContext::fkconstraints, Constraint::is_no_inherit, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), Constraint::location, CreateStmtContext::nnconstraints, parser_errposition(), and CreateStmtContext::pstate.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformTableLikeClause()

static void transformTableLikeClause ( CreateStmtContext cxt,
TableLikeClause table_like_clause 
)
static

Definition at line 1124 of file parse_utilcmd.c.

1125{
1127 Relation relation;
1130 char *comment;
1132
1134 table_like_clause->relation->location);
1135
1136 /* Open the relation referenced by the LIKE clause */
1137 relation = relation_openrv(table_like_clause->relation, AccessShareLock);
1138
1139 if (relation->rd_rel->relkind != RELKIND_RELATION &&
1140 relation->rd_rel->relkind != RELKIND_VIEW &&
1141 relation->rd_rel->relkind != RELKIND_MATVIEW &&
1142 relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1143 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1144 relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1145 ereport(ERROR,
1147 errmsg("relation \"%s\" is invalid in LIKE clause",
1148 RelationGetRelationName(relation)),
1149 errdetail_relkind_not_supported(relation->rd_rel->relkind)));
1150
1152
1153 /*
1154 * Check for privileges
1155 */
1156 if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1157 {
1158 aclresult = object_aclcheck(TypeRelationId, relation->rd_rel->reltype, GetUserId(),
1159 ACL_USAGE);
1160 if (aclresult != ACLCHECK_OK)
1162 RelationGetRelationName(relation));
1163 }
1164 else
1165 {
1167 ACL_SELECT);
1168 if (aclresult != ACLCHECK_OK)
1170 RelationGetRelationName(relation));
1171 }
1172
1173 tupleDesc = RelationGetDescr(relation);
1174
1175 /*
1176 * Insert the copied attributes into the cxt for the new table definition.
1177 * We must do this now so that they appear in the table in the relative
1178 * position where the LIKE clause is, as required by SQL99.
1179 */
1180 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1181 parent_attno++)
1182 {
1184 parent_attno - 1);
1185 ColumnDef *def;
1186
1187 /*
1188 * Ignore dropped columns in the parent.
1189 */
1190 if (attribute->attisdropped)
1191 continue;
1192
1193 /*
1194 * Create a new column definition
1195 */
1196 def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
1197 attribute->atttypmod, attribute->attcollation);
1198
1199 /*
1200 * Add to column list
1201 */
1202 cxt->columns = lappend(cxt->columns, def);
1203
1204 /*
1205 * Although we don't transfer the column's default/generation
1206 * expression now, we need to mark it GENERATED if appropriate.
1207 */
1208 if (attribute->atthasdef && attribute->attgenerated &&
1210 def->generated = attribute->attgenerated;
1211
1212 /*
1213 * Copy identity if requested
1214 */
1215 if (attribute->attidentity &&
1217 !cxt->isforeign)
1218 {
1219 Oid seq_relid;
1221
1222 /*
1223 * find sequence owned by old column; extract sequence parameters;
1224 * build new create sequence command
1225 */
1226 seq_relid = getIdentitySequence(relation, attribute->attnum, false);
1228 generateSerialExtraStmts(cxt, def,
1230 true, false,
1231 NULL, NULL);
1232 def->identity = attribute->attidentity;
1233 }
1234
1235 /* Likewise, copy storage if requested */
1237 !cxt->isforeign)
1238 def->storage = attribute->attstorage;
1239 else
1240 def->storage = 0;
1241
1242 /* Likewise, copy compression if requested */
1243 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMPRESSION) != 0 &&
1244 CompressionMethodIsValid(attribute->attcompression) &&
1245 !cxt->isforeign)
1246 def->compression =
1247 pstrdup(GetCompressionMethodName(attribute->attcompression));
1248 else
1249 def->compression = NULL;
1250
1251 /* Likewise, copy comment if requested */
1253 (comment = GetComment(attribute->attrelid,
1255 attribute->attnum)) != NULL)
1256 {
1258
1259 stmt->objtype = OBJECT_COLUMN;
1260 stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1262 makeString(def->colname));
1263 stmt->comment = comment;
1264
1265 cxt->alist = lappend(cxt->alist, stmt);
1266 }
1267 }
1268
1269 /*
1270 * Reproduce not-null constraints, if any, by copying them. We do this
1271 * regardless of options given.
1272 */
1273 if (tupleDesc->constr && tupleDesc->constr->has_not_null)
1274 {
1275 List *lst;
1276
1278 true);
1280
1281 /* Copy comments on not-null constraints */
1283 {
1285 {
1287 nnconstr->conname, false),
1289 0)) != NULL)
1290 {
1292
1293 stmt->objtype = OBJECT_TABCONSTRAINT;
1294 stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1296 makeString(nnconstr->conname));
1297 stmt->comment = comment;
1298 cxt->alist = lappend(cxt->alist, stmt);
1299 }
1300 }
1301 }
1302 }
1303
1304 /*
1305 * We cannot yet deal with defaults, CHECK constraints, indexes, or
1306 * statistics, since we don't yet know what column numbers the copied
1307 * columns will have in the finished table. If any of those options are
1308 * specified, add the LIKE clause to cxt->likeclauses so that
1309 * expandTableLikeClause will be called after we do know that.
1310 *
1311 * In order for this to work, we remember the relation OID so that
1312 * expandTableLikeClause is certain to open the same table.
1313 */
1314 if (table_like_clause->options &
1320 {
1321 table_like_clause->relationOid = RelationGetRelid(relation);
1323 }
1324
1325 /*
1326 * Close the parent rel, but keep our AccessShareLock on it until xact
1327 * commit. That will prevent someone else from deleting or ALTERing the
1328 * parent before we can run expandTableLikeClause.
1329 */
1330 table_close(relation, NoLock);
1331}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3880
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4083
List * sequence_options(Oid relid)
Definition sequence.c:1712
Oid GetUserId(void)
Definition miscinit.c:470
ObjectType get_relkind_objtype(char relkind)
#define ACL_USAGE
Definition parsenodes.h:84
@ OBJECT_COLUMN
@ OBJECT_TYPE
#define ACL_SELECT
Definition parsenodes.h:77
@ CREATE_TABLE_LIKE_IDENTITY
Definition parsenodes.h:810
@ CREATE_TABLE_LIKE_COMPRESSION
Definition parsenodes.h:806
@ CREATE_TABLE_LIKE_STORAGE
Definition parsenodes.h:813
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
List * RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
char identity
Definition parsenodes.h:781
char generated
Definition parsenodes.h:784
char storage
Definition parsenodes.h:777
char * compression
Definition parsenodes.h:772
const char * GetCompressionMethodName(char method)
#define CompressionMethodIsValid(cm)

References AccessShareLock, ACL_SELECT, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, CreateStmtContext::alist, cancel_parser_errposition_callback(), ColumnDef::colname, CreateStmtContext::columns, comment, ColumnDef::compression, CompressionMethodIsValid, CREATE_TABLE_LIKE_COMMENTS, CREATE_TABLE_LIKE_COMPRESSION, CREATE_TABLE_LIKE_CONSTRAINTS, CREATE_TABLE_LIKE_DEFAULTS, CREATE_TABLE_LIKE_GENERATED, CREATE_TABLE_LIKE_IDENTITY, CREATE_TABLE_LIKE_INDEXES, CREATE_TABLE_LIKE_STATISTICS, CREATE_TABLE_LIKE_STORAGE, ereport, errcode(), errdetail_relkind_not_supported(), errmsg, ERROR, fb(), foreach_node, ColumnDef::generated, generateSerialExtraStmts(), get_relation_constraint_oid(), get_relkind_objtype(), GetComment(), GetCompressionMethodName(), getIdentitySequence(), GetUserId(), ColumnDef::identity, InvalidOid, CreateStmtContext::isforeign, lappend(), CreateStmtContext::likeclauses, list_concat(), list_make3, makeColumnDef(), makeNode, makeString(), NameStr, CreateStmtContext::nnconstraints, NoLock, object_aclcheck(), OBJECT_COLUMN, OBJECT_TABCONSTRAINT, OBJECT_TYPE, pg_class_aclcheck(), CreateStmtContext::pstate, pstrdup(), RelationData::rd_rel, CreateStmtContext::relation, relation_openrv(), RelationGetDescr, RelationGetNotNullConstraints(), RelationGetRelationName, RelationGetRelid, RangeVar::relname, RangeVar::schemaname, sequence_options(), setup_parser_errposition_callback(), stmt, ColumnDef::storage, table_close(), and TupleDescAttr().

Referenced by transformCreateStmt().

◆ validateInfiniteBounds()

static void validateInfiniteBounds ( ParseState pstate,
List blist 
)
static

Definition at line 5115 of file parse_utilcmd.c.

5116{
5117 ListCell *lc;
5119
5120 foreach(lc, blist)
5121 {
5123
5124 if (kind == prd->kind)
5125 continue;
5126
5127 switch (kind)
5128 {
5130 kind = prd->kind;
5131 break;
5132
5134 ereport(ERROR,
5136 errmsg("every bound following MAXVALUE must also be MAXVALUE"),
5137 parser_errposition(pstate, exprLocation((Node *) prd))));
5138 break;
5139
5141 ereport(ERROR,
5143 errmsg("every bound following MINVALUE must also be MINVALUE"),
5144 parser_errposition(pstate, exprLocation((Node *) prd))));
5145 break;
5146 }
5147 }
5148}
PartitionRangeDatumKind
Definition parsenodes.h:968

References ereport, errcode(), errmsg, ERROR, exprLocation(), fb(), lfirst_node, parser_errposition(), PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, and PARTITION_RANGE_DATUM_VALUE.

Referenced by transformPartitionRangeBounds().