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, QueryCompletion *qc)
 
DestReceiverCreateTransientRelDestReceiver (Oid transientoid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Function Documentation

◆ CreateTransientRelDestReceiver()

DestReceiver* CreateTransientRelDestReceiver ( Oid  transientoid)

Definition at line 435 of file matview.c.

436 {
438 
439  self->pub.receiveSlot = transientrel_receive;
440  self->pub.rStartup = transientrel_startup;
441  self->pub.rShutdown = transientrel_shutdown;
442  self->pub.rDestroy = transientrel_destroy;
443  self->pub.mydest = DestTransientRel;
444  self->transientoid = transientoid;
445 
446  return (DestReceiver *) self;
447 }
@ DestTransientRel
Definition: dest.h:99
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:524
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:453
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:479
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:507
void * palloc0(Size size)
Definition: mcxt.c:1230

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

Referenced by CreateDestReceiver(), and ExecRefreshMatView().

◆ ExecRefreshMatView()

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

Definition at line 138 of file matview.c.

140 {
141  Oid matviewOid;
142  Relation matviewRel;
143  RewriteRule *rule;
144  List *actions;
145  Query *dataQuery;
146  Oid tableSpace;
147  Oid relowner;
148  Oid OIDNewHeap;
150  uint64 processed = 0;
151  bool concurrent;
152  LOCKMODE lockmode;
153  char relpersistence;
154  Oid save_userid;
155  int save_sec_context;
156  int save_nestlevel;
157  ObjectAddress address;
158 
159  /* Determine strength of lock needed. */
160  concurrent = stmt->concurrent;
161  lockmode = concurrent ? ExclusiveLock : AccessExclusiveLock;
162 
163  /*
164  * Get a lock until end of transaction.
165  */
166  matviewOid = RangeVarGetRelidExtended(stmt->relation,
167  lockmode, 0,
169  matviewRel = table_open(matviewOid, NoLock);
170  relowner = matviewRel->rd_rel->relowner;
171 
172  /*
173  * Switch to the owner's userid, so that any functions are run as that
174  * user. Also lock down security-restricted operations and arrange to
175  * make GUC variable changes local to this command.
176  */
177  GetUserIdAndSecContext(&save_userid, &save_sec_context);
178  SetUserIdAndSecContext(relowner,
179  save_sec_context | SECURITY_RESTRICTED_OPERATION);
180  save_nestlevel = NewGUCNestLevel();
181 
182  /* Make sure it is a materialized view. */
183  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
184  ereport(ERROR,
185  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
186  errmsg("\"%s\" is not a materialized view",
187  RelationGetRelationName(matviewRel))));
188 
189  /* Check that CONCURRENTLY is not specified if not populated. */
190  if (concurrent && !RelationIsPopulated(matviewRel))
191  ereport(ERROR,
192  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
193  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
194 
195  /* Check that conflicting options have not been specified. */
196  if (concurrent && stmt->skipData)
197  ereport(ERROR,
198  (errcode(ERRCODE_SYNTAX_ERROR),
199  errmsg("%s and %s options cannot be used together",
200  "CONCURRENTLY", "WITH NO DATA")));
201 
202  /*
203  * Check that everything is correct for a refresh. Problems at this point
204  * are internal errors, so elog is sufficient.
205  */
206  if (matviewRel->rd_rel->relhasrules == false ||
207  matviewRel->rd_rules->numLocks < 1)
208  elog(ERROR,
209  "materialized view \"%s\" is missing rewrite information",
210  RelationGetRelationName(matviewRel));
211 
212  if (matviewRel->rd_rules->numLocks > 1)
213  elog(ERROR,
214  "materialized view \"%s\" has too many rules",
215  RelationGetRelationName(matviewRel));
216 
217  rule = matviewRel->rd_rules->rules[0];
218  if (rule->event != CMD_SELECT || !(rule->isInstead))
219  elog(ERROR,
220  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
221  RelationGetRelationName(matviewRel));
222 
223  actions = rule->actions;
224  if (list_length(actions) != 1)
225  elog(ERROR,
226  "the rule for materialized view \"%s\" is not a single action",
227  RelationGetRelationName(matviewRel));
228 
229  /*
230  * Check that there is a unique index with no WHERE clause on one or more
231  * columns of the materialized view if CONCURRENTLY is specified.
232  */
233  if (concurrent)
234  {
235  List *indexoidlist = RelationGetIndexList(matviewRel);
236  ListCell *indexoidscan;
237  bool hasUniqueIndex = false;
238 
239  foreach(indexoidscan, indexoidlist)
240  {
241  Oid indexoid = lfirst_oid(indexoidscan);
242  Relation indexRel;
243 
244  indexRel = index_open(indexoid, AccessShareLock);
245  hasUniqueIndex = is_usable_unique_index(indexRel);
246  index_close(indexRel, AccessShareLock);
247  if (hasUniqueIndex)
248  break;
249  }
250 
251  list_free(indexoidlist);
252 
253  if (!hasUniqueIndex)
254  ereport(ERROR,
255  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
256  errmsg("cannot refresh materialized view \"%s\" concurrently",
258  RelationGetRelationName(matviewRel))),
259  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
260  }
261 
262  /*
263  * The stored query was rewritten at the time of the MV definition, but
264  * has not been scribbled on by the planner.
265  */
266  dataQuery = linitial_node(Query, actions);
267 
268  /*
269  * Check for active uses of the relation in the current transaction, such
270  * as open scans.
271  *
272  * NB: We count on this to protect us against problems with refreshing the
273  * data using TABLE_INSERT_FROZEN.
274  */
275  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
276 
277  /*
278  * Tentatively mark the matview as populated or not (this will roll back
279  * if we fail later).
280  */
281  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
282 
283  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
284  if (concurrent)
285  {
286  tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP, false);
287  relpersistence = RELPERSISTENCE_TEMP;
288  }
289  else
290  {
291  tableSpace = matviewRel->rd_rel->reltablespace;
292  relpersistence = matviewRel->rd_rel->relpersistence;
293  }
294 
295  /*
296  * Create the transient table that will receive the regenerated data. Lock
297  * it against access by any other process until commit (by which time it
298  * will be gone).
299  */
300  OIDNewHeap = make_new_heap(matviewOid, tableSpace,
301  matviewRel->rd_rel->relam,
302  relpersistence, ExclusiveLock);
304  dest = CreateTransientRelDestReceiver(OIDNewHeap);
305 
306  /* Generate the data, if wanted. */
307  if (!stmt->skipData)
308  processed = refresh_matview_datafill(dest, dataQuery, queryString);
309 
310  /* Make the matview match the newly generated data. */
311  if (concurrent)
312  {
313  int old_depth = matview_maintenance_depth;
314 
315  PG_TRY();
316  {
317  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
318  save_sec_context);
319  }
320  PG_CATCH();
321  {
322  matview_maintenance_depth = old_depth;
323  PG_RE_THROW();
324  }
325  PG_END_TRY();
326  Assert(matview_maintenance_depth == old_depth);
327  }
328  else
329  {
330  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
331 
332  /*
333  * Inform cumulative stats system about our activity: basically, we
334  * truncated the matview and inserted some new data. (The concurrent
335  * code path above doesn't need to worry about this because the
336  * inserts and deletes it issues get counted by lower-level code.)
337  */
338  pgstat_count_truncate(matviewRel);
339  if (!stmt->skipData)
340  pgstat_count_heap_insert(matviewRel, processed);
341  }
342 
343  table_close(matviewRel, NoLock);
344 
345  /* Roll back any GUC changes */
346  AtEOXact_GUC(false, save_nestlevel);
347 
348  /* Restore userid and security context */
349  SetUserIdAndSecContext(save_userid, save_sec_context);
350 
351  ObjectAddressSet(address, RelationRelationId, matviewOid);
352 
353  /*
354  * Save the rowcount so that pg_stat_statements can track the total number
355  * of rows processed by REFRESH MATERIALIZED VIEW command. Note that we
356  * still don't display the rowcount in the command completion tag output,
357  * i.e., the display_rowcount flag of CMDTAG_REFRESH_MATERIALIZED_VIEW
358  * command tag is left false in cmdtaglist.h. Otherwise, the change of
359  * completion tag output might break applications using it.
360  */
361  if (qc)
362  SetQueryCompletion(qc, CMDTAG_REFRESH_MATERIALIZED_VIEW, processed);
363 
364  return address;
365 }
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1149
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:688
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define PG_RE_THROW()
Definition: elog.h:350
#define PG_TRY(...)
Definition: elog.h:309
#define PG_END_TRY(...)
Definition: elog.h:334
#define ERROR
Definition: elog.h:35
#define PG_CATCH(...)
Definition: elog.h:319
#define ereport(elevel,...)
Definition: elog.h:145
int NewGUCNestLevel(void)
Definition: guc.c:2183
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2197
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_free(List *list)
Definition: list.c:1545
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
#define ExclusiveLock
Definition: lockdefs.h:42
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:376
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:584
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:435
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:866
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:84
static int matview_maintenance_depth
Definition: matview.c:61
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:856
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:618
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:625
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
@ CMD_SELECT
Definition: nodes.h:259
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static int list_length(const List *l)
Definition: pg_list.h:150
#define linitial_node(type, l)
Definition: pg_list.h:179
#define lfirst_oid(lc)
Definition: pg_list.h:172
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
void pgstat_count_truncate(Relation rel)
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RelationIsPopulated(relation)
Definition: rel.h:675
#define RelationGetNamespace(relation)
Definition: rel.h:542
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4731
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11613
Definition: pg_list.h:52
RangeVar * relation
Definition: parsenodes.h:3513
RuleLock * rd_rules
Definition: rel.h:114
Form_pg_class rd_rel
Definition: rel.h:110
RewriteRule ** rules
Definition: prs2lock.h:43
int numLocks
Definition: prs2lock.h:42
Definition: localtime.c:73
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16932
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4003

References AccessExclusiveLock, AccessShareLock, Assert(), AtEOXact_GUC(), CheckTableNotInUse(), CMD_SELECT, RefreshMatViewStmt::concurrent, CreateTransientRelDestReceiver(), generate_unaccent_rules::dest, elog(), ereport, errcode(), errhint(), errmsg(), ERROR, ExclusiveLock, get_namespace_name(), GetDefaultTablespace(), GetUserIdAndSecContext(), index_close(), index_open(), is_usable_unique_index(), 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, RuleLock::rules, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetQueryCompletion(), SetUserIdAndSecContext(), RefreshMatViewStmt::skipData, table_close(), and table_open().

Referenced by ProcessUtilitySlow().

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 920 of file matview.c.

921 {
922  return matview_maintenance_depth > 0;
923 }

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 84 of file matview.c.

85 {
86  Relation pgrel;
87  HeapTuple tuple;
88 
89  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
90 
91  /*
92  * Update relation's pg_class entry. Crucial side-effect: other backends
93  * (and this one too!) are sent SI message to make them rebuild relcache
94  * entries.
95  */
96  pgrel = table_open(RelationRelationId, RowExclusiveLock);
99  if (!HeapTupleIsValid(tuple))
100  elog(ERROR, "cache lookup failed for relation %u",
101  RelationGetRelid(relation));
102 
103  ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
104 
105  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
106 
107  heap_freetuple(tuple);
109 
110  /*
111  * Advance command counter to make the updated pg_class row locally
112  * visible.
113  */
115 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:137
#define RelationGetRelid(relation)
Definition: rel.h:501
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ RELOID
Definition: syscache.h:89
void CommandCounterIncrement(void)
Definition: xact.c:1077

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

Referenced by ExecRefreshMatView(), and intorel_startup().