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 (char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionCmd *cmd)
 
static ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *con, 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)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
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))

Referenced by transformConstraintAttrs().

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1186 of file parse_utilcmd.c.

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, CommentStmt::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, TupleConstr::defval, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), i, 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, TupleConstr::num_defval, CommentStmt::object, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, CommentStmt::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, stringToNode(), AlterTableCmd::subtype, table_close(), and TupleDescAttr.

Referenced by ProcessUtilitySlow().

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 
1226  /*
1227  * Process defaults, if required.
1228  */
1229  if ((table_like_clause->options &
1231  constr != NULL)
1232  {
1233  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1234  parent_attno++)
1235  {
1236  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1237  parent_attno - 1);
1238 
1239  /*
1240  * Ignore dropped columns in the parent.
1241  */
1242  if (attribute->attisdropped)
1243  continue;
1244 
1245  /*
1246  * Copy default, if present and it should be copied. We have
1247  * separate options for plain default expressions and GENERATED
1248  * defaults.
1249  */
1250  if (attribute->atthasdef &&
1251  (attribute->attgenerated ?
1252  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1253  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1254  {
1255  Node *this_default = NULL;
1256  AttrDefault *attrdef = constr->defval;
1257  AlterTableCmd *atsubcmd;
1258  bool found_whole_row;
1259 
1260  /* Find default in constraint structure */
1261  for (int i = 0; i < constr->num_defval; i++)
1262  {
1263  if (attrdef[i].adnum == parent_attno)
1264  {
1265  this_default = stringToNode(attrdef[i].adbin);
1266  break;
1267  }
1268  }
1269  if (this_default == NULL)
1270  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1271  parent_attno, RelationGetRelationName(relation));
1272 
1273  atsubcmd = makeNode(AlterTableCmd);
1274  atsubcmd->subtype = AT_CookedColumnDefault;
1275  atsubcmd->num = attmap->attnums[parent_attno - 1];
1276  atsubcmd->def = map_variable_attnos(this_default,
1277  1, 0,
1278  attmap,
1279  InvalidOid,
1280  &found_whole_row);
1281 
1282  /*
1283  * Prevent this for the same reason as for constraints below.
1284  * Note that defaults cannot contain any vars, so it's OK that
1285  * the error message refers to generated columns.
1286  */
1287  if (found_whole_row)
1288  ereport(ERROR,
1289  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1290  errmsg("cannot convert whole-row table reference"),
1291  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1292  NameStr(attribute->attname),
1293  RelationGetRelationName(relation))));
1294 
1295  atsubcmds = lappend(atsubcmds, atsubcmd);
1296  }
1297  }
1298  }
1299 
1300  /*
1301  * Copy CHECK constraints if requested, being careful to adjust attribute
1302  * numbers so they match the child.
1303  */
1304  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1305  constr != NULL)
1306  {
1307  int ccnum;
1308 
1309  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1310  {
1311  char *ccname = constr->check[ccnum].ccname;
1312  char *ccbin = constr->check[ccnum].ccbin;
1313  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1314  Node *ccbin_node;
1315  bool found_whole_row;
1316  Constraint *n;
1317  AlterTableCmd *atsubcmd;
1318 
1319  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1320  1, 0,
1321  attmap,
1322  InvalidOid, &found_whole_row);
1323 
1324  /*
1325  * We reject whole-row variables because the whole point of LIKE
1326  * is that the new table's rowtype might later diverge from the
1327  * parent's. So, while translation might be possible right now,
1328  * it wouldn't be possible to guarantee it would work in future.
1329  */
1330  if (found_whole_row)
1331  ereport(ERROR,
1332  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1333  errmsg("cannot convert whole-row table reference"),
1334  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1335  ccname,
1336  RelationGetRelationName(relation))));
1337 
1338  n = makeNode(Constraint);
1339  n->contype = CONSTR_CHECK;
1340  n->conname = pstrdup(ccname);
1341  n->location = -1;
1342  n->is_no_inherit = ccnoinherit;
1343  n->raw_expr = NULL;
1344  n->cooked_expr = nodeToString(ccbin_node);
1345 
1346  /* We can skip validation, since the new table should be empty. */
1347  n->skip_validation = true;
1348  n->initially_valid = true;
1349 
1350  atsubcmd = makeNode(AlterTableCmd);
1351  atsubcmd->subtype = AT_AddConstraint;
1352  atsubcmd->def = (Node *) n;
1353  atsubcmds = lappend(atsubcmds, atsubcmd);
1354 
1355  /* Copy comment on constraint */
1356  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1358  n->conname, false),
1359  ConstraintRelationId,
1360  0)) != NULL)
1361  {
1362  CommentStmt *stmt = makeNode(CommentStmt);
1363 
1364  stmt->objtype = OBJECT_TABCONSTRAINT;
1365  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1366  makeString(heapRel->relname),
1367  makeString(n->conname));
1368  stmt->comment = comment;
1369 
1370  result = lappend(result, stmt);
1371  }
1372  }
1373  }
1374 
1375  /*
1376  * If we generated any ALTER TABLE actions above, wrap them into a single
1377  * ALTER TABLE command. Stick it at the front of the result, so it runs
1378  * before any CommentStmts we made above.
1379  */
1380  if (atsubcmds)
1381  {
1383 
1384  atcmd->relation = copyObject(heapRel);
1385  atcmd->cmds = atsubcmds;
1386  atcmd->objtype = OBJECT_TABLE;
1387  atcmd->missing_ok = false;
1388  result = lcons(atcmd, result);
1389  }
1390 
1391  /*
1392  * Process indexes if required.
1393  */
1394  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1395  relation->rd_rel->relhasindex)
1396  {
1397  List *parent_indexes;
1398  ListCell *l;
1399 
1400  parent_indexes = RelationGetIndexList(relation);
1401 
1402  foreach(l, parent_indexes)
1403  {
1404  Oid parent_index_oid = lfirst_oid(l);
1405  Relation parent_index;
1406  IndexStmt *index_stmt;
1407 
1408  parent_index = index_open(parent_index_oid, AccessShareLock);
1409 
1410  /* Build CREATE INDEX statement to recreate the parent_index */
1411  index_stmt = generateClonedIndexStmt(heapRel,
1412  parent_index,
1413  attmap,
1414  NULL);
1415 
1416  /* Copy comment on index, if requested */
1417  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1418  {
1419  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1420 
1421  /*
1422  * We make use of IndexStmt's idxcomment option, so as not to
1423  * need to know now what name the index will have.
1424  */
1425  index_stmt->idxcomment = comment;
1426  }
1427 
1428  result = lappend(result, index_stmt);
1429 
1430  index_close(parent_index, AccessShareLock);
1431  }
1432  }
1433 
1434  /* Done with child rel */
1435  table_close(childrel, NoLock);
1436 
1437  /*
1438  * Close the parent rel, but keep our AccessShareLock on it until xact
1439  * commit. That will prevent someone else from deleting or ALTERing the
1440  * parent before the child is committed.
1441  */
1442  table_close(relation, NoLock);
1443 
1444  return result;
1445 }
ObjectType objtype
Definition: parsenodes.h:2780
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Node * raw_expr
Definition: parsenodes.h:2261
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
void * stringToNode(const char *str)
Definition: read.c:89
AlterTableType subtype
Definition: parsenodes.h:1950
char * comment
Definition: parsenodes.h:2782
char * conname
Definition: parsenodes.h:2254
Node * object
Definition: parsenodes.h:2781
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Definition: attmap.h:34
char * schemaname
Definition: primnodes.h:67
AttrDefault * defval
Definition: tupdesc.h:39
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
TupleConstr * constr
Definition: tupdesc.h:85
int errdetail(const char *fmt,...)
Definition: elog.c:1042
char * ccname
Definition: tupdesc.h:30
#define RelationGetRelationName(relation)
Definition: rel.h:511
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
ObjectType objtype
Definition: parsenodes.h:1861
List * lappend(List *list, void *datum)
Definition: list.c:336
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
uint16 num_check
Definition: tupdesc.h:43
#define InvalidOid
Definition: postgres_ext.h:36
bool is_no_inherit
Definition: parsenodes.h:2260
bool initially_valid
Definition: parsenodes.h:2297
#define ereport(elevel,...)
Definition: elog.h:157
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
List * lcons(void *datum, List *list)
Definition: list.c:468
#define makeNode(_type_)
Definition: nodes.h:587
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
AttrNumber * attnums
Definition: attmap.h:36
char * idxcomment
Definition: parsenodes.h:2886
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4573
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
uint16 num_defval
Definition: tupdesc.h:42
int errmsg(const char *fmt,...)
Definition: elog.c:909
RangeVar * relation
Definition: parsenodes.h:1859
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
char * nodeToString(const void *obj)
Definition: outfuncs.c:4542
ConstrType contype
Definition: parsenodes.h:2251
ConstrCheck * check
Definition: tupdesc.h:40
char * cooked_expr
Definition: parsenodes.h:2262
#define copyObject(obj)
Definition: nodes.h:655
Definition: pg_list.h:50
char * ccbin
Definition: tupdesc.h:31
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2296
#define RelationGetRelid(relation)
Definition: rel.h:477
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define lfirst_oid(lc)
Definition: pg_list.h:171
bool ccnoinherit
Definition: tupdesc.h:33

◆ generateClonedExtStatsStmt()

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

Definition at line 1869 of file parse_utilcmd.c.

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, STATEXTOID, stringToNode(), CreateStatsStmt::stxcomment, SysCacheGetAttr(), TextDatumGetCString, and CreateStatsStmt::transformed.

Referenced by transformTableLikeClause().

1871 {
1872  HeapTuple ht_stats;
1873  Form_pg_statistic_ext statsrec;
1874  CreateStatsStmt *stats;
1875  List *stat_types = NIL;
1876  List *def_names = NIL;
1877  bool isnull;
1878  Datum datum;
1879  ArrayType *arr;
1880  char *enabled;
1881  int i;
1882 
1883  Assert(OidIsValid(heapRelid));
1884  Assert(heapRel != NULL);
1885 
1886  /*
1887  * Fetch pg_statistic_ext tuple of source statistics object.
1888  */
1889  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1890  if (!HeapTupleIsValid(ht_stats))
1891  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1892  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1893 
1894  /* Determine which statistics types exist */
1895  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1896  Anum_pg_statistic_ext_stxkind, &isnull);
1897  Assert(!isnull);
1898  arr = DatumGetArrayTypeP(datum);
1899  if (ARR_NDIM(arr) != 1 ||
1900  ARR_HASNULL(arr) ||
1901  ARR_ELEMTYPE(arr) != CHAROID)
1902  elog(ERROR, "stxkind is not a 1-D char array");
1903  enabled = (char *) ARR_DATA_PTR(arr);
1904  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1905  {
1906  if (enabled[i] == STATS_EXT_NDISTINCT)
1907  stat_types = lappend(stat_types, makeString("ndistinct"));
1908  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1909  stat_types = lappend(stat_types, makeString("dependencies"));
1910  else if (enabled[i] == STATS_EXT_MCV)
1911  stat_types = lappend(stat_types, makeString("mcv"));
1912  else if (enabled[i] == STATS_EXT_EXPRESSIONS)
1913  /* expression stats are not exposed to users */
1914  continue;
1915  else
1916  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1917  }
1918 
1919  /* Determine which columns the statistics are on */
1920  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1921  {
1922  StatsElem *selem = makeNode(StatsElem);
1923  AttrNumber attnum = statsrec->stxkeys.values[i];
1924 
1925  selem->name = get_attname(heapRelid, attnum, false);
1926  selem->expr = NULL;
1927 
1928  def_names = lappend(def_names, selem);
1929  }
1930 
1931  /*
1932  * Now handle expressions, if there are any. The order (with respect to
1933  * regular attributes) does not really matter for extended stats, so we
1934  * simply append them after simple column references.
1935  *
1936  * XXX Some places during build/estimation treat expressions as if they
1937  * are before attributes, but for the CREATE command that's entirely
1938  * irrelevant.
1939  */
1940  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1941  Anum_pg_statistic_ext_stxexprs, &isnull);
1942 
1943  if (!isnull)
1944  {
1945  ListCell *lc;
1946  List *exprs = NIL;
1947  char *exprsString;
1948 
1949  exprsString = TextDatumGetCString(datum);
1950  exprs = (List *) stringToNode(exprsString);
1951 
1952  foreach(lc, exprs)
1953  {
1954  StatsElem *selem = makeNode(StatsElem);
1955 
1956  selem->name = NULL;
1957  selem->expr = (Node *) lfirst(lc);
1958 
1959  def_names = lappend(def_names, selem);
1960  }
1961 
1962  pfree(exprsString);
1963  }
1964 
1965  /* finally, build the output node */
1966  stats = makeNode(CreateStatsStmt);
1967  stats->defnames = NULL;
1968  stats->stat_types = stat_types;
1969  stats->exprs = def_names;
1970  stats->relations = list_make1(heapRel);
1971  stats->stxcomment = NULL;
1972  stats->transformed = true; /* don't need transformStatsStmt again */
1973  stats->if_not_exists = false;
1974 
1975  /* Clean up */
1976  ReleaseSysCache(ht_stats);
1977 
1978  return stats;
1979 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
char * name
Definition: parsenodes.h:2930
Definition: nodes.h:539
void * stringToNode(const char *str)
Definition: read.c:89
#define OidIsValid(objectId)
Definition: c.h:710
#define list_make1(x1)
Definition: pg_list.h:206
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Node * expr
Definition: parsenodes.h:2931
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define ARR_HASNULL(a)
Definition: array.h:284
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
int16 attnum
Definition: pg_attribute.h:83
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define ARR_NDIM(a)
Definition: array.h:283
#define elog(elevel,...)
Definition: elog.h:232
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
Definition: pg_list.h:50
#define ARR_ELEMTYPE(a)
Definition: array.h:285
int16 AttrNumber
Definition: attnum.h:21
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ generateClonedIndexStmt()

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

Definition at line 1511 of file parse_utilcmd.c.

References IndexStmt::accessMethod, IndexAmRoutine::amcanorder, AMOID, Assert, attname, attnum, AttributeNumberIsValid, IndexElem::collation, IndexStmt::concurrent, CONSTROID, DatumGetArrayTypeP, DatumGetObjectId, DatumGetPointer, deconstruct_array(), IndexStmt::deferrable, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, 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, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexElem::indexcolname, IndexStmt::indexIncludingParams, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, IndexStmt::initdeferred, InvalidOid, InvalidSubTransactionId, IndexStmt::isconstraint, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, OPEROID, IndexStmt::options, IndexElem::ordering, IndexStmt::primary, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELOID, IndexStmt::reset_default_tblspc, SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), IndexStmt::tableSpace, TextDatumGetCString, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

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

1514 {
1515  Oid source_relid = RelationGetRelid(source_idx);
1516  HeapTuple ht_idxrel;
1517  HeapTuple ht_idx;
1518  HeapTuple ht_am;
1519  Form_pg_class idxrelrec;
1520  Form_pg_index idxrec;
1521  Form_pg_am amrec;
1522  oidvector *indcollation;
1523  oidvector *indclass;
1524  IndexStmt *index;
1525  List *indexprs;
1526  ListCell *indexpr_item;
1527  Oid indrelid;
1528  int keyno;
1529  Oid keycoltype;
1530  Datum datum;
1531  bool isnull;
1532 
1533  if (constraintOid)
1534  *constraintOid = InvalidOid;
1535 
1536  /*
1537  * Fetch pg_class tuple of source index. We can't use the copy in the
1538  * relcache entry because it doesn't include optional fields.
1539  */
1540  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1541  if (!HeapTupleIsValid(ht_idxrel))
1542  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1543  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1544 
1545  /* Fetch pg_index tuple for source index from relcache entry */
1546  ht_idx = source_idx->rd_indextuple;
1547  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1548  indrelid = idxrec->indrelid;
1549 
1550  /* Fetch the pg_am tuple of the index' access method */
1551  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1552  if (!HeapTupleIsValid(ht_am))
1553  elog(ERROR, "cache lookup failed for access method %u",
1554  idxrelrec->relam);
1555  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1556 
1557  /* Extract indcollation from the pg_index tuple */
1558  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1559  Anum_pg_index_indcollation, &isnull);
1560  Assert(!isnull);
1561  indcollation = (oidvector *) DatumGetPointer(datum);
1562 
1563  /* Extract indclass from the pg_index tuple */
1564  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1565  Anum_pg_index_indclass, &isnull);
1566  Assert(!isnull);
1567  indclass = (oidvector *) DatumGetPointer(datum);
1568 
1569  /* Begin building the IndexStmt */
1570  index = makeNode(IndexStmt);
1571  index->relation = heapRel;
1572  index->accessMethod = pstrdup(NameStr(amrec->amname));
1573  if (OidIsValid(idxrelrec->reltablespace))
1574  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1575  else
1576  index->tableSpace = NULL;
1577  index->excludeOpNames = NIL;
1578  index->idxcomment = NULL;
1579  index->indexOid = InvalidOid;
1580  index->oldNode = InvalidOid;
1583  index->unique = idxrec->indisunique;
1584  index->primary = idxrec->indisprimary;
1585  index->transformed = true; /* don't need transformIndexStmt */
1586  index->concurrent = false;
1587  index->if_not_exists = false;
1588  index->reset_default_tblspc = false;
1589 
1590  /*
1591  * We don't try to preserve the name of the source index; instead, just
1592  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1593  * the name, we'd get duplicate-relation-name failures unless the source
1594  * table was in a different schema.)
1595  */
1596  index->idxname = NULL;
1597 
1598  /*
1599  * If the index is marked PRIMARY or has an exclusion condition, it's
1600  * certainly from a constraint; else, if it's not marked UNIQUE, it
1601  * certainly isn't. If it is or might be from a constraint, we have to
1602  * fetch the pg_constraint record.
1603  */
1604  if (index->primary || index->unique || idxrec->indisexclusion)
1605  {
1606  Oid constraintId = get_index_constraint(source_relid);
1607 
1608  if (OidIsValid(constraintId))
1609  {
1610  HeapTuple ht_constr;
1611  Form_pg_constraint conrec;
1612 
1613  if (constraintOid)
1614  *constraintOid = constraintId;
1615 
1616  ht_constr = SearchSysCache1(CONSTROID,
1617  ObjectIdGetDatum(constraintId));
1618  if (!HeapTupleIsValid(ht_constr))
1619  elog(ERROR, "cache lookup failed for constraint %u",
1620  constraintId);
1621  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1622 
1623  index->isconstraint = true;
1624  index->deferrable = conrec->condeferrable;
1625  index->initdeferred = conrec->condeferred;
1626 
1627  /* If it's an exclusion constraint, we need the operator names */
1628  if (idxrec->indisexclusion)
1629  {
1630  Datum *elems;
1631  int nElems;
1632  int i;
1633 
1634  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1635  /* Extract operator OIDs from the pg_constraint tuple */
1636  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1637  Anum_pg_constraint_conexclop,
1638  &isnull);
1639  if (isnull)
1640  elog(ERROR, "null conexclop for constraint %u",
1641  constraintId);
1642 
1644  OIDOID, sizeof(Oid), true, TYPALIGN_INT,
1645  &elems, NULL, &nElems);
1646 
1647  for (i = 0; i < nElems; i++)
1648  {
1649  Oid operid = DatumGetObjectId(elems[i]);
1650  HeapTuple opertup;
1651  Form_pg_operator operform;
1652  char *oprname;
1653  char *nspname;
1654  List *namelist;
1655 
1656  opertup = SearchSysCache1(OPEROID,
1657  ObjectIdGetDatum(operid));
1658  if (!HeapTupleIsValid(opertup))
1659  elog(ERROR, "cache lookup failed for operator %u",
1660  operid);
1661  operform = (Form_pg_operator) GETSTRUCT(opertup);
1662  oprname = pstrdup(NameStr(operform->oprname));
1663  /* For simplicity we always schema-qualify the op name */
1664  nspname = get_namespace_name(operform->oprnamespace);
1665  namelist = list_make2(makeString(nspname),
1666  makeString(oprname));
1667  index->excludeOpNames = lappend(index->excludeOpNames,
1668  namelist);
1669  ReleaseSysCache(opertup);
1670  }
1671  }
1672 
1673  ReleaseSysCache(ht_constr);
1674  }
1675  else
1676  index->isconstraint = false;
1677  }
1678  else
1679  index->isconstraint = false;
1680 
1681  /* Get the index expressions, if any */
1682  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1683  Anum_pg_index_indexprs, &isnull);
1684  if (!isnull)
1685  {
1686  char *exprsString;
1687 
1688  exprsString = TextDatumGetCString(datum);
1689  indexprs = (List *) stringToNode(exprsString);
1690  }
1691  else
1692  indexprs = NIL;
1693 
1694  /* Build the list of IndexElem */
1695  index->indexParams = NIL;
1696  index->indexIncludingParams = NIL;
1697 
1698  indexpr_item = list_head(indexprs);
1699  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1700  {
1701  IndexElem *iparam;
1702  AttrNumber attnum = idxrec->indkey.values[keyno];
1704  keyno);
1705  int16 opt = source_idx->rd_indoption[keyno];
1706 
1707  iparam = makeNode(IndexElem);
1708 
1709  if (AttributeNumberIsValid(attnum))
1710  {
1711  /* Simple index column */
1712  char *attname;
1713 
1714  attname = get_attname(indrelid, attnum, false);
1715  keycoltype = get_atttype(indrelid, attnum);
1716 
1717  iparam->name = attname;
1718  iparam->expr = NULL;
1719  }
1720  else
1721  {
1722  /* Expressional index */
1723  Node *indexkey;
1724  bool found_whole_row;
1725 
1726  if (indexpr_item == NULL)
1727  elog(ERROR, "too few entries in indexprs list");
1728  indexkey = (Node *) lfirst(indexpr_item);
1729  indexpr_item = lnext(indexprs, indexpr_item);
1730 
1731  /* Adjust Vars to match new table's column numbering */
1732  indexkey = map_variable_attnos(indexkey,
1733  1, 0,
1734  attmap,
1735  InvalidOid, &found_whole_row);
1736 
1737  /* As in expandTableLikeClause, reject whole-row variables */
1738  if (found_whole_row)
1739  ereport(ERROR,
1740  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1741  errmsg("cannot convert whole-row table reference"),
1742  errdetail("Index \"%s\" contains a whole-row table reference.",
1743  RelationGetRelationName(source_idx))));
1744 
1745  iparam->name = NULL;
1746  iparam->expr = indexkey;
1747 
1748  keycoltype = exprType(indexkey);
1749  }
1750 
1751  /* Copy the original index column name */
1752  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1753 
1754  /* Add the collation name, if non-default */
1755  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1756 
1757  /* Add the operator class name, if non-default */
1758  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1759  iparam->opclassopts =
1760  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1761 
1762  iparam->ordering = SORTBY_DEFAULT;
1764 
1765  /* Adjust options if necessary */
1766  if (source_idx->rd_indam->amcanorder)
1767  {
1768  /*
1769  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1770  * set non-default settings unnecessarily, though, so as to
1771  * improve the chance of recognizing equivalence to constraint
1772  * indexes.
1773  */
1774  if (opt & INDOPTION_DESC)
1775  {
1776  iparam->ordering = SORTBY_DESC;
1777  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1779  }
1780  else
1781  {
1782  if (opt & INDOPTION_NULLS_FIRST)
1784  }
1785  }
1786 
1787  index->indexParams = lappend(index->indexParams, iparam);
1788  }
1789 
1790  /* Handle included columns separately */
1791  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1792  {
1793  IndexElem *iparam;
1794  AttrNumber attnum = idxrec->indkey.values[keyno];
1796  keyno);
1797 
1798  iparam = makeNode(IndexElem);
1799 
1800  if (AttributeNumberIsValid(attnum))
1801  {
1802  /* Simple index column */
1803  char *attname;
1804 
1805  attname = get_attname(indrelid, attnum, false);
1806 
1807  iparam->name = attname;
1808  iparam->expr = NULL;
1809  }
1810  else
1811  ereport(ERROR,
1812  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1813  errmsg("expressions are not supported in included columns")));
1814 
1815  /* Copy the original index column name */
1816  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1817 
1818  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1819  }
1820  /* Copy reloptions if any */
1821  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1822  Anum_pg_class_reloptions, &isnull);
1823  if (!isnull)
1824  index->options = untransformRelOptions(datum);
1825 
1826  /* If it's a partial index, decompile and append the predicate */
1827  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1828  Anum_pg_index_indpred, &isnull);
1829  if (!isnull)
1830  {
1831  char *pred_str;
1832  Node *pred_tree;
1833  bool found_whole_row;
1834 
1835  /* Convert text string to node tree */
1836  pred_str = TextDatumGetCString(datum);
1837  pred_tree = (Node *) stringToNode(pred_str);
1838 
1839  /* Adjust Vars to match new table's column numbering */
1840  pred_tree = map_variable_attnos(pred_tree,
1841  1, 0,
1842  attmap,
1843  InvalidOid, &found_whole_row);
1844 
1845  /* As in expandTableLikeClause, reject whole-row variables */
1846  if (found_whole_row)
1847  ereport(ERROR,
1848  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1849  errmsg("cannot convert whole-row table reference"),
1850  errdetail("Index \"%s\" contains a whole-row table reference.",
1851  RelationGetRelationName(source_idx))));
1852 
1853  index->whereClause = pred_tree;
1854  }
1855 
1856  /* Clean up */
1857  ReleaseSysCache(ht_idxrel);
1858  ReleaseSysCache(ht_am);
1859 
1860  return index;
1861 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
bool deferrable
Definition: parsenodes.h:2895
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:660
bool primary
Definition: parsenodes.h:2893
struct IndexAmRoutine * rd_indam
Definition: rel.h:201
int16 * rd_indoption
Definition: rel.h:206
SortByDir ordering
Definition: parsenodes.h:720
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2883
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2889
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define RelationGetDescr(relation)
Definition: rel.h:503
char * tableSpace
Definition: parsenodes.h:2879
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:544
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Node * whereClause
Definition: parsenodes.h:2884
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
void * stringToNode(const char *str)
Definition: read.c:89
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
List * opclassopts
Definition: parsenodes.h:719
struct HeapTupleData * rd_indextuple
Definition: rel.h:189
List * indexIncludingParams
Definition: parsenodes.h:2881
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2887
Node * expr
Definition: parsenodes.h:715
RangeVar * relation
Definition: parsenodes.h:2877
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:995
SortByNulls nulls_ordering
Definition: parsenodes.h:721
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
NameData attname
Definition: pg_attribute.h:41
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
bool transformed
Definition: parsenodes.h:2897
int errdetail(const char *fmt,...)
Definition: elog.c:1042
char * indexcolname
Definition: parsenodes.h:716
#define RelationGetRelationName(relation)
Definition: rel.h:511
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:904
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2890
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:938
List * lappend(List *list, void *datum)
Definition: list.c:336
char * idxname
Definition: parsenodes.h:2876
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:83
bool reset_default_tblspc
Definition: parsenodes.h:2900
bool if_not_exists
Definition: parsenodes.h:2899
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
bool unique
Definition: parsenodes.h:2892
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1325
char * accessMethod
Definition: parsenodes.h:2878
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
List * opclass
Definition: parsenodes.h:718
#define makeNode(_type_)
Definition: nodes.h:587
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2880
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2885
bool initdeferred
Definition: parsenodes.h:2896
bool amcanorder
Definition: amapi.h:220
char * name
Definition: parsenodes.h:714
char * idxcomment
Definition: parsenodes.h:2886
#define InvalidSubTransactionId
Definition: c.h:593
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define DatumGetPointer(X)
Definition: postgres.h:593
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3490
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
bool concurrent
Definition: parsenodes.h:2898
bool isconstraint
Definition: parsenodes.h:2894
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1477
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
List * collation
Definition: parsenodes.h:717
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:477
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ 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 359 of file parse_utilcmd.c.

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_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::schemaname, CreateSeqStmt::sequence, AlterSeqStmt::sequence, and CreateStmtContext::stmtType.

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

363 {
364  ListCell *option;
365  DefElem *nameEl = NULL;
366  Oid snamespaceid;
367  char *snamespace;
368  char *sname;
369  CreateSeqStmt *seqstmt;
370  AlterSeqStmt *altseqstmt;
371  List *attnamelist;
372  int nameEl_idx = -1;
373 
374  /*
375  * Determine namespace and name to use for the sequence.
376  *
377  * First, check if a sequence name was passed in as an option. This is
378  * used by pg_dump. Else, generate a name.
379  *
380  * Although we use ChooseRelationName, it's not guaranteed that the
381  * selected sequence name won't conflict; given sufficiently long field
382  * names, two different serial columns in the same table could be assigned
383  * the same sequence name, and we'd not notice since we aren't creating
384  * the sequence quite yet. In practice this seems quite unlikely to be a
385  * problem, especially since few people would need two serial columns in
386  * one table.
387  */
388  foreach(option, seqoptions)
389  {
390  DefElem *defel = lfirst_node(DefElem, option);
391 
392  if (strcmp(defel->defname, "sequence_name") == 0)
393  {
394  if (nameEl)
395  errorConflictingDefElem(defel, cxt->pstate);
396  nameEl = defel;
397  nameEl_idx = foreach_current_index(option);
398  }
399  }
400 
401  if (nameEl)
402  {
404 
405  snamespace = rv->schemaname;
406  if (!snamespace)
407  {
408  /* Given unqualified SEQUENCE NAME, select namespace */
409  if (cxt->rel)
410  snamespaceid = RelationGetNamespace(cxt->rel);
411  else
412  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
413  snamespace = get_namespace_name(snamespaceid);
414  }
415  sname = rv->relname;
416  /* Remove the SEQUENCE NAME item from seqoptions */
417  seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
418  }
419  else
420  {
421  if (cxt->rel)
422  snamespaceid = RelationGetNamespace(cxt->rel);
423  else
424  {
425  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
426  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
427  }
428  snamespace = get_namespace_name(snamespaceid);
429  sname = ChooseRelationName(cxt->relation->relname,
430  column->colname,
431  "seq",
432  snamespaceid,
433  false);
434  }
435 
436  ereport(DEBUG1,
437  (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
438  cxt->stmtType, sname,
439  cxt->relation->relname, column->colname)));
440 
441  /*
442  * Build a CREATE SEQUENCE command to create the sequence object, and add
443  * it to the list of things to be done before this CREATE/ALTER TABLE.
444  */
445  seqstmt = makeNode(CreateSeqStmt);
446  seqstmt->for_identity = for_identity;
447  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
448  seqstmt->options = seqoptions;
449 
450  /*
451  * If a sequence data type was specified, add it to the options. Prepend
452  * to the list rather than append; in case a user supplied their own AS
453  * clause, the "redundant options" error will point to their occurrence,
454  * not our synthetic one.
455  */
456  if (seqtypid)
457  seqstmt->options = lcons(makeDefElem("as",
458  (Node *) makeTypeNameFromOid(seqtypid, -1),
459  -1),
460  seqstmt->options);
461 
462  /*
463  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
464  * the table's owner. The current user might be someone else (perhaps a
465  * superuser, or someone who's only a member of the owning role), but the
466  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
467  * exactly the same owning role.
468  */
469  if (cxt->rel)
470  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
471  else
472  seqstmt->ownerId = InvalidOid;
473 
474  cxt->blist = lappend(cxt->blist, seqstmt);
475 
476  /*
477  * Store the identity sequence name that we decided on. ALTER TABLE ...
478  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
479  * with values from the sequence, while the association of the sequence
480  * with the table is not set until after the ALTER TABLE.
481  */
482  column->identitySequence = seqstmt->sequence;
483 
484  /*
485  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
486  * owned by this column, and add it to the appropriate list of things to
487  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
488  * COLUMN, it must be done after the statement because we don't know the
489  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
490  * we can do the marking immediately, which improves some ALTER TABLE
491  * behaviors.
492  */
493  altseqstmt = makeNode(AlterSeqStmt);
494  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
495  attnamelist = list_make3(makeString(snamespace),
496  makeString(cxt->relation->relname),
497  makeString(column->colname));
498  altseqstmt->options = list_make1(makeDefElem("owned_by",
499  (Node *) attnamelist, -1));
500  altseqstmt->for_identity = for_identity;
501 
502  if (col_exists)
503  cxt->blist = lappend(cxt->blist, altseqstmt);
504  else
505  cxt->alist = lappend(cxt->alist, altseqstmt);
506 
507  if (snamespace_p)
508  *snamespace_p = snamespace;
509  if (sname_p)
510  *sname_p = sname;
511 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
Definition: nodes.h:539
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3107
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2284
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:642
List * options
Definition: parsenodes.h:2656
char * schemaname
Definition: primnodes.h:67
#define list_make1(x1)
Definition: pg_list.h:206
RangeVar * identitySequence
Definition: parsenodes.h:669
ParseState * pstate
Definition: parse_utilcmd.c:75
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:77
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
Node * arg
Definition: parsenodes.h:747
List * lappend(List *list, void *datum)
Definition: list.c:336
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2655
#define ereport(elevel,...)
Definition: elog.h:157
RangeVar * sequence
Definition: parsenodes.h:2645
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
List * lcons(void *datum, List *list)
Definition: list.c:468
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define makeNode(_type_)
Definition: nodes.h:587
const char * stmtType
Definition: parse_utilcmd.c:76
bool for_identity
Definition: parsenodes.h:2657
char * defname
Definition: parsenodes.h:746
char * colname
Definition: parsenodes.h:658
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:711
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:450
List * options
Definition: parsenodes.h:2646
#define foreach_current_index(cell)
Definition: pg_list.h:382
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ get_collation()

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

Definition at line 1988 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1989 {
1990  List *result;
1991  HeapTuple ht_coll;
1992  Form_pg_collation coll_rec;
1993  char *nsp_name;
1994  char *coll_name;
1995 
1996  if (!OidIsValid(collation))
1997  return NIL; /* easy case */
1998  if (collation == get_typcollation(actual_datatype))
1999  return NIL; /* just let it default */
2000 
2001  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2002  if (!HeapTupleIsValid(ht_coll))
2003  elog(ERROR, "cache lookup failed for collation %u", collation);
2004  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
2005 
2006  /* For simplicity, we always schema-qualify the name */
2007  nsp_name = get_namespace_name(coll_rec->collnamespace);
2008  coll_name = pstrdup(NameStr(coll_rec->collname));
2009  result = list_make2(makeString(nsp_name), makeString(coll_name));
2010 
2011  ReleaseSysCache(ht_coll);
2012  return result;
2013 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define OidIsValid(objectId)
Definition: c.h:710
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3003
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:56
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
Definition: pg_list.h:50

◆ get_opclass()

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

Definition at line 2022 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

2023 {
2024  List *result = NIL;
2025  HeapTuple ht_opc;
2026  Form_pg_opclass opc_rec;
2027 
2028  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2029  if (!HeapTupleIsValid(ht_opc))
2030  elog(ERROR, "cache lookup failed for opclass %u", opclass);
2031  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2032 
2033  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2034  {
2035  /* For simplicity, we always schema-qualify the name */
2036  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2037  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2038 
2039  result = list_make2(makeString(nsp_name), makeString(opc_name));
2040  }
2041 
2042  ReleaseSysCache(ht_opc);
2043  return result;
2044 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2089
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
Definition: pg_list.h:50

◆ setSchemaName()

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

Definition at line 3919 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3920 {
3921  if (*stmt_schema_name == NULL)
3922  *stmt_schema_name = context_schema;
3923  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3924  ereport(ERROR,
3925  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3926  errmsg("CREATE specifies a schema (%s) "
3927  "different from the one being created (%s)",
3928  *stmt_schema_name, context_schema)));
3929 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ transformAlterTableStmt()

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

Definition at line 3285 of file parse_utilcmd.c.

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, 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, IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

3288 {
3289  Relation rel;
3290  TupleDesc tupdesc;
3291  ParseState *pstate;
3292  CreateStmtContext cxt;
3293  List *save_alist;
3294  ListCell *lcmd,
3295  *l;
3296  List *newcmds = NIL;
3297  bool skipValidation = true;
3298  AlterTableCmd *newcmd;
3299  ParseNamespaceItem *nsitem;
3300 
3301  /* Caller is responsible for locking the relation */
3302  rel = relation_open(relid, NoLock);
3303  tupdesc = RelationGetDescr(rel);
3304 
3305  /* Set up pstate */
3306  pstate = make_parsestate(NULL);
3307  pstate->p_sourcetext = queryString;
3308  nsitem = addRangeTableEntryForRelation(pstate,
3309  rel,
3311  NULL,
3312  false,
3313  true);
3314  addNSItemToQuery(pstate, nsitem, false, true, true);
3315 
3316  /* Set up CreateStmtContext */
3317  cxt.pstate = pstate;
3318  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3319  {
3320  cxt.stmtType = "ALTER FOREIGN TABLE";
3321  cxt.isforeign = true;
3322  }
3323  else
3324  {
3325  cxt.stmtType = "ALTER TABLE";
3326  cxt.isforeign = false;
3327  }
3328  cxt.relation = stmt->relation;
3329  cxt.rel = rel;
3330  cxt.inhRelations = NIL;
3331  cxt.isalter = true;
3332  cxt.columns = NIL;
3333  cxt.ckconstraints = NIL;
3334  cxt.fkconstraints = NIL;
3335  cxt.ixconstraints = NIL;
3336  cxt.likeclauses = NIL;
3337  cxt.extstats = NIL;
3338  cxt.blist = NIL;
3339  cxt.alist = NIL;
3340  cxt.pkey = NULL;
3341  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3342  cxt.partbound = NULL;
3343  cxt.ofType = false;
3344 
3345  /*
3346  * Transform ALTER subcommands that need it (most don't). These largely
3347  * re-use code from CREATE TABLE.
3348  */
3349  foreach(lcmd, stmt->cmds)
3350  {
3351  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3352 
3353  switch (cmd->subtype)
3354  {
3355  case AT_AddColumn:
3356  case AT_AddColumnRecurse:
3357  {
3358  ColumnDef *def = castNode(ColumnDef, cmd->def);
3359 
3360  transformColumnDefinition(&cxt, def);
3361 
3362  /*
3363  * If the column has a non-null default, we can't skip
3364  * validation of foreign keys.
3365  */
3366  if (def->raw_default != NULL)
3367  skipValidation = false;
3368 
3369  /*
3370  * All constraints are processed in other ways. Remove the
3371  * original list
3372  */
3373  def->constraints = NIL;
3374 
3375  newcmds = lappend(newcmds, cmd);
3376  break;
3377  }
3378 
3379  case AT_AddConstraint:
3381 
3382  /*
3383  * The original AddConstraint cmd node doesn't go to newcmds
3384  */
3385  if (IsA(cmd->def, Constraint))
3386  {
3387  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3388  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3389  skipValidation = false;
3390  }
3391  else
3392  elog(ERROR, "unrecognized node type: %d",
3393  (int) nodeTag(cmd->def));
3394  break;
3395 
3396  case AT_AlterColumnType:
3397  {
3398  ColumnDef *def = castNode(ColumnDef, cmd->def);
3400 
3401  /*
3402  * For ALTER COLUMN TYPE, transform the USING clause if
3403  * one was specified.
3404  */
3405  if (def->raw_default)
3406  {
3407  def->cooked_default =
3408  transformExpr(pstate, def->raw_default,
3410  }
3411 
3412  /*
3413  * For identity column, create ALTER SEQUENCE command to
3414  * change the data type of the sequence.
3415  */
3416  attnum = get_attnum(relid, cmd->name);
3417  if (attnum == InvalidAttrNumber)
3418  ereport(ERROR,
3419  (errcode(ERRCODE_UNDEFINED_COLUMN),
3420  errmsg("column \"%s\" of relation \"%s\" does not exist",
3421  cmd->name, RelationGetRelationName(rel))));
3422 
3423  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3424  {
3425  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3426  Oid typeOid = typenameTypeId(pstate, def->typeName);
3427  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3428 
3429  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3430  get_rel_name(seq_relid),
3431  -1);
3432  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3433  altseqstmt->for_identity = true;
3434  cxt.blist = lappend(cxt.blist, altseqstmt);
3435  }
3436 
3437  newcmds = lappend(newcmds, cmd);
3438  break;
3439  }
3440 
3441  case AT_AddIdentity:
3442  {
3443  Constraint *def = castNode(Constraint, cmd->def);
3444  ColumnDef *newdef = makeNode(ColumnDef);
3446 
3447  newdef->colname = cmd->name;
3448  newdef->identity = def->generated_when;
3449  cmd->def = (Node *) newdef;
3450 
3451  attnum = get_attnum(relid, cmd->name);
3452  if (attnum == InvalidAttrNumber)
3453  ereport(ERROR,
3454  (errcode(ERRCODE_UNDEFINED_COLUMN),
3455  errmsg("column \"%s\" of relation \"%s\" does not exist",
3456  cmd->name, RelationGetRelationName(rel))));
3457 
3458  generateSerialExtraStmts(&cxt, newdef,
3459  get_atttype(relid, attnum),
3460  def->options, true, true,
3461  NULL, NULL);
3462 
3463  newcmds = lappend(newcmds, cmd);
3464  break;
3465  }
3466 
3467  case AT_SetIdentity:
3468  {
3469  /*
3470  * Create an ALTER SEQUENCE statement for the internal
3471  * sequence of the identity column.
3472  */
3473  ListCell *lc;
3474  List *newseqopts = NIL;
3475  List *newdef = NIL;
3477  Oid seq_relid;
3478 
3479  /*
3480  * Split options into those handled by ALTER SEQUENCE and
3481  * those for ALTER TABLE proper.
3482  */
3483  foreach(lc, castNode(List, cmd->def))
3484  {
3485  DefElem *def = lfirst_node(DefElem, lc);
3486 
3487  if (strcmp(def->defname, "generated") == 0)
3488  newdef = lappend(newdef, def);
3489  else
3490  newseqopts = lappend(newseqopts, def);
3491  }
3492 
3493  attnum = get_attnum(relid, cmd->name);
3494  if (attnum == InvalidAttrNumber)
3495  ereport(ERROR,
3496  (errcode(ERRCODE_UNDEFINED_COLUMN),
3497  errmsg("column \"%s\" of relation \"%s\" does not exist",
3498  cmd->name, RelationGetRelationName(rel))));
3499 
3500  seq_relid = getIdentitySequence(relid, attnum, true);
3501 
3502  if (seq_relid)
3503  {
3504  AlterSeqStmt *seqstmt;
3505 
3506  seqstmt = makeNode(AlterSeqStmt);
3508  get_rel_name(seq_relid), -1);
3509  seqstmt->options = newseqopts;
3510  seqstmt->for_identity = true;
3511  seqstmt->missing_ok = false;
3512 
3513  cxt.blist = lappend(cxt.blist, seqstmt);
3514  }
3515 
3516  /*
3517  * If column was not an identity column, we just let the
3518  * ALTER TABLE command error out later. (There are cases
3519  * this fails to cover, but we'll need to restructure
3520  * where creation of the sequence dependency linkage
3521  * happens before we can fix it.)
3522  */
3523 
3524  cmd->def = (Node *) newdef;
3525  newcmds = lappend(newcmds, cmd);
3526  break;
3527  }
3528 
3529  case AT_AttachPartition:
3530  case AT_DetachPartition:
3531  {
3532  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3533 
3534  transformPartitionCmd(&cxt, partcmd);
3535  /* assign transformed value of the partition bound */
3536  partcmd->bound = cxt.partbound;
3537  }
3538 
3539  newcmds = lappend(newcmds, cmd);
3540  break;
3541 
3542  default:
3543 
3544  /*
3545  * Currently, we shouldn't actually get here for subcommand
3546  * types that don't require transformation; but if we do, just
3547  * emit them unchanged.
3548  */
3549  newcmds = lappend(newcmds, cmd);
3550  break;
3551  }
3552  }
3553 
3554  /*
3555  * Transfer anything we already have in cxt.alist into save_alist, to keep
3556  * it separate from the output of transformIndexConstraints.
3557  */
3558  save_alist = cxt.alist;
3559  cxt.alist = NIL;
3560 
3561  /* Postprocess constraints */
3563  transformFKConstraints(&cxt, skipValidation, true);
3564  transformCheckConstraints(&cxt, false);
3565 
3566  /*
3567  * Push any index-creation commands into the ALTER, so that they can be
3568  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3569  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3570  * subcommand has already been through transformIndexStmt.
3571  */
3572  foreach(l, cxt.alist)
3573  {
3574  Node *istmt = (Node *) lfirst(l);
3575 
3576  /*
3577  * We assume here that cxt.alist contains only IndexStmts and possibly
3578  * ALTER TABLE SET NOT NULL statements generated from primary key
3579  * constraints. We absorb the subcommands of the latter directly.
3580  */
3581  if (IsA(istmt, IndexStmt))
3582  {
3583  IndexStmt *idxstmt = (IndexStmt *) istmt;
3584 
3585  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3586  newcmd = makeNode(AlterTableCmd);
3588  newcmd->def = (Node *) idxstmt;
3589  newcmds = lappend(newcmds, newcmd);
3590  }
3591  else if (IsA(istmt, AlterTableStmt))
3592  {
3593  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3594 
3595  newcmds = list_concat(newcmds, alterstmt->cmds);
3596  }
3597  else
3598  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3599  }
3600  cxt.alist = NIL;
3601 
3602  /* Append any CHECK or FK constraints to the commands list */
3603  foreach(l, cxt.ckconstraints)
3604  {
3605  newcmd = makeNode(AlterTableCmd);
3606  newcmd->subtype = AT_AddConstraint;
3607  newcmd->def = (Node *) lfirst(l);
3608  newcmds = lappend(newcmds, newcmd);
3609  }
3610  foreach(l, cxt.fkconstraints)
3611  {
3612  newcmd = makeNode(AlterTableCmd);
3613  newcmd->subtype = AT_AddConstraint;
3614  newcmd->def = (Node *) lfirst(l);
3615  newcmds = lappend(newcmds, newcmd);
3616  }
3617 
3618  /* Append extended statistic objects */
3620 
3621  /* Close rel */
3622  relation_close(rel, NoLock);
3623 
3624  /*
3625  * Output results.
3626  */
3627  stmt->cmds = newcmds;
3628 
3629  *beforeStmts = cxt.blist;
3630  *afterStmts = list_concat(cxt.alist, save_alist);
3631 
3632  return stmt;
3633 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
char generated_when
Definition: parsenodes.h:2263
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:503
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
char identity
Definition: parsenodes.h:668
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:674
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:698
AlterTableType subtype
Definition: parsenodes.h:1950
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:880
#define OidIsValid(objectId)
Definition: c.h:710
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2656
List * options
Definition: parsenodes.h:2275
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:206
ParseState * pstate
Definition: parse_utilcmd.c:75
Node * cooked_default
Definition: parsenodes.h:667
Oid indexOid
Definition: parsenodes.h:2887
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
#define RelationGetRelationName(relation)
Definition: rel.h:511
const char * p_sourcetext
Definition: parse_node.h:181
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:938
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
Node * raw_default
Definition: parsenodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:336
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
RangeVar * sequence
Definition: parsenodes.h:2655
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:587
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:875
TypeName * typeName
Definition: parsenodes.h:659
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:544
const char * stmtType
Definition: parse_utilcmd.c:76
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:909
RangeVar * relation
Definition: parsenodes.h:1859
#define elog(elevel,...)
Definition: elog.h:232
bool for_identity
Definition: parsenodes.h:2657
char * defname
Definition: parsenodes.h:746
char * colname
Definition: parsenodes.h:658
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2705 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2706 {
2707  ListCell *ckclist;
2708 
2709  if (cxt->ckconstraints == NIL)
2710  return;
2711 
2712  /*
2713  * If creating a new table (but not a foreign table), we can safely skip
2714  * validation of check constraints, and nonetheless mark them valid. (This
2715  * will override any user-supplied NOT VALID flag.)
2716  */
2717  if (skipValidation)
2718  {
2719  foreach(ckclist, cxt->ckconstraints)
2720  {
2721  Constraint *constraint = (Constraint *) lfirst(ckclist);
2722 
2723  constraint->skip_validation = true;
2724  constraint->initially_valid = true;
2725  }
2726  }
2727 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2297
#define lfirst(lc)
Definition: pg_list.h:169
bool skip_validation
Definition: parsenodes.h:2296

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 519 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, 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, OBJECT_FOREIGN_TABLE, AlterTableStmt::objtype, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, AlterTableStmt::relation, ReleaseSysCache(), RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

520 {
521  bool is_serial;
522  bool saw_nullable;
523  bool saw_default;
524  bool saw_identity;
525  bool saw_generated;
526  ListCell *clist;
527 
528  cxt->columns = lappend(cxt->columns, column);
529 
530  /* Check for SERIAL pseudo-types */
531  is_serial = false;
532  if (column->typeName
533  && list_length(column->typeName->names) == 1
534  && !column->typeName->pct_type)
535  {
536  char *typname = strVal(linitial(column->typeName->names));
537 
538  if (strcmp(typname, "smallserial") == 0 ||
539  strcmp(typname, "serial2") == 0)
540  {
541  is_serial = true;
542  column->typeName->names = NIL;
543  column->typeName->typeOid = INT2OID;
544  }
545  else if (strcmp(typname, "serial") == 0 ||
546  strcmp(typname, "serial4") == 0)
547  {
548  is_serial = true;
549  column->typeName->names = NIL;
550  column->typeName->typeOid = INT4OID;
551  }
552  else if (strcmp(typname, "bigserial") == 0 ||
553  strcmp(typname, "serial8") == 0)
554  {
555  is_serial = true;
556  column->typeName->names = NIL;
557  column->typeName->typeOid = INT8OID;
558  }
559 
560  /*
561  * We have to reject "serial[]" explicitly, because once we've set
562  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
563  * special coding for serial(typmod) though.
564  */
565  if (is_serial && column->typeName->arrayBounds != NIL)
566  ereport(ERROR,
567  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
568  errmsg("array of serial is not implemented"),
570  column->typeName->location)));
571  }
572 
573  /* Do necessary work on the column type declaration */
574  if (column->typeName)
575  transformColumnType(cxt, column);
576 
577  /* Special actions for SERIAL pseudo-types */
578  if (is_serial)
579  {
580  char *snamespace;
581  char *sname;
582  char *qstring;
583  A_Const *snamenode;
584  TypeCast *castnode;
585  FuncCall *funccallnode;
586  Constraint *constraint;
587 
588  generateSerialExtraStmts(cxt, column,
589  column->typeName->typeOid, NIL,
590  false, false,
591  &snamespace, &sname);
592 
593  /*
594  * Create appropriate constraints for SERIAL. We do this in full,
595  * rather than shortcutting, so that we will detect any conflicting
596  * constraints the user wrote (like a different DEFAULT).
597  *
598  * Create an expression tree representing the function call
599  * nextval('sequencename'). We cannot reduce the raw tree to cooked
600  * form until after the sequence is created, but there's no need to do
601  * so.
602  */
603  qstring = quote_qualified_identifier(snamespace, sname);
604  snamenode = makeNode(A_Const);
605  snamenode->val.type = T_String;
606  snamenode->val.val.str = qstring;
607  snamenode->location = -1;
608  castnode = makeNode(TypeCast);
609  castnode->typeName = SystemTypeName("regclass");
610  castnode->arg = (Node *) snamenode;
611  castnode->location = -1;
612  funccallnode = makeFuncCall(SystemFuncName("nextval"),
613  list_make1(castnode),
615  -1);
616  constraint = makeNode(Constraint);
617  constraint->contype = CONSTR_DEFAULT;
618  constraint->location = -1;
619  constraint->raw_expr = (Node *) funccallnode;
620  constraint->cooked_expr = NULL;
621  column->constraints = lappend(column->constraints, constraint);
622 
623  constraint = makeNode(Constraint);
624  constraint->contype = CONSTR_NOTNULL;
625  constraint->location = -1;
626  column->constraints = lappend(column->constraints, constraint);
627  }
628 
629  /* Process column constraints, if any... */
631 
632  saw_nullable = false;
633  saw_default = false;
634  saw_identity = false;
635  saw_generated = false;
636 
637  foreach(clist, column->constraints)
638  {
639  Constraint *constraint = lfirst_node(Constraint, clist);
640 
641  switch (constraint->contype)
642  {
643  case CONSTR_NULL:
644  if (saw_nullable && column->is_not_null)
645  ereport(ERROR,
646  (errcode(ERRCODE_SYNTAX_ERROR),
647  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
648  column->colname, cxt->relation->relname),
650  constraint->location)));
651  column->is_not_null = false;
652  saw_nullable = true;
653  break;
654 
655  case CONSTR_NOTNULL:
656  if (saw_nullable && !column->is_not_null)
657  ereport(ERROR,
658  (errcode(ERRCODE_SYNTAX_ERROR),
659  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
660  column->colname, cxt->relation->relname),
662  constraint->location)));
663  column->is_not_null = true;
664  saw_nullable = true;
665  break;
666 
667  case CONSTR_DEFAULT:
668  if (saw_default)
669  ereport(ERROR,
670  (errcode(ERRCODE_SYNTAX_ERROR),
671  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
672  column->colname, cxt->relation->relname),
674  constraint->location)));
675  column->raw_default = constraint->raw_expr;
676  Assert(constraint->cooked_expr == NULL);
677  saw_default = true;
678  break;
679 
680  case CONSTR_IDENTITY:
681  {
682  Type ctype;
683  Oid typeOid;
684 
685  if (cxt->ofType)
686  ereport(ERROR,
687  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
688  errmsg("identity columns are not supported on typed tables")));
689  if (cxt->partbound)
690  ereport(ERROR,
691  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
692  errmsg("identity columns are not supported on partitions")));
693 
694  ctype = typenameType(cxt->pstate, column->typeName, NULL);
695  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
696  ReleaseSysCache(ctype);
697 
698  if (saw_identity)
699  ereport(ERROR,
700  (errcode(ERRCODE_SYNTAX_ERROR),
701  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
702  column->colname, cxt->relation->relname),
704  constraint->location)));
705 
706  generateSerialExtraStmts(cxt, column,
707  typeOid, constraint->options,
708  true, false,
709  NULL, NULL);
710 
711  column->identity = constraint->generated_when;
712  saw_identity = true;
713 
714  /* An identity column is implicitly NOT NULL */
715  if (saw_nullable && !column->is_not_null)
716  ereport(ERROR,
717  (errcode(ERRCODE_SYNTAX_ERROR),
718  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
719  column->colname, cxt->relation->relname),
721  constraint->location)));
722  column->is_not_null = true;
723  saw_nullable = true;
724  break;
725  }
726 
727  case CONSTR_GENERATED:
728  if (cxt->ofType)
729  ereport(ERROR,
730  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
731  errmsg("generated columns are not supported on typed tables")));
732  if (cxt->partbound)
733  ereport(ERROR,
734  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
735  errmsg("generated columns are not supported on partitions")));
736 
737  if (saw_generated)
738  ereport(ERROR,
739  (errcode(ERRCODE_SYNTAX_ERROR),
740  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
741  column->colname, cxt->relation->relname),
743  constraint->location)));
744  column->generated = ATTRIBUTE_GENERATED_STORED;
745  column->raw_default = constraint->raw_expr;
746  Assert(constraint->cooked_expr == NULL);
747  saw_generated = true;
748  break;
749 
750  case CONSTR_CHECK:
751  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
752  break;
753 
754  case CONSTR_PRIMARY:
755  if (cxt->isforeign)
756  ereport(ERROR,
757  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
758  errmsg("primary key constraints are not supported on foreign tables"),
760  constraint->location)));
761  /* FALL THRU */
762 
763  case CONSTR_UNIQUE:
764  if (cxt->isforeign)
765  ereport(ERROR,
766  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
767  errmsg("unique constraints are not supported on foreign tables"),
769  constraint->location)));
770  if (constraint->keys == NIL)
771  constraint->keys = list_make1(makeString(column->colname));
772  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
773  break;
774 
775  case CONSTR_EXCLUSION:
776  /* grammar does not allow EXCLUDE as a column constraint */
777  elog(ERROR, "column exclusion constraints are not supported");
778  break;
779 
780  case CONSTR_FOREIGN:
781  if (cxt->isforeign)
782  ereport(ERROR,
783  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
784  errmsg("foreign key constraints are not supported on foreign tables"),
786  constraint->location)));
787 
788  /*
789  * Fill in the current attribute's name and throw it into the
790  * list of FK constraints to be processed later.
791  */
792  constraint->fk_attrs = list_make1(makeString(column->colname));
793  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
794  break;
795 
800  /* transformConstraintAttrs took care of these */
801  break;
802 
803  default:
804  elog(ERROR, "unrecognized constraint type: %d",
805  constraint->contype);
806  break;
807  }
808 
809  if (saw_default && saw_identity)
810  ereport(ERROR,
811  (errcode(ERRCODE_SYNTAX_ERROR),
812  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
813  column->colname, cxt->relation->relname),
815  constraint->location)));
816 
817  if (saw_default && saw_generated)
818  ereport(ERROR,
819  (errcode(ERRCODE_SYNTAX_ERROR),
820  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
821  column->colname, cxt->relation->relname),
823  constraint->location)));
824 
825  if (saw_identity && saw_generated)
826  ereport(ERROR,
827  (errcode(ERRCODE_SYNTAX_ERROR),
828  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
829  column->colname, cxt->relation->relname),
831  constraint->location)));
832  }
833 
834  /*
835  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
836  * per-column foreign data wrapper options to this column after creation.
837  */
838  if (column->fdwoptions != NIL)
839  {
840  AlterTableStmt *stmt;
841  AlterTableCmd *cmd;
842 
843  cmd = makeNode(AlterTableCmd);
845  cmd->name = column->colname;
846  cmd->def = (Node *) column->fdwoptions;
847  cmd->behavior = DROP_RESTRICT;
848  cmd->missing_ok = false;
849 
850  stmt = makeNode(AlterTableStmt);
851  stmt->relation = cxt->relation;
852  stmt->cmds = NIL;
854  stmt->cmds = lappend(stmt->cmds, cmd);
855 
856  cxt->alist = lappend(cxt->alist, stmt);
857  }
858 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
Oid typeOid
Definition: parsenodes.h:222
List * keys
Definition: parsenodes.h:2266
char generated_when
Definition: parsenodes.h:2263
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
List * names
Definition: parsenodes.h:221
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
char identity
Definition: parsenodes.h:668
List * constraints
Definition: parsenodes.h:674
Node * raw_expr
Definition: parsenodes.h:2261
Definition: nodes.h:539
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
AlterTableType subtype
Definition: parsenodes.h:1950
char generated
Definition: parsenodes.h:671
bool is_not_null
Definition: parsenodes.h:663
unsigned int Oid
Definition: postgres_ext.h:31
List * options
Definition: parsenodes.h:2275
int location
Definition: parsenodes.h:310
#define list_make1(x1)
Definition: pg_list.h:206
ParseState * pstate
Definition: parse_utilcmd.c:75
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:77
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
#define lfirst_node(type, lc)
Definition: pg_list.h:172
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:675
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
ObjectType objtype
Definition: parsenodes.h:1861
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
Node * raw_default
Definition: parsenodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:336
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:585
TypeName * SystemTypeName(char *name)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
TypeName * typeName
Definition: parsenodes.h:309
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:587
#define Assert(condition)
Definition: c.h:804
int location
Definition: parsenodes.h:299
int location
Definition: parsenodes.h:228
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:659
List * arrayBounds
Definition: parsenodes.h:227
int errmsg(const char *fmt,...)
Definition: elog.c:909
RangeVar * relation
Definition: parsenodes.h:1859
char * str
Definition: value.h:48
#define elog(elevel,...)
Definition: elog.h:232
ConstrType contype
Definition: parsenodes.h:2251
DropBehavior behavior
Definition: parsenodes.h:1958
char * colname
Definition: parsenodes.h:658
char * cooked_expr
Definition: parsenodes.h:2262
Value val
Definition: parsenodes.h:298
List * fk_attrs
Definition: parsenodes.h:2286
NodeTag type
Definition: value.h:44
bool pct_type
Definition: parsenodes.h:224
Node * arg
Definition: parsenodes.h:308

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3761 of file parse_utilcmd.c.

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

3762 {
3763  /*
3764  * All we really need to do here is verify that the type is valid,
3765  * including any collation spec that might be present.
3766  */
3767  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3768 
3769  if (column->collClause)
3770  {
3771  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3772 
3773  LookupCollation(cxt->pstate,
3774  column->collClause->collname,
3775  column->collClause->location);
3776  /* Complain if COLLATE is applied to an uncollatable type */
3777  if (!OidIsValid(typtup->typcollation))
3778  ereport(ERROR,
3779  (errcode(ERRCODE_DATATYPE_MISMATCH),
3780  errmsg("collations are not supported by type %s",
3781  format_type_be(typtup->oid)),
3783  column->collClause->location)));
3784  }
3785 
3786  ReleaseSysCache(ctype);
3787 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define OidIsValid(objectId)
Definition: c.h:710
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
#define ereport(elevel,...)
Definition: elog.h:157
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:659
CollateClause * collClause
Definition: parsenodes.h:672
List * collname
Definition: parsenodes.h:320
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3646 of file parse_utilcmd.c.

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

Referenced by transformColumnDefinition().

3647 {
3648  Constraint *lastprimarycon = NULL;
3649  bool saw_deferrability = false;
3650  bool saw_initially = false;
3651  ListCell *clist;
3652 
3653 #define SUPPORTS_ATTRS(node) \
3654  ((node) != NULL && \
3655  ((node)->contype == CONSTR_PRIMARY || \
3656  (node)->contype == CONSTR_UNIQUE || \
3657  (node)->contype == CONSTR_EXCLUSION || \
3658  (node)->contype == CONSTR_FOREIGN))
3659 
3660  foreach(clist, constraintList)
3661  {
3662  Constraint *con = (Constraint *) lfirst(clist);
3663 
3664  if (!IsA(con, Constraint))
3665  elog(ERROR, "unrecognized node type: %d",
3666  (int) nodeTag(con));
3667  switch (con->contype)
3668  {
3670  if (!SUPPORTS_ATTRS(lastprimarycon))
3671  ereport(ERROR,
3672  (errcode(ERRCODE_SYNTAX_ERROR),
3673  errmsg("misplaced DEFERRABLE clause"),
3674  parser_errposition(cxt->pstate, con->location)));
3675  if (saw_deferrability)
3676  ereport(ERROR,
3677  (errcode(ERRCODE_SYNTAX_ERROR),
3678  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3679  parser_errposition(cxt->pstate, con->location)));
3680  saw_deferrability = true;
3681  lastprimarycon->deferrable = true;
3682  break;
3683 
3685  if (!SUPPORTS_ATTRS(lastprimarycon))
3686  ereport(ERROR,
3687  (errcode(ERRCODE_SYNTAX_ERROR),
3688  errmsg("misplaced NOT DEFERRABLE clause"),
3689  parser_errposition(cxt->pstate, con->location)));
3690  if (saw_deferrability)
3691  ereport(ERROR,
3692  (errcode(ERRCODE_SYNTAX_ERROR),
3693  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3694  parser_errposition(cxt->pstate, con->location)));
3695  saw_deferrability = true;
3696  lastprimarycon->deferrable = false;
3697  if (saw_initially &&
3698  lastprimarycon->initdeferred)
3699  ereport(ERROR,
3700  (errcode(ERRCODE_SYNTAX_ERROR),
3701  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3702  parser_errposition(cxt->pstate, con->location)));
3703  break;
3704 
3705  case CONSTR_ATTR_DEFERRED:
3706  if (!SUPPORTS_ATTRS(lastprimarycon))
3707  ereport(ERROR,
3708  (errcode(ERRCODE_SYNTAX_ERROR),
3709  errmsg("misplaced INITIALLY DEFERRED clause"),
3710  parser_errposition(cxt->pstate, con->location)));
3711  if (saw_initially)
3712  ereport(ERROR,
3713  (errcode(ERRCODE_SYNTAX_ERROR),
3714  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3715  parser_errposition(cxt->pstate, con->location)));
3716  saw_initially = true;
3717  lastprimarycon->initdeferred = true;
3718 
3719  /*
3720  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3721  */
3722  if (!saw_deferrability)
3723  lastprimarycon->deferrable = true;
3724  else if (!lastprimarycon->deferrable)
3725  ereport(ERROR,
3726  (errcode(ERRCODE_SYNTAX_ERROR),
3727  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3728  parser_errposition(cxt->pstate, con->location)));
3729  break;
3730 
3731  case CONSTR_ATTR_IMMEDIATE:
3732  if (!SUPPORTS_ATTRS(lastprimarycon))
3733  ereport(ERROR,
3734  (errcode(ERRCODE_SYNTAX_ERROR),
3735  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3736  parser_errposition(cxt->pstate, con->location)));
3737  if (saw_initially)
3738  ereport(ERROR,
3739  (errcode(ERRCODE_SYNTAX_ERROR),
3740  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3741  parser_errposition(cxt->pstate, con->location)));
3742  saw_initially = true;
3743  lastprimarycon->initdeferred = false;
3744  break;
3745 
3746  default:
3747  /* Otherwise it's not an attribute */
3748  lastprimarycon = con;
3749  /* reset flags for new primary node */
3750  saw_deferrability = false;
3751  saw_initially = false;
3752  break;
3753  }
3754  }
3755 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
int errcode(int sqlerrcode)
Definition: elog.c:698
bool initdeferred
Definition: parsenodes.h:2256
ParseState * pstate
Definition: parse_utilcmd.c:75
#define ERROR
Definition: elog.h:46
bool deferrable
Definition: parsenodes.h:2255
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define nodeTag(nodeptr)
Definition: nodes.h:544
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define SUPPORTS_ATTRS(node)
#define elog(elevel,...)
Definition: elog.h:232
ConstrType contype
Definition: parsenodes.h:2251

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3814 of file parse_utilcmd.c.

References CreateSchemaStmtContext::authrole, CreateSchemaStmt::authrole, element(), elog, ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmt::schemaElts, RangeVar::schemaname, CreateSchemaStmtContext::schemaname, CreateSchemaStmt::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::stmtType, T_CreateSeqStmt, T_CreateStmt, T_CreateTrigStmt, T_GrantStmt, T_IndexStmt, T_ViewStmt, CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

3815 {
3817  List *result;
3818  ListCell *elements;
3819 
3820  cxt.stmtType = "CREATE SCHEMA";
3821  cxt.schemaname = stmt->schemaname;
3822  cxt.authrole = (RoleSpec *) stmt->authrole;
3823  cxt.sequences = NIL;
3824  cxt.tables = NIL;
3825  cxt.views = NIL;
3826  cxt.indexes = NIL;
3827  cxt.triggers = NIL;
3828  cxt.grants = NIL;
3829 
3830  /*
3831  * Run through each schema element in the schema element list. Separate
3832  * statements by type, and do preliminary analysis.
3833  */
3834  foreach(elements, stmt->schemaElts)
3835  {
3836  Node *element = lfirst(elements);
3837 
3838  switch (nodeTag(element))
3839  {
3840  case T_CreateSeqStmt:
3841  {
3842  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3843 
3845  cxt.sequences = lappend(cxt.sequences, element);
3846  }
3847  break;
3848 
3849  case T_CreateStmt:
3850  {
3851  CreateStmt *elp = (CreateStmt *) element;
3852 
3854 
3855  /*
3856  * XXX todo: deal with constraints
3857  */
3858  cxt.tables = lappend(cxt.tables, element);
3859  }
3860  break;
3861 
3862  case T_ViewStmt:
3863  {
3864  ViewStmt *elp = (ViewStmt *) element;
3865 
3866  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3867 
3868  /*
3869  * XXX todo: deal with references between views
3870  */
3871  cxt.views = lappend(cxt.views, element);
3872  }
3873  break;
3874 
3875  case T_IndexStmt:
3876  {
3877  IndexStmt *elp = (IndexStmt *) element;
3878 
3880  cxt.indexes = lappend(cxt.indexes, element);
3881  }
3882  break;
3883 
3884  case T_CreateTrigStmt:
3885  {
3886  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3887 
3889  cxt.triggers = lappend(cxt.triggers, element);
3890  }
3891  break;
3892 
3893  case T_GrantStmt:
3894  cxt.grants = lappend(cxt.grants, element);
3895  break;
3896 
3897  default:
3898  elog(ERROR, "unrecognized node type: %d",
3899  (int) nodeTag(element));
3900  }
3901  }
3902 
3903  result = NIL;
3904  result = list_concat(result, cxt.sequences);
3905  result = list_concat(result, cxt.tables);
3906  result = list_concat(result, cxt.views);
3907  result = list_concat(result, cxt.indexes);
3908  result = list_concat(result, cxt.triggers);
3909  result = list_concat(result, cxt.grants);
3910 
3911  return result;
3912 }
RangeVar * relation
Definition: parsenodes.h:2171
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
RangeVar * view
Definition: parsenodes.h:3254
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2877
RoleSpec * authrole
Definition: parsenodes.h:1841
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * sequence
Definition: parsenodes.h:2645
#define lfirst(lc)
Definition: pg_list.h:169
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define elog(elevel,...)
Definition: elog.h:232
RangeVar * relation
Definition: parsenodes.h:2532
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, CreateStmtContext::likeclauses, list_concat(), RangeVar::location, make_parsestate(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

166 {
167  ParseState *pstate;
168  CreateStmtContext cxt;
169  List *result;
170  List *save_alist;
171  ListCell *elements;
172  Oid namespaceid;
173  Oid existing_relid;
174  ParseCallbackState pcbstate;
175 
176  /* Set up pstate */
177  pstate = make_parsestate(NULL);
178  pstate->p_sourcetext = queryString;
179 
180  /*
181  * Look up the creation namespace. This also checks permissions on the
182  * target namespace, locks it against concurrent drops, checks for a
183  * preexisting relation in that namespace with the same name, and updates
184  * stmt->relation->relpersistence if the selected namespace is temporary.
185  */
186  setup_parser_errposition_callback(&pcbstate, pstate,
187  stmt->relation->location);
188  namespaceid =
190  &existing_relid);
192 
193  /*
194  * If the relation already exists and the user specified "IF NOT EXISTS",
195  * bail out with a NOTICE.
196  */
197  if (stmt->if_not_exists && OidIsValid(existing_relid))
198  {
199  ereport(NOTICE,
200  (errcode(ERRCODE_DUPLICATE_TABLE),
201  errmsg("relation \"%s\" already exists, skipping",
202  stmt->relation->relname)));
203  return NIL;
204  }
205 
206  /*
207  * If the target relation name isn't schema-qualified, make it so. This
208  * prevents some corner cases in which added-on rewritten commands might
209  * think they should apply to other relations that have the same name and
210  * are earlier in the search path. But a local temp table is effectively
211  * specified to be in pg_temp, so no need for anything extra in that case.
212  */
213  if (stmt->relation->schemaname == NULL
214  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
215  stmt->relation->schemaname = get_namespace_name(namespaceid);
216 
217  /* Set up CreateStmtContext */
218  cxt.pstate = pstate;
219  if (IsA(stmt, CreateForeignTableStmt))
220  {
221  cxt.stmtType = "CREATE FOREIGN TABLE";
222  cxt.isforeign = true;
223  }
224  else
225  {
226  cxt.stmtType = "CREATE TABLE";
227  cxt.isforeign = false;
228  }
229  cxt.relation = stmt->relation;
230  cxt.rel = NULL;
231  cxt.inhRelations = stmt->inhRelations;
232  cxt.isalter = false;
233  cxt.columns = NIL;
234  cxt.ckconstraints = NIL;
235  cxt.fkconstraints = NIL;
236  cxt.ixconstraints = NIL;
237  cxt.likeclauses = NIL;
238  cxt.extstats = NIL;
239  cxt.blist = NIL;
240  cxt.alist = NIL;
241  cxt.pkey = NULL;
242  cxt.ispartitioned = stmt->partspec != NULL;
243  cxt.partbound = stmt->partbound;
244  cxt.ofType = (stmt->ofTypename != NULL);
245 
246  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
247 
248  if (stmt->ofTypename)
249  transformOfType(&cxt, stmt->ofTypename);
250 
251  if (stmt->partspec)
252  {
253  if (stmt->inhRelations && !stmt->partbound)
254  ereport(ERROR,
255  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
256  errmsg("cannot create partitioned table as inheritance child")));
257  }
258 
259  /*
260  * Run through each primary element in the table creation clause. Separate
261  * column defs from constraints, and do preliminary analysis.
262  */
263  foreach(elements, stmt->tableElts)
264  {
265  Node *element = lfirst(elements);
266 
267  switch (nodeTag(element))
268  {
269  case T_ColumnDef:
270  transformColumnDefinition(&cxt, (ColumnDef *) element);
271  break;
272 
273  case T_Constraint:
274  transformTableConstraint(&cxt, (Constraint *) element);
275  break;
276 
277  case T_TableLikeClause:
278  transformTableLikeClause(&cxt, (TableLikeClause *) element);
279  break;
280 
281  default:
282  elog(ERROR, "unrecognized node type: %d",
283  (int) nodeTag(element));
284  break;
285  }
286  }
287 
288  /*
289  * Transfer anything we already have in cxt.alist into save_alist, to keep
290  * it separate from the output of transformIndexConstraints. (This may
291  * not be necessary anymore, but we'll keep doing it to preserve the
292  * historical order of execution of the alist commands.)
293  */
294  save_alist = cxt.alist;
295  cxt.alist = NIL;
296 
297  Assert(stmt->constraints == NIL);
298 
299  /*
300  * Postprocess constraints that give rise to index definitions.
301  */
303 
304  /*
305  * Re-consideration of LIKE clauses should happen after creation of
306  * indexes, but before creation of foreign keys. This order is critical
307  * because a LIKE clause may attempt to create a primary key. If there's
308  * also a pkey in the main CREATE TABLE list, creation of that will not
309  * check for a duplicate at runtime (since index_check_primary_key()
310  * expects that we rejected dups here). Creation of the LIKE-generated
311  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
312  * only works if it happens second. On the other hand, we want to make
313  * pkeys before foreign key constraints, in case the user tries to make a
314  * self-referential FK.
315  */
316  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
317 
318  /*
319  * Postprocess foreign-key constraints.
320  */
321  transformFKConstraints(&cxt, true, false);
322 
323  /*
324  * Postprocess check constraints.
325  *
326  * For regular tables all constraints can be marked valid immediately,
327  * because the table is new therefore empty. Not so for foreign tables.
328  */
330 
331  /*
332  * Postprocess extended statistics.
333  */
335 
336  /*
337  * Output results.
338  */
339  stmt->tableElts = cxt.columns;
340  stmt->constraints = cxt.ckconstraints;
341 
342  result = lappend(cxt.blist, stmt);
343  result = list_concat(result, cxt.alist);
344  result = list_concat(result, save_alist);
345 
346  return result;
347 }
RangeVar * relation
Definition: parsenodes.h:2171
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2173
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2178
bool if_not_exists
Definition: parsenodes.h:2183
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parsenodes.h:2175
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
#define ERROR
Definition: elog.h:46
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:181
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
List * lappend(List *list, void *datum)
Definition: list.c:336
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:535
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2172
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:544
const char * stmtType
Definition: parse_utilcmd.c:76
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2176
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2177
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2690 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2691 {
2692  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2693 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:530

◆ transformFKConstraints()

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

Definition at line 2734 of file parse_utilcmd.c.

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

2736 {
2737  ListCell *fkclist;
2738 
2739  if (cxt->fkconstraints == NIL)
2740  return;
2741 
2742  /*
2743  * If CREATE TABLE or adding a column with NULL default, we can safely
2744  * skip validation of FK constraints, and nonetheless mark them valid.
2745  * (This will override any user-supplied NOT VALID flag.)
2746  */
2747  if (skipValidation)
2748  {
2749  foreach(fkclist, cxt->fkconstraints)
2750  {
2751  Constraint *constraint = (Constraint *) lfirst(fkclist);
2752 
2753  constraint->skip_validation = true;
2754  constraint->initially_valid = true;
2755  }
2756  }
2757 
2758  /*
2759  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2760  * CONSTRAINT command to execute after the basic command is complete. (If
2761  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2762  * its own subcommand list.)
2763  *
2764  * Note: the ADD CONSTRAINT command must also execute after any index
2765  * creation commands. Thus, this should run after
2766  * transformIndexConstraints, so that the CREATE INDEX commands are
2767  * already in cxt->alist. See also the handling of cxt->likeclauses.
2768  */
2769  if (!isAddConstraint)
2770  {
2771  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2772 
2773  alterstmt->relation = cxt->relation;
2774  alterstmt->cmds = NIL;
2775  alterstmt->objtype = OBJECT_TABLE;
2776 
2777  foreach(fkclist, cxt->fkconstraints)
2778  {
2779  Constraint *constraint = (Constraint *) lfirst(fkclist);
2780  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2781 
2782  altercmd->subtype = AT_AddConstraint;
2783  altercmd->name = NULL;
2784  altercmd->def = (Node *) constraint;
2785  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2786  }
2787 
2788  cxt->alist = lappend(cxt->alist, alterstmt);
2789  }
2790 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:539
AlterTableType subtype
Definition: parsenodes.h:1950
RangeVar * relation
Definition: parse_utilcmd.c:77
ObjectType objtype
Definition: parsenodes.h:1861
List * lappend(List *list, void *datum)
Definition: list.c:336
bool initially_valid
Definition: parsenodes.h:2297
#define makeNode(_type_)
Definition: nodes.h:587
#define lfirst(lc)
Definition: pg_list.h:169
RangeVar * relation
Definition: parsenodes.h:1859
bool skip_validation
Definition: parsenodes.h:2296

◆ transformIndexConstraint()

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

Definition at line 2156 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, Constraint::including, index_open(), IndexElem::indexcolname, IndexStmt::indexIncludingParams, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, 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, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, 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, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, IndexStmt::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

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

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2054 of file parse_utilcmd.c.

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, CreateStmtContext::pkey, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2055 {
2056  IndexStmt *index;
2057  List *indexlist = NIL;
2058  List *finalindexlist = NIL;
2059  ListCell *lc;
2060 
2061  /*
2062  * Run through the constraints that need to generate an index. For PRIMARY
2063  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
2064  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
2065  * NULL.
2066  */
2067  foreach(lc, cxt->ixconstraints)
2068  {
2069  Constraint *constraint = lfirst_node(Constraint, lc);
2070 
2071  Assert(constraint->contype == CONSTR_PRIMARY ||
2072  constraint->contype == CONSTR_UNIQUE ||
2073  constraint->contype == CONSTR_EXCLUSION);
2074 
2075  index = transformIndexConstraint(constraint, cxt);
2076 
2077  indexlist = lappend(indexlist, index);
2078  }
2079 
2080  /*
2081  * Scan the index list and remove any redundant index specifications. This
2082  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2083  * strict reading of SQL would suggest raising an error instead, but that
2084  * strikes me as too anal-retentive. - tgl 2001-02-14
2085  *
2086  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2087  * pre-existing indexes, too.
2088  */
2089  if (cxt->pkey != NULL)
2090  {
2091  /* Make sure we keep the PKEY index in preference to others... */
2092  finalindexlist = list_make1(cxt->pkey);
2093  }
2094 
2095  foreach(lc, indexlist)
2096  {
2097  bool keep = true;
2098  ListCell *k;
2099 
2100  index = lfirst(lc);
2101 
2102  /* if it's pkey, it's already in finalindexlist */
2103  if (index == cxt->pkey)
2104  continue;
2105 
2106  foreach(k, finalindexlist)
2107  {
2108  IndexStmt *priorindex = lfirst(k);
2109 
2110  if (equal(index->indexParams, priorindex->indexParams) &&
2111  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2112  equal(index->whereClause, priorindex->whereClause) &&
2113  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2114  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2115  index->deferrable == priorindex->deferrable &&
2116  index->initdeferred == priorindex->initdeferred)
2117  {
2118  priorindex->unique |= index->unique;
2119 
2120  /*
2121  * If the prior index is as yet unnamed, and this one is
2122  * named, then transfer the name to the prior index. This
2123  * ensures that if we have named and unnamed constraints,
2124  * we'll use (at least one of) the names for the index.
2125  */
2126  if (priorindex->idxname == NULL)
2127  priorindex->idxname = index->idxname;
2128  keep = false;
2129  break;
2130  }
2131  }
2132 
2133  if (keep)
2134  finalindexlist = lappend(finalindexlist, index);
2135  }
2136 
2137  /*
2138  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
2139  * TABLE SET NOT NULL statement to support a primary key, it's already in
2140  * cxt->alist.
2141  */
2142  cxt->alist = list_concat(cxt->alist, finalindexlist);
2143 }
bool deferrable
Definition: parsenodes.h:2895
#define NIL
Definition: pg_list.h:65
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
Node * whereClause
Definition: parsenodes.h:2884
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * indexIncludingParams
Definition: parsenodes.h:2881
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:206
IndexStmt * pkey
Definition: parse_utilcmd.c:92
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:336
char * idxname
Definition: parsenodes.h:2876
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2892
char * accessMethod
Definition: parsenodes.h:2878
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2880
List * excludeOpNames
Definition: parsenodes.h:2885
bool initdeferred
Definition: parsenodes.h:2896
ConstrType contype
Definition: parsenodes.h:2251
Definition: pg_list.h:50

◆ transformIndexStmt()

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

Definition at line 2805 of file parse_utilcmd.c.

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, IndexStmt::indexParams, lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), table_close(), IndexStmt::transformed, transformExpr(), transformWhereClause(), and IndexStmt::whereClause.

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

2806 {
2807  ParseState *pstate;
2808  ParseNamespaceItem *nsitem;
2809  ListCell *l;
2810  Relation rel;
2811 
2812  /* Nothing to do if statement already transformed. */
2813  if (stmt->transformed)
2814  return stmt;
2815 
2816  /* Set up pstate */
2817  pstate = make_parsestate(NULL);
2818  pstate->p_sourcetext = queryString;
2819 
2820  /*
2821  * Put the parent table into the rtable so that the expressions can refer
2822  * to its fields without qualification. Caller is responsible for locking
2823  * relation, but we still need to open it.
2824  */
2825  rel = relation_open(relid, NoLock);
2826  nsitem = addRangeTableEntryForRelation(pstate, rel,
2828  NULL, false, true);
2829 
2830  /* no to join list, yes to namespaces */
2831  addNSItemToQuery(pstate, nsitem, false, true, true);
2832 
2833  /* take care of the where clause */
2834  if (stmt->whereClause)
2835  {
2836  stmt->whereClause = transformWhereClause(pstate,
2837  stmt->whereClause,
2839  "WHERE");
2840  /* we have to fix its collations too */
2841  assign_expr_collations(pstate, stmt->whereClause);
2842  }
2843 
2844  /* take care of any index expressions */
2845  foreach(l, stmt->indexParams)
2846  {
2847  IndexElem *ielem = (IndexElem *) lfirst(l);
2848 
2849  if (ielem->expr)
2850  {
2851  /* Extract preliminary index col name before transforming expr */
2852  if (ielem->indexcolname == NULL)
2853  ielem->indexcolname = FigureIndexColname(ielem->expr);
2854 
2855  /* Now do parse transformation of the expression */
2856  ielem->expr = transformExpr(pstate, ielem->expr,
2858 
2859  /* We have to fix its collations too */
2860  assign_expr_collations(pstate, ielem->expr);
2861 
2862  /*
2863  * transformExpr() should have already rejected subqueries,
2864  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2865  * for an index expression.
2866  *
2867  * DefineIndex() will make more checks.
2868  */
2869  }
2870  }
2871 
2872  /*
2873  * Check that only the base rel is mentioned. (This should be dead code
2874  * now that add_missing_from is history.)
2875  */
2876  if (list_length(pstate->p_rtable) != 1)
2877  ereport(ERROR,
2878  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2879  errmsg("index expressions and predicates can refer only to the table being indexed")));
2880 
2881  free_parsestate(pstate);
2882 
2883  /* Close relation */
2884  table_close(rel, NoLock);
2885 
2886  /* Mark statement as successfully transformed */
2887  stmt->transformed = true;
2888 
2889  return stmt;
2890 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Node * whereClause
Definition: parsenodes.h:2884
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:698
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:715
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2897
char * indexcolname
Definition: parsenodes.h:716
const char * p_sourcetext
Definition: parse_node.h:181
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2880
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:182

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1448 of file parse_utilcmd.c.

References AssertArg, check_of_type(), ColumnDef::collClause, ColumnDef::collOid, ColumnDef::colname, CreateStmtContext::columns, ColumnDef::constraints, ColumnDef::cooked_default, DecrTupleDescRefCount(), GETSTRUCT, i, ColumnDef::inhcount, ColumnDef::is_from_type, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), ColumnDef::location, lookup_rowtype_tupdesc(), makeNode, makeTypeNameFromOid(), NameStr, TupleDescData::natts, NIL, pstrdup(), ColumnDef::raw_default, ReleaseSysCache(), ColumnDef::storage, TupleDescAttr, ColumnDef::typeName, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

1449 {
1450  HeapTuple tuple;
1451  TupleDesc tupdesc;
1452  int i;
1453  Oid ofTypeId;
1454 
1455  AssertArg(ofTypename);
1456 
1457  tuple = typenameType(NULL, ofTypename, NULL);
1458  check_of_type(tuple);
1459  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1460  ofTypename->typeOid = ofTypeId; /* cached for later */
1461 
1462  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1463  for (i = 0; i < tupdesc->natts; i++)
1464  {
1465  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1466  ColumnDef *n;
1467 
1468  if (attr->attisdropped)
1469  continue;
1470 
1471  n = makeNode(ColumnDef);
1472  n->colname = pstrdup(NameStr(attr->attname));
1473  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1474  n->inhcount = 0;
1475  n->is_local = true;
1476  n->is_not_null = false;
1477  n->is_from_type = true;
1478  n->storage = 0;
1479  n->raw_default = NULL;
1480  n->cooked_default = NULL;
1481  n->collClause = NULL;
1482  n->collOid = attr->attcollation;
1483  n->constraints = NIL;
1484  n->location = -1;
1485  cxt->columns = lappend(cxt->columns, n);
1486  }
1487  DecrTupleDescRefCount(tupdesc);
1488 
1489  ReleaseSysCache(tuple);
1490 }
#define NIL
Definition: pg_list.h:65
Oid typeOid
Definition: parsenodes.h:222
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
char storage
Definition: parsenodes.h:665
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1824
bool is_local
Definition: parsenodes.h:662
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:674
char * pstrdup(const char *in)
Definition: mcxt.c:1299
bool is_not_null
Definition: parsenodes.h:663
unsigned int Oid
Definition: postgres_ext.h:31
Node * cooked_default
Definition: parsenodes.h:667
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:6488
Oid collOid
Definition: parsenodes.h:673
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
int location
Definition: parsenodes.h:676
#define AssertArg(condition)
Definition: c.h:806
Node * raw_default
Definition: parsenodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:336
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
bool is_from_type
Definition: parsenodes.h:664
#define makeNode(_type_)
Definition: nodes.h:587
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:384
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
TypeName * typeName
Definition: parsenodes.h:659
CollateClause * collClause
Definition: parsenodes.h:672
int i
int inhcount
Definition: parsenodes.h:661
#define NameStr(name)
Definition: c.h:681
char * colname
Definition: parsenodes.h:658

◆ transformPartitionBound()