PostgreSQL Source Code  git master
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

◆ CreateTransientRelDestReceiver()

DestReceiver* CreateTransientRelDestReceiver ( Oid  oid)

Definition at line 443 of file matview.c.

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

Referenced by CreateDestReceiver(), and ExecRefreshMatView().

444 {
446 
447  self->pub.receiveSlot = transientrel_receive;
448  self->pub.rStartup = transientrel_startup;
449  self->pub.rShutdown = transientrel_shutdown;
450  self->pub.rDestroy = transientrel_destroy;
451  self->pub.mydest = DestTransientRel;
452  self->transientoid = transientoid;
453 
454  return (DestReceiver *) self;
455 }
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:461
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:536
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:517
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:491
void * palloc0(Size size)
Definition: mcxt.c:877

◆ ExecRefreshMatView()

ObjectAddress ExecRefreshMatView ( RefreshMatViewStmt stmt,
const char *  queryString,
ParamListInfo  params,
char *  completionTag 
)

Definition at line 137 of file matview.c.

References AccessExclusiveLock, AccessShareLock, RewriteRule::actions, Assert, AtEOXact_GUC(), CheckTableNotInUse(), CMD_SELECT, RefreshMatViewStmt::concurrent, CreateTransientRelDestReceiver(), generate_unaccent_rules::dest, 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_node, list_free(), list_length(), LockRelationOid(), make_new_heap(), matview_maintenance_depth, NewGUCNestLevel(), NIL, NoLock, RuleLock::numLocks, ObjectAddressSet, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgstat_count_heap_insert(), pgstat_count_truncate(), 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().

139 {
140  Oid matviewOid;
141  Relation matviewRel;
142  RewriteRule *rule;
143  List *actions;
144  Query *dataQuery;
145  Oid tableSpace;
146  Oid relowner;
147  Oid OIDNewHeap;
149  uint64 processed = 0;
150  bool concurrent;
151  LOCKMODE lockmode;
152  char relpersistence;
153  Oid save_userid;
154  int save_sec_context;
155  int save_nestlevel;
156  ObjectAddress address;
157 
158  /* Determine strength of lock needed. */
159  concurrent = stmt->concurrent;
160  lockmode = concurrent ? ExclusiveLock : AccessExclusiveLock;
161 
162  /*
163  * Get a lock until end of transaction.
164  */
165  matviewOid = RangeVarGetRelidExtended(stmt->relation,
166  lockmode, false, false,
168  matviewRel = heap_open(matviewOid, NoLock);
169 
170  /* Make sure it is a materialized view. */
171  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
172  ereport(ERROR,
173  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
174  errmsg("\"%s\" is not a materialized view",
175  RelationGetRelationName(matviewRel))));
176 
177  /* Check that CONCURRENTLY is not specified if not populated. */
178  if (concurrent && !RelationIsPopulated(matviewRel))
179  ereport(ERROR,
180  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
181  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
182 
183  /* Check that conflicting options have not been specified. */
184  if (concurrent && stmt->skipData)
185  ereport(ERROR,
186  (errcode(ERRCODE_SYNTAX_ERROR),
187  errmsg("CONCURRENTLY and WITH NO DATA options cannot be used together")));
188 
189  /* We don't allow an oid column for a materialized view. */
190  Assert(!matviewRel->rd_rel->relhasoids);
191 
192  /*
193  * Check that everything is correct for a refresh. Problems at this point
194  * are internal errors, so elog is sufficient.
195  */
196  if (matviewRel->rd_rel->relhasrules == false ||
197  matviewRel->rd_rules->numLocks < 1)
198  elog(ERROR,
199  "materialized view \"%s\" is missing rewrite information",
200  RelationGetRelationName(matviewRel));
201 
202  if (matviewRel->rd_rules->numLocks > 1)
203  elog(ERROR,
204  "materialized view \"%s\" has too many rules",
205  RelationGetRelationName(matviewRel));
206 
207  rule = matviewRel->rd_rules->rules[0];
208  if (rule->event != CMD_SELECT || !(rule->isInstead))
209  elog(ERROR,
210  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
211  RelationGetRelationName(matviewRel));
212 
213  actions = rule->actions;
214  if (list_length(actions) != 1)
215  elog(ERROR,
216  "the rule for materialized view \"%s\" is not a single action",
217  RelationGetRelationName(matviewRel));
218 
219  /*
220  * Check that there is a unique index with no WHERE clause on one or more
221  * columns of the materialized view if CONCURRENTLY is specified.
222  */
223  if (concurrent)
224  {
225  List *indexoidlist = RelationGetIndexList(matviewRel);
226  ListCell *indexoidscan;
227  bool hasUniqueIndex = false;
228 
229  foreach(indexoidscan, indexoidlist)
230  {
231  Oid indexoid = lfirst_oid(indexoidscan);
232  Relation indexRel;
233  Form_pg_index indexStruct;
234 
235  indexRel = index_open(indexoid, AccessShareLock);
236  indexStruct = indexRel->rd_index;
237 
238  if (indexStruct->indisunique &&
239  IndexIsValid(indexStruct) &&
240  RelationGetIndexExpressions(indexRel) == NIL &&
241  RelationGetIndexPredicate(indexRel) == NIL &&
242  indexStruct->indnatts > 0)
243  {
244  hasUniqueIndex = true;
245  index_close(indexRel, AccessShareLock);
246  break;
247  }
248 
249  index_close(indexRel, AccessShareLock);
250  }
251 
252  list_free(indexoidlist);
253 
254  if (!hasUniqueIndex)
255  ereport(ERROR,
256  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
257  errmsg("cannot refresh materialized view \"%s\" concurrently",
259  RelationGetRelationName(matviewRel))),
260  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
261  }
262 
263  /*
264  * The stored query was rewritten at the time of the MV definition, but
265  * has not been scribbled on by the planner.
266  */
267  dataQuery = linitial_node(Query, actions);
268 
269  /*
270  * Check for active uses of the relation in the current transaction, such
271  * as open scans.
272  *
273  * NB: We count on this to protect us against problems with refreshing the
274  * data using HEAP_INSERT_FROZEN.
275  */
276  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
277 
278  /*
279  * Tentatively mark the matview as populated or not (this will roll back
280  * if we fail later).
281  */
282  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
283 
284  relowner = matviewRel->rd_rel->relowner;
285 
286  /*
287  * Switch to the owner's userid, so that any functions are run as that
288  * user. Also arrange to make GUC variable changes local to this command.
289  * Don't lock it down too tight to create a temporary table just yet. We
290  * will switch modes when we are about to execute user code.
291  */
292  GetUserIdAndSecContext(&save_userid, &save_sec_context);
293  SetUserIdAndSecContext(relowner,
294  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
295  save_nestlevel = NewGUCNestLevel();
296 
297  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
298  if (concurrent)
299  {
301  relpersistence = RELPERSISTENCE_TEMP;
302  }
303  else
304  {
305  tableSpace = matviewRel->rd_rel->reltablespace;
306  relpersistence = matviewRel->rd_rel->relpersistence;
307  }
308 
309  /*
310  * Create the transient table that will receive the regenerated data. Lock
311  * it against access by any other process until commit (by which time it
312  * will be gone).
313  */
314  OIDNewHeap = make_new_heap(matviewOid, tableSpace, relpersistence,
315  ExclusiveLock);
317  dest = CreateTransientRelDestReceiver(OIDNewHeap);
318 
319  /*
320  * Now lock down security-restricted operations.
321  */
322  SetUserIdAndSecContext(relowner,
323  save_sec_context | SECURITY_RESTRICTED_OPERATION);
324 
325  /* Generate the data, if wanted. */
326  if (!stmt->skipData)
327  processed = refresh_matview_datafill(dest, dataQuery, queryString);
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  {
349  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
350 
351  /*
352  * Inform stats collector about our activity: basically, we truncated
353  * the matview and inserted some new data. (The concurrent code path
354  * above doesn't need to worry about this because the inserts and
355  * deletes it issues get counted by lower-level code.)
356  */
357  pgstat_count_truncate(matviewRel);
358  if (!stmt->skipData)
359  pgstat_count_heap_insert(matviewRel, processed);
360  }
361 
362  heap_close(matviewRel, NoLock);
363 
364  /* Roll back any GUC changes */
365  AtEOXact_GUC(false, save_nestlevel);
366 
367  /* Restore userid and security context */
368  SetUserIdAndSecContext(save_userid, save_sec_context);
369 
370  ObjectAddressSet(address, RelationRelationId, matviewOid);
371 
372  return address;
373 }
#define RelationIsPopulated(relation)
Definition: rel.h:561
#define NIL
Definition: pg_list.h:69
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:13138
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:294
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
int LOCKMODE
Definition: lockdefs.h:26
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define ExclusiveLock
Definition: lockdefs.h:44
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#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:114
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
bool isInstead
Definition: prs2lock.h:31
RangeVar * relation
Definition: parsenodes.h:3177
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1111
Definition: localtime.c:78
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4779
Form_pg_index rd_index
Definition: rel.h:159
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3047
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4716
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5098
#define RelationGetRelationName(relation)
Definition: rel.h:445
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2008
RewriteRule ** rules
Definition: prs2lock.h:43
List * actions
Definition: prs2lock.h:29
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3063
#define ereport(elevel, rest)
Definition: elog.h:122
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:842
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10492
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:293
#define PG_CATCH()
Definition: elog.h:293
#define Assert(condition)
Definition: c.h:670
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:384
RuleLock * rd_rules
Definition: rel.h:118
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:4360
#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:45
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:443
int NewGUCNestLevel(void)
Definition: guc.c:5084
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:1907
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int matview_maintenance_depth
Definition: matview.c:57
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:83
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:608
#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:612
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 861 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

862 {
863  return matview_maintenance_depth > 0;
864 }
static int matview_maintenance_depth
Definition: matview.c:57

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

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

84 {
85  Relation pgrel;
86  HeapTuple tuple;
87 
88  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
89 
90  /*
91  * Update relation's pg_class entry. Crucial side-effect: other backends
92  * (and this one too!) are sent SI message to make them rebuild relcache
93  * entries.
94  */
98  if (!HeapTupleIsValid(tuple))
99  elog(ERROR, "cache lookup failed for relation %u",
100  RelationGetRelid(relation));
101 
102  ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
103 
104  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
105 
106  heap_freetuple(tuple);
108 
109  /*
110  * Advance command counter to make the updated pg_class row locally
111  * visible.
112  */
114 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:915
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#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:173
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:425