PostgreSQL Source Code  git master
matview.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/tableam.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, QueryCompletion *qc)
 
DestReceiverCreateTransientRelDestReceiver (Oid transientoid)
 
bool MatViewIncrementalMaintenanceIsEnabled (void)
 

Variables

static int matview_maintenance_depth = 0
 

Function Documentation

◆ CloseMatViewIncrementalMaintenance()

static void CloseMatViewIncrementalMaintenance ( void  )
static

Definition at line 920 of file matview.c.

References Assert, and matview_maintenance_depth.

Referenced by refresh_by_match_merge().

921 {
924 }
#define Assert(condition)
Definition: c.h:745
static int matview_maintenance_depth
Definition: matview.c:61

◆ 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:519
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:502
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:474
void * palloc0(Size size)
Definition: mcxt.c:981

◆ 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(), 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("CONCURRENTLY and WITH NO DATA options cannot be used together")));
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 TABLE_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, false);
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  table_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:612
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:854
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:15559
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1071
int numLocks
Definition: prs2lock.h:42
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:588
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:610
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:198
bool isInstead
Definition: prs2lock.h:31
RangeVar * relation
Definition: parsenodes.h:3294
Definition: localtime.c:72
#define ERROR
Definition: elog.h:43
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1138
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define NoLock
Definition: lockdefs.h:34
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:581
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5956
#define RelationGetRelationName(relation)
Definition: rel.h:490
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2098
RewriteRule ** rules
Definition: prs2lock.h:43
List * actions
Definition: prs2lock.h:29
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3589
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:844
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10790
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:298
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:745
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:371
RuleLock * rd_rules
Definition: rel.h:113
static int list_length(const List *l)
Definition: pg_list.h:169
#define PG_RE_THROW()
Definition: elog.h:336
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4514
#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:430
int NewGUCNestLevel(void)
Definition: guc.c:5942
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:1997
int errmsg(const char *fmt,...)
Definition: elog.c:824
static int matview_maintenance_depth
Definition: matview.c:61
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:214
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define PG_TRY()
Definition: elog.h:295
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:320
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:610
#define lfirst_oid(lc)
Definition: pg_list.h:192
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:576
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ is_usable_unique_index()

static bool is_usable_unique_index ( Relation  indexRel)
static

Definition at line 854 of file matview.c.

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

Referenced by ExecRefreshMatView(), and refresh_by_match_merge().

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

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

Referenced by refresh_by_match_merge().

534 {
535  StringInfoData namebuf;
536 
537  initStringInfo(&namebuf);
538  appendStringInfoString(&namebuf, tempname);
539  appendStringInfo(&namebuf, "_%d", n);
540  return namebuf.data;
541 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

◆ MatViewIncrementalMaintenanceIsEnabled()

bool MatViewIncrementalMaintenanceIsEnabled ( void  )

Definition at line 908 of file matview.c.

References matview_maintenance_depth.

Referenced by CheckValidResultRel().

909 {
910  return matview_maintenance_depth > 0;
911 }
static int matview_maintenance_depth
Definition: matview.c:61

◆ OpenMatViewIncrementalMaintenance()

static void OpenMatViewIncrementalMaintenance ( void  )
static

Definition at line 914 of file matview.c.

References matview_maintenance_depth.

Referenced by refresh_by_match_merge().

915 {
917 }
static int matview_maintenance_depth
Definition: matview.c:61

◆ refresh_by_heap_swap()

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

Definition at line 844 of file matview.c.

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

Referenced by ExecRefreshMatView().

845 {
846  finish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,
847  RecentXmin, ReadNextMultiXactId(), relpersistence);
848 }
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:1330
TransactionId RecentXmin
Definition: snapmgr.c:113
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ refresh_by_match_merge()

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

Definition at line 576 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, 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(), 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(), table_close(), table_open(), SPITupleTable::tupdesc, TupleDescAttr, SPITupleTable::vals, and oidvector::values.

Referenced by ExecRefreshMatView().

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

◆ 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, 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, queryString, 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 */
411  ExecutorStart(queryDesc, 0);
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:728
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:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
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:402
#define InvalidSnapshot
Definition: snapshot.h:123
uint64 es_processed
Definition: execnodes.h:556
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:214
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50

◆ 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:655
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#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:1021
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
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:174
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ transientrel_destroy()

static void transientrel_destroy ( DestReceiver self)
static

Definition at line 519 of file matview.c.

References pfree().

Referenced by CreateTransientRelDestReceiver().

520 {
521  pfree(self);
522 }
void pfree(void *pointer)
Definition: mcxt.c:1057

◆ transientrel_receive()

static bool transientrel_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 474 of file matview.c.

References DR_transientrel::bistate, DR_transientrel::output_cid, table_tuple_insert(), DR_transientrel::ti_options, and DR_transientrel::transientrel.

Referenced by CreateTransientRelDestReceiver().

475 {
476  DR_transientrel *myState = (DR_transientrel *) self;
477 
478  /*
479  * Note that the input slot might not be of the type of the target
480  * relation. That's supported by table_tuple_insert(), but slightly less
481  * efficient than inserting with the right slot - but the alternative
482  * would be to copy into a slot of the right type, which would not be
483  * cheap either. This also doesn't allow accessing per-AM data (say a
484  * tuple's xmin), but since we don't do that here...
485  */
486 
488  slot,
489  myState->output_cid,
490  myState->ti_options,
491  myState->bistate);
492 
493  /* We know this is a newly created relation, so there are no indexes */
494 
495  return true;
496 }
int ti_options
Definition: matview.c:57
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1178
Relation transientrel
Definition: matview.c:55
CommandId output_cid
Definition: matview.c:56
BulkInsertState bistate
Definition: matview.c:58

◆ transientrel_shutdown()

static void transientrel_shutdown ( DestReceiver self)
static

Definition at line 502 of file matview.c.

References DR_transientrel::bistate, FreeBulkInsertState(), NoLock, table_close(), table_finish_bulk_insert(), DR_transientrel::ti_options, and DR_transientrel::transientrel.

Referenced by CreateTransientRelDestReceiver().

503 {
504  DR_transientrel *myState = (DR_transientrel *) self;
505 
506  FreeBulkInsertState(myState->bistate);
507 
509 
510  /* close transientrel, but keep lock until commit */
511  table_close(myState->transientrel, NoLock);
512  myState->transientrel = NULL;
513 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1371
int ti_options
Definition: matview.c:57
#define NoLock
Definition: lockdefs.h:34
Relation transientrel
Definition: matview.c:55
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1820
BulkInsertState bistate
Definition: matview.c:58

◆ 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(), InvalidBlockNumber, NoLock, DR_transientrel::output_cid, RelationGetTargetBlock, TABLE_INSERT_FROZEN, TABLE_INSERT_SKIP_FSM, table_open(), DR_transientrel::ti_options, DR_transientrel::transientoid, and DR_transientrel::transientrel.

Referenced by CreateTransientRelDestReceiver().

449 {
450  DR_transientrel *myState = (DR_transientrel *) self;
451  Relation transientrel;
452 
453  transientrel = table_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);
461  myState->bistate = GetBulkInsertState();
462 
463  /*
464  * Valid smgr_targblock implies something already wrote to the relation.
465  * This may be harmless, but this function hasn't planned for it.
466  */
468 }
#define TABLE_INSERT_FROZEN
Definition: tableam.h:134
Oid transientoid
Definition: matview.c:53
#define RelationGetTargetBlock(relation)
Definition: rel.h:541
int ti_options
Definition: matview.c:57
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1806
#define NoLock
Definition: lockdefs.h:34
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:133
Relation transientrel
Definition: matview.c:55
#define Assert(condition)
Definition: c.h:745
#define InvalidBlockNumber
Definition: block.h:33
CommandId output_cid
Definition: matview.c:56
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
BulkInsertState bistate
Definition: matview.c:58

Variable Documentation

◆ matview_maintenance_depth

int matview_maintenance_depth = 0
static