PostgreSQL Source Code  git master
matview.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "commands/cluster.h"
#include "commands/matview.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
#include "storage/lmgr.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for matview.c:

Go to the source code of this file.

Data Structures

struct  DR_transientrel
 

Functions

static void transientrel_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
static bool transientrel_receive (TupleTableSlot *slot, DestReceiver *self)
 
static void transientrel_shutdown (DestReceiver *self)
 
static void transientrel_destroy (DestReceiver *self)
 
static uint64 refresh_matview_datafill (DestReceiver *dest, Query *query, const char *queryString)
 
static char * make_temptable_name_n (char *tempname, int n)
 
static void refresh_by_match_merge (Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
 
static void refresh_by_heap_swap (Oid matviewOid, Oid OIDNewHeap, char relpersistence)
 
static bool is_usable_unique_index (Relation indexRel)
 
static void OpenMatViewIncrementalMaintenance (void)
 
static void CloseMatViewIncrementalMaintenance (void)
 
void SetMatViewPopulatedState (Relation relation, bool newstate)
 
ObjectAddress ExecRefreshMatView (RefreshMatViewStmt *stmt, const char *queryString, ParamListInfo params, char *completionTag)
 
DestReceiverCreateTransientRelDestReceiver (Oid transientoid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Variables

static int matview_maintenance_depth = 0
 

Function Documentation

◆ CloseMatViewIncrementalMaintenance()

static void CloseMatViewIncrementalMaintenance ( void  )
static

Definition at line 924 of file matview.c.

References Assert, and matview_maintenance_depth.

Referenced by refresh_by_match_merge().

925 {
928 }
#define Assert(condition)
Definition: c.h:699
static int matview_maintenance_depth
Definition: matview.c:58

◆ CreateTransientRelDestReceiver()

DestReceiver* CreateTransientRelDestReceiver ( Oid  transientoid)

Definition at line 430 of file matview.c.

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

Referenced by CreateDestReceiver(), and ExecRefreshMatView().

431 {
433 
434  self->pub.receiveSlot = transientrel_receive;
435  self->pub.rStartup = transientrel_startup;
436  self->pub.rShutdown = transientrel_shutdown;
437  self->pub.rDestroy = transientrel_destroy;
438  self->pub.mydest = DestTransientRel;
439  self->transientoid = transientoid;
440 
441  return (DestReceiver *) self;
442 }
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:448
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:523
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:504
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:478
void * palloc0(Size size)
Definition: mcxt.c:955

◆ ExecRefreshMatView()

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

Definition at line 135 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(), heap_close, heap_open(), 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, relowner, relpersistence, RuleLock::rules, SECURITY_LOCAL_USERID_CHANGE, SECURITY_RESTRICTED_OPERATION, SetMatViewPopulatedState(), SetUserIdAndSecContext(), and RefreshMatViewStmt::skipData.

Referenced by ProcessUtilitySlow().

137 {
138  Oid matviewOid;
139  Relation matviewRel;
140  RewriteRule *rule;
141  List *actions;
142  Query *dataQuery;
143  Oid tableSpace;
144  Oid relowner;
145  Oid OIDNewHeap;
147  uint64 processed = 0;
148  bool concurrent;
149  LOCKMODE lockmode;
150  char relpersistence;
151  Oid save_userid;
152  int save_sec_context;
153  int save_nestlevel;
154  ObjectAddress address;
155 
156  /* Determine strength of lock needed. */
157  concurrent = stmt->concurrent;
158  lockmode = concurrent ? ExclusiveLock : AccessExclusiveLock;
159 
160  /*
161  * Get a lock until end of transaction.
162  */
163  matviewOid = RangeVarGetRelidExtended(stmt->relation,
164  lockmode, 0,
166  matviewRel = heap_open(matviewOid, NoLock);
167 
168  /* Make sure it is a materialized view. */
169  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
170  ereport(ERROR,
171  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
172  errmsg("\"%s\" is not a materialized view",
173  RelationGetRelationName(matviewRel))));
174 
175  /* Check that CONCURRENTLY is not specified if not populated. */
176  if (concurrent && !RelationIsPopulated(matviewRel))
177  ereport(ERROR,
178  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
179  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
180 
181  /* Check that conflicting options have not been specified. */
182  if (concurrent && stmt->skipData)
183  ereport(ERROR,
184  (errcode(ERRCODE_SYNTAX_ERROR),
185  errmsg("CONCURRENTLY and WITH NO DATA options cannot be used together")));
186 
187  /* We don't allow an oid column for a materialized view. */
188  Assert(!matviewRel->rd_rel->relhasoids);
189 
190  /*
191  * Check that everything is correct for a refresh. Problems at this point
192  * are internal errors, so elog is sufficient.
193  */
194  if (matviewRel->rd_rel->relhasrules == false ||
195  matviewRel->rd_rules->numLocks < 1)
196  elog(ERROR,
197  "materialized view \"%s\" is missing rewrite information",
198  RelationGetRelationName(matviewRel));
199 
200  if (matviewRel->rd_rules->numLocks > 1)
201  elog(ERROR,
202  "materialized view \"%s\" has too many rules",
203  RelationGetRelationName(matviewRel));
204 
205  rule = matviewRel->rd_rules->rules[0];
206  if (rule->event != CMD_SELECT || !(rule->isInstead))
207  elog(ERROR,
208  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
209  RelationGetRelationName(matviewRel));
210 
211  actions = rule->actions;
212  if (list_length(actions) != 1)
213  elog(ERROR,
214  "the rule for materialized view \"%s\" is not a single action",
215  RelationGetRelationName(matviewRel));
216 
217  /*
218  * Check that there is a unique index with no WHERE clause on one or more
219  * columns of the materialized view if CONCURRENTLY is specified.
220  */
221  if (concurrent)
222  {
223  List *indexoidlist = RelationGetIndexList(matviewRel);
224  ListCell *indexoidscan;
225  bool hasUniqueIndex = false;
226 
227  foreach(indexoidscan, indexoidlist)
228  {
229  Oid indexoid = lfirst_oid(indexoidscan);
230  Relation indexRel;
231 
232  indexRel = index_open(indexoid, AccessShareLock);
233  hasUniqueIndex = is_usable_unique_index(indexRel);
234  index_close(indexRel, AccessShareLock);
235  if (hasUniqueIndex)
236  break;
237  }
238 
239  list_free(indexoidlist);
240 
241  if (!hasUniqueIndex)
242  ereport(ERROR,
243  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
244  errmsg("cannot refresh materialized view \"%s\" concurrently",
246  RelationGetRelationName(matviewRel))),
247  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
248  }
249 
250  /*
251  * The stored query was rewritten at the time of the MV definition, but
252  * has not been scribbled on by the planner.
253  */
254  dataQuery = linitial_node(Query, actions);
255 
256  /*
257  * Check for active uses of the relation in the current transaction, such
258  * as open scans.
259  *
260  * NB: We count on this to protect us against problems with refreshing the
261  * data using HEAP_INSERT_FROZEN.
262  */
263  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
264 
265  /*
266  * Tentatively mark the matview as populated or not (this will roll back
267  * if we fail later).
268  */
269  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
270 
271  relowner = matviewRel->rd_rel->relowner;
272 
273  /*
274  * Switch to the owner's userid, so that any functions are run as that
275  * user. Also arrange to make GUC variable changes local to this command.
276  * Don't lock it down too tight to create a temporary table just yet. We
277  * will switch modes when we are about to execute user code.
278  */
279  GetUserIdAndSecContext(&save_userid, &save_sec_context);
280  SetUserIdAndSecContext(relowner,
281  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
282  save_nestlevel = NewGUCNestLevel();
283 
284  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
285  if (concurrent)
286  {
287  tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP);
288  relpersistence = RELPERSISTENCE_TEMP;
289  }
290  else
291  {
292  tableSpace = matviewRel->rd_rel->reltablespace;
293  relpersistence = matviewRel->rd_rel->relpersistence;
294  }
295 
296  /*
297  * Create the transient table that will receive the regenerated data. Lock
298  * it against access by any other process until commit (by which time it
299  * will be gone).
300  */
301  OIDNewHeap = make_new_heap(matviewOid, tableSpace, relpersistence,
302  ExclusiveLock);
304  dest = CreateTransientRelDestReceiver(OIDNewHeap);
305 
306  /*
307  * Now lock down security-restricted operations.
308  */
309  SetUserIdAndSecContext(relowner,
310  save_sec_context | SECURITY_RESTRICTED_OPERATION);
311 
312  /* Generate the data, if wanted. */
313  if (!stmt->skipData)
314  processed = refresh_matview_datafill(dest, dataQuery, queryString);
315 
316  /* Make the matview match the newly generated data. */
317  if (concurrent)
318  {
319  int old_depth = matview_maintenance_depth;
320 
321  PG_TRY();
322  {
323  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
324  save_sec_context);
325  }
326  PG_CATCH();
327  {
328  matview_maintenance_depth = old_depth;
329  PG_RE_THROW();
330  }
331  PG_END_TRY();
332  Assert(matview_maintenance_depth == old_depth);
333  }
334  else
335  {
336  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
337 
338  /*
339  * Inform stats collector about our activity: basically, we truncated
340  * the matview and inserted some new data. (The concurrent code path
341  * above doesn't need to worry about this because the inserts and
342  * deletes it issues get counted by lower-level code.)
343  */
344  pgstat_count_truncate(matviewRel);
345  if (!stmt->skipData)
346  pgstat_count_heap_insert(matviewRel, processed);
347  }
348 
349  heap_close(matviewRel, NoLock);
350 
351  /* Roll back any GUC changes */
352  AtEOXact_GUC(false, save_nestlevel);
353 
354  /* Restore userid and security context */
355  SetUserIdAndSecContext(save_userid, save_sec_context);
356 
357  ObjectAddressSet(address, RelationRelationId, matviewOid);
358 
359  return address;
360 }
#define RelationIsPopulated(relation)
Definition: rel.h:557
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:858
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:13387
int errhint(const char *fmt,...)
Definition: elog.c:987
int numLocks
Definition: prs2lock.h:42
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
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:575
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
bool isInstead
Definition: prs2lock.h:31
RangeVar * relation
Definition: parsenodes.h:3212
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1113
Definition: localtime.c:77
#define ERROR
Definition: elog.h:43
char relpersistence
Definition: pg_class.h:50
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:484
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5322
#define RelationGetRelationName(relation)
Definition: rel.h:441
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:227
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2008
RewriteRule ** rules
Definition: prs2lock.h:43
List * actions
Definition: prs2lock.h:29
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3222
#define ereport(elevel, rest)
Definition: elog.h:122
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:848
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
#define PG_CATCH()
Definition: elog.h:293
#define Assert(condition)
Definition: c.h:699
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:371
RuleLock * rd_rules
Definition: rel.h:88
static int list_length(const List *l)
Definition: pg_list.h:89
#define PG_RE_THROW()
Definition: elog.h:314
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4260
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define AccessExclusiveLock
Definition: lockdefs.h:45
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:430
int NewGUCNestLevel(void)
Definition: guc.c:5308
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:1907
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int matview_maintenance_depth
Definition: matview.c:58
void list_free(List *list)
Definition: list.c:1133
#define elog
Definition: elog.h:219
Oid relowner
Definition: pg_class.h:37
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define PG_TRY()
Definition: elog.h:284
Definition: pg_list.h:45
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:81
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
#define PG_END_TRY()
Definition: elog.h:300
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:622
#define lfirst_oid(lc)
Definition: pg_list.h:108
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:580
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ is_usable_unique_index()

static bool is_usable_unique_index ( Relation  indexRel)
static

Definition at line 858 of file matview.c.

References attnum, i, IndexIsValid, NIL, RelationData::rd_index, RelationData::rd_rel, and RelationGetIndexPredicate().

Referenced by ExecRefreshMatView(), and refresh_by_match_merge().

859 {
860  Form_pg_index indexStruct = indexRel->rd_index;
861 
862  /*
863  * Must be unique, valid, immediate, non-partial, and be defined over
864  * plain user columns (not expressions). We also require it to be a
865  * btree. Even if we had any other unique index kinds, we'd not know how
866  * to identify the corresponding equality operator, nor could we be sure
867  * that the planner could implement the required FULL JOIN with non-btree
868  * operators.
869  */
870  if (indexStruct->indisunique &&
871  indexStruct->indimmediate &&
872  indexRel->rd_rel->relam == BTREE_AM_OID &&
873  IndexIsValid(indexStruct) &&
874  RelationGetIndexPredicate(indexRel) == NIL &&
875  indexStruct->indnatts > 0)
876  {
877  /*
878  * The point of groveling through the index columns individually is to
879  * reject both index expressions and system columns. Currently,
880  * matviews couldn't have OID columns so there's no way to create an
881  * index on a system column; but maybe someday that wouldn't be true,
882  * so let's be safe.
883  */
884  int numatts = indexStruct->indnatts;
885  int i;
886 
887  for (i = 0; i < numatts; i++)
888  {
889  int attnum = indexStruct->indkey.values[i];
890 
891  if (attnum <= 0)
892  return false;
893  }
894  return true;
895  }
896  return false;
897 }
#define NIL
Definition: pg_list.h:69
#define IndexIsValid(indexForm)
Definition: pg_index.h:85
Form_pg_class rd_rel
Definition: rel.h:84
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4678
Form_pg_index rd_index
Definition: rel.h:131
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
int16 attnum
Definition: pg_attribute.h:79
int i

◆ make_temptable_name_n()

static char * make_temptable_name_n ( char *  tempname,
int  n 
)
static

Definition at line 537 of file matview.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, and initStringInfo().

Referenced by refresh_by_match_merge().

538 {
539  StringInfoData namebuf;
540 
541  initStringInfo(&namebuf);
542  appendStringInfoString(&namebuf, tempname);
543  appendStringInfo(&namebuf, "_%d", n);
544  return namebuf.data;
545 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 912 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

913 {
914  return matview_maintenance_depth > 0;
915 }
static int matview_maintenance_depth
Definition: matview.c:58

◆ OpenMatViewIncrementalMaintenance()

static void OpenMatViewIncrementalMaintenance ( void  )
static

Definition at line 918 of file matview.c.

References matview_maintenance_depth.

Referenced by refresh_by_match_merge().

919 {
921 }
static int matview_maintenance_depth
Definition: matview.c:58

◆ refresh_by_heap_swap()

static void refresh_by_heap_swap ( Oid  matviewOid,
Oid  OIDNewHeap,
char  relpersistence 
)
static

Definition at line 848 of file matview.c.

References finish_heap_swap(), ReadNextMultiXactId(), and RecentXmin.

Referenced by ExecRefreshMatView().

849 {
850  finish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,
852 }
void finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap, bool is_system_catalog, bool swap_toast_by_content, bool check_constraints, bool is_internal, TransactionId frozenXid, MultiXactId cutoffMulti, char newrelpersistence)
Definition: cluster.c:1515
TransactionId RecentXmin
Definition: snapmgr.c:165
char relpersistence
Definition: pg_class.h:50
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:721

◆ refresh_by_match_merge()

static void refresh_by_match_merge ( Oid  matviewOid,
Oid  tempOid,
Oid  relowner,
int  save_sec_context 
)
static

Definition at line 580 of file matview.c.

References appendStringInfo(), appendStringInfoString(), Assert, attnum, BTEqualStrategyNumber, CLAOID, CloseMatViewIncrementalMaintenance(), StringInfoData::data, DatumGetPointer, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, generate_operator_clause(), get_namespace_name(), get_opfamily_member(), GETSTRUCT, heap_close, heap_open(), HeapTupleIsValid, i, index_close(), index_open(), INDEXRELID, initStringInfo(), is_usable_unique_index(), lfirst_oid, list_free(), make_temptable_name_n(), NameStr, NoLock, ObjectIdGetDatum, OidIsValid, OpenMatViewIncrementalMaintenance(), palloc0(), quote_qualified_identifier(), RelationData::rd_att, RelationData::rd_index, RelationData::rd_indextuple, RelationGetIndexList(), RelationGetNamespace, RelationGetNumberOfAttributes, RelationGetRelationName, ReleaseSysCache(), relnatts, resetStringInfo(), RowExclusiveLock, SearchSysCache1(), SECURITY_LOCAL_USERID_CHANGE, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), SPI_connect(), SPI_exec(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_CONNECT, SPI_OK_DELETE, SPI_OK_FINISH, SPI_OK_INSERT, SPI_OK_SELECT, SPI_OK_UTILITY, SPI_processed, SPI_tuptable, SysCacheGetAttr(), SPITupleTable::tupdesc, TupleDescAttr, SPITupleTable::vals, and oidvector::values.

Referenced by ExecRefreshMatView().

582 {
583  StringInfoData querybuf;
584  Relation matviewRel;
585  Relation tempRel;
586  char *matviewname;
587  char *tempname;
588  char *diffname;
589  TupleDesc tupdesc;
590  bool foundUniqueIndex;
591  List *indexoidlist;
592  ListCell *indexoidscan;
593  int16 relnatts;
594  Oid *opUsedForQual;
595 
596  initStringInfo(&querybuf);
597  matviewRel = heap_open(matviewOid, NoLock);
599  RelationGetRelationName(matviewRel));
600  tempRel = heap_open(tempOid, NoLock);
602  RelationGetRelationName(tempRel));
603  diffname = make_temptable_name_n(tempname, 2);
604 
605  relnatts = RelationGetNumberOfAttributes(matviewRel);
606 
607  /* Open SPI context. */
608  if (SPI_connect() != SPI_OK_CONNECT)
609  elog(ERROR, "SPI_connect failed");
610 
611  /* Analyze the temp table with the new contents. */
612  appendStringInfo(&querybuf, "ANALYZE %s", tempname);
613  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
614  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
615 
616  /*
617  * We need to ensure that there are not duplicate rows without NULLs in
618  * the new data set before we can count on the "diff" results. Check for
619  * that in a way that allows showing the first duplicated row found. Even
620  * after we pass this test, a unique index on the materialized view may
621  * find a duplicate key problem.
622  */
623  resetStringInfo(&querybuf);
624  appendStringInfo(&querybuf,
625  "SELECT newdata FROM %s newdata "
626  "WHERE newdata IS NOT NULL AND EXISTS "
627  "(SELECT 1 FROM %s newdata2 WHERE newdata2 IS NOT NULL "
628  "AND newdata2 OPERATOR(pg_catalog.*=) newdata "
629  "AND newdata2.ctid OPERATOR(pg_catalog.<>) "
630  "newdata.ctid)",
631  tempname, tempname);
632  if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
633  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
634  if (SPI_processed > 0)
635  {
636  /*
637  * Note that this ereport() is returning data to the user. Generally,
638  * we would want to make sure that the user has been granted access to
639  * this data. However, REFRESH MAT VIEW is only able to be run by the
640  * owner of the mat view (or a superuser) and therefore there is no
641  * need to check for access to data in the mat view.
642  */
643  ereport(ERROR,
644  (errcode(ERRCODE_CARDINALITY_VIOLATION),
645  errmsg("new data for materialized view \"%s\" contains duplicate rows without any null columns",
646  RelationGetRelationName(matviewRel)),
647  errdetail("Row: %s",
649  }
650 
652  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
653 
654  /* Start building the query for creating the diff table. */
655  resetStringInfo(&querybuf);
656  appendStringInfo(&querybuf,
657  "CREATE TEMP TABLE %s AS "
658  "SELECT mv.ctid AS tid, newdata "
659  "FROM %s mv FULL JOIN %s newdata ON (",
660  diffname, matviewname, tempname);
661 
662  /*
663  * Get the list of index OIDs for the table from the relcache, and look up
664  * each one in the pg_index syscache. We will test for equality on all
665  * columns present in all unique indexes which only reference columns and
666  * include all rows.
667  */
668  tupdesc = matviewRel->rd_att;
669  opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
670  foundUniqueIndex = false;
671 
672  indexoidlist = RelationGetIndexList(matviewRel);
673 
674  foreach(indexoidscan, indexoidlist)
675  {
676  Oid indexoid = lfirst_oid(indexoidscan);
677  Relation indexRel;
678 
679  indexRel = index_open(indexoid, RowExclusiveLock);
680  if (is_usable_unique_index(indexRel))
681  {
682  Form_pg_index indexStruct = indexRel->rd_index;
683  int indnkeyatts = indexStruct->indnkeyatts;
684  oidvector *indclass;
685  Datum indclassDatum;
686  bool isnull;
687  int i;
688 
689  /* Must get indclass the hard way. */
690  indclassDatum = SysCacheGetAttr(INDEXRELID,
691  indexRel->rd_indextuple,
692  Anum_pg_index_indclass,
693  &isnull);
694  Assert(!isnull);
695  indclass = (oidvector *) DatumGetPointer(indclassDatum);
696 
697  /* Add quals for all columns from this index. */
698  for (i = 0; i < indnkeyatts; i++)
699  {
700  int attnum = indexStruct->indkey.values[i];
701  Oid opclass = indclass->values[i];
702  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
703  Oid attrtype = attr->atttypid;
704  HeapTuple cla_ht;
705  Form_pg_opclass cla_tup;
706  Oid opfamily;
707  Oid opcintype;
708  Oid op;
709  const char *leftop;
710  const char *rightop;
711 
712  /*
713  * Identify the equality operator associated with this index
714  * column. First we need to look up the column's opclass.
715  */
716  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
717  if (!HeapTupleIsValid(cla_ht))
718  elog(ERROR, "cache lookup failed for opclass %u", opclass);
719  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
720  Assert(cla_tup->opcmethod == BTREE_AM_OID);
721  opfamily = cla_tup->opcfamily;
722  opcintype = cla_tup->opcintype;
723  ReleaseSysCache(cla_ht);
724 
725  op = get_opfamily_member(opfamily, opcintype, opcintype,
727  if (!OidIsValid(op))
728  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
729  BTEqualStrategyNumber, opcintype, opcintype, opfamily);
730 
731  /*
732  * If we find the same column with the same equality semantics
733  * in more than one index, we only need to emit the equality
734  * clause once.
735  *
736  * Since we only remember the last equality operator, this
737  * code could be fooled into emitting duplicate clauses given
738  * multiple indexes with several different opclasses ... but
739  * that's so unlikely it doesn't seem worth spending extra
740  * code to avoid.
741  */
742  if (opUsedForQual[attnum - 1] == op)
743  continue;
744  opUsedForQual[attnum - 1] = op;
745 
746  /*
747  * Actually add the qual, ANDed with any others.
748  */
749  if (foundUniqueIndex)
750  appendStringInfoString(&querybuf, " AND ");
751 
752  leftop = quote_qualified_identifier("newdata",
753  NameStr(attr->attname));
754  rightop = quote_qualified_identifier("mv",
755  NameStr(attr->attname));
756 
757  generate_operator_clause(&querybuf,
758  leftop, attrtype,
759  op,
760  rightop, attrtype);
761 
762  foundUniqueIndex = true;
763  }
764  }
765 
766  /* Keep the locks, since we're about to run DML which needs them. */
767  index_close(indexRel, NoLock);
768  }
769 
770  list_free(indexoidlist);
771 
772  /*
773  * There must be at least one usable unique index on the matview.
774  *
775  * ExecRefreshMatView() checks that after taking the exclusive lock on the
776  * matview. So at least one unique index is guaranteed to exist here
777  * because the lock is still being held; so an Assert seems sufficient.
778  */
779  Assert(foundUniqueIndex);
780 
781  appendStringInfoString(&querybuf,
782  " AND newdata OPERATOR(pg_catalog.*=) mv) "
783  "WHERE newdata IS NULL OR mv IS NULL "
784  "ORDER BY tid");
785 
786  /* Create the temporary "diff" table. */
787  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
788  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
789 
791  save_sec_context | SECURITY_RESTRICTED_OPERATION);
792 
793  /*
794  * We have no further use for data from the "full-data" temp table, but we
795  * must keep it around because its type is referenced from the diff table.
796  */
797 
798  /* Analyze the diff table. */
799  resetStringInfo(&querybuf);
800  appendStringInfo(&querybuf, "ANALYZE %s", diffname);
801  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
802  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
803 
805 
806  /* Deletes must come before inserts; do them first. */
807  resetStringInfo(&querybuf);
808  appendStringInfo(&querybuf,
809  "DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY "
810  "(SELECT diff.tid FROM %s diff "
811  "WHERE diff.tid IS NOT NULL "
812  "AND diff.newdata IS NULL)",
813  matviewname, diffname);
814  if (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)
815  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
816 
817  /* Inserts go last. */
818  resetStringInfo(&querybuf);
819  appendStringInfo(&querybuf,
820  "INSERT INTO %s SELECT (diff.newdata).* "
821  "FROM %s diff WHERE tid IS NULL",
822  matviewname, diffname);
823  if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
824  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
825 
826  /* We're done maintaining the materialized view. */
828  heap_close(tempRel, NoLock);
829  heap_close(matviewRel, NoLock);
830 
831  /* Clean up temp tables. */
832  resetStringInfo(&querybuf);
833  appendStringInfo(&querybuf, "DROP TABLE %s, %s", diffname, tempname);
834  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
835  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
836 
837  /* Close SPI context. */
838  if (SPI_finish() != SPI_OK_FINISH)
839  elog(ERROR, "SPI_finish failed");
840 }
signed short int16
Definition: c.h:312
Definition: c.h:555
#define SPI_OK_CONNECT
Definition: spi.h:50
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:858
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
int SPI_connect(void)
Definition: spi.c:84
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:413
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
#define SPI_OK_DELETE
Definition: spi.h:57
int SPI_finish(void)
Definition: spi.c:161
SPITupleTable * SPI_tuptable
Definition: spi.c:41
static void CloseMatViewIncrementalMaintenance(void)
Definition: matview.c:924
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:28
#define OidIsValid(objectId)
Definition: c.h:605
uint64 SPI_processed
Definition: spi.c:39
struct HeapTupleData * rd_indextuple
Definition: rel.h:133
static char * make_temptable_name_n(char *tempname, int n)
Definition: matview.c:537
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:902
Form_pg_index rd_index
Definition: rel.h:131
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
int SPI_exec(const char *src, long tcount)
Definition: spi.c:428
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:563
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define SPI_OK_UTILITY
Definition: spi.h:53
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
#define RelationGetRelationName(relation)
Definition: rel.h:441
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
#define ereport(elevel, rest)
Definition: elog.h:122
int16 relnatts
Definition: pg_class.h:52
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void * palloc0(Size size)
Definition: mcxt.c:955
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
TupleDesc tupdesc
Definition: spi.h:27
TupleDesc rd_att
Definition: rel.h:85
#define SPI_OK_SELECT
Definition: spi.h:54
int16 attnum
Definition: pg_attribute.h:79
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
#define SPI_OK_FINISH
Definition: spi.h:51
static void OpenMatViewIncrementalMaintenance(void)
Definition: matview.c:918
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4260
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define DatumGetPointer(X)
Definition: postgres.h:534
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
int i
#define NameStr(name)
Definition: c.h:576
#define SPI_OK_INSERT
Definition: spi.h:56
#define elog
Definition: elog.h:219
Oid relowner
Definition: pg_class.h:37
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:81
Definition: pg_list.h:45
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:10907
#define lfirst_oid(lc)
Definition: pg_list.h:108
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:400
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ refresh_matview_datafill()

static uint64 refresh_matview_datafill ( DestReceiver dest,
Query query,
const char *  queryString 
)
static

Definition at line 371 of file matview.c.

References AcquireRewriteLocks(), CHECK_FOR_INTERRUPTS, copyObject, CreateQueryDesc(), elog, ERROR, EState::es_processed, QueryDesc::estate, EXEC_FLAG_WITHOUT_OIDS, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), InvalidSnapshot, linitial, list_length(), pg_plan_query(), PopActiveSnapshot(), PushCopiedSnapshot(), QueryRewrite(), and UpdateActiveSnapshotCommandId().

Referenced by ExecRefreshMatView().

373 {
374  List *rewritten;
375  PlannedStmt *plan;
376  QueryDesc *queryDesc;
377  Query *copied_query;
378  uint64 processed;
379 
380  /* Lock and rewrite, using a copy to preserve the original query. */
381  copied_query = copyObject(query);
382  AcquireRewriteLocks(copied_query, true, false);
383  rewritten = QueryRewrite(copied_query);
384 
385  /* SELECT should never rewrite to more or less than one SELECT query */
386  if (list_length(rewritten) != 1)
387  elog(ERROR, "unexpected rewrite result for REFRESH MATERIALIZED VIEW");
388  query = (Query *) linitial(rewritten);
389 
390  /* Check for user-requested abort. */
392 
393  /* Plan the query which will generate data for the refresh. */
394  plan = pg_plan_query(query, 0, NULL);
395 
396  /*
397  * Use a snapshot with an updated command ID to ensure this query sees
398  * results of any previously executed queries. (This could only matter if
399  * the planner executed an allegedly-stable function that changed the
400  * database contents, but let's do it anyway to be safe.)
401  */
404 
405  /* Create a QueryDesc, redirecting output to our tuple receiver */
406  queryDesc = CreateQueryDesc(plan, queryString,
408  dest, NULL, NULL, 0);
409 
410  /* call ExecutorStart to prepare the plan for execution */
412 
413  /* run the plan */
414  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
415 
416  processed = queryDesc->estate->es_processed;
417 
418  /* and clean up */
419  ExecutorFinish(queryDesc);
420  ExecutorEnd(queryDesc);
421 
422  FreeQueryDesc(queryDesc);
423 
425 
426  return processed;
427 }
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:781
List * QueryRewrite(Query *parsetree)
EState * estate
Definition: execdesc.h:48
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:141
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
#define linitial(l)
Definition: pg_list.h:111
#define EXEC_FLAG_WITHOUT_OIDS
Definition: executor.h:64
#define ERROR
Definition: elog.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:299
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:769
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
#define InvalidSnapshot
Definition: snapshot.h:25
uint64 es_processed
Definition: execnodes.h:529
static int list_length(const List *l)
Definition: pg_list.h:89
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:629
Definition: pg_list.h:45
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:792

◆ SetMatViewPopulatedState()

void SetMatViewPopulatedState ( Relation  relation,
bool  newstate 
)

Definition at line 81 of file matview.c.

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

Referenced by ExecRefreshMatView(), and intorel_startup().

82 {
83  Relation pgrel;
84  HeapTuple tuple;
85 
86  Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
87 
88  /*
89  * Update relation's pg_class entry. Crucial side-effect: other backends
90  * (and this one too!) are sent SI message to make them rebuild relcache
91  * entries.
92  */
93  pgrel = heap_open(RelationRelationId, RowExclusiveLock);
96  if (!HeapTupleIsValid(tuple))
97  elog(ERROR, "cache lookup failed for relation %u",
98  RelationGetRelid(relation));
99 
101 
102  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
103 
104  heap_freetuple(tuple);
106 
107  /*
108  * Advance command counter to make the updated pg_class row locally
109  * visible.
110  */
112 }
bool relispopulated
Definition: pg_class.h:67
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
void CommandCounterIncrement(void)
Definition: xact.c:914
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
FormData_pg_class * Form_pg_class
Definition: pg_class.h:93
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ transientrel_destroy()

static void transientrel_destroy ( DestReceiver self)
static

Definition at line 523 of file matview.c.

References pfree().

Referenced by CreateTransientRelDestReceiver().

524 {
525  pfree(self);
526 }
void pfree(void *pointer)
Definition: mcxt.c:1031

◆ transientrel_receive()

static bool transientrel_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 478 of file matview.c.

References DR_transientrel::bistate, ExecMaterializeSlot(), heap_insert(), DR_transientrel::hi_options, DR_transientrel::output_cid, and DR_transientrel::transientrel.

Referenced by CreateTransientRelDestReceiver().

479 {
480  DR_transientrel *myState = (DR_transientrel *) self;
481  HeapTuple tuple;
482 
483  /*
484  * get the heap tuple out of the tuple table slot, making sure we have a
485  * writable copy
486  */
487  tuple = ExecMaterializeSlot(slot);
488 
489  heap_insert(myState->transientrel,
490  tuple,
491  myState->output_cid,
492  myState->hi_options,
493  myState->bistate);
494 
495  /* We know this is a newly created relation, so there are no indexes */
496 
497  return true;
498 }
Oid heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2441
Relation transientrel
Definition: matview.c:52
int hi_options
Definition: matview.c:54
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:781
CommandId output_cid
Definition: matview.c:53
BulkInsertState bistate
Definition: matview.c:55

◆ transientrel_shutdown()

static void transientrel_shutdown ( DestReceiver self)
static

Definition at line 504 of file matview.c.

References DR_transientrel::bistate, FreeBulkInsertState(), heap_close, HEAP_INSERT_SKIP_WAL, heap_sync(), DR_transientrel::hi_options, NoLock, and DR_transientrel::transientrel.

Referenced by CreateTransientRelDestReceiver().

505 {
506  DR_transientrel *myState = (DR_transientrel *) self;
507 
508  FreeBulkInsertState(myState->bistate);
509 
510  /* If we skipped using WAL, must heap_sync before commit */
511  if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
512  heap_sync(myState->transientrel);
513 
514  /* close transientrel, but keep lock until commit */
515  heap_close(myState->transientrel, NoLock);
516  myState->transientrel = NULL;
517 }
void heap_sync(Relation rel)
Definition: heapam.c:9370
#define HEAP_INSERT_SKIP_WAL
Definition: heapam.h:28
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
Relation transientrel
Definition: matview.c:52
int hi_options
Definition: matview.c:54
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:2378
BulkInsertState bistate
Definition: matview.c:55

◆ transientrel_startup()

static void transientrel_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)
static

Definition at line 448 of file matview.c.

References Assert, DR_transientrel::bistate, GetBulkInsertState(), GetCurrentCommandId(), HEAP_INSERT_FROZEN, HEAP_INSERT_SKIP_FSM, HEAP_INSERT_SKIP_WAL, heap_open(), DR_transientrel::hi_options, InvalidBlockNumber, NoLock, DR_transientrel::output_cid, RelationGetTargetBlock, DR_transientrel::transientoid, DR_transientrel::transientrel, and XLogIsNeeded.

Referenced by CreateTransientRelDestReceiver().

449 {
450  DR_transientrel *myState = (DR_transientrel *) self;
451  Relation transientrel;
452 
453  transientrel = heap_open(myState->transientoid, NoLock);
454 
455  /*
456  * Fill private fields of myState for use by later routines
457  */
458  myState->transientrel = transientrel;
459  myState->output_cid = GetCurrentCommandId(true);
460 
461  /*
462  * We can skip WAL-logging the insertions, unless PITR or streaming
463  * replication is in use. We can skip the FSM in any case.
464  */
466  if (!XLogIsNeeded())
467  myState->hi_options |= HEAP_INSERT_SKIP_WAL;
468  myState->bistate = GetBulkInsertState();
469 
470  /* Not using WAL requires smgr_targblock be initially invalid */
472 }
#define HEAP_INSERT_FROZEN
Definition: heapam.h:30
Oid transientoid
Definition: matview.c:50
#define XLogIsNeeded()
Definition: xlog.h:146
#define HEAP_INSERT_SKIP_WAL
Definition: heapam.h:28
#define RelationGetTargetBlock(relation)
Definition: rel.h:493
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:2364
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
Relation transientrel
Definition: matview.c:52
int hi_options
Definition: matview.c:54
#define Assert(condition)
Definition: c.h:699
#define InvalidBlockNumber
Definition: block.h:33
#define HEAP_INSERT_SKIP_FSM
Definition: heapam.h:29
CommandId output_cid
Definition: matview.c:53
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:679
BulkInsertState bistate
Definition: matview.c:55

Variable Documentation

◆ matview_maintenance_depth

int matview_maintenance_depth = 0
static