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

433 {
435 
436  self->pub.receiveSlot = transientrel_receive;
437  self->pub.rStartup = transientrel_startup;
438  self->pub.rShutdown = transientrel_shutdown;
439  self->pub.rDestroy = transientrel_destroy;
440  self->pub.mydest = DestTransientRel;
441  self->transientoid = transientoid;
442 
443  return (DestReceiver *) self;
444 }
@ DestTransientRel
Definition: dest.h:97
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:521
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:450
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:476
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:504
void * palloc0(Size size)
Definition: mcxt.c:1346

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

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

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(), RangeVarCallbackMaintainsTable(), RangeVarGetRelidExtended(), 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(), stmt, table_close(), and table_open().

Referenced by ProcessUtilitySlow().

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 936 of file matview.c.

937 {
938  return matview_maintenance_depth > 0;
939 }

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

◆ 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:1097

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 ExecRefreshMatView(), and intorel_startup().