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 430 of file matview.c.

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

Referenced by CreateDestReceiver(), and ExecRefreshMatView().

431 {
433 
434  self->pub.receiveSlot = transientrel_receive;
435  self->pub.rStartup = transientrel_startup;
436  self->pub.rShutdown = transientrel_shutdown;
437  self->pub.rDestroy = transientrel_destroy;
438  self->pub.mydest = DestTransientRel;
439  self->transientoid = transientoid;
440 
441  return (DestReceiver *) self;
442 }
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:448
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:523
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:504
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:478
void * palloc0(Size size)
Definition: mcxt.c:955

◆ ExecRefreshMatView()

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

Definition at line 135 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(), is_usable_unique_index(), RewriteRule::isInstead, lfirst_oid, linitial_node, list_free(), list_length(), LockRelationOid(), make_new_heap(), matview_maintenance_depth, NewGUCNestLevel(), 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_rel, RelationData::rd_rules, refresh_by_heap_swap(), refresh_by_match_merge(), refresh_matview_datafill(), RefreshMatViewStmt::relation, RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, RelationIsPopulated, relowner, relpersistence, RuleLock::rules, SECURITY_LOCAL_USERID_CHANGE, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetUserIdAndSecContext(), and RefreshMatViewStmt::skipData.

Referenced by ProcessUtilitySlow().

137 {
138  Oid matviewOid;
139  Relation matviewRel;
140  RewriteRule *rule;
141  List *actions;
142  Query *dataQuery;
143  Oid tableSpace;
144  Oid relowner;
145  Oid OIDNewHeap;
147  uint64 processed = 0;
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, 0,
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 
232  indexRel = index_open(indexoid, AccessShareLock);
233  hasUniqueIndex = is_usable_unique_index(indexRel);
234  index_close(indexRel, AccessShareLock);
235  if (hasUniqueIndex)
236  break;
237  }
238 
239  list_free(indexoidlist);
240 
241  if (!hasUniqueIndex)
242  ereport(ERROR,
243  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
244  errmsg("cannot refresh materialized view \"%s\" concurrently",
246  RelationGetRelationName(matviewRel))),
247  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
248  }
249 
250  /*
251  * The stored query was rewritten at the time of the MV definition, but
252  * has not been scribbled on by the planner.
253  */
254  dataQuery = linitial_node(Query, actions);
255 
256  /*
257  * Check for active uses of the relation in the current transaction, such
258  * as open scans.
259  *
260  * NB: We count on this to protect us against problems with refreshing the
261  * data using HEAP_INSERT_FROZEN.
262  */
263  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
264 
265  /*
266  * Tentatively mark the matview as populated or not (this will roll back
267  * if we fail later).
268  */
269  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
270 
271  relowner = matviewRel->rd_rel->relowner;
272 
273  /*
274  * Switch to the owner's userid, so that any functions are run as that
275  * user. Also arrange to make GUC variable changes local to this command.
276  * Don't lock it down too tight to create a temporary table just yet. We
277  * will switch modes when we are about to execute user code.
278  */
279  GetUserIdAndSecContext(&save_userid, &save_sec_context);
280  SetUserIdAndSecContext(relowner,
281  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
282  save_nestlevel = NewGUCNestLevel();
283 
284  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
285  if (concurrent)
286  {
287  tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP);
288  relpersistence = RELPERSISTENCE_TEMP;
289  }
290  else
291  {
292  tableSpace = matviewRel->rd_rel->reltablespace;
293  relpersistence = matviewRel->rd_rel->relpersistence;
294  }
295 
296  /*
297  * Create the transient table that will receive the regenerated data. Lock
298  * it against access by any other process until commit (by which time it
299  * will be gone).
300  */
301  OIDNewHeap = make_new_heap(matviewOid, tableSpace, relpersistence,
302  ExclusiveLock);
304  dest = CreateTransientRelDestReceiver(OIDNewHeap);
305 
306  /*
307  * Now lock down security-restricted operations.
308  */
309  SetUserIdAndSecContext(relowner,
310  save_sec_context | SECURITY_RESTRICTED_OPERATION);
311 
312  /* Generate the data, if wanted. */
313  if (!stmt->skipData)
314  processed = refresh_matview_datafill(dest, dataQuery, queryString);
315 
316  /* Make the matview match the newly generated data. */
317  if (concurrent)
318  {
319  int old_depth = matview_maintenance_depth;
320 
321  PG_TRY();
322  {
323  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
324  save_sec_context);
325  }
326  PG_CATCH();
327  {
328  matview_maintenance_depth = old_depth;
329  PG_RE_THROW();
330  }
331  PG_END_TRY();
332  Assert(matview_maintenance_depth == old_depth);
333  }
334  else
335  {
336  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
337 
338  /*
339  * Inform stats collector about our activity: basically, we truncated
340  * the matview and inserted some new data. (The concurrent code path
341  * above doesn't need to worry about this because the inserts and
342  * deletes it issues get counted by lower-level code.)
343  */
344  pgstat_count_truncate(matviewRel);
345  if (!stmt->skipData)
346  pgstat_count_heap_insert(matviewRel, processed);
347  }
348 
349  heap_close(matviewRel, NoLock);
350 
351  /* Roll back any GUC changes */
352  AtEOXact_GUC(false, save_nestlevel);
353 
354  /* Restore userid and security context */
355  SetUserIdAndSecContext(save_userid, save_sec_context);
356 
357  ObjectAddressSet(address, RelationRelationId, matviewOid);
358 
359  return address;
360 }
#define RelationIsPopulated(relation)
Definition: rel.h:557
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:858
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:13373
int errhint(const char *fmt,...)
Definition: elog.c:987
int numLocks
Definition: prs2lock.h:42
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
int LOCKMODE
Definition: lockdefs.h:26
#define ExclusiveLock
Definition: lockdefs.h:44
#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:84
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:3212
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1113
Definition: localtime.c:78
#define ERROR
Definition: elog.h:43
char relpersistence
Definition: pg_class.h:50
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:484
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5299
#define RelationGetRelationName(relation)
Definition: rel.h:441
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:227
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:3208
#define ereport(elevel, rest)
Definition: elog.h:122
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:848
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
#define PG_CATCH()
Definition: elog.h:293
#define Assert(condition)
Definition: c.h:699
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:371
RuleLock * rd_rules
Definition: rel.h:88
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:4190
#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:430
int NewGUCNestLevel(void)
Definition: guc.c:5285
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:58
void list_free(List *list)
Definition: list.c:1133
#define elog
Definition: elog.h:219
Oid relowner
Definition: pg_class.h:37
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define PG_TRY()
Definition: elog.h:284
Definition: pg_list.h:45
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:81
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
#define PG_END_TRY()
Definition: elog.h:300
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:622
#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:580
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 912 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

913 {
914  return matview_maintenance_depth > 0;
915 }
static int matview_maintenance_depth
Definition: matview.c:58

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 81 of file matview.c.

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

Referenced by ExecRefreshMatView(), and intorel_startup().

82 {
83  Relation pgrel;
84  HeapTuple tuple;
85 
86  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
87 
88  /*
89  * Update relation's pg_class entry. Crucial side-effect: other backends
90  * (and this one too!) are sent SI message to make them rebuild relcache
91  * entries.
92  */
93  pgrel = heap_open(RelationRelationId, RowExclusiveLock);
96  if (!HeapTupleIsValid(tuple))
97  elog(ERROR, "cache lookup failed for relation %u",
98  RelationGetRelid(relation));
99 
101 
102  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
103 
104  heap_freetuple(tuple);
106 
107  /*
108  * Advance command counter to make the updated pg_class row locally
109  * visible.
110  */
112 }
bool relispopulated
Definition: pg_class.h:67
#define GETSTRUCT(TUP)
Definition: htup_details.h:673
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#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:914
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
FormData_pg_class * Form_pg_class
Definition: pg_class.h:92
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:407