PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
matview.h File Reference
#include "catalog/objectaddress.h"
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "tcop/dest.h"
#include "utils/relcache.h"
Include dependency graph for matview.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void SetMatViewPopulatedState (Relation relation, bool newstate)
 
ObjectAddress ExecRefreshMatView (RefreshMatViewStmt *stmt, const char *queryString, ParamListInfo params, char *completionTag)
 
DestReceiverCreateTransientRelDestReceiver (Oid oid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Function Documentation

DestReceiver* CreateTransientRelDestReceiver ( Oid  oid)

Definition at line 419 of file matview.c.

References DestTransientRel, palloc0(), transientrel_destroy(), transientrel_receive(), transientrel_shutdown(), and transientrel_startup().

Referenced by CreateDestReceiver(), and ExecRefreshMatView().

420 {
422 
423  self->pub.receiveSlot = transientrel_receive;
424  self->pub.rStartup = transientrel_startup;
425  self->pub.rShutdown = transientrel_shutdown;
426  self->pub.rDestroy = transientrel_destroy;
427  self->pub.mydest = DestTransientRel;
428  self->transientoid = transientoid;
429 
430  return (DestReceiver *) self;
431 }
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:437
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:512
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:493
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:467
void * palloc0(Size size)
Definition: mcxt.c:920
ObjectAddress ExecRefreshMatView ( RefreshMatViewStmt stmt,
const char *  queryString,
ParamListInfo  params,
char *  completionTag 
)

Definition at line 136 of file matview.c.

References AccessExclusiveLock, AccessShareLock, RewriteRule::actions, Assert, AtEOXact_GUC(), castNode, CheckTableNotInUse(), CMD_SELECT, RefreshMatViewStmt::concurrent, CreateTransientRelDestReceiver(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, RewriteRule::event, ExclusiveLock, get_namespace_name(), GetDefaultTablespace(), GetUserIdAndSecContext(), heap_close, heap_open(), index_close(), index_open(), IndexIsValid, RewriteRule::isInstead, lfirst_oid, linitial, list_free(), list_length(), LockRelationOid(), make_new_heap(), matview_maintenance_depth, NewGUCNestLevel(), NIL, NoLock, NULL, RuleLock::numLocks, ObjectAddressSet, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, quote_qualified_identifier(), RangeVarCallbackOwnsTable(), RangeVarGetRelidExtended(), RelationData::rd_index, RelationData::rd_rel, RelationData::rd_rules, refresh_by_heap_swap(), refresh_by_match_merge(), refresh_matview_datafill(), RefreshMatViewStmt::relation, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationIsPopulated, RelationRelationId, RELKIND_MATVIEW, RELPERSISTENCE_TEMP, RuleLock::rules, SECURITY_LOCAL_USERID_CHANGE, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetUserIdAndSecContext(), and RefreshMatViewStmt::skipData.

Referenced by ProcessUtilitySlow().

138 {
139  Oid matviewOid;
140  Relation matviewRel;
141  RewriteRule *rule;
142  List *actions;
143  Query *dataQuery;
144  Oid tableSpace;
145  Oid relowner;
146  Oid OIDNewHeap;
147  DestReceiver *dest;
148  bool concurrent;
149  LOCKMODE lockmode;
150  char relpersistence;
151  Oid save_userid;
152  int save_sec_context;
153  int save_nestlevel;
154  ObjectAddress address;
155 
156  /* Determine strength of lock needed. */
157  concurrent = stmt->concurrent;
158  lockmode = concurrent ? ExclusiveLock : AccessExclusiveLock;
159 
160  /*
161  * Get a lock until end of transaction.
162  */
163  matviewOid = RangeVarGetRelidExtended(stmt->relation,
164  lockmode, false, false,
166  matviewRel = heap_open(matviewOid, NoLock);
167 
168  /* Make sure it is a materialized view. */
169  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
170  ereport(ERROR,
171  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
172  errmsg("\"%s\" is not a materialized view",
173  RelationGetRelationName(matviewRel))));
174 
175  /* Check that CONCURRENTLY is not specified if not populated. */
176  if (concurrent && !RelationIsPopulated(matviewRel))
177  ereport(ERROR,
178  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
179  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
180 
181  /* Check that conflicting options have not been specified. */
182  if (concurrent && stmt->skipData)
183  ereport(ERROR,
184  (errcode(ERRCODE_SYNTAX_ERROR),
185  errmsg("CONCURRENTLY and WITH NO DATA options cannot be used together")));
186 
187  /* We don't allow an oid column for a materialized view. */
188  Assert(!matviewRel->rd_rel->relhasoids);
189 
190  /*
191  * Check that everything is correct for a refresh. Problems at this point
192  * are internal errors, so elog is sufficient.
193  */
194  if (matviewRel->rd_rel->relhasrules == false ||
195  matviewRel->rd_rules->numLocks < 1)
196  elog(ERROR,
197  "materialized view \"%s\" is missing rewrite information",
198  RelationGetRelationName(matviewRel));
199 
200  if (matviewRel->rd_rules->numLocks > 1)
201  elog(ERROR,
202  "materialized view \"%s\" has too many rules",
203  RelationGetRelationName(matviewRel));
204 
205  rule = matviewRel->rd_rules->rules[0];
206  if (rule->event != CMD_SELECT || !(rule->isInstead))
207  elog(ERROR,
208  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
209  RelationGetRelationName(matviewRel));
210 
211  actions = rule->actions;
212  if (list_length(actions) != 1)
213  elog(ERROR,
214  "the rule for materialized view \"%s\" is not a single action",
215  RelationGetRelationName(matviewRel));
216 
217  /*
218  * Check that there is a unique index with no WHERE clause on one or more
219  * columns of the materialized view if CONCURRENTLY is specified.
220  */
221  if (concurrent)
222  {
223  List *indexoidlist = RelationGetIndexList(matviewRel);
224  ListCell *indexoidscan;
225  bool hasUniqueIndex = false;
226 
227  foreach(indexoidscan, indexoidlist)
228  {
229  Oid indexoid = lfirst_oid(indexoidscan);
230  Relation indexRel;
231  Form_pg_index indexStruct;
232 
233  indexRel = index_open(indexoid, AccessShareLock);
234  indexStruct = indexRel->rd_index;
235 
236  if (indexStruct->indisunique &&
237  IndexIsValid(indexStruct) &&
238  RelationGetIndexExpressions(indexRel) == NIL &&
239  RelationGetIndexPredicate(indexRel) == NIL &&
240  indexStruct->indnatts > 0)
241  {
242  hasUniqueIndex = true;
243  index_close(indexRel, AccessShareLock);
244  break;
245  }
246 
247  index_close(indexRel, AccessShareLock);
248  }
249 
250  list_free(indexoidlist);
251 
252  if (!hasUniqueIndex)
253  ereport(ERROR,
254  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
255  errmsg("cannot refresh materialized view \"%s\" concurrently",
257  RelationGetRelationName(matviewRel))),
258  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
259  }
260 
261  /*
262  * The stored query was rewritten at the time of the MV definition, but
263  * has not been scribbled on by the planner.
264  */
265  dataQuery = castNode(Query, linitial(actions));
266 
267  /*
268  * Check for active uses of the relation in the current transaction, such
269  * as open scans.
270  *
271  * NB: We count on this to protect us against problems with refreshing the
272  * data using HEAP_INSERT_FROZEN.
273  */
274  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
275 
276  /*
277  * Tentatively mark the matview as populated or not (this will roll back
278  * if we fail later).
279  */
280  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
281 
282  relowner = matviewRel->rd_rel->relowner;
283 
284  /*
285  * Switch to the owner's userid, so that any functions are run as that
286  * user. Also arrange to make GUC variable changes local to this command.
287  * Don't lock it down too tight to create a temporary table just yet. We
288  * will switch modes when we are about to execute user code.
289  */
290  GetUserIdAndSecContext(&save_userid, &save_sec_context);
291  SetUserIdAndSecContext(relowner,
292  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
293  save_nestlevel = NewGUCNestLevel();
294 
295  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
296  if (concurrent)
297  {
299  relpersistence = RELPERSISTENCE_TEMP;
300  }
301  else
302  {
303  tableSpace = matviewRel->rd_rel->reltablespace;
304  relpersistence = matviewRel->rd_rel->relpersistence;
305  }
306 
307  /*
308  * Create the transient table that will receive the regenerated data. Lock
309  * it against access by any other process until commit (by which time it
310  * will be gone).
311  */
312  OIDNewHeap = make_new_heap(matviewOid, tableSpace, relpersistence,
313  ExclusiveLock);
315  dest = CreateTransientRelDestReceiver(OIDNewHeap);
316 
317  /*
318  * Now lock down security-restricted operations.
319  */
320  SetUserIdAndSecContext(relowner,
321  save_sec_context | SECURITY_RESTRICTED_OPERATION);
322 
323  /* Generate the data, if wanted. */
324  if (!stmt->skipData)
325  refresh_matview_datafill(dest, dataQuery, queryString);
326 
327  heap_close(matviewRel, NoLock);
328 
329  /* Make the matview match the newly generated data. */
330  if (concurrent)
331  {
332  int old_depth = matview_maintenance_depth;
333 
334  PG_TRY();
335  {
336  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
337  save_sec_context);
338  }
339  PG_CATCH();
340  {
341  matview_maintenance_depth = old_depth;
342  PG_RE_THROW();
343  }
344  PG_END_TRY();
345  Assert(matview_maintenance_depth == old_depth);
346  }
347  else
348  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
349 
350  /* Roll back any GUC changes */
351  AtEOXact_GUC(false, save_nestlevel);
352 
353  /* Restore userid and security context */
354  SetUserIdAndSecContext(save_userid, save_sec_context);
355 
356  ObjectAddressSet(address, RelationRelationId, matviewOid);
357 
358  return address;
359 }
#define RelationIsPopulated(relation)
Definition: rel.h:549
#define NIL
Definition: pg_list.h:69
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:12585
int errhint(const char *fmt,...)
Definition: elog.c:987
int numLocks
Definition: prs2lock.h:42
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:292
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
int LOCKMODE
Definition: lockdefs.h:26
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:217
#define ExclusiveLock
Definition: lockdefs.h:44
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:167
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool isInstead
Definition: prs2lock.h:31
RangeVar * relation
Definition: parsenodes.h:3036
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1112
Definition: localtime.c:74
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4676
Form_pg_index rd_index
Definition: rel.h:155
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4613
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5040
static void refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:365
#define RelationGetRelationName(relation)
Definition: rel.h:433
RewriteRule ** rules
Definition: prs2lock.h:43
List * actions
Definition: prs2lock.h:29
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2950
#define ereport(elevel, rest)
Definition: elog.h:122
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:817
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10054
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:291
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
RuleLock * rd_rules
Definition: rel.h:117
static int list_length(const List *l)
Definition: pg_list.h:89
#define PG_RE_THROW()
Definition: elog.h:314
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4336
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define AccessExclusiveLock
Definition: lockdefs.h:46
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:419
int NewGUCNestLevel(void)
Definition: guc.c:5026
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int matview_maintenance_depth
Definition: matview.c:56
void list_free(List *list)
Definition: list.c:1133
#define elog
Definition: elog.h:219
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
#define PG_TRY()
Definition: elog.h:284
Definition: pg_list.h:45
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:82
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define PG_END_TRY()
Definition: elog.h:300
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:606
#define lfirst_oid(lc)
Definition: pg_list.h:108
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:588
#define RelationGetNamespace(relation)
Definition: rel.h:440
bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 836 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

837 {
838  return matview_maintenance_depth > 0;
839 }
static int matview_maintenance_depth
Definition: matview.c:56
void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 82 of file matview.c.

References Assert, CatalogTupleUpdate(), CommandCounterIncrement(), elog, ERROR, GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, ObjectIdGetDatum, RelationData::rd_rel, RelationGetRelid, RelationRelationId, RELKIND_MATVIEW, RELOID, RowExclusiveLock, SearchSysCacheCopy1, and HeapTupleData::t_self.

Referenced by ExecRefreshMatView(), and intorel_startup().

83 {
84  Relation pgrel;
85  HeapTuple tuple;
86 
87  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
88 
89  /*
90  * Update relation's pg_class entry. Crucial side-effect: other backends
91  * (and this one too!) are sent SI message to make them rebuild relcache
92  * entries.
93  */
97  if (!HeapTupleIsValid(tuple))
98  elog(ERROR, "cache lookup failed for relation %u",
99  RelationGetRelid(relation));
100 
101  ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
102 
103  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
104 
105  heap_freetuple(tuple);
107 
108  /*
109  * Advance command counter to make the updated pg_class row locally
110  * visible.
111  */
113 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:167
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
void CommandCounterIncrement(void)
Definition: xact.c:921
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:670
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:158
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:413