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 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:532
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:515
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:487
void * palloc0(Size size)
Definition: mcxt.c:1093

◆ ExecRefreshMatView()

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

Definition at line 138 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(), 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, RuleLock::rules, SECURITY_LOCAL_USERID_CHANGE, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetQueryCompletion(), SetUserIdAndSecContext(), RefreshMatViewStmt::skipData, table_close(), and table_open().

Referenced by ProcessUtilitySlow().

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

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 928 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

929 {
930  return matview_maintenance_depth > 0;
931 }
static int matview_maintenance_depth
Definition: matview.c:61

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 84 of file matview.c.

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

Referenced by ExecRefreshMatView(), and intorel_startup().

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 table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
void CommandCounterIncrement(void)
Definition: xact.c:1022
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:137
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:477