PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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)
extern

Definition at line 464 of file matview.c.

465{
467
473 self->transientoid = transientoid;
474
475 return (DestReceiver *) self;
476}
@ DestTransientRel
Definition dest.h:97
#define palloc0_object(type)
Definition fe_memutils.h:75
static void transientrel_destroy(DestReceiver *self)
Definition matview.c:553
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition matview.c:482
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition matview.c:508
static void transientrel_shutdown(DestReceiver *self)
Definition matview.c:536
DestReceiver pub
Definition matview.c:47
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_object, 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 
)
extern

Definition at line 120 of file matview.c.

122{
124 LOCKMODE lockmode;
125
126 /* Determine strength of lock needed. */
127 lockmode = stmt->concurrent ? ExclusiveLock : AccessExclusiveLock;
128
129 /*
130 * Get a lock until end of transaction.
131 */
133 lockmode, 0,
135 NULL);
136
137 return RefreshMatViewByOid(matviewOid, false, stmt->skipData,
138 stmt->concurrent, queryString, qc);
139}
#define stmt
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:164
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:440
unsigned int Oid
static int fb(int x)
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)

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

Referenced by ProcessUtilitySlow().

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )
extern

Definition at line 952 of file matview.c.

953{
954 return matview_maintenance_depth > 0;
955}
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 
)
extern

Definition at line 164 of file matview.c.

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

References AccessExclusiveLock, AccessShareLock, Assert, AtEOXact_GUC(), CheckRelationOidLockedByMe(), CheckTableNotInUse(), CMD_SELECT, CreateTransientRelDestReceiver(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, ExclusiveLock, fb(), get_namespace_name(), GetDefaultTablespace(), GetUserIdAndSecContext(), index_close(), index_open(), is_usable_unique_index(), lfirst_oid, linitial_node, list_free(), list_length(), make_new_heap(), matview_maintenance_depth, NewGUCNestLevel(), NoLock, ObjectAddressSet, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgstat_count_heap_insert(), pgstat_count_truncate(), quote_qualified_identifier(), refresh_by_heap_swap(), refresh_by_match_merge(), refresh_matview_datafill(), RelationGetIndexList(), RelationGetNamespace, RelationGetRelationName, RelationIsPopulated, RestrictSearchPath(), SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetQueryCompletion(), SetUserIdAndSecContext(), table_close(), and table_open().

Referenced by ExecCreateTableAs(), and ExecRefreshMatView().

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)
extern

Definition at line 78 of file matview.c.

79{
81 HeapTuple tuple;
82
83 Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
84
85 /*
86 * Update relation's pg_class entry. Crucial side-effect: other backends
87 * (and this one too!) are sent SI message to make them rebuild relcache
88 * entries.
89 */
93 if (!HeapTupleIsValid(tuple))
94 elog(ERROR, "cache lookup failed for relation %u",
95 RelationGetRelid(relation));
96
97 ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
98
99 CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
100
101 heap_freetuple(tuple);
103
104 /*
105 * Advance command counter to make the updated pg_class row locally
106 * visible.
107 */
109}
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
#define RowExclusiveLock
Definition lockdefs.h:38
FormData_pg_class * Form_pg_class
Definition pg_class.h:156
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
static struct state * newstate(struct nfa *nfa)
Definition regc_nfa.c:137
#define RelationGetRelid(relation)
Definition rel.h:514
ItemPointerData t_self
Definition htup.h:65
Form_pg_class rd_rel
Definition rel.h:111
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
void CommandCounterIncrement(void)
Definition xact.c:1101

References Assert, CatalogTupleUpdate(), CommandCounterIncrement(), elog, ERROR, fb(), 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().