PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
Include dependency graph for parse_utilcmd.c:

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 
struct  CreateSchemaStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

static void transformColumnDefinition (CreateStmtContext *cxt, ColumnDef *column)
 
static void transformTableConstraint (CreateStmtContext *cxt, Constraint *constraint)
 
static void transformTableLikeClause (CreateStmtContext *cxt, TableLikeClause *table_like_clause)
 
static void transformOfType (CreateStmtContext *cxt, TypeName *ofTypename)
 
static CreateStatsStmtgenerateClonedExtStatsStmt (RangeVar *heapRel, Oid heapRelid, Oid source_statsid)
 
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 transformExtendedStatistics (CreateStmtContext *cxt)
 
static void transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (CreateStmtContext *cxt, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void setSchemaName (const char *context_schema, char **stmt_schema_name)
 
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)
 
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 (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
Definition: parsenodes.h:2714
@ CONSTR_UNIQUE
Definition: parsenodes.h:2712
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2713
@ CONSTR_PRIMARY
Definition: parsenodes.h:2711

Function Documentation

◆ checkPartition()

static void checkPartition ( Relation  rel,
Oid  partRelOid 
)
static

Definition at line 3246 of file parse_utilcmd.c.

3247 {
3248  Relation partRel;
3249 
3250  partRel = relation_open(partRelOid, AccessShareLock);
3251 
3252  if (partRel->rd_rel->relkind != RELKIND_RELATION)
3253  ereport(ERROR,
3254  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3255  errmsg("\"%s\" is not a table",
3256  RelationGetRelationName(partRel))));
3257 
3258  if (!partRel->rd_rel->relispartition)
3259  ereport(ERROR,
3260  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3261  errmsg("\"%s\" is not a partition",
3262  RelationGetRelationName(partRel))));
3263 
3264  if (get_partition_parent(partRelOid, false) != RelationGetRelid(rel))
3265  ereport(ERROR,
3267  errmsg("relation \"%s\" is not a partition of relation \"%s\"",
3268  RelationGetRelationName(partRel),
3269  RelationGetRelationName(rel))));
3270 
3271  /* Permissions checks */
3272  if (!object_ownercheck(RelationRelationId, RelationGetRelid(partRel), GetUserId()))
3274  RelationGetRelationName(partRel));
3275 
3276  relation_close(partRel, AccessShareLock);
3277 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2702
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4144
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define AccessShareLock
Definition: lockdefs.h:36
Oid GetUserId(void)
Definition: miscinit.c:514
ObjectType get_relkind_objtype(char relkind)
Oid get_partition_parent(Oid relid, bool even_if_detached)
Definition: partition.c:53
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetRelationName(relation)
Definition: rel.h:539
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
Form_pg_class rd_rel
Definition: rel.h:111

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), ERROR, get_partition_parent(), get_relkind_objtype(), GetUserId(), object_ownercheck(), RelationData::rd_rel, relation_close(), relation_open(), RelationGetRelationName, and RelationGetRelid.

Referenced by transformPartitionCmdForMerge(), and transformPartitionCmdForSplit().

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1186 of file parse_utilcmd.c.

1187 {
1188  List *result = NIL;
1189  List *atsubcmds = NIL;
1190  AttrNumber parent_attno;
1191  Relation relation;
1192  Relation childrel;
1193  TupleDesc tupleDesc;
1194  TupleConstr *constr;
1195  AttrMap *attmap;
1196  char *comment;
1197 
1198  /*
1199  * Open the relation referenced by the LIKE clause. We should still have
1200  * the table lock obtained by transformTableLikeClause (and this'll throw
1201  * an assertion failure if not). Hence, no need to recheck privileges
1202  * etc. We must open the rel by OID not name, to be sure we get the same
1203  * table.
1204  */
1205  if (!OidIsValid(table_like_clause->relationOid))
1206  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1207 
1208  relation = relation_open(table_like_clause->relationOid, NoLock);
1209 
1210  tupleDesc = RelationGetDescr(relation);
1211  constr = tupleDesc->constr;
1212 
1213  /*
1214  * Open the newly-created child relation; we have lock on that too.
1215  */
1216  childrel = relation_openrv(heapRel, NoLock);
1217 
1218  /*
1219  * Construct a map from the LIKE relation's attnos to the child rel's.
1220  * This re-checks type match etc, although it shouldn't be possible to
1221  * have a failure since both tables are locked.
1222  */
1223  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1224  tupleDesc,
1225  false);
1226 
1227  /*
1228  * Process defaults, if required.
1229  */
1230  if ((table_like_clause->options &
1232  constr != NULL)
1233  {
1234  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1235  parent_attno++)
1236  {
1237  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1238  parent_attno - 1);
1239 
1240  /*
1241  * Ignore dropped columns in the parent.
1242  */
1243  if (attribute->attisdropped)
1244  continue;
1245 
1246  /*
1247  * Copy default, if present and it should be copied. We have
1248  * separate options for plain default expressions and GENERATED
1249  * defaults.
1250  */
1251  if (attribute->atthasdef &&
1252  (attribute->attgenerated ?
1253  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1254  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1255  {
1256  Node *this_default;
1257  AlterTableCmd *atsubcmd;
1258  bool found_whole_row;
1259 
1260  this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1261  if (this_default == NULL)
1262  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1263  parent_attno, RelationGetRelationName(relation));
1264 
1265  atsubcmd = makeNode(AlterTableCmd);
1266  atsubcmd->subtype = AT_CookedColumnDefault;
1267  atsubcmd->num = attmap->attnums[parent_attno - 1];
1268  atsubcmd->def = map_variable_attnos(this_default,
1269  1, 0,
1270  attmap,
1271  InvalidOid,
1272  &found_whole_row);
1273 
1274  /*
1275  * Prevent this for the same reason as for constraints below.
1276  * Note that defaults cannot contain any vars, so it's OK that
1277  * the error message refers to generated columns.
1278  */
1279  if (found_whole_row)
1280  ereport(ERROR,
1281  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1282  errmsg("cannot convert whole-row table reference"),
1283  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1284  NameStr(attribute->attname),
1285  RelationGetRelationName(relation))));
1286 
1287  atsubcmds = lappend(atsubcmds, atsubcmd);
1288  }
1289  }
1290  }
1291 
1292  /*
1293  * Copy CHECK constraints if requested, being careful to adjust attribute
1294  * numbers so they match the child.
1295  */
1296  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1297  constr != NULL)
1298  {
1299  int ccnum;
1300 
1301  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1302  {
1303  char *ccname = constr->check[ccnum].ccname;
1304  char *ccbin = constr->check[ccnum].ccbin;
1305  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1306  Node *ccbin_node;
1307  bool found_whole_row;
1308  Constraint *n;
1309  AlterTableCmd *atsubcmd;
1310 
1311  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1312  1, 0,
1313  attmap,
1314  InvalidOid, &found_whole_row);
1315 
1316  /*
1317  * We reject whole-row variables because the whole point of LIKE
1318  * is that the new table's rowtype might later diverge from the
1319  * parent's. So, while translation might be possible right now,
1320  * it wouldn't be possible to guarantee it would work in future.
1321  */
1322  if (found_whole_row)
1323  ereport(ERROR,
1324  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1325  errmsg("cannot convert whole-row table reference"),
1326  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1327  ccname,
1328  RelationGetRelationName(relation))));
1329 
1330  n = makeNode(Constraint);
1331  n->contype = CONSTR_CHECK;
1332  n->conname = pstrdup(ccname);
1333  n->location = -1;
1334  n->is_no_inherit = ccnoinherit;
1335  n->raw_expr = NULL;
1336  n->cooked_expr = nodeToString(ccbin_node);
1337 
1338  /* We can skip validation, since the new table should be empty. */
1339  n->skip_validation = true;
1340  n->initially_valid = true;
1341 
1342  atsubcmd = makeNode(AlterTableCmd);
1343  atsubcmd->subtype = AT_AddConstraint;
1344  atsubcmd->def = (Node *) n;
1345  atsubcmds = lappend(atsubcmds, atsubcmd);
1346 
1347  /* Copy comment on constraint */
1348  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1350  n->conname, false),
1351  ConstraintRelationId,
1352  0)) != NULL)
1353  {
1355 
1356  stmt->objtype = OBJECT_TABCONSTRAINT;
1357  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1358  makeString(heapRel->relname),
1359  makeString(n->conname));
1360  stmt->comment = comment;
1361 
1362  result = lappend(result, stmt);
1363  }
1364  }
1365  }
1366 
1367  /*
1368  * If we generated any ALTER TABLE actions above, wrap them into a single
1369  * ALTER TABLE command. Stick it at the front of the result, so it runs
1370  * before any CommentStmts we made above.
1371  */
1372  if (atsubcmds)
1373  {
1375 
1376  atcmd->relation = copyObject(heapRel);
1377  atcmd->cmds = atsubcmds;
1378  atcmd->objtype = OBJECT_TABLE;
1379  atcmd->missing_ok = false;
1380  result = lcons(atcmd, result);
1381  }
1382 
1383  /*
1384  * Process indexes if required.
1385  */
1386  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1387  relation->rd_rel->relhasindex)
1388  {
1389  List *parent_indexes;
1390  ListCell *l;
1391 
1392  parent_indexes = RelationGetIndexList(relation);
1393 
1394  foreach(l, parent_indexes)
1395  {
1396  Oid parent_index_oid = lfirst_oid(l);
1397  Relation parent_index;
1398  IndexStmt *index_stmt;
1399 
1400  parent_index = index_open(parent_index_oid, AccessShareLock);
1401 
1402  /* Build CREATE INDEX statement to recreate the parent_index */
1403  index_stmt = generateClonedIndexStmt(heapRel,
1404  parent_index,
1405  attmap,
1406  NULL);
1407 
1408  /* Copy comment on index, if requested */
1409  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1410  {
1411  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1412 
1413  /*
1414  * We make use of IndexStmt's idxcomment option, so as not to
1415  * need to know now what name the index will have.
1416  */
1417  index_stmt->idxcomment = comment;
1418  }
1419 
1420  result = lappend(result, index_stmt);
1421 
1422  index_close(parent_index, AccessShareLock);
1423  }
1424  }
1425 
1426  /* Done with child rel */
1427  table_close(childrel, NoLock);
1428 
1429  /*
1430  * Close the parent rel, but keep our AccessShareLock on it until xact
1431  * commit. That will prevent someone else from deleting or ALTERing the
1432  * parent before the child is committed.
1433  */
1434  table_close(relation, NoLock);
1435 
1436  return result;
1437 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:177
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:746
#define OidIsValid(objectId)
Definition: c.h:775
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define elog(elevel,...)
Definition: elog.h:224
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lcons(void *datum, List *list)
Definition: list.c:495
#define NoLock
Definition: lockdefs.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1695
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
char * nodeToString(const void *obj)
Definition: outfuncs.c:791
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2710
@ OBJECT_TABLE
Definition: parsenodes.h:2302
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2301
@ AT_AddConstraint
Definition: parsenodes.h:2370
@ AT_CookedColumnDefault
Definition: parsenodes.h:2356
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:761
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:765
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:767
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:764
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:763
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define NIL
Definition: pg_list.h:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:531
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4760
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:137
AlterTableType subtype
Definition: parsenodes.h:2434
RangeVar * relation
Definition: parsenodes.h:2345
ObjectType objtype
Definition: parsenodes.h:2347
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ParseLoc location
Definition: parsenodes.h:2777
ConstrType contype
Definition: parsenodes.h:2736
bool is_no_inherit
Definition: parsenodes.h:2742
char * cooked_expr
Definition: parsenodes.h:2745
bool initially_valid
Definition: parsenodes.h:2741
bool skip_validation
Definition: parsenodes.h:2740
Node * raw_expr
Definition: parsenodes.h:2743
char * conname
Definition: parsenodes.h:2737
char * idxcomment
Definition: parsenodes.h:3366
Definition: pg_list.h:54
Definition: nodes.h:129
char * relname
Definition: primnodes.h:82
char * schemaname
Definition: primnodes.h:79
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:899
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

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

Referenced by ProcessUtilitySlow().

◆ generateClonedExtStatsStmt()

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

Definition at line 1842 of file parse_utilcmd.c.

1844 {
1845  HeapTuple ht_stats;
1846  Form_pg_statistic_ext statsrec;
1847  CreateStatsStmt *stats;
1848  List *stat_types = NIL;
1849  List *def_names = NIL;
1850  bool isnull;
1851  Datum datum;
1852  ArrayType *arr;
1853  char *enabled;
1854  int i;
1855 
1856  Assert(OidIsValid(heapRelid));
1857  Assert(heapRel != NULL);
1858 
1859  /*
1860  * Fetch pg_statistic_ext tuple of source statistics object.
1861  */
1862  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1863  if (!HeapTupleIsValid(ht_stats))
1864  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1865  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1866 
1867  /* Determine which statistics types exist */
1868  datum = SysCacheGetAttrNotNull(STATEXTOID, ht_stats,
1869  Anum_pg_statistic_ext_stxkind);
1870  arr = DatumGetArrayTypeP(datum);
1871  if (ARR_NDIM(arr) != 1 ||
1872  ARR_HASNULL(arr) ||
1873  ARR_ELEMTYPE(arr) != CHAROID)
1874  elog(ERROR, "stxkind is not a 1-D char array");
1875  enabled = (char *) ARR_DATA_PTR(arr);
1876  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1877  {
1878  if (enabled[i] == STATS_EXT_NDISTINCT)
1879  stat_types = lappend(stat_types, makeString("ndistinct"));
1880  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1881  stat_types = lappend(stat_types, makeString("dependencies"));
1882  else if (enabled[i] == STATS_EXT_MCV)
1883  stat_types = lappend(stat_types, makeString("mcv"));
1884  else if (enabled[i] == STATS_EXT_EXPRESSIONS)
1885  /* expression stats are not exposed to users */
1886  continue;
1887  else
1888  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1889  }
1890 
1891  /* Determine which columns the statistics are on */
1892  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1893  {
1894  StatsElem *selem = makeNode(StatsElem);
1895  AttrNumber attnum = statsrec->stxkeys.values[i];
1896 
1897  selem->name = get_attname(heapRelid, attnum, false);
1898  selem->expr = NULL;
1899 
1900  def_names = lappend(def_names, selem);
1901  }
1902 
1903  /*
1904  * Now handle expressions, if there are any. The order (with respect to
1905  * regular attributes) does not really matter for extended stats, so we
1906  * simply append them after simple column references.
1907  *
1908  * XXX Some places during build/estimation treat expressions as if they
1909  * are before attributes, but for the CREATE command that's entirely
1910  * irrelevant.
1911  */
1912  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1913  Anum_pg_statistic_ext_stxexprs, &isnull);
1914 
1915  if (!isnull)
1916  {
1917  ListCell *lc;
1918  List *exprs = NIL;
1919  char *exprsString;
1920 
1921  exprsString = TextDatumGetCString(datum);
1922  exprs = (List *) stringToNode(exprsString);
1923 
1924  foreach(lc, exprs)
1925  {
1926  StatsElem *selem = makeNode(StatsElem);
1927 
1928  selem->name = NULL;
1929  selem->expr = (Node *) lfirst(lc);
1930 
1931  def_names = lappend(def_names, selem);
1932  }
1933 
1934  pfree(exprsString);
1935  }
1936 
1937  /* finally, build the output node */
1938  stats = makeNode(CreateStatsStmt);
1939  stats->defnames = NULL;
1940  stats->stat_types = stat_types;
1941  stats->exprs = def_names;
1942  stats->relations = list_make1(heapRel);
1943  stats->stxcomment = NULL;
1944  stats->transformed = true; /* don't need transformStatsStmt again */
1945  stats->if_not_exists = false;
1946 
1947  /* Clean up */
1948  ReleaseSysCache(ht_stats);
1949 
1950  return stats;
1951 }
#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:98
#define Assert(condition)
Definition: c.h:858
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int i
Definition: isn.c:73
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:827
void pfree(void *pointer)
Definition: mcxt.c:1520
int16 attnum
Definition: pg_attribute.h:74
#define lfirst(lc)
Definition: pg_list.h:172
#define list_make1(x1)
Definition: pg_list.h:212
FormData_pg_statistic_ext * Form_pg_statistic_ext
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
char * name
Definition: parsenodes.h:3411
Node * expr
Definition: parsenodes.h:3412
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510

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

Referenced by transformTableLikeClause().

◆ generateClonedIndexStmt()

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

Definition at line 1493 of file parse_utilcmd.c.

1496 {
1497  Oid source_relid = RelationGetRelid(source_idx);
1498  HeapTuple ht_idxrel;
1499  HeapTuple ht_idx;
1500  HeapTuple ht_am;
1501  Form_pg_class idxrelrec;
1502  Form_pg_index idxrec;
1503  Form_pg_am amrec;
1504  oidvector *indcollation;
1505  oidvector *indclass;
1506  IndexStmt *index;
1507  List *indexprs;
1508  ListCell *indexpr_item;
1509  Oid indrelid;
1510  int keyno;
1511  Oid keycoltype;
1512  Datum datum;
1513  bool isnull;
1514 
1515  if (constraintOid)
1516  *constraintOid = InvalidOid;
1517 
1518  /*
1519  * Fetch pg_class tuple of source index. We can't use the copy in the
1520  * relcache entry because it doesn't include optional fields.
1521  */
1522  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1523  if (!HeapTupleIsValid(ht_idxrel))
1524  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1525  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1526 
1527  /* Fetch pg_index tuple for source index from relcache entry */
1528  ht_idx = source_idx->rd_indextuple;
1529  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1530  indrelid = idxrec->indrelid;
1531 
1532  /* Fetch the pg_am tuple of the index' access method */
1533  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1534  if (!HeapTupleIsValid(ht_am))
1535  elog(ERROR, "cache lookup failed for access method %u",
1536  idxrelrec->relam);
1537  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1538 
1539  /* Extract indcollation from the pg_index tuple */
1540  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1541  Anum_pg_index_indcollation);
1542  indcollation = (oidvector *) DatumGetPointer(datum);
1543 
1544  /* Extract indclass from the pg_index tuple */
1545  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
1546  indclass = (oidvector *) DatumGetPointer(datum);
1547 
1548  /* Begin building the IndexStmt */
1550  index->relation = heapRel;
1551  index->accessMethod = pstrdup(NameStr(amrec->amname));
1552  if (OidIsValid(idxrelrec->reltablespace))
1553  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1554  else
1555  index->tableSpace = NULL;
1556  index->excludeOpNames = NIL;
1557  index->idxcomment = NULL;
1558  index->indexOid = InvalidOid;
1559  index->oldNumber = InvalidRelFileNumber;
1560  index->oldCreateSubid = InvalidSubTransactionId;
1561  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1562  index->unique = idxrec->indisunique;
1563  index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1564  index->primary = idxrec->indisprimary;
1565  index->transformed = true; /* don't need transformIndexStmt */
1566  index->concurrent = false;
1567  index->if_not_exists = false;
1568  index->reset_default_tblspc = false;
1569 
1570  /*
1571  * We don't try to preserve the name of the source index; instead, just
1572  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1573  * the name, we'd get duplicate-relation-name failures unless the source
1574  * table was in a different schema.)
1575  */
1576  index->idxname = NULL;
1577 
1578  /*
1579  * If the index is marked PRIMARY or has an exclusion condition, it's
1580  * certainly from a constraint; else, if it's not marked UNIQUE, it
1581  * certainly isn't. If it is or might be from a constraint, we have to
1582  * fetch the pg_constraint record.
1583  */
1584  if (index->primary || index->unique || idxrec->indisexclusion)
1585  {
1586  Oid constraintId = get_index_constraint(source_relid);
1587 
1588  if (OidIsValid(constraintId))
1589  {
1590  HeapTuple ht_constr;
1591  Form_pg_constraint conrec;
1592 
1593  if (constraintOid)
1594  *constraintOid = constraintId;
1595 
1596  ht_constr = SearchSysCache1(CONSTROID,
1597  ObjectIdGetDatum(constraintId));
1598  if (!HeapTupleIsValid(ht_constr))
1599  elog(ERROR, "cache lookup failed for constraint %u",
1600  constraintId);
1601  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1602 
1603  index->isconstraint = true;
1604  index->deferrable = conrec->condeferrable;
1605  index->initdeferred = conrec->condeferred;
1606 
1607  /* If it's an exclusion constraint, we need the operator names */
1608  if (idxrec->indisexclusion)
1609  {
1610  Datum *elems;
1611  int nElems;
1612  int i;
1613 
1614  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1615  /* Extract operator OIDs from the pg_constraint tuple */
1616  datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
1617  Anum_pg_constraint_conexclop);
1618  deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1619 
1620  for (i = 0; i < nElems; i++)
1621  {
1622  Oid operid = DatumGetObjectId(elems[i]);
1623  HeapTuple opertup;
1624  Form_pg_operator operform;
1625  char *oprname;
1626  char *nspname;
1627  List *namelist;
1628 
1629  opertup = SearchSysCache1(OPEROID,
1630  ObjectIdGetDatum(operid));
1631  if (!HeapTupleIsValid(opertup))
1632  elog(ERROR, "cache lookup failed for operator %u",
1633  operid);
1634  operform = (Form_pg_operator) GETSTRUCT(opertup);
1635  oprname = pstrdup(NameStr(operform->oprname));
1636  /* For simplicity we always schema-qualify the op name */
1637  nspname = get_namespace_name(operform->oprnamespace);
1638  namelist = list_make2(makeString(nspname),
1639  makeString(oprname));
1640  index->excludeOpNames = lappend(index->excludeOpNames,
1641  namelist);
1642  ReleaseSysCache(opertup);
1643  }
1644  }
1645 
1646  ReleaseSysCache(ht_constr);
1647  }
1648  else
1649  index->isconstraint = false;
1650  }
1651  else
1652  index->isconstraint = false;
1653 
1654  /* Get the index expressions, if any */
1655  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1656  Anum_pg_index_indexprs, &isnull);
1657  if (!isnull)
1658  {
1659  char *exprsString;
1660 
1661  exprsString = TextDatumGetCString(datum);
1662  indexprs = (List *) stringToNode(exprsString);
1663  }
1664  else
1665  indexprs = NIL;
1666 
1667  /* Build the list of IndexElem */
1668  index->indexParams = NIL;
1669  index->indexIncludingParams = NIL;
1670 
1671  indexpr_item = list_head(indexprs);
1672  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1673  {
1674  IndexElem *iparam;
1675  AttrNumber attnum = idxrec->indkey.values[keyno];
1677  keyno);
1678  int16 opt = source_idx->rd_indoption[keyno];
1679 
1680  iparam = makeNode(IndexElem);
1681 
1683  {
1684  /* Simple index column */
1685  char *attname;
1686 
1687  attname = get_attname(indrelid, attnum, false);
1688  keycoltype = get_atttype(indrelid, attnum);
1689 
1690  iparam->name = attname;
1691  iparam->expr = NULL;
1692  }
1693  else
1694  {
1695  /* Expressional index */
1696  Node *indexkey;
1697  bool found_whole_row;
1698 
1699  if (indexpr_item == NULL)
1700  elog(ERROR, "too few entries in indexprs list");
1701  indexkey = (Node *) lfirst(indexpr_item);
1702  indexpr_item = lnext(indexprs, indexpr_item);
1703 
1704  /* Adjust Vars to match new table's column numbering */
1705  indexkey = map_variable_attnos(indexkey,
1706  1, 0,
1707  attmap,
1708  InvalidOid, &found_whole_row);
1709 
1710  /* As in expandTableLikeClause, reject whole-row variables */
1711  if (found_whole_row)
1712  ereport(ERROR,
1713  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1714  errmsg("cannot convert whole-row table reference"),
1715  errdetail("Index \"%s\" contains a whole-row table reference.",
1716  RelationGetRelationName(source_idx))));
1717 
1718  iparam->name = NULL;
1719  iparam->expr = indexkey;
1720 
1721  keycoltype = exprType(indexkey);
1722  }
1723 
1724  /* Copy the original index column name */
1725  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1726 
1727  /* Add the collation name, if non-default */
1728  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1729 
1730  /* Add the operator class name, if non-default */
1731  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1732  iparam->opclassopts =
1733  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1734 
1735  iparam->ordering = SORTBY_DEFAULT;
1737 
1738  /* Adjust options if necessary */
1739  if (source_idx->rd_indam->amcanorder)
1740  {
1741  /*
1742  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1743  * set non-default settings unnecessarily, though, so as to
1744  * improve the chance of recognizing equivalence to constraint
1745  * indexes.
1746  */
1747  if (opt & INDOPTION_DESC)
1748  {
1749  iparam->ordering = SORTBY_DESC;
1750  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1752  }
1753  else
1754  {
1755  if (opt & INDOPTION_NULLS_FIRST)
1757  }
1758  }
1759 
1760  index->indexParams = lappend(index->indexParams, iparam);
1761  }
1762 
1763  /* Handle included columns separately */
1764  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1765  {
1766  IndexElem *iparam;
1767  AttrNumber attnum = idxrec->indkey.values[keyno];
1769  keyno);
1770 
1771  iparam = makeNode(IndexElem);
1772 
1774  {
1775  /* Simple index column */
1776  char *attname;
1777 
1778  attname = get_attname(indrelid, attnum, false);
1779 
1780  iparam->name = attname;
1781  iparam->expr = NULL;
1782  }
1783  else
1784  ereport(ERROR,
1785  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1786  errmsg("expressions are not supported in included columns")));
1787 
1788  /* Copy the original index column name */
1789  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1790 
1791  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1792  }
1793  /* Copy reloptions if any */
1794  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1795  Anum_pg_class_reloptions, &isnull);
1796  if (!isnull)
1797  index->options = untransformRelOptions(datum);
1798 
1799  /* If it's a partial index, decompile and append the predicate */
1800  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1801  Anum_pg_index_indpred, &isnull);
1802  if (!isnull)
1803  {
1804  char *pred_str;
1805  Node *pred_tree;
1806  bool found_whole_row;
1807 
1808  /* Convert text string to node tree */
1809  pred_str = TextDatumGetCString(datum);
1810  pred_tree = (Node *) stringToNode(pred_str);
1811 
1812  /* Adjust Vars to match new table's column numbering */
1813  pred_tree = map_variable_attnos(pred_tree,
1814  1, 0,
1815  attmap,
1816  InvalidOid, &found_whole_row);
1817 
1818  /* As in expandTableLikeClause, reject whole-row variables */
1819  if (found_whole_row)
1820  ereport(ERROR,
1821  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1822  errmsg("cannot convert whole-row table reference"),
1823  errdetail("Index \"%s\" contains a whole-row table reference.",
1824  RelationGetRelationName(source_idx))));
1825 
1826  index->whereClause = pred_tree;
1827  }
1828 
1829  /* Clean up */
1830  ReleaseSysCache(ht_idxrel);
1831  ReleaseSysCache(ht_am);
1832 
1833  return index;
1834 }
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3678
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
signed short int16
Definition: c.h:493
#define InvalidSubTransactionId
Definition: c.h:658
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:970
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:913
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static List * get_collation(Oid collation, Oid actual_datatype)
static List * get_opclass(Oid opclass, Oid actual_datatype)
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
NameData attname
Definition: pg_attribute.h:41
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_constraint * Form_pg_constraint
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:995
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define list_make2(x1, x2)
Definition: pg_list.h:214
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1331
#define InvalidRelFileNumber
Definition: relpath.h:26
bool amcanorder
Definition: amapi.h:224
Node * expr
Definition: parsenodes.h:784
SortByDir ordering
Definition: parsenodes.h:789
List * opclassopts
Definition: parsenodes.h:788
char * indexcolname
Definition: parsenodes.h:785
SortByNulls nulls_ordering
Definition: parsenodes.h:790
List * opclass
Definition: parsenodes.h:787
char * name
Definition: parsenodes.h:783
List * collation
Definition: parsenodes.h:786
struct IndexAmRoutine * rd_indam
Definition: rel.h:206
struct HeapTupleData * rd_indextuple
Definition: rel.h:194
int16 * rd_indoption
Definition: rel.h:211
Definition: type.h:95
Definition: c.h:726
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:733

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

Referenced by AttachPartitionEnsureIndexes(), 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 370 of file parse_utilcmd.c.

374 {
375  ListCell *option;
376  DefElem *nameEl = NULL;
377  Oid snamespaceid;
378  char *snamespace;
379  char *sname;
380  CreateSeqStmt *seqstmt;
381  AlterSeqStmt *altseqstmt;
382  List *attnamelist;
383  int nameEl_idx = -1;
384 
385  /* Make a copy of this as we may end up modifying it in the code below */
386  seqoptions = list_copy(seqoptions);
387 
388  /*
389  * Determine namespace and name to use for the sequence.
390  *
391  * First, check if a sequence name was passed in as an option. This is
392  * used by pg_dump. Else, generate a name.
393  *
394  * Although we use ChooseRelationName, it's not guaranteed that the
395  * selected sequence name won't conflict; given sufficiently long field
396  * names, two different serial columns in the same table could be assigned
397  * the same sequence name, and we'd not notice since we aren't creating
398  * the sequence quite yet. In practice this seems quite unlikely to be a
399  * problem, especially since few people would need two serial columns in
400  * one table.
401  */
402  foreach(option, seqoptions)
403  {
404  DefElem *defel = lfirst_node(DefElem, option);
405 
406  if (strcmp(defel->defname, "sequence_name") == 0)
407  {
408  if (nameEl)
409  errorConflictingDefElem(defel, cxt->pstate);
410  nameEl = defel;
411  nameEl_idx = foreach_current_index(option);
412  }
413  }
414 
415  if (nameEl)
416  {
418 
419  snamespace = rv->schemaname;
420  if (!snamespace)
421  {
422  /* Given unqualified SEQUENCE NAME, select namespace */
423  if (cxt->rel)
424  snamespaceid = RelationGetNamespace(cxt->rel);
425  else
426  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
427  snamespace = get_namespace_name(snamespaceid);
428  }
429  sname = rv->relname;
430  /* Remove the SEQUENCE NAME item from seqoptions */
431  seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
432  }
433  else
434  {
435  if (cxt->rel)
436  snamespaceid = RelationGetNamespace(cxt->rel);
437  else
438  {
439  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
440  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
441  }
442  snamespace = get_namespace_name(snamespaceid);
443  sname = ChooseRelationName(cxt->relation->relname,
444  column->colname,
445  "seq",
446  snamespaceid,
447  false);
448  }
449 
450  ereport(DEBUG1,
451  (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
452  cxt->stmtType, sname,
453  cxt->relation->relname, column->colname)));
454 
455  /*
456  * Build a CREATE SEQUENCE command to create the sequence object, and add
457  * it to the list of things to be done before this CREATE/ALTER TABLE.
458  */
459  seqstmt = makeNode(CreateSeqStmt);
460  seqstmt->for_identity = for_identity;
461  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
462 
463  /*
464  * Copy the persistence of the table. For CREATE TABLE, we get the
465  * persistence from cxt->relation, which comes from the CreateStmt in
466  * progress. For ALTER TABLE, the parser won't set
467  * cxt->relation->relpersistence, but we have cxt->rel as the existing
468  * table, so we copy the persistence from there.
469  */
470  seqstmt->sequence->relpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
471 
472  seqstmt->options = seqoptions;
473 
474  /*
475  * If a sequence data type was specified, add it to the options. Prepend
476  * to the list rather than append; in case a user supplied their own AS
477  * clause, the "redundant options" error will point to their occurrence,
478  * not our synthetic one.
479  */
480  if (seqtypid)
481  seqstmt->options = lcons(makeDefElem("as",
482  (Node *) makeTypeNameFromOid(seqtypid, -1),
483  -1),
484  seqstmt->options);
485 
486  /*
487  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
488  * the table's owner. The current user might be someone else (perhaps a
489  * superuser, or someone who's only a member of the owning role), but the
490  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
491  * exactly the same owning role.
492  */
493  if (cxt->rel)
494  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
495  else
496  seqstmt->ownerId = InvalidOid;
497 
498  cxt->blist = lappend(cxt->blist, seqstmt);
499 
500  /*
501  * Store the identity sequence name that we decided on. ALTER TABLE ...
502  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
503  * with values from the sequence, while the association of the sequence
504  * with the table is not set until after the ALTER TABLE.
505  */
506  column->identitySequence = seqstmt->sequence;
507 
508  /*
509  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
510  * owned by this column, and add it to the appropriate list of things to
511  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
512  * COLUMN, it must be done after the statement because we don't know the
513  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
514  * we can do the marking immediately, which improves some ALTER TABLE
515  * behaviors.
516  */
517  altseqstmt = makeNode(AlterSeqStmt);
518  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
519  attnamelist = list_make3(makeString(snamespace),
520  makeString(cxt->relation->relname),
521  makeString(column->colname));
522  altseqstmt->options = list_make1(makeDefElem("owned_by",
523  (Node *) attnamelist, -1));
524  altseqstmt->for_identity = for_identity;
525 
526  if (col_exists)
527  cxt->blist = lappend(cxt->blist, altseqstmt);
528  else
529  cxt->alist = lappend(cxt->alist, altseqstmt);
530 
531  if (snamespace_p)
532  *snamespace_p = snamespace;
533  if (sname_p)
534  *sname_p = sname;
535 }
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define DEBUG1
Definition: elog.h:30
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2495
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:767
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:564
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:474
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:831
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:639
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3539
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define RelationGetNamespace(relation)
Definition: rel.h:546
List * options
Definition: parsenodes.h:3136
RangeVar * sequence
Definition: parsenodes.h:3135
bool for_identity
Definition: parsenodes.h:3137
RangeVar * identitySequence
Definition: parsenodes.h:738
char * colname
Definition: parsenodes.h:726
List * options
Definition: parsenodes.h:3126
RangeVar * sequence
Definition: parsenodes.h:3125
const char * stmtType
Definition: parse_utilcmd.c:79
RangeVar * relation
Definition: parse_utilcmd.c:80
ParseState * pstate
Definition: parse_utilcmd.c:78
char * defname
Definition: parsenodes.h:815
Node * arg
Definition: parsenodes.h:816
char relpersistence
Definition: primnodes.h:88

References CreateStmtContext::alist, DefElem::arg, CreateStmtContext::blist, castNode, ChooseRelationName(), ColumnDef::colname, DEBUG1, DefElem::defname, ereport, errmsg_internal(), errorConflictingDefElem(), CreateSeqStmt::for_identity, AlterSeqStmt::for_identity, foreach_current_index, get_namespace_name(), ColumnDef::identitySequence, InvalidOid, lappend(), lcons(), lfirst_node, list_copy(), list_delete_nth_cell(), list_make1, list_make3, makeDefElem(), makeNode, makeRangeVar(), makeRangeVarFromNameList(), makeString(), makeTypeNameFromOid(), CreateSeqStmt::options, AlterSeqStmt::options, CreateSeqStmt::ownerId, CreateStmtContext::pstate, RangeVarAdjustRelationPersistence(), RangeVarGetCreationNamespace(), RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetNamespace, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, CreateSeqStmt::sequence, AlterSeqStmt::sequence, and CreateStmtContext::stmtType.

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

◆ get_collation()

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

Definition at line 1960 of file parse_utilcmd.c.

1961 {
1962  List *result;
1963  HeapTuple ht_coll;
1964  Form_pg_collation coll_rec;
1965  char *nsp_name;
1966  char *coll_name;
1967 
1968  if (!OidIsValid(collation))
1969  return NIL; /* easy case */
1970  if (collation == get_typcollation(actual_datatype))
1971  return NIL; /* just let it default */
1972 
1973  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1974  if (!HeapTupleIsValid(ht_coll))
1975  elog(ERROR, "cache lookup failed for collation %u", collation);
1976  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1977 
1978  /* For simplicity, we always schema-qualify the name */
1979  nsp_name = get_namespace_name(coll_rec->collnamespace);
1980  coll_name = pstrdup(NameStr(coll_rec->collname));
1981  result = list_make2(makeString(nsp_name), makeString(coll_name));
1982 
1983  ReleaseSysCache(ht_coll);
1984  return result;
1985 }
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3056
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58

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

Referenced by generateClonedIndexStmt().

◆ get_opclass()

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

Definition at line 1994 of file parse_utilcmd.c.

1995 {
1996  List *result = NIL;
1997  HeapTuple ht_opc;
1998  Form_pg_opclass opc_rec;
1999 
2000  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2001  if (!HeapTupleIsValid(ht_opc))
2002  elog(ERROR, "cache lookup failed for opclass %u", opclass);
2003  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2004 
2005  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2006  {
2007  /* For simplicity, we always schema-qualify the name */
2008  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2009  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2010 
2011  result = list_make2(makeString(nsp_name), makeString(opc_name));
2012  }
2013 
2014  ReleaseSysCache(ht_opc);
2015  return result;
2016 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2300
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

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

Referenced by generateClonedIndexStmt().

◆ setSchemaName()

static void setSchemaName ( const char *  context_schema,
char **  stmt_schema_name 
)
static

Definition at line 4069 of file parse_utilcmd.c.

4070 {
4071  if (*stmt_schema_name == NULL)
4072  *stmt_schema_name = unconstify(char *, context_schema);
4073  else if (strcmp(context_schema, *stmt_schema_name) != 0)
4074  ereport(ERROR,
4075  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
4076  errmsg("CREATE specifies a schema (%s) "
4077  "different from the one being created (%s)",
4078  *stmt_schema_name, context_schema)));
4079 }
#define unconstify(underlying_type, expr)
Definition: c.h:1245

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

Referenced by transformCreateSchemaStmtElements().

◆ transformAlterTableStmt()

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

Definition at line 3408 of file parse_utilcmd.c.

3411 {
3412  Relation rel;
3413  TupleDesc tupdesc;
3414  ParseState *pstate;
3415  CreateStmtContext cxt;
3416  List *save_alist;
3417  ListCell *lcmd,
3418  *l;
3419  List *newcmds = NIL;
3420  bool skipValidation = true;
3421  AlterTableCmd *newcmd;
3422  ParseNamespaceItem *nsitem;
3423 
3424  /* Caller is responsible for locking the relation */
3425  rel = relation_open(relid, NoLock);
3426  tupdesc = RelationGetDescr(rel);
3427 
3428  /* Set up pstate */
3429  pstate = make_parsestate(NULL);
3430  pstate->p_sourcetext = queryString;
3431  nsitem = addRangeTableEntryForRelation(pstate,
3432  rel,
3434  NULL,
3435  false,
3436  true);
3437  addNSItemToQuery(pstate, nsitem, false, true, true);
3438 
3439  /* Set up CreateStmtContext */
3440  cxt.pstate = pstate;
3441  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3442  {
3443  cxt.stmtType = "ALTER FOREIGN TABLE";
3444  cxt.isforeign = true;
3445  }
3446  else
3447  {
3448  cxt.stmtType = "ALTER TABLE";
3449  cxt.isforeign = false;
3450  }
3451  cxt.relation = stmt->relation;
3452  cxt.rel = rel;
3453  cxt.inhRelations = NIL;
3454  cxt.isalter = true;
3455  cxt.columns = NIL;
3456  cxt.ckconstraints = NIL;
3457  cxt.fkconstraints = NIL;
3458  cxt.ixconstraints = NIL;
3459  cxt.likeclauses = NIL;
3460  cxt.extstats = NIL;
3461  cxt.blist = NIL;
3462  cxt.alist = NIL;
3463  cxt.pkey = NULL;
3464  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3465  cxt.partbound = NULL;
3466  cxt.ofType = false;
3467 
3468  /*
3469  * Transform ALTER subcommands that need it (most don't). These largely
3470  * re-use code from CREATE TABLE.
3471  */
3472  foreach(lcmd, stmt->cmds)
3473  {
3474  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3475 
3476  switch (cmd->subtype)
3477  {
3478  case AT_AddColumn:
3479  {
3480  ColumnDef *def = castNode(ColumnDef, cmd->def);
3481 
3482  transformColumnDefinition(&cxt, def);
3483 
3484  /*
3485  * If the column has a non-null default, we can't skip
3486  * validation of foreign keys.
3487  */
3488  if (def->raw_default != NULL)
3489  skipValidation = false;
3490 
3491  /*
3492  * All constraints are processed in other ways. Remove the
3493  * original list
3494  */
3495  def->constraints = NIL;
3496 
3497  newcmds = lappend(newcmds, cmd);
3498  break;
3499  }
3500 
3501  case AT_AddConstraint:
3502 
3503  /*
3504  * The original AddConstraint cmd node doesn't go to newcmds
3505  */
3506  if (IsA(cmd->def, Constraint))
3507  {
3508  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3509  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3510  skipValidation = false;
3511  }
3512  else
3513  elog(ERROR, "unrecognized node type: %d",
3514  (int) nodeTag(cmd->def));
3515  break;
3516 
3517  case AT_AlterColumnType:
3518  {
3519  ColumnDef *def = castNode(ColumnDef, cmd->def);
3521 
3522  /*
3523  * For ALTER COLUMN TYPE, transform the USING clause if
3524  * one was specified.
3525  */
3526  if (def->raw_default)
3527  {
3528  def->cooked_default =
3529  transformExpr(pstate, def->raw_default,
3531  }
3532 
3533  /*
3534  * For identity column, create ALTER SEQUENCE command to
3535  * change the data type of the sequence. Identity sequence
3536  * is associated with the top level partitioned table.
3537  * Hence ignore partitions.
3538  */
3539  if (!RelationGetForm(rel)->relispartition)
3540  {
3541  attnum = get_attnum(relid, cmd->name);
3542  if (attnum == InvalidAttrNumber)
3543  ereport(ERROR,
3544  (errcode(ERRCODE_UNDEFINED_COLUMN),
3545  errmsg("column \"%s\" of relation \"%s\" does not exist",
3546  cmd->name, RelationGetRelationName(rel))));
3547 
3548  if (attnum > 0 &&
3549  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3550  {
3551  Oid seq_relid = getIdentitySequence(rel, attnum, false);
3552  Oid typeOid = typenameTypeId(pstate, def->typeName);
3553  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3554 
3555  altseqstmt->sequence
3557  get_rel_name(seq_relid),
3558  -1);
3559  altseqstmt->options = list_make1(makeDefElem("as",
3560  (Node *) makeTypeNameFromOid(typeOid, -1),
3561  -1));
3562  altseqstmt->for_identity = true;
3563  cxt.blist = lappend(cxt.blist, altseqstmt);
3564  }
3565  }
3566 
3567  newcmds = lappend(newcmds, cmd);
3568  break;
3569  }
3570 
3571  case AT_AddIdentity:
3572  {
3573  Constraint *def = castNode(Constraint, cmd->def);
3574  ColumnDef *newdef = makeNode(ColumnDef);
3576 
3577  newdef->colname = cmd->name;
3578  newdef->identity = def->generated_when;
3579  cmd->def = (Node *) newdef;
3580 
3581  attnum = get_attnum(relid, cmd->name);
3582  if (attnum == InvalidAttrNumber)
3583  ereport(ERROR,
3584  (errcode(ERRCODE_UNDEFINED_COLUMN),
3585  errmsg("column \"%s\" of relation \"%s\" does not exist",
3586  cmd->name, RelationGetRelationName(rel))));
3587 
3588  generateSerialExtraStmts(&cxt, newdef,
3589  get_atttype(relid, attnum),
3590  def->options, true, true,
3591  NULL, NULL);
3592 
3593  newcmds = lappend(newcmds, cmd);
3594  break;
3595  }
3596 
3597  case AT_SetIdentity:
3598  {
3599  /*
3600  * Create an ALTER SEQUENCE statement for the internal
3601  * sequence of the identity column.
3602  */
3603  ListCell *lc;
3604  List *newseqopts = NIL;
3605  List *newdef = NIL;
3607  Oid seq_relid;
3608 
3609  /*
3610  * Split options into those handled by ALTER SEQUENCE and
3611  * those for ALTER TABLE proper.
3612  */
3613  foreach(lc, castNode(List, cmd->def))
3614  {
3615  DefElem *def = lfirst_node(DefElem, lc);
3616 
3617  if (strcmp(def->defname, "generated") == 0)
3618  newdef = lappend(newdef, def);
3619  else
3620  newseqopts = lappend(newseqopts, def);
3621  }
3622 
3623  attnum = get_attnum(relid, cmd->name);
3624  if (attnum == InvalidAttrNumber)
3625  ereport(ERROR,
3626  (errcode(ERRCODE_UNDEFINED_COLUMN),
3627  errmsg("column \"%s\" of relation \"%s\" does not exist",
3628  cmd->name, RelationGetRelationName(rel))));
3629 
3630  seq_relid = getIdentitySequence(rel, attnum, true);
3631 
3632  if (seq_relid)
3633  {
3634  AlterSeqStmt *seqstmt;
3635 
3636  seqstmt = makeNode(AlterSeqStmt);
3638  get_rel_name(seq_relid), -1);
3639  seqstmt->options = newseqopts;
3640  seqstmt->for_identity = true;
3641  seqstmt->missing_ok = false;
3642 
3643  cxt.blist = lappend(cxt.blist, seqstmt);
3644  }
3645 
3646  /*
3647  * If column was not an identity column, we just let the
3648  * ALTER TABLE command error out later. (There are cases
3649  * this fails to cover, but we'll need to restructure
3650  * where creation of the sequence dependency linkage
3651  * happens before we can fix it.)
3652  */
3653 
3654  cmd->def = (Node *) newdef;
3655  newcmds = lappend(newcmds, cmd);
3656  break;
3657  }
3658 
3659  case AT_AttachPartition:
3660  case AT_DetachPartition:
3661  {
3662  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3663 
3664  transformPartitionCmd(&cxt, partcmd->bound);
3665  /* assign transformed value of the partition bound */
3666  partcmd->bound = cxt.partbound;
3667  }
3668 
3669  newcmds = lappend(newcmds, cmd);
3670  break;
3671 
3672  case AT_SplitPartition:
3673  case AT_MergePartitions:
3674  {
3675  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3676 
3677  if (list_length(partcmd->partlist) < 2)
3678  ereport(ERROR,
3679  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3680  errmsg("list of new partitions should contain at least two items")));
3681 
3682  if (cmd->subtype == AT_SplitPartition)
3683  transformPartitionCmdForSplit(&cxt, partcmd);
3684  else
3685  transformPartitionCmdForMerge(&cxt, partcmd);
3686  newcmds = lappend(newcmds, cmd);
3687  break;
3688  }
3689 
3690  default:
3691 
3692  /*
3693  * Currently, we shouldn't actually get here for subcommand
3694  * types that don't require transformation; but if we do, just
3695  * emit them unchanged.
3696  */
3697  newcmds = lappend(newcmds, cmd);
3698  break;
3699  }
3700  }
3701 
3702  /*
3703  * Transfer anything we already have in cxt.alist into save_alist, to keep
3704  * it separate from the output of transformIndexConstraints.
3705  */
3706  save_alist = cxt.alist;
3707  cxt.alist = NIL;
3708 
3709  /* Postprocess constraints */
3711  transformFKConstraints(&cxt, skipValidation, true);
3712  transformCheckConstraints(&cxt, false);
3713 
3714  /*
3715  * Push any index-creation commands into the ALTER, so that they can be
3716  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3717  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3718  * subcommand has already been through transformIndexStmt.
3719  */
3720  foreach(l, cxt.alist)
3721  {
3722  Node *istmt = (Node *) lfirst(l);
3723 
3724  /*
3725  * We assume here that cxt.alist contains only IndexStmts and possibly
3726  * ALTER TABLE SET NOT NULL statements generated from primary key
3727  * constraints. We absorb the subcommands of the latter directly.
3728  */
3729  if (IsA(istmt, IndexStmt))
3730  {
3731  IndexStmt *idxstmt = (IndexStmt *) istmt;
3732 
3733  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3734  newcmd = makeNode(AlterTableCmd);
3736  newcmd->def = (Node *) idxstmt;
3737  newcmds = lappend(newcmds, newcmd);
3738  }
3739  else if (IsA(istmt, AlterTableStmt))
3740  {
3741  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3742 
3743  newcmds = list_concat(newcmds, alterstmt->cmds);
3744  }
3745  else
3746  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3747  }
3748  cxt.alist = NIL;
3749 
3750  /* Append any CHECK or FK constraints to the commands list */
3751  foreach(l, cxt.ckconstraints)
3752  {
3753  newcmd = makeNode(AlterTableCmd);
3754  newcmd->subtype = AT_AddConstraint;
3755  newcmd->def = (Node *) lfirst_node(Constraint, l);
3756  newcmds = lappend(newcmds, newcmd);
3757  }
3758  foreach(l, cxt.fkconstraints)
3759  {
3760  newcmd = makeNode(AlterTableCmd);
3761  newcmd->subtype = AT_AddConstraint;
3762  newcmd->def = (Node *) lfirst_node(Constraint, l);
3763  newcmds = lappend(newcmds, newcmd);
3764  }
3765 
3766  /* Append extended statistics objects */
3768 
3769  /* Close rel */
3770  relation_close(rel, NoLock);
3771 
3772  /*
3773  * Output results.
3774  */
3775  stmt->cmds = newcmds;
3776 
3777  *beforeStmts = cxt.blist;
3778  *afterStmts = list_concat(cxt.alist, save_alist);
3779 
3780  return stmt;
3781 }
#define InvalidAttrNumber
Definition: attnum.h:23
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:858
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
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:75
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformExtendedStatistics(CreateStmtContext *cxt)
static void transformPartitionCmdForSplit(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformPartitionCmdForMerge(CreateStmtContext *cxt, PartitionCmd *partcmd)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
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
Definition: parsenodes.h:2375
@ AT_MergePartitions
Definition: parsenodes.h:2417
@ AT_SetIdentity
Definition: parsenodes.h:2419
@ AT_AddIndex
Definition: parsenodes.h:2368
@ AT_AddIdentity
Definition: parsenodes.h:2418
@ AT_AlterColumnType
Definition: parsenodes.h:2378
@ AT_DetachPartition
Definition: parsenodes.h:2414
@ AT_AttachPartition
Definition: parsenodes.h:2413
@ AT_SplitPartition
Definition: parsenodes.h:2416
@ AT_AddColumn
Definition: parsenodes.h:2353
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:946
static int list_length(const List *l)
Definition: pg_list.h:152
#define RelationGetForm(relation)
Definition: rel.h:499
char identity
Definition: parsenodes.h:737
List * constraints
Definition: parsenodes.h:743
Node * cooked_default
Definition: parsenodes.h:736
TypeName * typeName
Definition: parsenodes.h:727
Node * raw_default
Definition: parsenodes.h:735
List * options
Definition: parsenodes.h:2757
char generated_when
Definition: parsenodes.h:2747
IndexStmt * pkey
Definition: parse_utilcmd.c:95
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Oid indexOid
Definition: parsenodes.h:3367
const char * p_sourcetext
Definition: parse_node.h:193
PartitionBoundSpec * bound
Definition: parsenodes.h:958
List * partlist
Definition: parsenodes.h:959

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, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, if(), IndexStmt::indexOid, 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(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, PartitionCmd::partlist, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetForm, RelationGetRelationName, AlterSeqStmt::sequence, stmt, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), 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 2678 of file parse_utilcmd.c.

2679 {
2680  ListCell *ckclist;
2681 
2682  if (cxt->ckconstraints == NIL)
2683  return;
2684 
2685  /*
2686  * If creating a new table (but not a foreign table), we can safely skip
2687  * validation of check constraints, and nonetheless mark them valid. (This
2688  * will override any user-supplied NOT VALID flag.)
2689  */
2690  if (skipValidation)
2691  {
2692  foreach(ckclist, cxt->ckconstraints)
2693  {
2694  Constraint *constraint = (Constraint *) lfirst(ckclist);
2695 
2696  constraint->skip_validation = true;
2697  constraint->initially_valid = true;
2698  }
2699  }
2700 }

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 543 of file parse_utilcmd.c.

544 {
545  bool is_serial;
546  bool saw_nullable;
547  bool saw_default;
548  bool saw_identity;
549  bool saw_generated;
550  ListCell *clist;
551 
552  cxt->columns = lappend(cxt->columns, column);
553 
554  /* Check for SERIAL pseudo-types */
555  is_serial = false;
556  if (column->typeName
557  && list_length(column->typeName->names) == 1
558  && !column->typeName->pct_type)
559  {
560  char *typname = strVal(linitial(column->typeName->names));
561 
562  if (strcmp(typname, "smallserial") == 0 ||
563  strcmp(typname, "serial2") == 0)
564  {
565  is_serial = true;
566  column->typeName->names = NIL;
567  column->typeName->typeOid = INT2OID;
568  }
569  else if (strcmp(typname, "serial") == 0 ||
570  strcmp(typname, "serial4") == 0)
571  {
572  is_serial = true;
573  column->typeName->names = NIL;
574  column->typeName->typeOid = INT4OID;
575  }
576  else if (strcmp(typname, "bigserial") == 0 ||
577  strcmp(typname, "serial8") == 0)
578  {
579  is_serial = true;
580  column->typeName->names = NIL;
581  column->typeName->typeOid = INT8OID;
582  }
583 
584  /*
585  * We have to reject "serial[]" explicitly, because once we've set
586  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
587  * special coding for serial(typmod) though.
588  */
589  if (is_serial && column->typeName->arrayBounds != NIL)
590  ereport(ERROR,
591  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
592  errmsg("array of serial is not implemented"),
594  column->typeName->location)));
595  }
596 
597  /* Do necessary work on the column type declaration */
598  if (column->typeName)
599  transformColumnType(cxt, column);
600 
601  /* Special actions for SERIAL pseudo-types */
602  if (is_serial)
603  {
604  char *snamespace;
605  char *sname;
606  char *qstring;
607  A_Const *snamenode;
608  TypeCast *castnode;
609  FuncCall *funccallnode;
610  Constraint *constraint;
611 
612  generateSerialExtraStmts(cxt, column,
613  column->typeName->typeOid, NIL,
614  false, false,
615  &snamespace, &sname);
616 
617  /*
618  * Create appropriate constraints for SERIAL. We do this in full,
619  * rather than shortcutting, so that we will detect any conflicting
620  * constraints the user wrote (like a different DEFAULT).
621  *
622  * Create an expression tree representing the function call
623  * nextval('sequencename'). We cannot reduce the raw tree to cooked
624  * form until after the sequence is created, but there's no need to do
625  * so.
626  */
627  qstring = quote_qualified_identifier(snamespace, sname);
628  snamenode = makeNode(A_Const);
629  snamenode->val.node.type = T_String;
630  snamenode->val.sval.sval = qstring;
631  snamenode->location = -1;
632  castnode = makeNode(TypeCast);
633  castnode->typeName = SystemTypeName("regclass");
634  castnode->arg = (Node *) snamenode;
635  castnode->location = -1;
636  funccallnode = makeFuncCall(SystemFuncName("nextval"),
637  list_make1(castnode),
639  -1);
640  constraint = makeNode(Constraint);
641  constraint->contype = CONSTR_DEFAULT;
642  constraint->location = -1;
643  constraint->raw_expr = (Node *) funccallnode;
644  constraint->cooked_expr = NULL;
645  column->constraints = lappend(column->constraints, constraint);
646 
647  constraint = makeNode(Constraint);
648  constraint->contype = CONSTR_NOTNULL;
649  constraint->location = -1;
650  column->constraints = lappend(column->constraints, constraint);
651  }
652 
653  /* Process column constraints, if any... */
655 
656  saw_nullable = false;
657  saw_default = false;
658  saw_identity = false;
659  saw_generated = false;
660 
661  foreach(clist, column->constraints)
662  {
663  Constraint *constraint = lfirst_node(Constraint, clist);
664 
665  switch (constraint->contype)
666  {
667  case CONSTR_NULL:
668  if (saw_nullable && column->is_not_null)
669  ereport(ERROR,
670  (errcode(ERRCODE_SYNTAX_ERROR),
671  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
672  column->colname, cxt->relation->relname),
674  constraint->location)));
675  column->is_not_null = false;
676  saw_nullable = true;
677  break;
678 
679  case CONSTR_NOTNULL:
680  if (saw_nullable && !column->is_not_null)
681  ereport(ERROR,
682  (errcode(ERRCODE_SYNTAX_ERROR),
683  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
684  column->colname, cxt->relation->relname),
686  constraint->location)));
687  column->is_not_null = true;
688  saw_nullable = true;
689  break;
690 
691  case CONSTR_DEFAULT:
692  if (saw_default)
693  ereport(ERROR,
694  (errcode(ERRCODE_SYNTAX_ERROR),
695  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
696  column->colname, cxt->relation->relname),
698  constraint->location)));
699  column->raw_default = constraint->raw_expr;
700  Assert(constraint->cooked_expr == NULL);
701  saw_default = true;
702  break;
703 
704  case CONSTR_IDENTITY:
705  {
706  Type ctype;
707  Oid typeOid;
708 
709  if (cxt->ofType)
710  ereport(ERROR,
711  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
712  errmsg("identity columns are not supported on typed tables")));
713  if (cxt->partbound)
714  ereport(ERROR,
715  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
716  errmsg("identity columns are not supported on partitions")));
717 
718  ctype = typenameType(cxt->pstate, column->typeName, NULL);
719  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
720  ReleaseSysCache(ctype);
721 
722  if (saw_identity)
723  ereport(ERROR,
724  (errcode(ERRCODE_SYNTAX_ERROR),
725  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
726  column->colname, cxt->relation->relname),
728  constraint->location)));
729 
730  generateSerialExtraStmts(cxt, column,
731  typeOid, constraint->options,
732  true, false,
733  NULL, NULL);
734 
735  column->identity = constraint->generated_when;
736  saw_identity = true;
737 
738  /* An identity column is implicitly NOT NULL */
739  if (saw_nullable && !column->is_not_null)
740  ereport(ERROR,
741  (errcode(ERRCODE_SYNTAX_ERROR),
742  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
743  column->colname, cxt->relation->relname),
745  constraint->location)));
746  column->is_not_null = true;
747  saw_nullable = true;
748  break;
749  }
750 
751  case CONSTR_GENERATED:
752  if (cxt->ofType)
753  ereport(ERROR,
754  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
755  errmsg("generated columns are not supported on typed tables")));
756  if (saw_generated)
757  ereport(ERROR,
758  (errcode(ERRCODE_SYNTAX_ERROR),
759  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
760  column->colname, cxt->relation->relname),
762  constraint->location)));
763  column->generated = ATTRIBUTE_GENERATED_STORED;
764  column->raw_default = constraint->raw_expr;
765  Assert(constraint->cooked_expr == NULL);
766  saw_generated = true;
767  break;
768 
769  case CONSTR_CHECK:
770  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
771  break;
772 
773  case CONSTR_PRIMARY:
774  if (cxt->isforeign)
775  ereport(ERROR,
776  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
777  errmsg("primary key constraints are not supported on foreign tables"),
779  constraint->location)));
780  /* FALL THRU */
781 
782  case CONSTR_UNIQUE:
783  if (cxt->isforeign)
784  ereport(ERROR,
785  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
786  errmsg("unique constraints are not supported on foreign tables"),
788  constraint->location)));
789  if (constraint->keys == NIL)
790  constraint->keys = list_make1(makeString(column->colname));
791  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
792  break;
793 
794  case CONSTR_EXCLUSION:
795  /* grammar does not allow EXCLUDE as a column constraint */
796  elog(ERROR, "column exclusion constraints are not supported");
797  break;
798 
799  case CONSTR_FOREIGN:
800  if (cxt->isforeign)
801  ereport(ERROR,
802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
803  errmsg("foreign key constraints are not supported on foreign tables"),
805  constraint->location)));
806 
807  /*
808  * Fill in the current attribute's name and throw it into the
809  * list of FK constraints to be processed later.
810  */
811  constraint->fk_attrs = list_make1(makeString(column->colname));
812  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
813  break;
814 
819  /* transformConstraintAttrs took care of these */
820  break;
821 
822  default:
823  elog(ERROR, "unrecognized constraint type: %d",
824  constraint->contype);
825  break;
826  }
827 
828  if (saw_default && saw_identity)
829  ereport(ERROR,
830  (errcode(ERRCODE_SYNTAX_ERROR),
831  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
832  column->colname, cxt->relation->relname),
834  constraint->location)));
835 
836  if (saw_default && saw_generated)
837  ereport(ERROR,
838  (errcode(ERRCODE_SYNTAX_ERROR),
839  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
840  column->colname, cxt->relation->relname),
842  constraint->location)));
843 
844  if (saw_identity && saw_generated)
845  ereport(ERROR,
846  (errcode(ERRCODE_SYNTAX_ERROR),
847  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
848  column->colname, cxt->relation->relname),
850  constraint->location)));
851  }
852 
853  /*
854  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
855  * per-column foreign data wrapper options to this column after creation.
856  */
857  if (column->fdwoptions != NIL)
858  {
860  AlterTableCmd *cmd;
861 
862  cmd = makeNode(AlterTableCmd);
864  cmd->name = column->colname;
865  cmd->def = (Node *) column->fdwoptions;
866  cmd->behavior = DROP_RESTRICT;
867  cmd->missing_ok = false;
868 
870  stmt->relation = cxt->relation;
871  stmt->cmds = NIL;
872  stmt->objtype = OBJECT_FOREIGN_TABLE;
873  stmt->cmds = lappend(stmt->cmds, cmd);
874 
875  cxt->alist = lappend(cxt->alist, stmt);
876  }
877 }
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:603
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
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(CreateStmtContext *cxt, List *constraintList)
@ CONSTR_ATTR_DEFERRED
Definition: parsenodes.h:2717
@ CONSTR_IDENTITY
Definition: parsenodes.h:2708
@ CONSTR_ATTR_NOT_DEFERRABLE
Definition: parsenodes.h:2716
@ CONSTR_DEFAULT
Definition: parsenodes.h:2707
@ CONSTR_NOTNULL
Definition: parsenodes.h:2706
@ CONSTR_ATTR_IMMEDIATE
Definition: parsenodes.h:2718
@ CONSTR_NULL
Definition: parsenodes.h:2704
@ CONSTR_GENERATED
Definition: parsenodes.h:2709
@ CONSTR_ATTR_DEFERRABLE
Definition: parsenodes.h:2715
@ DROP_RESTRICT
Definition: parsenodes.h:2334
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:2279
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2379
TypeName * SystemTypeName(char *name)
List * SystemFuncName(char *name)
#define linitial(l)
Definition: pg_list.h:178
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
NameData typname
Definition: pg_type.h:41
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:734
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12680
union ValUnion val
Definition: parsenodes.h:362
ParseLoc location
Definition: parsenodes.h:364
DropBehavior behavior
Definition: parsenodes.h:2442
bool is_not_null
Definition: parsenodes.h:731
char generated
Definition: parsenodes.h:740
List * fdwoptions
Definition: parsenodes.h:744
List * keys
Definition: parsenodes.h:2751
List * fk_attrs
Definition: parsenodes.h:2767
NodeTag type
Definition: nodes.h:130
char * sval
Definition: value.h:68
TypeName * typeName
Definition: parsenodes.h:374
ParseLoc location
Definition: parsenodes.h:375
Node * arg
Definition: parsenodes.h:373
Oid typeOid
Definition: parsenodes.h:269
bool pct_type
Definition: parsenodes.h:271
List * names
Definition: parsenodes.h:268
List * arrayBounds
Definition: parsenodes.h:274
ParseLoc location
Definition: parsenodes.h:275
Node node
Definition: parsenodes.h:349
String sval
Definition: parsenodes.h:353
#define strVal(v)
Definition: value.h:82

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, COERCE_EXPLICIT_CALL, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, ColumnDef::identity, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, ValUnion::node, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, ReleaseSysCache(), RangeVar::relname, stmt, strVal, AlterTableCmd::subtype, ValUnion::sval, String::sval, SystemFuncName(), SystemTypeName(), transformColumnType(), transformConstraintAttrs(), Node::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3909 of file parse_utilcmd.c.

3910 {
3911  /*
3912  * All we really need to do here is verify that the type is valid,
3913  * including any collation spec that might be present.
3914  */
3915  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3916 
3917  if (column->collClause)
3918  {
3919  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3920 
3921  LookupCollation(cxt->pstate,
3922  column->collClause->collname,
3923  column->collClause->location);
3924  /* Complain if COLLATE is applied to an uncollatable type */
3925  if (!OidIsValid(typtup->typcollation))
3926  ereport(ERROR,
3927  (errcode(ERRCODE_DATATYPE_MISMATCH),
3928  errmsg("collations are not supported by type %s",
3929  format_type_be(typtup->oid)),
3931  column->collClause->location)));
3932  }
3933 
3934  ReleaseSysCache(ctype);
3935 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
List * collname
Definition: parsenodes.h:385
ParseLoc location
Definition: parsenodes.h:386
CollateClause * collClause
Definition: parsenodes.h:741

References ColumnDef::collClause, CollateClause::collname, ereport, errcode(), errmsg(), ERROR, format_type_be(), GETSTRUCT, CollateClause::location, LookupCollation(), OidIsValid, parser_errposition(), CreateStmtContext::pstate, ReleaseSysCache(), ColumnDef::typeName, and typenameType().

Referenced by transformColumnDefinition().

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3794 of file parse_utilcmd.c.

3795 {
3796  Constraint *lastprimarycon = NULL;
3797  bool saw_deferrability = false;
3798  bool saw_initially = false;
3799  ListCell *clist;
3800 
3801 #define SUPPORTS_ATTRS(node) \
3802  ((node) != NULL && \
3803  ((node)->contype == CONSTR_PRIMARY || \
3804  (node)->contype == CONSTR_UNIQUE || \
3805  (node)->contype == CONSTR_EXCLUSION || \
3806  (node)->contype == CONSTR_FOREIGN))
3807 
3808  foreach(clist, constraintList)
3809  {
3810  Constraint *con = (Constraint *) lfirst(clist);
3811 
3812  if (!IsA(con, Constraint))
3813  elog(ERROR, "unrecognized node type: %d",
3814  (int) nodeTag(con));
3815  switch (con->contype)
3816  {
3818  if (!SUPPORTS_ATTRS(lastprimarycon))
3819  ereport(ERROR,
3820  (errcode(ERRCODE_SYNTAX_ERROR),
3821  errmsg("misplaced DEFERRABLE clause"),
3822  parser_errposition(cxt->pstate, con->location)));
3823  if (saw_deferrability)
3824  ereport(ERROR,
3825  (errcode(ERRCODE_SYNTAX_ERROR),
3826  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3827  parser_errposition(cxt->pstate, con->location)));
3828  saw_deferrability = true;
3829  lastprimarycon->deferrable = true;
3830  break;
3831 
3833  if (!SUPPORTS_ATTRS(lastprimarycon))
3834  ereport(ERROR,
3835  (errcode(ERRCODE_SYNTAX_ERROR),
3836  errmsg("misplaced NOT DEFERRABLE clause"),
3837  parser_errposition(cxt->pstate, con->location)));
3838  if (saw_deferrability)
3839  ereport(ERROR,
3840  (errcode(ERRCODE_SYNTAX_ERROR),
3841  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3842  parser_errposition(cxt->pstate, con->location)));
3843  saw_deferrability = true;
3844  lastprimarycon->deferrable = false;
3845  if (saw_initially &&
3846  lastprimarycon->initdeferred)
3847  ereport(ERROR,
3848  (errcode(ERRCODE_SYNTAX_ERROR),
3849  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3850  parser_errposition(cxt->pstate, con->location)));
3851  break;
3852 
3853  case CONSTR_ATTR_DEFERRED:
3854  if (!SUPPORTS_ATTRS(lastprimarycon))
3855  ereport(ERROR,
3856  (errcode(ERRCODE_SYNTAX_ERROR),
3857  errmsg("misplaced INITIALLY DEFERRED clause"),
3858  parser_errposition(cxt->pstate, con->location)));
3859  if (saw_initially)
3860  ereport(ERROR,
3861  (errcode(ERRCODE_SYNTAX_ERROR),
3862  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3863  parser_errposition(cxt->pstate, con->location)));
3864  saw_initially = true;
3865  lastprimarycon->initdeferred = true;
3866 
3867  /*
3868  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3869  */
3870  if (!saw_deferrability)
3871  lastprimarycon->deferrable = true;
3872  else if (!lastprimarycon->deferrable)
3873  ereport(ERROR,
3874  (errcode(ERRCODE_SYNTAX_ERROR),
3875  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3876  parser_errposition(cxt->pstate, con->location)));
3877  break;
3878 
3879  case CONSTR_ATTR_IMMEDIATE:
3880  if (!SUPPORTS_ATTRS(lastprimarycon))
3881  ereport(ERROR,
3882  (errcode(ERRCODE_SYNTAX_ERROR),
3883  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3884  parser_errposition(cxt->pstate, con->location)));
3885  if (saw_initially)
3886  ereport(ERROR,
3887  (errcode(ERRCODE_SYNTAX_ERROR),
3888  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3889  parser_errposition(cxt->pstate, con->location)));
3890  saw_initially = true;
3891  lastprimarycon->initdeferred = false;
3892  break;
3893 
3894  default:
3895  /* Otherwise it's not an attribute */
3896  lastprimarycon = con;
3897  /* reset flags for new primary node */
3898  saw_deferrability = false;
3899  saw_initially = false;
3900  break;
3901  }
3902  }
3903 }
#define SUPPORTS_ATTRS(node)
bool initdeferred
Definition: parsenodes.h:2739
bool deferrable
Definition: parsenodes.h:2738

References CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, Constraint::contype, Constraint::deferrable, elog, ereport, errcode(), errmsg(), ERROR, Constraint::initdeferred, IsA, lfirst, Constraint::location, nodeTag, parser_errposition(), CreateStmtContext::pstate, and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition().

◆ transformCreateSchemaStmtElements()

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

Definition at line 3966 of file parse_utilcmd.c.

3967 {
3969  List *result;
3970  ListCell *elements;
3971 
3972  cxt.schemaname = schemaName;
3973  cxt.sequences = NIL;
3974  cxt.tables = NIL;
3975  cxt.views = NIL;
3976  cxt.indexes = NIL;
3977  cxt.triggers = NIL;
3978  cxt.grants = NIL;
3979 
3980  /*
3981  * Run through each schema element in the schema element list. Separate
3982  * statements by type, and do preliminary analysis.
3983  */
3984  foreach(elements, schemaElts)
3985  {
3986  Node *element = lfirst(elements);
3987 
3988  switch (nodeTag(element))
3989  {
3990  case T_CreateSeqStmt:
3991  {
3992  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3993 
3995  cxt.sequences = lappend(cxt.sequences, element);
3996  }
3997  break;
3998 
3999  case T_CreateStmt:
4000  {
4001  CreateStmt *elp = (CreateStmt *) element;
4002 
4004 
4005  /*
4006  * XXX todo: deal with constraints
4007  */
4008  cxt.tables = lappend(cxt.tables, element);
4009  }
4010  break;
4011 
4012  case T_ViewStmt:
4013  {
4014  ViewStmt *elp = (ViewStmt *) element;
4015 
4016  setSchemaName(cxt.schemaname, &elp->view->schemaname);
4017 
4018  /*
4019  * XXX todo: deal with references between views
4020  */
4021  cxt.views = lappend(cxt.views, element);
4022  }
4023  break;
4024 
4025  case T_IndexStmt:
4026  {
4027  IndexStmt *elp = (IndexStmt *) element;
4028 
4030  cxt.indexes = lappend(cxt.indexes, element);
4031  }
4032  break;
4033 
4034  case T_CreateTrigStmt:
4035  {
4037 
4039  cxt.triggers = lappend(cxt.triggers, element);
4040  }
4041  break;
4042 
4043  case T_GrantStmt:
4044  cxt.grants = lappend(cxt.grants, element);
4045  break;
4046 
4047  default:
4048  elog(ERROR, "unrecognized node type: %d",
4049  (int) nodeTag(element));
4050  }
4051  }
4052 
4053  result = NIL;
4054  result = list_concat(result, cxt.sequences);
4055  result = list_concat(result, cxt.tables);
4056  result = list_concat(result, cxt.views);
4057  result = list_concat(result, cxt.indexes);
4058  result = list_concat(result, cxt.triggers);
4059  result = list_concat(result, cxt.grants);
4060 
4061  return result;
4062 }
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * relation
Definition: parsenodes.h:2656
RangeVar * relation
Definition: parsenodes.h:3012
RangeVar * relation
Definition: parsenodes.h:3357
RangeVar * view
Definition: parsenodes.h:3748

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

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 166 of file parse_utilcmd.c.

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

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

Referenced by ProcessUtilitySlow().

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2663 of file parse_utilcmd.c.

2664 {
2665  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2666 }

References CreateStmtContext::alist, CreateStmtContext::extstats, and list_concat().

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformFKConstraints()

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

Definition at line 2707 of file parse_utilcmd.c.

2709 {
2710  ListCell *fkclist;
2711 
2712  if (cxt->fkconstraints == NIL)
2713  return;
2714 
2715  /*
2716  * If CREATE TABLE or adding a column with NULL default, we can safely
2717  * skip validation of FK constraints, and nonetheless mark them valid.
2718  * (This will override any user-supplied NOT VALID flag.)
2719  */
2720  if (skipValidation)
2721  {
2722  foreach(fkclist, cxt->fkconstraints)
2723  {
2724  Constraint *constraint = (Constraint *) lfirst(fkclist);
2725 
2726  constraint->skip_validation = true;
2727  constraint->initially_valid = true;
2728  }
2729  }
2730 
2731  /*
2732  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2733  * CONSTRAINT command to execute after the basic command is complete. (If
2734  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2735  * its own subcommand list.)
2736  *
2737  * Note: the ADD CONSTRAINT command must also execute after any index
2738  * creation commands. Thus, this should run after
2739  * transformIndexConstraints, so that the CREATE INDEX commands are
2740  * already in cxt->alist. See also the handling of cxt->likeclauses.
2741  */
2742  if (!isAddConstraint)
2743  {
2744  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2745 
2746  alterstmt->relation = cxt->relation;
2747  alterstmt->cmds = NIL;
2748  alterstmt->objtype = OBJECT_TABLE;
2749 
2750  foreach(fkclist, cxt->fkconstraints)
2751  {
2752  Constraint *constraint = (Constraint *) lfirst(fkclist);
2753  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2754 
2755  altercmd->subtype = AT_AddConstraint;
2756  altercmd->name = NULL;
2757  altercmd->def = (Node *) constraint;
2758  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2759  }
2760 
2761  cxt->alist = lappend(cxt->alist, alterstmt);
2762  }
2763 }

References CreateStmtContext::alist, AT_AddConstraint, AlterTableStmt::cmds, AlterTableCmd::def, CreateStmtContext::fkconstraints, Constraint::initially_valid, lappend(), lfirst, makeNode, AlterTableCmd::name, NIL, OBJECT_TABLE, AlterTableStmt::objtype, CreateStmtContext::relation, AlterTableStmt::relation, Constraint::skip_validation, and AlterTableCmd::subtype.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexConstraint()

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

Definition at line 2129 of file parse_utilcmd.c.

2130 {
2131  IndexStmt *index;
2132  List *notnullcmds = NIL;
2133  ListCell *lc;
2134 
2136 
2137  index->unique = (constraint->contype != CONSTR_EXCLUSION);
2138  index->primary = (constraint->contype == CONSTR_PRIMARY);
2139  if (index->primary)
2140  {
2141  if (cxt->pkey != NULL)
2142  ereport(ERROR,
2143  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2144  errmsg("multiple primary keys for table \"%s\" are not allowed",
2145  cxt->relation->relname),
2146  parser_errposition(cxt->pstate, constraint->location)));
2147  cxt->pkey = index;
2148 
2149  /*
2150  * In ALTER TABLE case, a primary index might already exist, but
2151  * DefineIndex will check for it.
2152  */
2153  }
2154  index->nulls_not_distinct = constraint->nulls_not_distinct;
2155  index->isconstraint = true;
2156  index->deferrable = constraint->deferrable;
2157  index->initdeferred = constraint->initdeferred;
2158 
2159  if (constraint->conname != NULL)
2160  index->idxname = pstrdup(constraint->conname);
2161  else
2162  index->idxname = NULL; /* DefineIndex will choose name */
2163 
2164  index->relation = cxt->relation;
2165  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2166  index->options = constraint->options;
2167  index->tableSpace = constraint->indexspace;
2168  index->whereClause = constraint->where_clause;
2169  index->indexParams = NIL;
2170  index->indexIncludingParams = NIL;
2171  index->excludeOpNames = NIL;
2172  index->idxcomment = NULL;
2173  index->indexOid = InvalidOid;
2174  index->oldNumber = InvalidRelFileNumber;
2175  index->oldCreateSubid = InvalidSubTransactionId;
2176  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2177  index->transformed = false;
2178  index->concurrent = false;
2179  index->if_not_exists = false;
2180  index->reset_default_tblspc = constraint->reset_default_tblspc;
2181 
2182  /*
2183  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2184  * verify it's usable, then extract the implied column name list. (We
2185  * will not actually need the column name list at runtime, but we need it
2186  * now to check for duplicate column entries below.)
2187  */
2188  if (constraint->indexname != NULL)
2189  {
2190  char *index_name = constraint->indexname;
2191  Relation heap_rel = cxt->rel;
2192  Oid index_oid;
2193  Relation index_rel;
2194  Form_pg_index index_form;
2195  oidvector *indclass;
2196  Datum indclassDatum;
2197  int i;
2198 
2199  /* Grammar should not allow this with explicit column list */
2200  Assert(constraint->keys == NIL);
2201 
2202  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2203  Assert(constraint->contype == CONSTR_PRIMARY ||
2204  constraint->contype == CONSTR_UNIQUE);
2205 
2206  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2207  if (!cxt->isalter)
2208  ereport(ERROR,
2209  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2210  errmsg("cannot use an existing index in CREATE TABLE"),
2211  parser_errposition(cxt->pstate, constraint->location)));
2212 
2213  /* Look for the index in the same schema as the table */
2214  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2215 
2216  if (!OidIsValid(index_oid))
2217  ereport(ERROR,
2218  (errcode(ERRCODE_UNDEFINED_OBJECT),
2219  errmsg("index \"%s\" does not exist", index_name),
2220  parser_errposition(cxt->pstate, constraint->location)));
2221 
2222  /* Open the index (this will throw an error if it is not an index) */
2223  index_rel = index_open(index_oid, AccessShareLock);
2224  index_form = index_rel->rd_index;
2225 
2226  /* Check that it does not have an associated constraint already */
2227  if (OidIsValid(get_index_constraint(index_oid)))
2228  ereport(ERROR,
2229  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2230  errmsg("index \"%s\" is already associated with a constraint",
2231  index_name),
2232  parser_errposition(cxt->pstate, constraint->location)));
2233 
2234  /* Perform validity checks on the index */
2235  if (index_form->indrelid != RelationGetRelid(heap_rel))
2236  ereport(ERROR,
2237  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2238  errmsg("index \"%s\" does not belong to table \"%s\"",
2239  index_name, RelationGetRelationName(heap_rel)),
2240  parser_errposition(cxt->pstate, constraint->location)));
2241 
2242  if (!index_form->indisvalid)
2243  ereport(ERROR,
2244  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2245  errmsg("index \"%s\" is not valid", index_name),
2246  parser_errposition(cxt->pstate, constraint->location)));
2247 
2248  if (!index_form->indisunique)
2249  ereport(ERROR,
2250  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2251  errmsg("\"%s\" is not a unique index", index_name),
2252  errdetail("Cannot create a primary key or unique constraint using such an index."),
2253  parser_errposition(cxt->pstate, constraint->location)));
2254 
2255  if (RelationGetIndexExpressions(index_rel) != NIL)
2256  ereport(ERROR,
2257  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2258  errmsg("index \"%s\" contains expressions", index_name),
2259  errdetail("Cannot create a primary key or unique constraint using such an index."),
2260  parser_errposition(cxt->pstate, constraint->location)));
2261 
2262  if (RelationGetIndexPredicate(index_rel) != NIL)
2263  ereport(ERROR,
2264  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2265  errmsg("\"%s\" is a partial index", index_name),
2266  errdetail("Cannot create a primary key or unique constraint using such an index."),
2267  parser_errposition(cxt->pstate, constraint->location)));
2268 
2269  /*
2270  * It's probably unsafe to change a deferred index to non-deferred. (A
2271  * non-constraint index couldn't be deferred anyway, so this case
2272  * should never occur; no need to sweat, but let's check it.)
2273  */
2274  if (!index_form->indimmediate && !constraint->deferrable)
2275  ereport(ERROR,
2276  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2277  errmsg("\"%s\" is a deferrable index", index_name),
2278  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2279  parser_errposition(cxt->pstate, constraint->location)));
2280 
2281  /*
2282  * Insist on it being a btree. That's the only kind that supports
2283  * uniqueness at the moment anyway; but we must have an index that
2284  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2285  * else dump and reload will produce a different index (breaking
2286  * pg_upgrade in particular).
2287  */
2288  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2289  ereport(ERROR,
2290  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2291  errmsg("index \"%s\" is not a btree", index_name),
2292  parser_errposition(cxt->pstate, constraint->location)));
2293 
2294  /* Must get indclass the hard way */
2295  indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
2296  index_rel->rd_indextuple,
2297  Anum_pg_index_indclass);
2298  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2299 
2300  for (i = 0; i < index_form->indnatts; i++)
2301  {
2302  int16 attnum = index_form->indkey.values[i];
2303  const FormData_pg_attribute *attform;
2304  char *attname;
2305  Oid defopclass;
2306 
2307  /*
2308  * We shouldn't see attnum == 0 here, since we already rejected
2309  * expression indexes. If we do, SystemAttributeDefinition will
2310  * throw an error.
2311  */
2312  if (attnum > 0)
2313  {
2314  Assert(attnum <= heap_rel->rd_att->natts);
2315  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2316  }
2317  else
2318  attform = SystemAttributeDefinition(attnum);
2319  attname = pstrdup(NameStr(attform->attname));
2320 
2321  if (i < index_form->indnkeyatts)
2322  {
2323  /*
2324  * Insist on default opclass, collation, and sort options.
2325  * While the index would still work as a constraint with
2326  * non-default settings, it might not provide exactly the same
2327  * uniqueness semantics as you'd get from a normally-created
2328  * constraint; and there's also the dump/reload problem
2329  * mentioned above.
2330  */
2331  Datum attoptions =
2332  get_attoptions(RelationGetRelid(index_rel), i + 1);
2333 
2334  defopclass = GetDefaultOpClass(attform->atttypid,
2335  index_rel->rd_rel->relam);
2336  if (indclass->values[i] != defopclass ||
2337  attform->attcollation != index_rel->rd_indcollation[i] ||
2338  attoptions != (Datum) 0 ||
2339  index_rel->rd_indoption[i] != 0)
2340  ereport(ERROR,
2341  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2342  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2343  errdetail("Cannot create a primary key or unique constraint using such an index."),
2344  parser_errposition(cxt->pstate, constraint->location)));
2345 
2346  constraint->keys = lappend(constraint->keys, makeString(attname));
2347  }
2348  else
2349  constraint->including = lappend(constraint->including, makeString(attname));
2350  }
2351 
2352  /* Close the index relation but keep the lock */
2353  relation_close(index_rel, NoLock);
2354 
2355  index->indexOid = index_oid;
2356  }
2357 
2358  /*
2359  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2360  * IndexElems and operator names. We have to break that apart into
2361  * separate lists.
2362  */
2363  if (constraint->contype == CONSTR_EXCLUSION)
2364  {
2365  foreach(lc, constraint->exclusions)
2366  {
2367  List *pair = (List *) lfirst(lc);
2368  IndexElem *elem;
2369  List *opname;
2370 
2371  Assert(list_length(pair) == 2);
2372  elem = linitial_node(IndexElem, pair);
2373  opname = lsecond_node(List, pair);
2374 
2375  index->indexParams = lappend(index->indexParams, elem);
2376  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2377  }
2378  }
2379 
2380  /*
2381  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2382  *
2383  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2384  * also make sure they are NOT NULL.
2385  */
2386  else
2387  {
2388  foreach(lc, constraint->keys)
2389  {
2390  char *key = strVal(lfirst(lc));
2391  bool found = false;
2392  bool forced_not_null = false;
2393  ColumnDef *column = NULL;
2394  ListCell *columns;
2395  IndexElem *iparam;
2396 
2397  /* Make sure referenced column exists. */
2398  foreach(columns, cxt->columns)
2399  {
2400  column = lfirst_node(ColumnDef, columns);
2401  if (strcmp(column->colname, key) == 0)
2402  {
2403  found = true;
2404  break;
2405  }
2406  }
2407  if (found)
2408  {
2409  /*
2410  * column is defined in the new table. For PRIMARY KEY, we
2411  * can apply the not-null constraint cheaply here ... unless
2412  * the column is marked is_from_type, in which case marking it
2413  * here would be ineffective (see MergeAttributes).
2414  */
2415  if (constraint->contype == CONSTR_PRIMARY &&
2416  !column->is_from_type)
2417  {
2418  column->is_not_null = true;
2419  forced_not_null = true;
2420  }
2421  }
2422  else if (SystemAttributeByName(key) != NULL)
2423  {
2424  /*
2425  * column will be a system column in the new table, so accept
2426  * it. System columns can't ever be null, so no need to worry
2427  * about PRIMARY/not-null constraint.
2428  */
2429  found = true;
2430  }
2431  else if (cxt->inhRelations)
2432  {
2433  /* try inherited tables */
2434  ListCell *inher;
2435 
2436  foreach(inher, cxt->inhRelations)
2437  {
2438  RangeVar *inh = lfirst_node(RangeVar, inher);
2439  Relation rel;
2440  int count;
2441 
2442  rel = table_openrv(inh, AccessShareLock);
2443  /* check user requested inheritance from valid relkind */
2444  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2445  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2446  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2447  ereport(ERROR,
2448  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2449  errmsg("inherited relation \"%s\" is not a table or foreign table",
2450  inh->relname)));
2451  for (count = 0; count < rel->rd_att->natts; count++)
2452  {
2453  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2454  count);
2455  char *inhname = NameStr(inhattr->attname);
2456 
2457  if (inhattr->attisdropped)
2458  continue;
2459  if (strcmp(key, inhname) == 0)
2460  {
2461  found = true;
2462 
2463  /*
2464  * It's tempting to set forced_not_null if the
2465  * parent column is already NOT NULL, but that
2466  * seems unsafe because the column's NOT NULL
2467  * marking might disappear between now and
2468  * execution. Do the runtime check to be safe.
2469  */
2470  break;
2471  }
2472  }
2473  table_close(rel, NoLock);
2474  if (found)
2475  break;
2476  }
2477  }
2478 
2479  /*
2480  * In the ALTER TABLE case, don't complain about index keys not
2481  * created in the command; they may well exist already.
2482  * DefineIndex will complain about them if not.
2483  */
2484  if (!found && !cxt->isalter)
2485  ereport(ERROR,
2486  (errcode(ERRCODE_UNDEFINED_COLUMN),
2487  errmsg("column \"%s\" named in key does not exist", key),
2488  parser_errposition(cxt->pstate, constraint->location)));
2489 
2490  /* Check for PRIMARY KEY(foo, foo) */
2491  foreach(columns, index->indexParams)
2492  {
2493  iparam = (IndexElem *) lfirst(columns);
2494  if (iparam->name && strcmp(key, iparam->name) == 0)
2495  {
2496  if (index->primary)
2497  ereport(ERROR,
2498  (errcode(ERRCODE_DUPLICATE_COLUMN),
2499  errmsg("column \"%s\" appears twice in primary key constraint",
2500  key),
2501  parser_errposition(cxt->pstate, constraint->location)));
2502  else
2503  ereport(ERROR,
2504  (errcode(ERRCODE_DUPLICATE_COLUMN),
2505  errmsg("column \"%s\" appears twice in unique constraint",
2506  key),
2507  parser_errposition(cxt->pstate, constraint->location)));
2508  }
2509  }
2510 
2511  /* OK, add it to the index definition */
2512  iparam = makeNode(IndexElem);
2513  iparam->name = pstrdup(key);
2514  iparam->expr = NULL;
2515  iparam->indexcolname = NULL;
2516  iparam->collation = NIL;
2517  iparam->opclass = NIL;
2518  iparam->opclassopts = NIL;
2519  iparam->ordering = SORTBY_DEFAULT;
2521  index->indexParams = lappend(index->indexParams, iparam);
2522 
2523  /*
2524  * For a primary-key column, also create an item for ALTER TABLE
2525  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2526  */
2527  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2528  {
2529  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2530 
2531  notnullcmd->subtype = AT_SetNotNull;
2532  notnullcmd->name = pstrdup(key);
2533  notnullcmds = lappend(notnullcmds, notnullcmd);
2534  }
2535  }
2536  }
2537 
2538  /*
2539  * Add included columns to index definition. This is much like the
2540  * simple-column-name-list code above, except that we don't worry about
2541  * NOT NULL marking; included columns in a primary key should not be
2542  * forced NOT NULL. We don't complain about duplicate columns, either,
2543  * though maybe we should?
2544  */
2545  foreach(lc, constraint->including)
2546  {
2547  char *key = strVal(lfirst(lc));
2548  bool found = false;
2549  ColumnDef *column = NULL;
2550  ListCell *columns;
2551  IndexElem *iparam;
2552 
2553  foreach(columns, cxt->columns)
2554  {
2555  column = lfirst_node(ColumnDef, columns);
2556  if (strcmp(column->colname, key) == 0)
2557  {
2558  found = true;
2559  break;
2560  }
2561  }
2562 
2563  if (!found)
2564  {
2565  if (SystemAttributeByName(key) != NULL)
2566  {
2567  /*
2568  * column will be a system column in the new table, so accept
2569  * it.
2570  */
2571  found = true;
2572  }
2573  else if (cxt->inhRelations)
2574  {
2575  /* try inherited tables */
2576  ListCell *inher;
2577 
2578  foreach(inher, cxt->inhRelations)
2579  {
2580  RangeVar *inh = lfirst_node(RangeVar, inher);
2581  Relation rel;
2582  int count;
2583 
2584  rel = table_openrv(inh, AccessShareLock);
2585  /* check user requested inheritance from valid relkind */
2586  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2587  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2588  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2589  ereport(ERROR,
2590  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2591  errmsg("inherited relation \"%s\" is not a table or foreign table",
2592  inh->relname)));
2593  for (count = 0; count < rel->rd_att->natts; count++)
2594  {
2595  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2596  count);
2597  char *inhname = NameStr(inhattr->attname);
2598 
2599  if (inhattr->attisdropped)
2600  continue;
2601  if (strcmp(key, inhname) == 0)
2602  {
2603  found = true;
2604  break;
2605  }
2606  }
2607  table_close(rel, NoLock);
2608  if (found)
2609  break;
2610  }
2611  }
2612  }
2613 
2614  /*
2615  * In the ALTER TABLE case, don't complain about index keys not
2616  * created in the command; they may well exist already. DefineIndex
2617  * will complain about them if not.
2618  */
2619  if (!found && !cxt->isalter)
2620  ereport(ERROR,
2621  (errcode(ERRCODE_UNDEFINED_COLUMN),
2622  errmsg("column \"%s\" named in key does not exist", key),
2623  parser_errposition(cxt->pstate, constraint->location)));
2624 
2625  /* OK, add it to the index definition */
2626  iparam = makeNode(IndexElem);
2627  iparam->name = pstrdup(key);
2628  iparam->expr = NULL;
2629  iparam->indexcolname = NULL;
2630  iparam->collation = NIL;
2631  iparam->opclass = NIL;
2632  iparam->opclassopts = NIL;
2633  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2634  }
2635 
2636  /*
2637  * If we found anything that requires run-time SET NOT NULL, build a full
2638  * ALTER TABLE command for that and add it to cxt->alist.
2639  */
2640  if (notnullcmds)
2641  {
2642  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2643 
2644  alterstmt->relation = copyObject(cxt->relation);
2645  alterstmt->cmds = notnullcmds;
2646  alterstmt->objtype = OBJECT_TABLE;
2647  alterstmt->missing_ok = false;
2648 
2649  cxt->alist = lappend(cxt->alist, alterstmt);
2650  }
2651 
2652  return index;
2653 }
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:163
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:240
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:252
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
@ AT_SetNotNull
Definition: parsenodes.h:2358
FormData_pg_attribute
Definition: pg_attribute.h:193
#define linitial_node(type, l)
Definition: pg_list.h:181
#define lsecond_node(type, l)
Definition: pg_list.h:186
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5110
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4997
bool is_from_type
Definition: parsenodes.h:732
List * exclusions
Definition: parsenodes.h:2755
bool reset_default_tblspc
Definition: parsenodes.h:2760
Node * where_clause
Definition: parsenodes.h:2763
char * indexname
Definition: parsenodes.h:2758
char * indexspace
Definition: parsenodes.h:2759
char * access_method
Definition: parsenodes.h:2762
bool nulls_not_distinct
Definition: parsenodes.h:2750
List * including
Definition: parsenodes.h:2753
TupleDesc rd_att
Definition: rel.h:112
Form_pg_index rd_index
Definition: rel.h:192
Oid * rd_indcollation
Definition: rel.h:217
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

References Constraint::access_method, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer(), DEFAULT_INDEX_TYPE, Constraint::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, Constraint::including, index_open(), IndexElem::indexcolname, Constraint::indexname, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, sort-test::key, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, NoLock, Constraint::nulls_not_distinct, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttrNotNull(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), TupleDescAttr, oidvector::values, and Constraint::where_clause.

Referenced by transformIndexConstraints().

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2026 of file parse_utilcmd.c.

2027 {
2028  IndexStmt *index;
2029  List *indexlist = NIL;
2030  List *finalindexlist = NIL;
2031  ListCell *lc;
2032 
2033  /*
2034  * Run through the constraints that need to generate an index. For PRIMARY
2035  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
2036  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
2037  * NULL.
2038  */
2039  foreach(lc, cxt->ixconstraints)
2040  {
2041  Constraint *constraint = lfirst_node(Constraint, lc);
2042 
2043  Assert(constraint->contype == CONSTR_PRIMARY ||
2044  constraint->contype == CONSTR_UNIQUE ||
2045  constraint->contype == CONSTR_EXCLUSION);
2046 
2047  index = transformIndexConstraint(constraint, cxt);
2048 
2049  indexlist = lappend(indexlist, index);
2050  }
2051 
2052  /*
2053  * Scan the index list and remove any redundant index specifications. This
2054  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2055  * strict reading of SQL would suggest raising an error instead, but that
2056  * strikes me as too anal-retentive. - tgl 2001-02-14
2057  *
2058  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2059  * pre-existing indexes, too.
2060  */
2061  if (cxt->pkey != NULL)
2062  {
2063  /* Make sure we keep the PKEY index in preference to others... */
2064  finalindexlist = list_make1(cxt->pkey);
2065  }
2066 
2067  foreach(lc, indexlist)
2068  {
2069  bool keep = true;
2070  ListCell *k;
2071 
2072  index = lfirst(lc);
2073 
2074  /* if it's pkey, it's already in finalindexlist */
2075  if (index == cxt->pkey)
2076  continue;
2077 
2078  foreach(k, finalindexlist)
2079  {
2080  IndexStmt *priorindex = lfirst(k);
2081 
2082  if (equal(index->indexParams, priorindex->indexParams) &&
2083  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2084  equal(index->whereClause, priorindex->whereClause) &&
2085  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2086  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2087  index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2088  index->deferrable == priorindex->deferrable &&
2089  index->initdeferred == priorindex->initdeferred)
2090  {
2091  priorindex->unique |= index->unique;
2092 
2093  /*
2094  * If the prior index is as yet unnamed, and this one is
2095  * named, then transfer the name to the prior index. This
2096  * ensures that if we have named and unnamed constraints,
2097  * we'll use (at least one of) the names for the index.
2098  */
2099  if (priorindex->idxname == NULL)
2100  priorindex->idxname = index->idxname;
2101  keep = false;
2102  break;
2103  }
2104  }
2105 
2106  if (keep)
2107  finalindexlist = lappend(finalindexlist, index);
2108  }
2109 
2110  /*
2111  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
2112  * TABLE SET NOT NULL statement to support a primary key, it's already in
2113  * cxt->alist.
2114  */
2115  cxt->alist = list_concat(cxt->alist, finalindexlist);
2116 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:3372
bool deferrable
Definition: parsenodes.h:3376
List * indexParams
Definition: parsenodes.h:3360
bool initdeferred
Definition: parsenodes.h:3377
List * excludeOpNames
Definition: parsenodes.h:3365
bool nulls_not_distinct
Definition: parsenodes.h:3373
char * idxname
Definition: parsenodes.h:3356
Node * whereClause
Definition: parsenodes.h:3364
char * accessMethod
Definition: parsenodes.h:3358
List * indexIncludingParams
Definition: parsenodes.h:3361

References IndexStmt::accessMethod, CreateStmtContext::alist, Assert, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, IndexStmt::deferrable, equal(), IndexStmt::excludeOpNames, IndexStmt::idxname, IndexStmt::indexIncludingParams, IndexStmt::indexParams, IndexStmt::initdeferred, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, NIL, IndexStmt::nulls_not_distinct, CreateStmtContext::pkey, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexStmt()

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

Definition at line 2778 of file parse_utilcmd.c.

2779 {
2780  ParseState *pstate;
2781  ParseNamespaceItem *nsitem;
2782  ListCell *l;
2783  Relation rel;
2784 
2785  /* Nothing to do if statement already transformed. */
2786  if (stmt->transformed)
2787  return stmt;
2788 
2789  /* Set up pstate */
2790  pstate = make_parsestate(NULL);
2791  pstate->p_sourcetext = queryString;
2792 
2793  /*
2794  * Put the parent table into the rtable so that the expressions can refer
2795  * to its fields without qualification. Caller is responsible for locking
2796  * relation, but we still need to open it.
2797  */
2798  rel = relation_open(relid, NoLock);
2799  nsitem = addRangeTableEntryForRelation(pstate, rel,
2801  NULL, false, true);
2802 
2803  /* no to join list, yes to namespaces */
2804  addNSItemToQuery(pstate, nsitem, false, true, true);
2805 
2806  /* take care of the where clause */
2807  if (stmt->whereClause)
2808  {
2809  stmt->whereClause = transformWhereClause(pstate,
2810  stmt->whereClause,
2812  "WHERE");
2813  /* we have to fix its collations too */
2814  assign_expr_collations(pstate, stmt->whereClause);
2815  }
2816 
2817  /* take care of any index expressions */
2818  foreach(l, stmt->indexParams)
2819  {
2820  IndexElem *ielem = (IndexElem *) lfirst(l);
2821 
2822  if (ielem->expr)
2823  {
2824  /* Extract preliminary index col name before transforming expr */
2825  if (ielem->indexcolname == NULL)
2826  ielem->indexcolname = FigureIndexColname(ielem->expr);
2827 
2828  /* Now do parse transformation of the expression */
2829  ielem->expr = transformExpr(pstate, ielem->expr,
2831 
2832  /* We have to fix its collations too */
2833  assign_expr_collations(pstate, ielem->expr);
2834 
2835  /*
2836  * transformExpr() should have already rejected subqueries,
2837  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2838  * for an index expression.
2839  *
2840  * DefineIndex() will make more checks.
2841  */
2842  }
2843  }
2844 
2845  /*
2846  * Check that only the base rel is mentioned. (This should be dead code
2847  * now that add_missing_from is history.)
2848  */
2849  if (list_length(pstate->p_rtable) != 1)
2850  ereport(ERROR,
2851  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2852  errmsg("index expressions and predicates can refer only to the table being indexed")));
2853 
2854  free_parsestate(pstate);
2855 
2856  /* Close relation */
2857  table_close(rel, NoLock);
2858 
2859  /* Mark statement as successfully transformed */
2860  stmt->transformed = true;
2861 
2862  return stmt;
2863 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:72
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
char * FigureIndexColname(Node *node)
List * p_rtable
Definition: parse_node.h:194

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

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

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1440 of file parse_utilcmd.c.

1441 {
1442  HeapTuple tuple;
1443  TupleDesc tupdesc;
1444  int i;
1445  Oid ofTypeId;
1446 
1447  Assert(ofTypename);
1448 
1449  tuple = typenameType(NULL, ofTypename, NULL);
1450  check_of_type(tuple);
1451  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1452  ofTypename->typeOid = ofTypeId; /* cached for later */
1453 
1454  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1455  for (i = 0; i < tupdesc->natts; i++)
1456  {
1457  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1458  ColumnDef *n;
1459 
1460  if (attr->attisdropped)
1461  continue;
1462 
1463  n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1464  attr->atttypmod, attr->attcollation);
1465  n->is_from_type = true;
1466 
1467  cxt->columns = lappend(cxt->columns, n);
1468  }
1469  ReleaseTupleDesc(tupdesc);
1470 
1471  ReleaseSysCache(tuple);
1472 }
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition: makefuncs.c:492
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:6919
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1833

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

Referenced by transformCreateStmt().

◆ transformPartitionBound()

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

Definition at line 4142 of file parse_utilcmd.c.

4144 {
4145  PartitionBoundSpec *result_spec;
4147  char strategy = get_partition_strategy(key);
4148  int partnatts = get_partition_natts(key);
4149  List *partexprs = get_partition_exprs(key);
4150 
4151  /* Avoid scribbling on input */
4152  result_spec = copyObject(spec);
4153 
4154  if (spec->is_default)
4155  {
4156  /*
4157  * Hash partitioning does not support a default partition; there's no
4158  * use case for it (since the set of partitions to create is perfectly
4159  * defined), and if users do get into it accidentally, it's hard to
4160  * back out from it afterwards.
4161  */
4162  if (strategy == PARTITION_STRATEGY_HASH)
4163  ereport(ERROR,
4164  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4165  errmsg("a hash-partitioned table may not have a default partition")));
4166 
4167  /*
4168  * In case of the default partition, parser had no way to identify the
4169  * partition strategy. Assign the parent's strategy to the default
4170  * partition bound spec.
4171  */
4172  result_spec->strategy = strategy;
4173 
4174  return result_spec;
4175  }
4176 
4177  if (strategy == PARTITION_STRATEGY_HASH)
4178  {
4179  if (spec->strategy != PARTITION_STRATEGY_HASH)
4180  ereport(ERROR,
4181  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4182  errmsg("invalid bound specification for a hash partition"),
4183  parser_errposition(pstate, exprLocation((Node *) spec))));
4184 
4185  if (spec->modulus <= 0)
4186  ereport(ERROR,
4187  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4188  errmsg("modulus for hash partition must be an integer value greater than zero")));
4189 
4190  Assert(spec->remainder >= 0);
4191 
4192  if (spec->remainder >= spec->modulus)
4193  ereport(ERROR,
4194  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4195  errmsg("remainder for hash partition must be less than modulus")));
4196  }
4197  else if (strategy == PARTITION_STRATEGY_LIST)
4198  {
4199  ListCell *cell;
4200  char *colname;
4201  Oid coltype;
4202  int32 coltypmod;
4203  Oid partcollation;
4204 
4205  if (spec->strategy != PARTITION_STRATEGY_LIST)
4206  ereport(ERROR,
4207  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4208  errmsg("invalid bound specification for a list partition"),
4209  parser_errposition(pstate, exprLocation((Node *) spec))));
4210 
4211  /* Get the only column's name in case we need to output an error */
4212  if (key->partattrs[0] != 0)
4213  colname = get_attname(RelationGetRelid(parent),
4214  key->partattrs[0], false);
4215  else
4216  colname = deparse_expression((Node *) linitial(partexprs),
4218  RelationGetRelid(parent)),
4219  false, false);
4220  /* Need its type data too */
4221  coltype = get_partition_col_typid(key, 0);
4222  coltypmod = get_partition_col_typmod(key, 0);
4223  partcollation = get_partition_col_collation(key, 0);
4224 
4225  result_spec->listdatums = NIL;
4226  foreach(cell, spec->listdatums)
4227  {
4228  Node *expr = lfirst(cell);
4229  Const *value;
4230  ListCell *cell2;
4231  bool duplicate;
4232 
4233  value = transformPartitionBoundValue(pstate, expr,
4234  colname, coltype, coltypmod,
4235  partcollation);
4236 
4237  /* Don't add to the result if the value is a duplicate */
4238  duplicate = false;
4239  foreach(cell2, result_spec->listdatums)
4240  {
4241  Const *value2 = lfirst_node(Const, cell2);
4242 
4243  if (equal(value, value2))
4244  {
4245  duplicate = true;
4246  break;
4247  }
4248  }
4249  if (duplicate)
4250  continue;
4251 
4252  result_spec->listdatums = lappend(result_spec->listdatums,
4253  value);
4254  }
4255  }
4256  else if (strategy == PARTITION_STRATEGY_RANGE)
4257  {
4258  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4259  ereport(ERROR,
4260  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4261  errmsg("invalid bound specification for a range partition"),
4262  parser_errposition(pstate, exprLocation((Node *) spec))));
4263 
4264  if (list_length(spec->lowerdatums) != partnatts)
4265  ereport(ERROR,
4266  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4267  errmsg("FROM must specify exactly one value per partitioning column")));
4268  if (list_length(spec->upperdatums) != partnatts)
4269  ereport(ERROR,
4270  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4271  errmsg("TO must specify exactly one value per partitioning column")));
4272 
4273  /*
4274  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4275  * any necessary validation.
4276  */
4277  result_spec->lowerdatums =
4279  parent);
4280  result_spec->upperdatums =
4282  parent);
4283  }
4284  else
4285  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4286 
4287  return result_spec;
4288 }
signed int int32
Definition: c.h:494
static struct @155 value
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1386
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:874
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:872
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:873
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 Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:98
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:71
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3598
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3658

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

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformPartitionBoundValue()

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

Definition at line 4452 of file parse_utilcmd.c.

4455 {
4456  Node *value;
4457 
4458  /* Transform raw parsetree */
4460 
4461  /*
4462  * transformExpr() should have already rejected column references,
4463  * subqueries, aggregates, window functions, and SRFs, based on the
4464  * EXPR_KIND_ of a partition bound expression.
4465  */
4467 
4468  /*
4469  * Coerce to the correct type. This might cause an explicit coercion step
4470  * to be added on top of the expression, which must be evaluated before
4471  * returning the result to the caller.
4472  */
4473  value = coerce_to_target_type(pstate,
4474  value, exprType(value),
4475  colType,
4476  colTypmod,
4479  -1);
4480 
4481  if (value == NULL)
4482  ereport(ERROR,
4483  (errcode(ERRCODE_DATATYPE_MISMATCH),
4484  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4485  format_type_be(colType), colName),
4486  parser_errposition(pstate, exprLocation(val))));
4487 
4488  /*
4489  * Evaluate the expression, if needed, assigning the partition key's data
4490  * type and collation to the resulting Const node.
4491  */
4492  if (!IsA(value, Const))
4493  {
4494  assign_expr_collations(pstate, value);
4495  value = (Node *) expression_planner((Expr *) value);
4496  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4497  partCollation);
4498  if (!IsA(value, Const))
4499  elog(ERROR, "could not evaluate partition bound expression");
4500  }
4501  else
4502  {
4503  /*
4504  * If the expression is already a Const, as is often the case, we can
4505  * skip the rather expensive steps above. But we still have to insert
4506  * the right collation, since coerce_to_target_type doesn't handle
4507  * that.
4508  */
4509  ((Const *) value)->constcollid = partCollation;
4510  }
4511 
4512  /*
4513  * Attach original expression's parse location to the Const, so that
4514  * that's what will be reported for any later errors related to this
4515  * partition bound.
4516  */
4517  ((Const *) value)->location = exprLocation(val);
4518 
4519  return (Const *) value;
4520 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4961
long val
Definition: informix.c:670
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:79
Expr * expression_planner(Expr *expr)
Definition: planner.c:6491
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
@ COERCION_ASSIGNMENT
Definition: primnodes.h:715
bool contain_var_clause(Node *node)
Definition: var.c:403

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(), 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 4089 of file parse_utilcmd.c.

4090 {
4091  Relation parentRel = cxt->rel;
4092 
4093  switch (parentRel->rd_rel->relkind)
4094  {
4095  case RELKIND_PARTITIONED_TABLE:
4096  /* transform the partition bound, if any */
4097  Assert(RelationGetPartitionKey(parentRel) != NULL);
4098  if (bound != NULL)
4099  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
4100  bound);
4101  break;
4102  case RELKIND_PARTITIONED_INDEX:
4103 
4104  /*
4105  * A partitioned index cannot have a partition bound set. ALTER
4106  * INDEX prevents that with its grammar, but not ALTER TABLE.
4107  */
4108  if (bound != NULL)
4109  ereport(ERROR,
4110  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4111  errmsg("\"%s\" is not a partitioned table",
4112  RelationGetRelationName(parentRel))));
4113  break;
4114  case RELKIND_RELATION:
4115  /* the table must be partitioned */
4116  ereport(ERROR,
4117  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4118  errmsg("table \"%s\" is not partitioned",
4119  RelationGetRelationName(parentRel))));
4120  break;
4121  case RELKIND_INDEX:
4122  /* the index must be partitioned */
4123  ereport(ERROR,
4124  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4125  errmsg("index \"%s\" is not partitioned",
4126  RelationGetRelationName(parentRel))));
4127  break;
4128  default:
4129  /* parser shouldn't let this case through */
4130  elog(ERROR, "\"%s\" is not a partitioned table or index",
4131  RelationGetRelationName(parentRel));
4132  break;
4133  }
4134 }
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)

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

Referenced by transformAlterTableStmt(), and transformPartitionCmdForSplit().

◆ transformPartitionCmdForMerge()

static void transformPartitionCmdForMerge ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3326 of file parse_utilcmd.c.

3327 {
3328  Oid defaultPartOid;
3329  Oid partOid;
3330  Relation parent = cxt->rel;
3331  PartitionKey key;
3332  char strategy;
3333  ListCell *listptr,
3334  *listptr2;
3335  bool isDefaultPart = false;
3336  List *partOids = NIL;
3337 
3338  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3339  ereport(ERROR,
3340  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3341  errmsg("\"%s\" is not a partitioned table", RelationGetRelationName(parent))));
3342 
3343  key = RelationGetPartitionKey(parent);
3344  strategy = get_partition_strategy(key);
3345 
3346  if (strategy == PARTITION_STRATEGY_HASH)
3347  ereport(ERROR,
3348  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3349  errmsg("partition of hash-partitioned table cannot be merged")));
3350 
3351  /* Is current partition a DEFAULT partition? */
3352  defaultPartOid = get_default_oid_from_partdesc(
3353  RelationGetPartitionDesc(parent, true));
3354 
3355  foreach(listptr, partcmd->partlist)
3356  {
3357  RangeVar *name = (RangeVar *) lfirst(listptr);
3358 
3359  /* Partitions in the list should have different names. */
3360  for_each_cell(listptr2, partcmd->partlist, lnext(partcmd->partlist, listptr))
3361  {
3362  RangeVar *name2 = (RangeVar *) lfirst(listptr2);
3363 
3364  if (equal(name, name2))
3365  ereport(ERROR,
3366  (errcode(ERRCODE_DUPLICATE_TABLE),
3367  errmsg("partition with name \"%s\" is already used", name->relname)),
3368  parser_errposition(cxt->pstate, name2->location));
3369  }
3370 
3371  /* Search DEFAULT partition in the list. */
3372  partOid = RangeVarGetRelid(name, NoLock, false);
3373  if (partOid == defaultPartOid)
3374  isDefaultPart = true;
3375 
3376  checkPartition(parent, partOid);
3377 
3378  partOids = lappend_oid(partOids, partOid);
3379  }
3380 
3381  /* Allocate bound of resulting partition. */
3382  Assert(partcmd->bound == NULL);
3383  partcmd->bound = makeNode(PartitionBoundSpec);
3384 
3385  /* Fill partition bound. */
3386  partcmd->bound->strategy = strategy;
3387  partcmd->bound->location = -1;
3388  partcmd->bound->is_default = isDefaultPart;
3389  if (!isDefaultPart)
3391  partOids, partcmd->bound,
3392  cxt->pstate);
3393 }
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
static void checkPartition(Relation rel, Oid partRelOid)
void calculate_partition_bound_for_merge(Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
Definition: partbounds.c:5782
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:70
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partdesc.c:459
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438
ParseLoc location
Definition: primnodes.h:94
const char * name

References Assert, PartitionCmd::bound, calculate_partition_bound_for_merge(), checkPartition(), equal(), ereport, errcode(), errmsg(), ERROR, for_each_cell, get_default_oid_from_partdesc(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend_oid(), lfirst, lnext(), PartitionBoundSpec::location, RangeVar::location, makeNode, name, NIL, NoLock, parser_errposition(), PARTITION_STRATEGY_HASH, PartitionCmd::partlist, CreateStmtContext::pstate, RangeVarGetRelid, RelationData::rd_rel, CreateStmtContext::rel, RelationGetPartitionDesc(), RelationGetPartitionKey(), RelationGetRelationName, and PartitionBoundSpec::strategy.

Referenced by transformAlterTableStmt().

◆ transformPartitionCmdForSplit()

static void transformPartitionCmdForSplit ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3287 of file parse_utilcmd.c.

3288 {
3289  Relation parent = cxt->rel;
3290  Oid splitPartOid;
3291  ListCell *listptr;
3292 
3293  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3294  ereport(ERROR,
3295  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3296  errmsg("\"%s\" is not a partitioned table", RelationGetRelationName(parent))));
3297 
3298  /* Transform partition bounds for all partitions in the list: */
3299  foreach(listptr, partcmd->partlist)
3300  {
3301  SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
3302 
3303  cxt->partbound = NULL;
3304  transformPartitionCmd(cxt, sps->bound);
3305  /* Assign transformed value of the partition bound. */
3306  sps->bound = cxt->partbound;
3307  }
3308 
3309  splitPartOid = RangeVarGetRelid(partcmd->name, NoLock, false);
3310 
3311  checkPartition(parent, splitPartOid);
3312 
3313  /* Then we should check partitions with transformed bounds. */
3314  check_partitions_for_split(parent, splitPartOid, partcmd->name, partcmd->partlist, cxt->pstate);
3315 }
void check_partitions_for_split(Relation parent, Oid splitPartOid, RangeVar *splitPartName, List *partlist, ParseState *pstate)
Definition: partbounds.c:5563
RangeVar * name
Definition: parsenodes.h:957
PartitionBoundSpec * bound
Definition: parsenodes.h:948

References SinglePartitionSpec::bound, check_partitions_for_split(), checkPartition(), ereport, errcode(), errmsg(), ERROR, lfirst, PartitionCmd::name, NoLock, CreateStmtContext::partbound, PartitionCmd::partlist, CreateStmtContext::pstate, RangeVarGetRelid, RelationData::rd_rel, CreateStmtContext::rel, RelationGetRelationName, and transformPartitionCmd().

Referenced by transformAlterTableStmt().

◆ transformPartitionRangeBounds()

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

Definition at line 4296 of file parse_utilcmd.c.

4298 {
4299  List *result = NIL;
4301  List *partexprs = get_partition_exprs(key);
4302  ListCell *lc;
4303  int i,
4304  j;
4305 
4306  i = j = 0;
4307  foreach(lc, blist)
4308  {
4309  Node *expr = lfirst(lc);
4310  PartitionRangeDatum *prd = NULL;
4311 
4312  /*
4313  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
4314  * as ColumnRefs.
4315  */
4316  if (IsA(expr, ColumnRef))
4317  {
4318  ColumnRef *cref = (ColumnRef *) expr;
4319  char *cname = NULL;
4320 
4321  /*
4322  * There should be a single field named either "minvalue" or
4323  * "maxvalue".
4324  */
4325  if (list_length(cref->fields) == 1 &&
4326  IsA(linitial(cref->fields), String))
4327  cname = strVal(linitial(cref->fields));
4328 
4329  if (cname == NULL)
4330  {
4331  /*
4332  * ColumnRef is not in the desired single-field-name form. For
4333  * consistency between all partition strategies, let the
4334  * expression transformation report any errors rather than
4335  * doing it ourselves.
4336  */
4337  }
4338  else if (strcmp("minvalue", cname) == 0)
4339  {
4342  prd->value = NULL;
4343  }
4344  else if (strcmp("maxvalue", cname) == 0)
4345  {
4348  prd->value = NULL;
4349  }
4350  }
4351 
4352  if (prd == NULL)
4353  {
4354  char *colname;
4355  Oid coltype;
4356  int32 coltypmod;
4357  Oid partcollation;
4358  Const *value;
4359 
4360  /* Get the column's name in case we need to output an error */
4361  if (key->partattrs[i] != 0)
4362  colname = get_attname(RelationGetRelid(parent),
4363  key->partattrs[i], false);
4364  else
4365  {
4366  colname = deparse_expression((Node *) list_nth(partexprs, j),
4368  RelationGetRelid(parent)),
4369  false, false);
4370  ++j;
4371  }
4372 
4373  /* Need its type data too */
4374  coltype = get_partition_col_typid(key, i);
4375  coltypmod = get_partition_col_typmod(key, i);
4376  partcollation = get_partition_col_collation(key, i);
4377 
4378  value = transformPartitionBoundValue(pstate, expr,
4379  colname,
4380  coltype, coltypmod,
4381  partcollation);
4382  if (value->constisnull)
4383  ereport(ERROR,
4384  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4385  errmsg("cannot specify NULL in range bound")));
4388  prd->value = (Node *) value;
4389  ++i;
4390  }
4391 
4392  prd->location = exprLocation(expr);
4393 
4394  result = lappend(result, prd);
4395  }
4396 
4397  /*
4398  * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
4399  * must be the same.
4400  */
4401  validateInfiniteBounds(pstate, result);
4402 
4403  return result;
4404 }
int j
Definition: isn.c:74
static void validateInfiniteBounds(ParseState *pstate, List *blist)
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition: parsenodes.h:926
@ PARTITION_RANGE_DATUM_VALUE
Definition: parsenodes.h:925
@ PARTITION_RANGE_DATUM_MINVALUE
Definition: parsenodes.h:924
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * fields
Definition: parsenodes.h:294
PartitionRangeDatumKind kind
Definition: parsenodes.h:933
Definition: value.h:64

References deparse_context_for(), deparse_expression(), ereport, errcode(), errmsg(), ERROR, exprLocation(), ColumnRef::fields, get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), i, IsA, j, sort-test::key, PartitionRangeDatum::kind, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionRangeDatum::location, makeNode, NIL, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, strVal, transformPartitionBoundValue(), validateInfiniteBounds(), PartitionRangeDatum::value, and value.

Referenced by transformPartitionBound().

◆ transformRuleStmt()

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

Definition at line 2948 of file parse_utilcmd.c.

2950 {
2951  Relation rel;
2952  ParseState *pstate;
2953  ParseNamespaceItem *oldnsitem;
2954  ParseNamespaceItem *newnsitem;
2955 
2956  /*
2957  * To avoid deadlock, make sure the first thing we do is grab
2958  * AccessExclusiveLock on the target relation. This will be needed by
2959  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2960  * beforehand.
2961  */
2962  rel = table_openrv(stmt->relation, AccessExclusiveLock);
2963 
2964  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2965  ereport(ERROR,
2966  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2967  errmsg("rules on materialized views are not supported")));
2968 
2969  /* Set up pstate */
2970  pstate = make_parsestate(NULL);
2971  pstate->p_sourcetext = queryString;
2972 
2973  /*
2974  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2975  * Set up their ParseNamespaceItems in the main pstate for use in parsing
2976  * the rule qualification.
2977  */
2978  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
2980  makeAlias("old", NIL),
2981  false, false);
2982  newnsitem = addRangeTableEntryForRelation(pstate, rel,
2984  makeAlias("new", NIL),
2985  false, false);
2986 
2987  /*
2988  * They must be in the namespace too for lookup purposes, but only add the
2989  * one(s) that are relevant for the current kind of rule. In an UPDATE
2990  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2991  * there's no need to be so picky for INSERT & DELETE. We do not add them
2992  * to the joinlist.
2993  */
2994  switch (stmt->event)
2995  {
2996  case CMD_SELECT:
2997  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2998  break;
2999  case CMD_UPDATE:
3000  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3001  addNSItemToQuery(pstate, newnsitem, false, true, true);
3002  break;
3003  case CMD_INSERT:
3004  addNSItemToQuery(pstate, newnsitem, false, true, true);
3005  break;
3006  case CMD_DELETE:
3007  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3008  break;
3009  default:
3010  elog(ERROR, "unrecognized event type: %d",
3011  (int) stmt->event);
3012  break;
3013  }
3014 
3015  /* take care of the where clause */
3016  *whereClause = transformWhereClause(pstate,
3017  stmt->whereClause,
3019  "WHERE");
3020  /* we have to fix its collations too */
3021  assign_expr_collations(pstate, *whereClause);
3022 
3023  /* this is probably dead code without add_missing_from: */
3024  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3025  ereport(ERROR,
3026  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3027  errmsg("rule WHERE condition cannot contain references to other relations")));
3028 
3029  /*
3030  * 'instead nothing' rules with a qualification need a query rangetable so
3031  * the rewrite handler can add the negated rule qualification to the
3032  * original query. We create a query with the new command type CMD_NOTHING
3033  * here that is treated specially by the rewrite system.
3034  */
3035  if (stmt->actions == NIL)
3036  {
3037  Query *nothing_qry = makeNode(Query);
3038 
3039  nothing_qry->commandType = CMD_NOTHING;
3040  nothing_qry->rtable = pstate->p_rtable;
3041  nothing_qry->rteperminfos = pstate->p_rteperminfos;
3042  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3043 
3044  *actions = list_make1(nothing_qry);
3045  }
3046  else
3047  {
3048  ListCell *l;
3049  List *newactions = NIL;
3050 
3051  /*
3052  * transform each statement, like parse_sub_analyze()
3053  */
3054  foreach(l, stmt->actions)
3055  {
3056  Node *action = (Node *) lfirst(l);
3057  ParseState *sub_pstate = make_parsestate(NULL);
3058  Query *sub_qry,
3059  *top_subqry;
3060  bool has_old,
3061  has_new;
3062 
3063  /*
3064  * Since outer ParseState isn't parent of inner, have to pass down
3065  * the query text by hand.
3066  */
3067  sub_pstate->p_sourcetext = queryString;
3068 
3069  /*
3070  * Set up OLD/NEW in the rtable for this statement. The entries
3071  * are added only to relnamespace, not varnamespace, because we
3072  * don't want them to be referred to by unqualified field names
3073  * nor "*" in the rule actions. We decide later whether to put
3074  * them in the joinlist.
3075  */
3076  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3078  makeAlias("old", NIL),
3079  false, false);
3080  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3082  makeAlias("new", NIL),
3083  false, false);
3084  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3085  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3086 
3087  /* Transform the rule action statement */
3088  top_subqry = transformStmt(sub_pstate, action);
3089 
3090  /*
3091  * We cannot support utility-statement actions (eg NOTIFY) with
3092  * nonempty rule WHERE conditions, because there's no way to make
3093  * the utility action execute conditionally.
3094  */
3095  if (top_subqry->commandType == CMD_UTILITY &&
3096  *whereClause != NULL)
3097  ereport(ERROR,
3098  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3099  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3100 
3101  /*
3102  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3103  * into the SELECT, and that's what we need to look at. (Ugly
3104  * kluge ... try to fix this when we redesign querytrees.)
3105  */
3106  sub_qry = getInsertSelectQuery(top_subqry, NULL);
3107 
3108  /*
3109  * If the sub_qry is a setop, we cannot attach any qualifications
3110  * to it, because the planner won't notice them. This could
3111  * perhaps be relaxed someday, but for now, we may as well reject
3112  * such a rule immediately.
3113  */
3114  if (sub_qry->setOperations != NULL && *whereClause != NULL)
3115  ereport(ERROR,
3116  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3117  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3118 
3119  /*
3120  * Validate action's use of OLD/NEW, qual too
3121  */
3122  has_old =
3123  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3124  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3125  has_new =
3126  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3127  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3128 
3129  switch (stmt->event)
3130  {
3131  case CMD_SELECT:
3132  if (has_old)
3133  ereport(ERROR,
3134  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3135  errmsg("ON SELECT rule cannot use OLD")));
3136  if (has_new)
3137  ereport(ERROR,
3138  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3139  errmsg("ON SELECT rule cannot use NEW")));
3140  break;
3141  case CMD_UPDATE:
3142  /* both are OK */
3143  break;
3144  case CMD_INSERT:
3145  if (has_old)
3146  ereport(ERROR,
3147  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3148  errmsg("ON INSERT rule cannot use OLD")));
3149  break;
3150  case CMD_DELETE:
3151  if (has_new)
3152  ereport(ERROR,
3153  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3154  errmsg("ON DELETE rule cannot use NEW")));
3155  break;
3156  default:
3157  elog(ERROR, "unrecognized event type: %d",
3158  (int) stmt->event);
3159  break;
3160  }
3161 
3162  /*
3163  * OLD/NEW are not allowed in WITH queries, because they would
3164  * amount to outer references for the WITH, which we disallow.
3165  * However, they were already in the outer rangetable when we
3166  * analyzed the query, so we have to check.
3167  *
3168  * Note that in the INSERT...SELECT case, we need to examine the
3169  * CTE lists of both top_subqry and sub_qry.
3170  *
3171  * Note that we aren't digging into the body of the query looking
3172  * for WITHs in nested sub-SELECTs. A WITH down there can
3173  * legitimately refer to OLD/NEW, because it'd be an
3174