PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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, QueryCompletion *qc)
 
ObjectAddress RefreshMatViewByOid (Oid matviewOid, bool is_create, bool skipData, bool concurrent, const char *queryString, QueryCompletion *qc)
 
DestReceiverCreateTransientRelDestReceiver (Oid transientoid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Function Documentation

◆ CreateTransientRelDestReceiver()

DestReceiver * CreateTransientRelDestReceiver ( Oid  transientoid)

Definition at line 465 of file matview.c.

466{
468
474 self->transientoid = transientoid;
475
476 return (DestReceiver *) self;
477}
@ DestTransientRel
Definition: dest.h:97
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:554
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:483
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:509
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:537
void * palloc0(Size size)
Definition: mcxt.c:1347
DestReceiver pub
Definition: matview.c:47
Oid transientoid
Definition: matview.c:48
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:121
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:124
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:118
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
CommandDest mydest
Definition: dest.h:128

References DestTransientRel, _DestReceiver::mydest, palloc0(), DR_transientrel::pub, _DestReceiver::rDestroy, _DestReceiver::receiveSlot, _DestReceiver::rShutdown, _DestReceiver::rStartup, DR_transientrel::transientoid, transientrel_destroy(), transientrel_receive(), transientrel_shutdown(), and transientrel_startup().

Referenced by CreateDestReceiver(), and RefreshMatViewByOid().

◆ ExecRefreshMatView()

ObjectAddress ExecRefreshMatView ( RefreshMatViewStmt stmt,
const char *  queryString,
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, false, stmt->skipData,
139 stmt->concurrent, queryString, 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 is_create, bool skipData, bool concurrent, const char *queryString, QueryCompletion *qc)
Definition: matview.c:165
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:441
unsigned int Oid
Definition: postgres_ext.h:31
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:18261

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

Referenced by ProcessUtilitySlow().

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 970 of file matview.c.

971{
972 return matview_maintenance_depth > 0;
973}
static int matview_maintenance_depth
Definition: matview.c:56

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

◆ RefreshMatViewByOid()

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

Definition at line 165 of file matview.c.

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

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:1435
#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:91
void CommandCounterIncrement(void)
Definition: xact.c:1099

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().