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)
 
ObjectAddress RefreshMatViewByOid (Oid matviewOid, bool skipData, bool concurrent, const char *queryString, ParamListInfo params, QueryCompletion *qc)
 
DestReceiverCreateTransientRelDestReceiver (Oid transientoid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Function Documentation

◆ CreateTransientRelDestReceiver()

DestReceiver* CreateTransientRelDestReceiver ( Oid  transientoid)

Definition at line 448 of file matview.c.

449 {
451 
452  self->pub.receiveSlot = transientrel_receive;
453  self->pub.rStartup = transientrel_startup;
454  self->pub.rShutdown = transientrel_shutdown;
455  self->pub.rDestroy = transientrel_destroy;
456  self->pub.mydest = DestTransientRel;
457  self->transientoid = transientoid;
458 
459  return (DestReceiver *) self;
460 }
@ DestTransientRel
Definition: dest.h:97
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:537
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:466
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:492
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:520
void * palloc0(Size size)
Definition: mcxt.c:1347

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

Referenced by CreateDestReceiver(), and RefreshMatViewByOid().

◆ ExecRefreshMatView()

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

Definition at line 121 of file matview.c.

123 {
124  Oid matviewOid;
125  LOCKMODE lockmode;
126 
127  /* Determine strength of lock needed. */
128  lockmode = stmt->concurrent ? ExclusiveLock : AccessExclusiveLock;
129 
130  /*
131  * Get a lock until end of transaction.
132  */
133  matviewOid = RangeVarGetRelidExtended(stmt->relation,
134  lockmode, 0,
136  NULL);
137 
138  return RefreshMatViewByOid(matviewOid, stmt->skipData, stmt->concurrent,
139  queryString, params, qc);
140 }
#define stmt
Definition: indent_codes.h:59
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ExclusiveLock
Definition: lockdefs.h:42
ObjectAddress RefreshMatViewByOid(Oid matviewOid, bool skipData, bool concurrent, const char *queryString, ParamListInfo params, QueryCompletion *qc)
Definition: matview.c:162
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
unsigned int Oid
Definition: postgres_ext.h:31
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:17585

References AccessExclusiveLock, ExclusiveLock, RangeVarCallbackMaintainsTable(), RangeVarGetRelidExtended(), RefreshMatViewByOid(), and stmt.

Referenced by ProcessUtilitySlow().

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 954 of file matview.c.

955 {
956  return matview_maintenance_depth > 0;
957 }
static int matview_maintenance_depth
Definition: matview.c:56

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

◆ RefreshMatViewByOid()

ObjectAddress RefreshMatViewByOid ( Oid  matviewOid,
bool  skipData,
bool  concurrent,
const char *  queryString,
ParamListInfo  params,
QueryCompletion qc 
)

Definition at line 162 of file matview.c.

165 {
166  Relation matviewRel;
167  RewriteRule *rule;
168  List *actions;
169  Query *dataQuery;
170  Oid tableSpace;
171  Oid relowner;
172  Oid OIDNewHeap;
174  uint64 processed = 0;
175  char relpersistence;
176  Oid save_userid;
177  int save_sec_context;
178  int save_nestlevel;
179  ObjectAddress address;
180 
181  matviewRel = table_open(matviewOid, NoLock);
182  relowner = matviewRel->rd_rel->relowner;
183 
184  /*
185  * Switch to the owner's userid, so that any functions are run as that
186  * user. Also lock down security-restricted operations and arrange to
187  * make GUC variable changes local to this command.
188  */
189  GetUserIdAndSecContext(&save_userid, &save_sec_context);
190  SetUserIdAndSecContext(relowner,
191  save_sec_context | SECURITY_RESTRICTED_OPERATION);
192  save_nestlevel = NewGUCNestLevel();
194 
195  /* Make sure it is a materialized view. */
196  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
197  ereport(ERROR,
198  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
199  errmsg("\"%s\" is not a materialized view",
200  RelationGetRelationName(matviewRel))));
201 
202  /* Check that CONCURRENTLY is not specified if not populated. */
203  if (concurrent && !RelationIsPopulated(matviewRel))
204  ereport(ERROR,
205  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
206  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
207 
208  /* Check that conflicting options have not been specified. */
209  if (concurrent && skipData)
210  ereport(ERROR,
211  (errcode(ERRCODE_SYNTAX_ERROR),
212  errmsg("%s and %s options cannot be used together",
213  "CONCURRENTLY", "WITH NO DATA")));
214 
215  /*
216  * Check that everything is correct for a refresh. Problems at this point
217  * are internal errors, so elog is sufficient.
218  */
219  if (matviewRel->rd_rel->relhasrules == false ||
220  matviewRel->rd_rules->numLocks < 1)
221  elog(ERROR,
222  "materialized view \"%s\" is missing rewrite information",
223  RelationGetRelationName(matviewRel));
224 
225  if (matviewRel->rd_rules->numLocks > 1)
226  elog(ERROR,
227  "materialized view \"%s\" has too many rules",
228  RelationGetRelationName(matviewRel));
229 
230  rule = matviewRel->rd_rules->rules[0];
231  if (rule->event != CMD_SELECT || !(rule->isInstead))
232  elog(ERROR,
233  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
234  RelationGetRelationName(matviewRel));
235 
236  actions = rule->actions;
237  if (list_length(actions) != 1)
238  elog(ERROR,
239  "the rule for materialized view \"%s\" is not a single action",
240  RelationGetRelationName(matviewRel));
241 
242  /*
243  * Check that there is a unique index with no WHERE clause on one or more
244  * columns of the materialized view if CONCURRENTLY is specified.
245  */
246  if (concurrent)
247  {
248  List *indexoidlist = RelationGetIndexList(matviewRel);
249  ListCell *indexoidscan;
250  bool hasUniqueIndex = false;
251 
252  foreach(indexoidscan, indexoidlist)
253  {
254  Oid indexoid = lfirst_oid(indexoidscan);
255  Relation indexRel;
256 
257  indexRel = index_open(indexoid, AccessShareLock);
258  hasUniqueIndex = is_usable_unique_index(indexRel);
259  index_close(indexRel, AccessShareLock);
260  if (hasUniqueIndex)
261  break;
262  }
263 
264  list_free(indexoidlist);
265 
266  if (!hasUniqueIndex)
267  ereport(ERROR,
268  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
269  errmsg("cannot refresh materialized view \"%s\" concurrently",
271  RelationGetRelationName(matviewRel))),
272  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
273  }
274 
275  /*
276  * The stored query was rewritten at the time of the MV definition, but
277  * has not been scribbled on by the planner.
278  */
279  dataQuery = linitial_node(Query, actions);
280 
281  /*
282  * Check for active uses of the relation in the current transaction, such
283  * as open scans.
284  *
285  * NB: We count on this to protect us against problems with refreshing the
286  * data using TABLE_INSERT_FROZEN.
287  */
288  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
289 
290  /*
291  * Tentatively mark the matview as populated or not (this will roll back
292  * if we fail later).
293  */
294  SetMatViewPopulatedState(matviewRel, !skipData);
295 
296  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
297  if (concurrent)
298  {
299  tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP, false);
300  relpersistence = RELPERSISTENCE_TEMP;
301  }
302  else
303  {
304  tableSpace = matviewRel->rd_rel->reltablespace;
305  relpersistence = matviewRel->rd_rel->relpersistence;
306  }
307 
308  /*
309  * Create the transient table that will receive the regenerated data. Lock
310  * it against access by any other process until commit (by which time it
311  * will be gone).
312  */
313  OIDNewHeap = make_new_heap(matviewOid, tableSpace,
314  matviewRel->rd_rel->relam,
315  relpersistence, ExclusiveLock);
317  dest = CreateTransientRelDestReceiver(OIDNewHeap);
318 
319  /* Generate the data, if wanted. */
320  if (!skipData)
321  processed = refresh_matview_datafill(dest, dataQuery, queryString);
322 
323  /* Make the matview match the newly generated data. */
324  if (concurrent)
325  {
326  int old_depth = matview_maintenance_depth;
327 
328  PG_TRY();
329  {
330  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
331  save_sec_context);
332  }
333  PG_CATCH();
334  {
335  matview_maintenance_depth = old_depth;
336  PG_RE_THROW();
337  }
338  PG_END_TRY();
339  Assert(matview_maintenance_depth == old_depth);
340  }
341  else
342  {
343  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
344 
345  /*
346  * Inform cumulative stats system about our activity: basically, we
347  * truncated the matview and inserted some new data. (The concurrent
348  * code path above doesn't need to worry about this because the
349  * inserts and deletes it issues get counted by lower-level code.)
350  */
351  pgstat_count_truncate(matviewRel);
352  if (!skipData)
353  pgstat_count_heap_insert(matviewRel, processed);
354  }
355 
356  table_close(matviewRel, NoLock);
357 
358  /* Roll back any GUC changes */
359  AtEOXact_GUC(false, save_nestlevel);
360 
361  /* Restore userid and security context */
362  SetUserIdAndSecContext(save_userid, save_sec_context);
363 
364  ObjectAddressSet(address, RelationRelationId, matviewOid);
365 
366  /*
367  * Save the rowcount so that pg_stat_statements can track the total number
368  * of rows processed by REFRESH MATERIALIZED VIEW command. Note that we
369  * still don't display the rowcount in the command completion tag output,
370  * i.e., the display_rowcount flag of CMDTAG_REFRESH_MATERIALIZED_VIEW
371  * command tag is left false in cmdtaglist.h. Otherwise, the change of
372  * completion tag output might break applications using it.
373  */
374  if (qc)
375  SetQueryCompletion(qc, CMDTAG_REFRESH_MATERIALIZED_VIEW, processed);
376 
377  return address;
378 }
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1143
#define Assert(condition)
Definition: c.h:858
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:37
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:380
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
int NewGUCNestLevel(void)
Definition: guc.c:2234
void RestrictSearchPath(void)
Definition: guc.c:2245
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2261
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
void list_free(List *list)
Definition: list.c:1546
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:389
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:597
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:448
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:900
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:79
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:890
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:315
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
@ CMD_SELECT
Definition: nodes.h:265
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define lfirst_oid(lc)
Definition: pg_list.h:174
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
void pgstat_count_truncate(Relation rel)
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationIsPopulated(relation)
Definition: rel.h:677
#define RelationGetNamespace(relation)
Definition: rel.h:546
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4801
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12680
Definition: pg_list.h:54
RuleLock * rd_rules
Definition: rel.h:115
Form_pg_class rd_rel
Definition: rel.h:111
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 CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4244

References AccessExclusiveLock, AccessShareLock, Assert, AtEOXact_GUC(), CheckTableNotInUse(), CMD_SELECT, 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(), RelationData::rd_rel, RelationData::rd_rules, refresh_by_heap_swap(), refresh_by_match_merge(), refresh_matview_datafill(), RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, RelationIsPopulated, RestrictSearchPath(), RuleLock::rules, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetQueryCompletion(), SetUserIdAndSecContext(), table_close(), and table_open().

Referenced by ExecCreateTableAs(), and ExecRefreshMatView().

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 79 of file matview.c.

80 {
81  Relation pgrel;
82  HeapTuple tuple;
83 
84  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
85 
86  /*
87  * Update relation's pg_class entry. Crucial side-effect: other backends
88  * (and this one too!) are sent SI message to make them rebuild relcache
89  * entries.
90  */
91  pgrel = table_open(RelationRelationId, RowExclusiveLock);
92  tuple = SearchSysCacheCopy1(RELOID,
94  if (!HeapTupleIsValid(tuple))
95  elog(ERROR, "cache lookup failed for relation %u",
96  RelationGetRelid(relation));
97 
98  ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
99 
100  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
101 
102  heap_freetuple(tuple);
104 
105  /*
106  * Advance command counter to make the updated pg_class row locally
107  * visible.
108  */
110 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
#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:252
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:137
#define RelationGetRelid(relation)
Definition: rel.h:505
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
void CommandCounterIncrement(void)
Definition: xact.c:1098

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

Referenced by intorel_startup(), and RefreshMatViewByOid().