PostgreSQL Source Code  git master
parse_utilcmd.h File Reference
Include dependency graph for parse_utilcmd.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Function Documentation

◆ transformAlterTableStmt()

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

Definition at line 2651 of file parse_utilcmd.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_ProcessedConstraint, AT_SetIdentity, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attidentity(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getOwnedSequence(), getOwnedSequences(), CreateStmtContext::hasoids, ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, linitial_oid, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, OBJECT_FOREIGN_TABLE, 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(), AlterTableStmt::relkind, RELKIND_PARTITIONED_TABLE, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), ColumnDef::typeName, and typenameTypeId().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

2653 {
2654  Relation rel;
2655  ParseState *pstate;
2656  CreateStmtContext cxt;
2657  List *result;
2658  List *save_alist;
2659  ListCell *lcmd,
2660  *l;
2661  List *newcmds = NIL;
2662  bool skipValidation = true;
2663  AlterTableCmd *newcmd;
2664  RangeTblEntry *rte;
2665 
2666  /*
2667  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2668  * is overkill, but easy.)
2669  */
2670  stmt = copyObject(stmt);
2671 
2672  /* Caller is responsible for locking the relation */
2673  rel = relation_open(relid, NoLock);
2674 
2675  /* Set up pstate */
2676  pstate = make_parsestate(NULL);
2677  pstate->p_sourcetext = queryString;
2678  rte = addRangeTableEntryForRelation(pstate,
2679  rel,
2680  NULL,
2681  false,
2682  true);
2683  addRTEtoQuery(pstate, rte, false, true, true);
2684 
2685  /* Set up CreateStmtContext */
2686  cxt.pstate = pstate;
2687  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2688  {
2689  cxt.stmtType = "ALTER FOREIGN TABLE";
2690  cxt.isforeign = true;
2691  }
2692  else
2693  {
2694  cxt.stmtType = "ALTER TABLE";
2695  cxt.isforeign = false;
2696  }
2697  cxt.relation = stmt->relation;
2698  cxt.rel = rel;
2699  cxt.inhRelations = NIL;
2700  cxt.isalter = true;
2701  cxt.hasoids = false; /* need not be right */
2702  cxt.columns = NIL;
2703  cxt.ckconstraints = NIL;
2704  cxt.fkconstraints = NIL;
2705  cxt.ixconstraints = NIL;
2706  cxt.inh_indexes = NIL;
2707  cxt.blist = NIL;
2708  cxt.alist = NIL;
2709  cxt.pkey = NULL;
2710  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
2711  cxt.partbound = NULL;
2712  cxt.ofType = false;
2713 
2714  /*
2715  * The only subtypes that currently require parse transformation handling
2716  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2717  * code from CREATE TABLE.
2718  */
2719  foreach(lcmd, stmt->cmds)
2720  {
2721  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2722 
2723  switch (cmd->subtype)
2724  {
2725  case AT_AddColumn:
2726  case AT_AddColumnToView:
2727  {
2728  ColumnDef *def = castNode(ColumnDef, cmd->def);
2729 
2730  transformColumnDefinition(&cxt, def);
2731 
2732  /*
2733  * If the column has a non-null default, we can't skip
2734  * validation of foreign keys.
2735  */
2736  if (def->raw_default != NULL)
2737  skipValidation = false;
2738 
2739  /*
2740  * All constraints are processed in other ways. Remove the
2741  * original list
2742  */
2743  def->constraints = NIL;
2744 
2745  newcmds = lappend(newcmds, cmd);
2746  break;
2747  }
2748 
2749  case AT_AddConstraint:
2750 
2751  /*
2752  * The original AddConstraint cmd node doesn't go to newcmds
2753  */
2754  if (IsA(cmd->def, Constraint))
2755  {
2756  transformTableConstraint(&cxt, (Constraint *) cmd->def);
2757  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2758  skipValidation = false;
2759  }
2760  else
2761  elog(ERROR, "unrecognized node type: %d",
2762  (int) nodeTag(cmd->def));
2763  break;
2764 
2766 
2767  /*
2768  * Already-transformed ADD CONSTRAINT, so just make it look
2769  * like the standard case.
2770  */
2771  cmd->subtype = AT_AddConstraint;
2772  newcmds = lappend(newcmds, cmd);
2773  break;
2774 
2775  case AT_AlterColumnType:
2776  {
2777  ColumnDef *def = (ColumnDef *) cmd->def;
2778  AttrNumber attnum;
2779 
2780  /*
2781  * For ALTER COLUMN TYPE, transform the USING clause if
2782  * one was specified.
2783  */
2784  if (def->raw_default)
2785  {
2786  def->cooked_default =
2787  transformExpr(pstate, def->raw_default,
2789  }
2790 
2791  /*
2792  * For identity column, create ALTER SEQUENCE command to
2793  * change the data type of the sequence.
2794  */
2795  attnum = get_attnum(relid, cmd->name);
2796 
2797  /*
2798  * if attribute not found, something will error about it
2799  * later
2800  */
2801  if (attnum != InvalidAttrNumber && get_attidentity(relid, attnum))
2802  {
2803  Oid seq_relid = getOwnedSequence(relid, attnum);
2804  Oid typeOid = typenameTypeId(pstate, def->typeName);
2805  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
2806 
2807  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
2808  get_rel_name(seq_relid),
2809  -1);
2810  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
2811  altseqstmt->for_identity = true;
2812  cxt.blist = lappend(cxt.blist, altseqstmt);
2813  }
2814 
2815  newcmds = lappend(newcmds, cmd);
2816  break;
2817  }
2818 
2819  case AT_AddIdentity:
2820  {
2821  Constraint *def = castNode(Constraint, cmd->def);
2822  ColumnDef *newdef = makeNode(ColumnDef);
2823  AttrNumber attnum;
2824 
2825  newdef->colname = cmd->name;
2826  newdef->identity = def->generated_when;
2827  cmd->def = (Node *) newdef;
2828 
2829  attnum = get_attnum(relid, cmd->name);
2830 
2831  /*
2832  * if attribute not found, something will error about it
2833  * later
2834  */
2835  if (attnum != InvalidAttrNumber)
2836  generateSerialExtraStmts(&cxt, newdef,
2837  get_atttype(relid, attnum),
2838  def->options, true,
2839  NULL, NULL);
2840 
2841  newcmds = lappend(newcmds, cmd);
2842  break;
2843  }
2844 
2845  case AT_SetIdentity:
2846  {
2847  /*
2848  * Create an ALTER SEQUENCE statement for the internal
2849  * sequence of the identity column.
2850  */
2851  ListCell *lc;
2852  List *newseqopts = NIL;
2853  List *newdef = NIL;
2854  List *seqlist;
2855  AttrNumber attnum;
2856 
2857  /*
2858  * Split options into those handled by ALTER SEQUENCE and
2859  * those for ALTER TABLE proper.
2860  */
2861  foreach(lc, castNode(List, cmd->def))
2862  {
2863  DefElem *def = lfirst_node(DefElem, lc);
2864 
2865  if (strcmp(def->defname, "generated") == 0)
2866  newdef = lappend(newdef, def);
2867  else
2868  newseqopts = lappend(newseqopts, def);
2869  }
2870 
2871  attnum = get_attnum(relid, cmd->name);
2872 
2873  if (attnum)
2874  {
2875  seqlist = getOwnedSequences(relid, attnum);
2876  if (seqlist)
2877  {
2878  AlterSeqStmt *seqstmt;
2879  Oid seq_relid;
2880 
2881  seqstmt = makeNode(AlterSeqStmt);
2882  seq_relid = linitial_oid(seqlist);
2884  get_rel_name(seq_relid), -1);
2885  seqstmt->options = newseqopts;
2886  seqstmt->for_identity = true;
2887  seqstmt->missing_ok = false;
2888 
2889  cxt.alist = lappend(cxt.alist, seqstmt);
2890  }
2891  }
2892 
2893  /*
2894  * If column was not found or was not an identity column,
2895  * we just let the ALTER TABLE command error out later.
2896  */
2897 
2898  cmd->def = (Node *) newdef;
2899  newcmds = lappend(newcmds, cmd);
2900  break;
2901  }
2902 
2903  case AT_AttachPartition:
2904  case AT_DetachPartition:
2905  {
2906  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
2907 
2908  transformPartitionCmd(&cxt, partcmd);
2909  /* assign transformed value of the partition bound */
2910  partcmd->bound = cxt.partbound;
2911  }
2912 
2913  newcmds = lappend(newcmds, cmd);
2914  break;
2915 
2916  default:
2917  newcmds = lappend(newcmds, cmd);
2918  break;
2919  }
2920  }
2921 
2922  /*
2923  * transformIndexConstraints wants cxt.alist to contain only index
2924  * statements, so transfer anything we already have into save_alist
2925  * immediately.
2926  */
2927  save_alist = cxt.alist;
2928  cxt.alist = NIL;
2929 
2930  /* Postprocess constraints */
2932  transformFKConstraints(&cxt, skipValidation, true);
2933  transformCheckConstraints(&cxt, false);
2934 
2935  /*
2936  * Push any index-creation commands into the ALTER, so that they can be
2937  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2938  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2939  * subcommand has already been through transformIndexStmt.
2940  */
2941  foreach(l, cxt.alist)
2942  {
2943  IndexStmt *idxstmt = lfirst_node(IndexStmt, l);
2944 
2945  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2946  newcmd = makeNode(AlterTableCmd);
2948  newcmd->def = (Node *) idxstmt;
2949  newcmds = lappend(newcmds, newcmd);
2950  }
2951  cxt.alist = NIL;
2952 
2953  /* Append any CHECK or FK constraints to the commands list */
2954  foreach(l, cxt.ckconstraints)
2955  {
2956  newcmd = makeNode(AlterTableCmd);
2957  newcmd->subtype = AT_AddConstraint;
2958  newcmd->def = (Node *) lfirst(l);
2959  newcmds = lappend(newcmds, newcmd);
2960  }
2961  foreach(l, cxt.fkconstraints)
2962  {
2963  newcmd = makeNode(AlterTableCmd);
2964  newcmd->subtype = AT_AddConstraint;
2965  newcmd->def = (Node *) lfirst(l);
2966  newcmds = lappend(newcmds, newcmd);
2967  }
2968 
2969  /* Close rel */
2970  relation_close(rel, NoLock);
2971 
2972  /*
2973  * Output results.
2974  */
2975  stmt->cmds = newcmds;
2976 
2977  result = lappend(cxt.blist, stmt);
2978  result = list_concat(result, cxt.alist);
2979  result = list_concat(result, save_alist);
2980 
2981  return result;
2982 }
#define NIL
Definition: pg_list.h:69
Oid getOwnedSequence(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:605
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
char get_attidentity(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:851
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
char generated_when
Definition: parsenodes.h:2104
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
char identity
Definition: parsenodes.h:649
List * constraints
Definition: parsenodes.h:652
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1769
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:512
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
AlterTableType subtype
Definition: parsenodes.h:1787
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2492
List * options
Definition: parsenodes.h:2113
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
ParseState * pstate
Definition: parse_utilcmd.c:75
Node * cooked_default
Definition: parsenodes.h:648
Oid indexOid
Definition: parsenodes.h:2719
RangeVar * relation
Definition: parse_utilcmd.c:77
IndexStmt * pkey
Definition: parse_utilcmd.c:92
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:821
const char * p_sourcetext
Definition: parse_node.h:172
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:878
ObjectType relkind
Definition: parsenodes.h:1701
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:94
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
List * getOwnedSequences(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:548
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
RangeVar * sequence
Definition: parsenodes.h:2491
#define makeNode(_type_)
Definition: nodes.h:560
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:848
#define linitial_oid(l)
Definition: pg_list.h:113
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
TypeName * typeName
Definition: parsenodes.h:640
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:517
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parsenodes.h:1699
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
bool for_identity
Definition: parsenodes.h:2493
char * defname
Definition: parsenodes.h:719
char * colname
Definition: parsenodes.h:639
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
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:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3163 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().

3164 {
3166  List *result;
3167  ListCell *elements;
3168 
3169  cxt.stmtType = "CREATE SCHEMA";
3170  cxt.schemaname = stmt->schemaname;
3171  cxt.authrole = (RoleSpec *) stmt->authrole;
3172  cxt.sequences = NIL;
3173  cxt.tables = NIL;
3174  cxt.views = NIL;
3175  cxt.indexes = NIL;
3176  cxt.triggers = NIL;
3177  cxt.grants = NIL;
3178 
3179  /*
3180  * Run through each schema element in the schema element list. Separate
3181  * statements by type, and do preliminary analysis.
3182  */
3183  foreach(elements, stmt->schemaElts)
3184  {
3185  Node *element = lfirst(elements);
3186 
3187  switch (nodeTag(element))
3188  {
3189  case T_CreateSeqStmt:
3190  {
3191  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3192 
3194  cxt.sequences = lappend(cxt.sequences, element);
3195  }
3196  break;
3197 
3198  case T_CreateStmt:
3199  {
3200  CreateStmt *elp = (CreateStmt *) element;
3201 
3203 
3204  /*
3205  * XXX todo: deal with constraints
3206  */
3207  cxt.tables = lappend(cxt.tables, element);
3208  }
3209  break;
3210 
3211  case T_ViewStmt:
3212  {
3213  ViewStmt *elp = (ViewStmt *) element;
3214 
3215  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3216 
3217  /*
3218  * XXX todo: deal with references between views
3219  */
3220  cxt.views = lappend(cxt.views, element);
3221  }
3222  break;
3223 
3224  case T_IndexStmt:
3225  {
3226  IndexStmt *elp = (IndexStmt *) element;
3227 
3229  cxt.indexes = lappend(cxt.indexes, element);
3230  }
3231  break;
3232 
3233  case T_CreateTrigStmt:
3234  {
3235  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3236 
3238  cxt.triggers = lappend(cxt.triggers, element);
3239  }
3240  break;
3241 
3242  case T_GrantStmt:
3243  cxt.grants = lappend(cxt.grants, element);
3244  break;
3245 
3246  default:
3247  elog(ERROR, "unrecognized node type: %d",
3248  (int) nodeTag(element));
3249  }
3250  }
3251 
3252  result = NIL;
3253  result = list_concat(result, cxt.sequences);
3254  result = list_concat(result, cxt.tables);
3255  result = list_concat(result, cxt.views);
3256  result = list_concat(result, cxt.indexes);
3257  result = list_concat(result, cxt.triggers);
3258  result = list_concat(result, cxt.grants);
3259 
3260  return result;
3261 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:512
List * list_concat(List *list1, List *list2)
Definition: list.c:321
RangeVar * view
Definition: parsenodes.h:3024
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2711
RoleSpec * authrole
Definition: parsenodes.h:1681
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2481
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:517
RangeVar * relation
Definition: parsenodes.h:2366
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ transformCreateStmt()

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

Definition at line 159 of file parse_utilcmd.c.

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

Referenced by ProcessUtilitySlow().

160 {
161  ParseState *pstate;
162  CreateStmtContext cxt;
163  List *result;
164  List *save_alist;
165  ListCell *elements;
166  Oid namespaceid;
167  Oid existing_relid;
168  ParseCallbackState pcbstate;
169  bool like_found = false;
170  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
171 
172  /*
173  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
174  * overkill, but easy.)
175  */
176  stmt = copyObject(stmt);
177 
178  /* Set up pstate */
179  pstate = make_parsestate(NULL);
180  pstate->p_sourcetext = queryString;
181 
182  /*
183  * Look up the creation namespace. This also checks permissions on the
184  * target namespace, locks it against concurrent drops, checks for a
185  * preexisting relation in that namespace with the same name, and updates
186  * stmt->relation->relpersistence if the selected namespace is temporary.
187  */
188  setup_parser_errposition_callback(&pcbstate, pstate,
189  stmt->relation->location);
190  namespaceid =
192  &existing_relid);
194 
195  /*
196  * If the relation already exists and the user specified "IF NOT EXISTS",
197  * bail out with a NOTICE.
198  */
199  if (stmt->if_not_exists && OidIsValid(existing_relid))
200  {
201  ereport(NOTICE,
202  (errcode(ERRCODE_DUPLICATE_TABLE),
203  errmsg("relation \"%s\" already exists, skipping",
204  stmt->relation->relname)));
205  return NIL;
206  }
207 
208  /*
209  * If the target relation name isn't schema-qualified, make it so. This
210  * prevents some corner cases in which added-on rewritten commands might
211  * think they should apply to other relations that have the same name and
212  * are earlier in the search path. But a local temp table is effectively
213  * specified to be in pg_temp, so no need for anything extra in that case.
214  */
215  if (stmt->relation->schemaname == NULL
217  stmt->relation->schemaname = get_namespace_name(namespaceid);
218 
219  /* Set up CreateStmtContext */
220  cxt.pstate = pstate;
221  if (IsA(stmt, CreateForeignTableStmt))
222  {
223  cxt.stmtType = "CREATE FOREIGN TABLE";
224  cxt.isforeign = true;
225  }
226  else
227  {
228  cxt.stmtType = "CREATE TABLE";
229  cxt.isforeign = false;
230  }
231  cxt.relation = stmt->relation;
232  cxt.rel = NULL;
233  cxt.inhRelations = stmt->inhRelations;
234  cxt.isalter = false;
235  cxt.columns = NIL;
236  cxt.ckconstraints = NIL;
237  cxt.fkconstraints = NIL;
238  cxt.ixconstraints = NIL;
239  cxt.inh_indexes = NIL;
240  cxt.blist = NIL;
241  cxt.alist = NIL;
242  cxt.pkey = NULL;
243  cxt.ispartitioned = stmt->partspec != NULL;
244  cxt.partbound = stmt->partbound;
245  cxt.ofType = (stmt->ofTypename != NULL);
246 
247  /*
248  * Notice that we allow OIDs here only for plain tables, even though
249  * foreign tables also support them. This is necessary because the
250  * default_with_oids GUC must apply only to plain tables and not any other
251  * relkind; doing otherwise would break existing pg_dump files. We could
252  * allow explicit "WITH OIDS" while not allowing default_with_oids to
253  * affect other relkinds, but it would complicate interpretOidsOption(),
254  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
255  * anyway.
256  */
257  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
258 
259  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
260 
261  if (stmt->ofTypename)
262  transformOfType(&cxt, stmt->ofTypename);
263 
264  if (stmt->partspec)
265  {
266  if (stmt->inhRelations && !stmt->partbound)
267  ereport(ERROR,
268  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
269  errmsg("cannot create partitioned table as inheritance child")));
270  }
271 
272  /*
273  * Run through each primary element in the table creation clause. Separate
274  * column defs from constraints, and do preliminary analysis.
275  */
276  foreach(elements, stmt->tableElts)
277  {
278  Node *element = lfirst(elements);
279 
280  switch (nodeTag(element))
281  {
282  case T_ColumnDef:
283  transformColumnDefinition(&cxt, (ColumnDef *) element);
284  break;
285 
286  case T_Constraint:
287  transformTableConstraint(&cxt, (Constraint *) element);
288  break;
289 
290  case T_TableLikeClause:
291  like_found = true;
292  transformTableLikeClause(&cxt, (TableLikeClause *) element);
293  break;
294 
295  default:
296  elog(ERROR, "unrecognized node type: %d",
297  (int) nodeTag(element));
298  break;
299  }
300  }
301 
302  /*
303  * If we had any LIKE tables, they may require creation of an OID column
304  * even though the command's own WITH clause didn't ask for one (or,
305  * perhaps, even specifically rejected having one). Insert a WITH option
306  * to ensure that happens. We prepend to the list because the first oid
307  * option will be honored, and we want to override anything already there.
308  * (But note that DefineRelation will override this again to add an OID
309  * column if one appears in an inheritance parent table.)
310  */
311  if (like_found && cxt.hasoids)
312  stmt->options = lcons(makeDefElem("oids",
313  (Node *) makeInteger(true), -1),
314  stmt->options);
315 
316  /*
317  * transformIndexConstraints wants cxt.alist to contain only index
318  * statements, so transfer anything we already have into save_alist.
319  */
320  save_alist = cxt.alist;
321  cxt.alist = NIL;
322 
323  Assert(stmt->constraints == NIL);
324 
325  /*
326  * Postprocess constraints that give rise to index definitions.
327  */
329 
330  /*
331  * Postprocess foreign-key constraints.
332  */
333  transformFKConstraints(&cxt, true, false);
334 
335  /*
336  * Postprocess check constraints.
337  */
338  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
339 
340  /*
341  * Output results.
342  */
343  stmt->tableElts = cxt.columns;
344  stmt->constraints = cxt.ckconstraints;
345 
346  result = lappend(cxt.blist, stmt);
347  result = list_concat(result, cxt.alist);
348  result = list_concat(result, save_alist);
349 
350  return result;
351 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
List * inhRelations
Definition: parsenodes.h:2016
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2021
bool if_not_exists
Definition: parsenodes.h:2025
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parsenodes.h:2018
char * relname
Definition: primnodes.h:68
Value * makeInteger(long i)
Definition: value.c:23
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:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
List * options
Definition: parsenodes.h:2022
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
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:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2015
List * lcons(void *datum, List *list)
Definition: list.c:259
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:517
const char * stmtType
Definition: parse_utilcmd.c:76
char relpersistence
Definition: primnodes.h:71
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2019
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2020
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

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

Definition at line 2241 of file parse_utilcmd.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), copyObject, ereport, errcode(), errmsg(), ERROR, IndexElem::expr, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, FigureIndexColname(), free_parsestate(), heap_close, IndexElem::indexcolname, IndexStmt::indexParams, lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), IndexStmt::transformed, transformExpr(), transformWhereClause(), and IndexStmt::whereClause.

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

2242 {
2243  ParseState *pstate;
2244  RangeTblEntry *rte;
2245  ListCell *l;
2246  Relation rel;
2247 
2248  /* Nothing to do if statement already transformed. */
2249  if (stmt->transformed)
2250  return stmt;
2251 
2252  /*
2253  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2254  * overkill, but easy.)
2255  */
2256  stmt = copyObject(stmt);
2257 
2258  /* Set up pstate */
2259  pstate = make_parsestate(NULL);
2260  pstate->p_sourcetext = queryString;
2261 
2262  /*
2263  * Put the parent table into the rtable so that the expressions can refer
2264  * to its fields without qualification. Caller is responsible for locking
2265  * relation, but we still need to open it.
2266  */
2267  rel = relation_open(relid, NoLock);
2268  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2269 
2270  /* no to join list, yes to namespaces */
2271  addRTEtoQuery(pstate, rte, false, true, true);
2272 
2273  /* take care of the where clause */
2274  if (stmt->whereClause)
2275  {
2276  stmt->whereClause = transformWhereClause(pstate,
2277  stmt->whereClause,
2279  "WHERE");
2280  /* we have to fix its collations too */
2281  assign_expr_collations(pstate, stmt->whereClause);
2282  }
2283 
2284  /* take care of any index expressions */
2285  foreach(l, stmt->indexParams)
2286  {
2287  IndexElem *ielem = (IndexElem *) lfirst(l);
2288 
2289  if (ielem->expr)
2290  {
2291  /* Extract preliminary index col name before transforming expr */
2292  if (ielem->indexcolname == NULL)
2293  ielem->indexcolname = FigureIndexColname(ielem->expr);
2294 
2295  /* Now do parse transformation of the expression */
2296  ielem->expr = transformExpr(pstate, ielem->expr,
2298 
2299  /* We have to fix its collations too */
2300  assign_expr_collations(pstate, ielem->expr);
2301 
2302  /*
2303  * transformExpr() should have already rejected subqueries,
2304  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2305  * for an index expression.
2306  *
2307  * DefineIndex() will make more checks.
2308  */
2309  }
2310  }
2311 
2312  /*
2313  * Check that only the base rel is mentioned. (This should be dead code
2314  * now that add_missing_from is history.)
2315  */
2316  if (list_length(pstate->p_rtable) != 1)
2317  ereport(ERROR,
2318  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2319  errmsg("index expressions and predicates can refer only to the table being indexed")));
2320 
2321  free_parsestate(pstate);
2322 
2323  /* Close relation */
2324  heap_close(rel, NoLock);
2325 
2326  /* Mark statement as successfully transformed */
2327  stmt->transformed = true;
2328 
2329  return stmt;
2330 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Node * whereClause
Definition: parsenodes.h:2716
int errcode(int sqlerrcode)
Definition: elog.c:575
char * FigureIndexColname(Node *node)
#define heap_close(r, l)
Definition: heapam.h:97
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:689
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2726
char * indexcolname
Definition: parsenodes.h:690
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2714
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define copyObject(obj)
Definition: nodes.h:625
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:173

◆ transformPartitionBound()

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

Definition at line 3312 of file parse_utilcmd.c.

References Assert, castNode, Const::constisnull, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), forboth, get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), get_relid_attribute_name(), i, PartitionBoundSpec::is_default, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), PartitionBoundSpec::upperdatums, validateInfiniteBounds(), value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3314 {
3315  PartitionBoundSpec *result_spec;
3316  PartitionKey key = RelationGetPartitionKey(parent);
3317  char strategy = get_partition_strategy(key);
3318  int partnatts = get_partition_natts(key);
3319  List *partexprs = get_partition_exprs(key);
3320 
3321  /* Avoid scribbling on input */
3322  result_spec = copyObject(spec);
3323 
3324  if (spec->is_default)
3325  {
3326  if (strategy == PARTITION_STRATEGY_HASH)
3327  ereport(ERROR,
3328  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3329  errmsg("a hash-partitioned table may not have a default partition")));
3330 
3331  /*
3332  * In case of the default partition, parser had no way to identify the
3333  * partition strategy. Assign the parent's strategy to the default
3334  * partition bound spec.
3335  */
3336  result_spec->strategy = strategy;
3337 
3338  return result_spec;
3339  }
3340 
3341  if (strategy == PARTITION_STRATEGY_HASH)
3342  {
3343  if (spec->strategy != PARTITION_STRATEGY_HASH)
3344  ereport(ERROR,
3345  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3346  errmsg("invalid bound specification for a hash partition"),
3347  parser_errposition(pstate, exprLocation((Node *) spec))));
3348 
3349  if (spec->modulus <= 0)
3350  ereport(ERROR,
3351  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3352  errmsg("modulus for hash partition must be a positive integer")));
3353 
3354  Assert(spec->remainder >= 0);
3355 
3356  if (spec->remainder >= spec->modulus)
3357  ereport(ERROR,
3358  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3359  errmsg("remainder for hash partition must be less than modulus")));
3360  }
3361  else if (strategy == PARTITION_STRATEGY_LIST)
3362  {
3363  ListCell *cell;
3364  char *colname;
3365  Oid coltype;
3366  int32 coltypmod;
3367 
3368  if (spec->strategy != PARTITION_STRATEGY_LIST)
3369  ereport(ERROR,
3370  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3371  errmsg("invalid bound specification for a list partition"),
3372  parser_errposition(pstate, exprLocation((Node *) spec))));
3373 
3374  /* Get the only column's name in case we need to output an error */
3375  if (key->partattrs[0] != 0)
3376  colname = get_relid_attribute_name(RelationGetRelid(parent),
3377  key->partattrs[0]);
3378  else
3379  colname = deparse_expression((Node *) linitial(partexprs),
3381  RelationGetRelid(parent)),
3382  false, false);
3383  /* Need its type data too */
3384  coltype = get_partition_col_typid(key, 0);
3385  coltypmod = get_partition_col_typmod(key, 0);
3386 
3387  result_spec->listdatums = NIL;
3388  foreach(cell, spec->listdatums)
3389  {
3390  A_Const *con = castNode(A_Const, lfirst(cell));
3391  Const *value;
3392  ListCell *cell2;
3393  bool duplicate;
3394 
3395  value = transformPartitionBoundValue(pstate, con,
3396  colname, coltype, coltypmod);
3397 
3398  /* Don't add to the result if the value is a duplicate */
3399  duplicate = false;
3400  foreach(cell2, result_spec->listdatums)
3401  {
3402  Const *value2 = castNode(Const, lfirst(cell2));
3403 
3404  if (equal(value, value2))
3405  {
3406  duplicate = true;
3407  break;
3408  }
3409  }
3410  if (duplicate)
3411  continue;
3412 
3413  result_spec->listdatums = lappend(result_spec->listdatums,
3414  value);
3415  }
3416  }
3417  else if (strategy == PARTITION_STRATEGY_RANGE)
3418  {
3419  ListCell *cell1,
3420  *cell2;
3421  int i,
3422  j;
3423 
3424  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3425  ereport(ERROR,
3426  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3427  errmsg("invalid bound specification for a range partition"),
3428  parser_errposition(pstate, exprLocation((Node *) spec))));
3429 
3430  if (list_length(spec->lowerdatums) != partnatts)
3431  ereport(ERROR,
3432  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3433  errmsg("FROM must specify exactly one value per partitioning column")));
3434  if (list_length(spec->upperdatums) != partnatts)
3435  ereport(ERROR,
3436  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3437  errmsg("TO must specify exactly one value per partitioning column")));
3438 
3439  /*
3440  * Once we see MINVALUE or MAXVALUE for one column, the remaining
3441  * columns must be the same.
3442  */
3443  validateInfiniteBounds(pstate, spec->lowerdatums);
3444  validateInfiniteBounds(pstate, spec->upperdatums);
3445 
3446  /* Transform all the constants */
3447  i = j = 0;
3448  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3449  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3450  {
3451  PartitionRangeDatum *ldatum = (PartitionRangeDatum *) lfirst(cell1);
3452  PartitionRangeDatum *rdatum = (PartitionRangeDatum *) lfirst(cell2);
3453  char *colname;
3454  Oid coltype;
3455  int32 coltypmod;
3456  A_Const *con;
3457  Const *value;
3458 
3459  /* Get the column's name in case we need to output an error */
3460  if (key->partattrs[i] != 0)
3461  colname = get_relid_attribute_name(RelationGetRelid(parent),
3462  key->partattrs[i]);
3463  else
3464  {
3465  colname = deparse_expression((Node *) list_nth(partexprs, j),
3467  RelationGetRelid(parent)),
3468  false, false);
3469  ++j;
3470  }
3471  /* Need its type data too */
3472  coltype = get_partition_col_typid(key, i);
3473  coltypmod = get_partition_col_typmod(key, i);
3474 
3475  if (ldatum->value)
3476  {
3477  con = castNode(A_Const, ldatum->value);
3478  value = transformPartitionBoundValue(pstate, con,
3479  colname,
3480  coltype, coltypmod);
3481  if (value->constisnull)
3482  ereport(ERROR,
3483  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3484  errmsg("cannot specify NULL in range bound")));
3485  ldatum = copyObject(ldatum); /* don't scribble on input */
3486  ldatum->value = (Node *) value;
3487  }
3488 
3489  if (rdatum->value)
3490  {
3491  con = castNode(A_Const, rdatum->value);
3492  value = transformPartitionBoundValue(pstate, con,
3493  colname,
3494  coltype, coltypmod);
3495  if (value->constisnull)
3496  ereport(ERROR,
3497  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3498  errmsg("cannot specify NULL in range bound")));
3499  rdatum = copyObject(rdatum); /* don't scribble on input */
3500  rdatum->value = (Node *) value;
3501  }
3502 
3503  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3504  ldatum);
3505  result_spec->upperdatums = lappend(result_spec->upperdatums,
3506  rdatum);
3507 
3508  ++i;
3509  }
3510  }
3511  else
3512  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3513 
3514  return result_spec;
3515 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
static struct @130 value
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
static Const * transformPartitionBoundValue(ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:294
static int get_partition_natts(PartitionKey key)
Definition: rel.h:605
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static void validateInfiniteBounds(ParseState *pstate, List *blist)
void * list_nth(const List *list, int n)
Definition: list.c:410
static List * get_partition_exprs(PartitionKey key)
Definition: rel.h:611
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3067
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: rel.h:632
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
AttrNumber * partattrs
Definition: rel.h:56
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:626
static int get_partition_strategy(PartitionKey key)
Definition: rel.h:599
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:787
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3008
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:788
#define RelationGetPartitionKey(relation)
Definition: rel.h:593
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:789
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:425
bool constisnull
Definition: primnodes.h:197

◆ transformRuleStmt()

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

Definition at line 2346 of file parse_utilcmd.c.

References AccessExclusiveLock, generate_unaccent_rules::action, RuleStmt::actions, addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, copyObject, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), getInsertSelectQuery(), heap_close, heap_openrv(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_joinlist, ParseState::p_rtable, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RELKIND_MATVIEW, RangeTblEntry::requiredPerms, Query::rtable, Query::setOperations, transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2348 {
2349  Relation rel;
2350  ParseState *pstate;
2351  RangeTblEntry *oldrte;
2352  RangeTblEntry *newrte;
2353 
2354  /*
2355  * To avoid deadlock, make sure the first thing we do is grab
2356  * AccessExclusiveLock on the target relation. This will be needed by
2357  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2358  * beforehand.
2359  */
2361 
2362  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2363  ereport(ERROR,
2364  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2365  errmsg("rules on materialized views are not supported")));
2366 
2367  /* Set up pstate */
2368  pstate = make_parsestate(NULL);
2369  pstate->p_sourcetext = queryString;
2370 
2371  /*
2372  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2373  * Set up their RTEs in the main pstate for use in parsing the rule
2374  * qualification.
2375  */
2376  oldrte = addRangeTableEntryForRelation(pstate, rel,
2377  makeAlias("old", NIL),
2378  false, false);
2379  newrte = addRangeTableEntryForRelation(pstate, rel,
2380  makeAlias("new", NIL),
2381  false, false);
2382  /* Must override addRangeTableEntry's default access-check flags */
2383  oldrte->requiredPerms = 0;
2384  newrte->requiredPerms = 0;
2385 
2386  /*
2387  * They must be in the namespace too for lookup purposes, but only add the
2388  * one(s) that are relevant for the current kind of rule. In an UPDATE
2389  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2390  * there's no need to be so picky for INSERT & DELETE. We do not add them
2391  * to the joinlist.
2392  */
2393  switch (stmt->event)
2394  {
2395  case CMD_SELECT:
2396  addRTEtoQuery(pstate, oldrte, false, true, true);
2397  break;
2398  case CMD_UPDATE:
2399  addRTEtoQuery(pstate, oldrte, false, true, true);
2400  addRTEtoQuery(pstate, newrte, false, true, true);
2401  break;
2402  case CMD_INSERT:
2403  addRTEtoQuery(pstate, newrte, false, true, true);
2404  break;
2405  case CMD_DELETE:
2406  addRTEtoQuery(pstate, oldrte, false, true, true);
2407  break;
2408  default:
2409  elog(ERROR, "unrecognized event type: %d",
2410  (int) stmt->event);
2411  break;
2412  }
2413 
2414  /* take care of the where clause */
2415  *whereClause = transformWhereClause(pstate,
2416  (Node *) copyObject(stmt->whereClause),
2418  "WHERE");
2419  /* we have to fix its collations too */
2420  assign_expr_collations(pstate, *whereClause);
2421 
2422  /* this is probably dead code without add_missing_from: */
2423  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2424  ereport(ERROR,
2425  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2426  errmsg("rule WHERE condition cannot contain references to other relations")));
2427 
2428  /*
2429  * 'instead nothing' rules with a qualification need a query rangetable so
2430  * the rewrite handler can add the negated rule qualification to the
2431  * original query. We create a query with the new command type CMD_NOTHING
2432  * here that is treated specially by the rewrite system.
2433  */
2434  if (stmt->actions == NIL)
2435  {
2436  Query *nothing_qry = makeNode(Query);
2437 
2438  nothing_qry->commandType = CMD_NOTHING;
2439  nothing_qry->rtable = pstate->p_rtable;
2440  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2441 
2442  *actions = list_make1(nothing_qry);
2443  }
2444  else
2445  {
2446  ListCell *l;
2447  List *newactions = NIL;
2448 
2449  /*
2450  * transform each statement, like parse_sub_analyze()
2451  */
2452  foreach(l, stmt->actions)
2453  {
2454  Node *action = (Node *) lfirst(l);
2455  ParseState *sub_pstate = make_parsestate(NULL);
2456  Query *sub_qry,
2457  *top_subqry;
2458  bool has_old,
2459  has_new;
2460 
2461  /*
2462  * Since outer ParseState isn't parent of inner, have to pass down
2463  * the query text by hand.
2464  */
2465  sub_pstate->p_sourcetext = queryString;
2466 
2467  /*
2468  * Set up OLD/NEW in the rtable for this statement. The entries
2469  * are added only to relnamespace, not varnamespace, because we
2470  * don't want them to be referred to by unqualified field names
2471  * nor "*" in the rule actions. We decide later whether to put
2472  * them in the joinlist.
2473  */
2474  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2475  makeAlias("old", NIL),
2476  false, false);
2477  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2478  makeAlias("new", NIL),
2479  false, false);
2480  oldrte->requiredPerms = 0;
2481  newrte->requiredPerms = 0;
2482  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2483  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2484 
2485  /* Transform the rule action statement */
2486  top_subqry = transformStmt(sub_pstate,
2487  (Node *) copyObject(action));
2488 
2489  /*
2490  * We cannot support utility-statement actions (eg NOTIFY) with
2491  * nonempty rule WHERE conditions, because there's no way to make
2492  * the utility action execute conditionally.
2493  */
2494  if (top_subqry->commandType == CMD_UTILITY &&
2495  *whereClause != NULL)
2496  ereport(ERROR,
2497  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2498  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2499 
2500  /*
2501  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2502  * into the SELECT, and that's what we need to look at. (Ugly
2503  * kluge ... try to fix this when we redesign querytrees.)
2504  */
2505  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2506 
2507  /*
2508  * If the sub_qry is a setop, we cannot attach any qualifications
2509  * to it, because the planner won't notice them. This could
2510  * perhaps be relaxed someday, but for now, we may as well reject
2511  * such a rule immediately.
2512  */
2513  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2514  ereport(ERROR,
2515  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2516  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2517 
2518  /*
2519  * Validate action's use of OLD/NEW, qual too
2520  */
2521  has_old =
2522  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2523  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2524  has_new =
2525  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2526  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2527 
2528  switch (stmt->event)
2529  {
2530  case CMD_SELECT:
2531  if (has_old)
2532  ereport(ERROR,
2533  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2534  errmsg("ON SELECT rule cannot use OLD")));
2535  if (has_new)
2536  ereport(ERROR,
2537  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2538  errmsg("ON SELECT rule cannot use NEW")));
2539  break;
2540  case CMD_UPDATE:
2541  /* both are OK */
2542  break;
2543  case CMD_INSERT:
2544  if (has_old)
2545  ereport(ERROR,
2546  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2547  errmsg("ON INSERT rule cannot use OLD")));
2548  break;
2549  case CMD_DELETE:
2550  if (has_new)
2551  ereport(ERROR,
2552  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2553  errmsg("ON DELETE rule cannot use NEW")));
2554  break;
2555  default:
2556  elog(ERROR, "unrecognized event type: %d",
2557  (int) stmt->event);
2558  break;
2559  }
2560 
2561  /*
2562  * OLD/NEW are not allowed in WITH queries, because they would
2563  * amount to outer references for the WITH, which we disallow.
2564  * However, they were already in the outer rangetable when we
2565  * analyzed the query, so we have to check.
2566  *
2567  * Note that in the INSERT...SELECT case, we need to examine the
2568  * CTE lists of both top_subqry and sub_qry.
2569  *
2570  * Note that we aren't digging into the body of the query looking
2571  * for WITHs in nested sub-SELECTs. A WITH down there can
2572  * legitimately refer to OLD/NEW, because it'd be an
2573  * indirect-correlated outer reference.
2574  */
2575  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2576  PRS2_OLD_VARNO, 0) ||
2577  rangeTableEntry_used((Node *) sub_qry->cteList,
2578  PRS2_OLD_VARNO, 0))
2579  ereport(ERROR,
2580  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2581  errmsg("cannot refer to OLD within WITH query")));
2582  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2583  PRS2_NEW_VARNO, 0) ||
2584  rangeTableEntry_used((Node *) sub_qry->cteList,
2585  PRS2_NEW_VARNO, 0))
2586  ereport(ERROR,
2587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2588  errmsg("cannot refer to NEW within WITH query")));
2589 
2590  /*
2591  * For efficiency's sake, add OLD to the rule action's jointree
2592  * only if it was actually referenced in the statement or qual.
2593  *
2594  * For INSERT, NEW is not really a relation (only a reference to
2595  * the to-be-inserted tuple) and should never be added to the
2596  * jointree.
2597  *
2598  * For UPDATE, we treat NEW as being another kind of reference to
2599  * OLD, because it represents references to *transformed* tuples
2600  * of the existing relation. It would be wrong to enter NEW
2601  * separately in the jointree, since that would cause a double
2602  * join of the updated relation. It's also wrong to fail to make
2603  * a jointree entry if only NEW and not OLD is mentioned.
2604  */
2605  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2606  {
2607  /*
2608  * If sub_qry is a setop, manipulating its jointree will do no
2609  * good at all, because the jointree is dummy. (This should be
2610  * a can't-happen case because of prior tests.)
2611  */
2612  if (sub_qry->setOperations != NULL)
2613  ereport(ERROR,
2614  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2615  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2616  /* hack so we can use addRTEtoQuery() */
2617  sub_pstate->p_rtable = sub_qry->rtable;
2618  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2619  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2620  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2621  }
2622 
2623  newactions = lappend(newactions, top_subqry);
2624 
2625  free_parsestate(sub_pstate);
2626  }
2627 
2628  *actions = newactions;
2629  }
2630 
2631  free_parsestate(pstate);
2632 
2633  /* Close relation, but keep the exclusive lock */
2634  heap_close(rel, NoLock);
2635 }
#define NIL
Definition: pg_list.h:69
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:284
FromExpr * jointree
Definition: parsenodes.h:136
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
List * actions
Definition: parsenodes.h:2901
AclMode requiredPerms
Definition: parsenodes.h:1059
List * fromlist
Definition: primnodes.h:1478
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:386
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:172
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:250
List * lappend(List *list, void *datum)
Definition: list.c:128
#define PRS2_OLD_VARNO
Definition: primnodes.h:160
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:560
CmdType event
Definition: parsenodes.h:2899
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2898
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * p_joinlist
Definition: parse_node.h:175
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
RangeVar * relation
Definition: parsenodes.h:2896
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
#define PRS2_NEW_VARNO
Definition: primnodes.h:161
List * p_rtable
Definition: parse_node.h:173