PostgreSQL Source Code  git master
matview.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * matview.c
4  * materialized view support
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/commands/matview.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/htup_details.h"
20 #include "access/multixact.h"
21 #include "access/tableam.h"
22 #include "access/xact.h"
23 #include "access/xlog.h"
24 #include "catalog/catalog.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_am.h"
28 #include "catalog/pg_opclass.h"
29 #include "catalog/pg_operator.h"
30 #include "commands/cluster.h"
31 #include "commands/matview.h"
32 #include "commands/tablecmds.h"
33 #include "commands/tablespace.h"
34 #include "executor/executor.h"
35 #include "executor/spi.h"
36 #include "miscadmin.h"
37 #include "parser/parse_relation.h"
38 #include "pgstat.h"
39 #include "rewrite/rewriteHandler.h"
40 #include "storage/lmgr.h"
41 #include "storage/smgr.h"
42 #include "tcop/tcopprot.h"
43 #include "utils/builtins.h"
44 #include "utils/lsyscache.h"
45 #include "utils/rel.h"
46 #include "utils/snapmgr.h"
47 #include "utils/syscache.h"
48 
49 
50 typedef struct
51 {
52  DestReceiver pub; /* publicly-known function pointers */
53  Oid transientoid; /* OID of new heap into which to store */
54  /* These fields are filled by transientrel_startup: */
55  Relation transientrel; /* relation to write to */
56  CommandId output_cid; /* cmin to insert in output tuples */
57  int ti_options; /* table_tuple_insert performance options */
58  BulkInsertState bistate; /* bulk insert state */
60 
62 
63 static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
64 static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self);
65 static void transientrel_shutdown(DestReceiver *self);
66 static void transientrel_destroy(DestReceiver *self);
67 static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query,
68  const char *queryString);
69 static char *make_temptable_name_n(char *tempname, int n);
70 static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
71  int save_sec_context);
72 static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence);
73 static bool is_usable_unique_index(Relation indexRel);
74 static void OpenMatViewIncrementalMaintenance(void);
75 static void CloseMatViewIncrementalMaintenance(void);
76 
77 /*
78  * SetMatViewPopulatedState
79  * Mark a materialized view as populated, or not.
80  *
81  * NOTE: caller must be holding an appropriate lock on the relation.
82  */
83 void
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 }
116 
117 /*
118  * ExecRefreshMatView -- execute a REFRESH MATERIALIZED VIEW command
119  *
120  * This refreshes the materialized view by creating a new table and swapping
121  * the relfilenodes of the new table and the old materialized view, so the OID
122  * of the original materialized view is preserved. Thus we do not lose GRANT
123  * nor references to this materialized view.
124  *
125  * If WITH NO DATA was specified, this is effectively like a TRUNCATE;
126  * otherwise it is like a TRUNCATE followed by an INSERT using the SELECT
127  * statement associated with the materialized view. The statement node's
128  * skipData field shows whether the clause was used.
129  *
130  * Indexes are rebuilt too, via REINDEX. Since we are effectively bulk-loading
131  * the new heap, it's better to create the indexes afterwards than to fill them
132  * incrementally while we load.
133  *
134  * The matview's "populated" state is changed based on whether the contents
135  * reflect the result set of the materialized view's query.
136  */
138 ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
139  ParamListInfo params, QueryCompletion *qc)
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  /*
360  * Save the rowcount so that pg_stat_statements can track the total number
361  * of rows processed by REFRESH MATERIALIZED VIEW command. Note that we
362  * still don't display the rowcount in the command completion tag output,
363  * i.e., the display_rowcount flag of CMDTAG_REFRESH_MATERIALIZED_VIEW
364  * command tag is left false in cmdtaglist.h. Otherwise, the change of
365  * completion tag output might break applications using it.
366  */
367  if (qc)
368  SetQueryCompletion(qc, CMDTAG_REFRESH_MATERIALIZED_VIEW, processed);
369 
370  return address;
371 }
372 
373 /*
374  * refresh_matview_datafill
375  *
376  * Execute the given query, sending result rows to "dest" (which will
377  * insert them into the target matview).
378  *
379  * Returns number of rows inserted.
380  */
381 static uint64
383  const char *queryString)
384 {
385  List *rewritten;
386  PlannedStmt *plan;
387  QueryDesc *queryDesc;
388  Query *copied_query;
389  uint64 processed;
390 
391  /* Lock and rewrite, using a copy to preserve the original query. */
392  copied_query = copyObject(query);
393  AcquireRewriteLocks(copied_query, true, false);
394  rewritten = QueryRewrite(copied_query);
395 
396  /* SELECT should never rewrite to more or less than one SELECT query */
397  if (list_length(rewritten) != 1)
398  elog(ERROR, "unexpected rewrite result for REFRESH MATERIALIZED VIEW");
399  query = (Query *) linitial(rewritten);
400 
401  /* Check for user-requested abort. */
403 
404  /* Plan the query which will generate data for the refresh. */
405  plan = pg_plan_query(query, queryString, 0, NULL);
406 
407  /*
408  * Use a snapshot with an updated command ID to ensure this query sees
409  * results of any previously executed queries. (This could only matter if
410  * the planner executed an allegedly-stable function that changed the
411  * database contents, but let's do it anyway to be safe.)
412  */
415 
416  /* Create a QueryDesc, redirecting output to our tuple receiver */
417  queryDesc = CreateQueryDesc(plan, queryString,
419  dest, NULL, NULL, 0);
420 
421  /* call ExecutorStart to prepare the plan for execution */
422  ExecutorStart(queryDesc, 0);
423 
424  /* run the plan */
425  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
426 
427  processed = queryDesc->estate->es_processed;
428 
429  /* and clean up */
430  ExecutorFinish(queryDesc);
431  ExecutorEnd(queryDesc);
432 
433  FreeQueryDesc(queryDesc);
434 
436 
437  return processed;
438 }
439 
440 DestReceiver *
442 {
444 
445  self->pub.receiveSlot = transientrel_receive;
446  self->pub.rStartup = transientrel_startup;
447  self->pub.rShutdown = transientrel_shutdown;
448  self->pub.rDestroy = transientrel_destroy;
449  self->pub.mydest = DestTransientRel;
450  self->transientoid = transientoid;
451 
452  return (DestReceiver *) self;
453 }
454 
455 /*
456  * transientrel_startup --- executor startup
457  */
458 static void
459 transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
460 {
461  DR_transientrel *myState = (DR_transientrel *) self;
462  Relation transientrel;
463 
464  transientrel = table_open(myState->transientoid, NoLock);
465 
466  /*
467  * Fill private fields of myState for use by later routines
468  */
469  myState->transientrel = transientrel;
470  myState->output_cid = GetCurrentCommandId(true);
472  myState->bistate = GetBulkInsertState();
473 
474  /*
475  * Valid smgr_targblock implies something already wrote to the relation.
476  * This may be harmless, but this function hasn't planned for it.
477  */
479 }
480 
481 /*
482  * transientrel_receive --- receive one tuple
483  */
484 static bool
486 {
487  DR_transientrel *myState = (DR_transientrel *) self;
488 
489  /*
490  * Note that the input slot might not be of the type of the target
491  * relation. That's supported by table_tuple_insert(), but slightly less
492  * efficient than inserting with the right slot - but the alternative
493  * would be to copy into a slot of the right type, which would not be
494  * cheap either. This also doesn't allow accessing per-AM data (say a
495  * tuple's xmin), but since we don't do that here...
496  */
497 
499  slot,
500  myState->output_cid,
501  myState->ti_options,
502  myState->bistate);
503 
504  /* We know this is a newly created relation, so there are no indexes */
505 
506  return true;
507 }
508 
509 /*
510  * transientrel_shutdown --- executor end
511  */
512 static void
514 {
515  DR_transientrel *myState = (DR_transientrel *) self;
516 
517  FreeBulkInsertState(myState->bistate);
518 
520 
521  /* close transientrel, but keep lock until commit */
522  table_close(myState->transientrel, NoLock);
523  myState->transientrel = NULL;
524 }
525 
526 /*
527  * transientrel_destroy --- release DestReceiver object
528  */
529 static void
531 {
532  pfree(self);
533 }
534 
535 
536 /*
537  * Given a qualified temporary table name, append an underscore followed by
538  * the given integer, to make a new table name based on the old one.
539  *
540  * This leaks memory through palloc(), which won't be cleaned up until the
541  * current memory context is freed.
542  */
543 static char *
544 make_temptable_name_n(char *tempname, int n)
545 {
546  StringInfoData namebuf;
547 
548  initStringInfo(&namebuf);
549  appendStringInfoString(&namebuf, tempname);
550  appendStringInfo(&namebuf, "_%d", n);
551  return namebuf.data;
552 }
553 
554 /*
555  * refresh_by_match_merge
556  *
557  * Refresh a materialized view with transactional semantics, while allowing
558  * concurrent reads.
559  *
560  * This is called after a new version of the data has been created in a
561  * temporary table. It performs a full outer join against the old version of
562  * the data, producing "diff" results. This join cannot work if there are any
563  * duplicated rows in either the old or new versions, in the sense that every
564  * column would compare as equal between the two rows. It does work correctly
565  * in the face of rows which have at least one NULL value, with all non-NULL
566  * columns equal. The behavior of NULLs on equality tests and on UNIQUE
567  * indexes turns out to be quite convenient here; the tests we need to make
568  * are consistent with default behavior. If there is at least one UNIQUE
569  * index on the materialized view, we have exactly the guarantee we need.
570  *
571  * The temporary table used to hold the diff results contains just the TID of
572  * the old record (if matched) and the ROW from the new table as a single
573  * column of complex record type (if matched).
574  *
575  * Once we have the diff table, we perform set-based DELETE and INSERT
576  * operations against the materialized view, and discard both temporary
577  * tables.
578  *
579  * Everything from the generation of the new data to applying the differences
580  * takes place under cover of an ExclusiveLock, since it seems as though we
581  * would want to prohibit not only concurrent REFRESH operations, but also
582  * incremental maintenance. It also doesn't seem reasonable or safe to allow
583  * SELECT FOR UPDATE or SELECT FOR SHARE on rows being updated or deleted by
584  * this command.
585  */
586 static void
587 refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
588  int save_sec_context)
589 {
590  StringInfoData querybuf;
591  Relation matviewRel;
592  Relation tempRel;
593  char *matviewname;
594  char *tempname;
595  char *diffname;
596  TupleDesc tupdesc;
597  bool foundUniqueIndex;
598  List *indexoidlist;
599  ListCell *indexoidscan;
600  int16 relnatts;
601  Oid *opUsedForQual;
602 
603  initStringInfo(&querybuf);
604  matviewRel = table_open(matviewOid, NoLock);
606  RelationGetRelationName(matviewRel));
607  tempRel = table_open(tempOid, NoLock);
609  RelationGetRelationName(tempRel));
610  diffname = make_temptable_name_n(tempname, 2);
611 
612  relnatts = RelationGetNumberOfAttributes(matviewRel);
613 
614  /* Open SPI context. */
615  if (SPI_connect() != SPI_OK_CONNECT)
616  elog(ERROR, "SPI_connect failed");
617 
618  /* Analyze the temp table with the new contents. */
619  appendStringInfo(&querybuf, "ANALYZE %s", tempname);
620  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
621  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
622 
623  /*
624  * We need to ensure that there are not duplicate rows without NULLs in
625  * the new data set before we can count on the "diff" results. Check for
626  * that in a way that allows showing the first duplicated row found. Even
627  * after we pass this test, a unique index on the materialized view may
628  * find a duplicate key problem.
629  */
630  resetStringInfo(&querybuf);
631  appendStringInfo(&querybuf,
632  "SELECT newdata FROM %s newdata "
633  "WHERE newdata IS NOT NULL AND EXISTS "
634  "(SELECT 1 FROM %s newdata2 WHERE newdata2 IS NOT NULL "
635  "AND newdata2 OPERATOR(pg_catalog.*=) newdata "
636  "AND newdata2.ctid OPERATOR(pg_catalog.<>) "
637  "newdata.ctid)",
638  tempname, tempname);
639  if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
640  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
641  if (SPI_processed > 0)
642  {
643  /*
644  * Note that this ereport() is returning data to the user. Generally,
645  * we would want to make sure that the user has been granted access to
646  * this data. However, REFRESH MAT VIEW is only able to be run by the
647  * owner of the mat view (or a superuser) and therefore there is no
648  * need to check for access to data in the mat view.
649  */
650  ereport(ERROR,
651  (errcode(ERRCODE_CARDINALITY_VIOLATION),
652  errmsg("new data for materialized view \"%s\" contains duplicate rows without any null columns",
653  RelationGetRelationName(matviewRel)),
654  errdetail("Row: %s",
656  }
657 
658  SetUserIdAndSecContext(relowner,
659  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
660 
661  /* Start building the query for creating the diff table. */
662  resetStringInfo(&querybuf);
663  appendStringInfo(&querybuf,
664  "CREATE TEMP TABLE %s AS "
665  "SELECT mv.ctid AS tid, newdata "
666  "FROM %s mv FULL JOIN %s newdata ON (",
667  diffname, matviewname, tempname);
668 
669  /*
670  * Get the list of index OIDs for the table from the relcache, and look up
671  * each one in the pg_index syscache. We will test for equality on all
672  * columns present in all unique indexes which only reference columns and
673  * include all rows.
674  */
675  tupdesc = matviewRel->rd_att;
676  opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
677  foundUniqueIndex = false;
678 
679  indexoidlist = RelationGetIndexList(matviewRel);
680 
681  foreach(indexoidscan, indexoidlist)
682  {
683  Oid indexoid = lfirst_oid(indexoidscan);
684  Relation indexRel;
685 
686  indexRel = index_open(indexoid, RowExclusiveLock);
687  if (is_usable_unique_index(indexRel))
688  {
689  Form_pg_index indexStruct = indexRel->rd_index;
690  int indnkeyatts = indexStruct->indnkeyatts;
691  oidvector *indclass;
692  Datum indclassDatum;
693  bool isnull;
694  int i;
695 
696  /* Must get indclass the hard way. */
697  indclassDatum = SysCacheGetAttr(INDEXRELID,
698  indexRel->rd_indextuple,
699  Anum_pg_index_indclass,
700  &isnull);
701  Assert(!isnull);
702  indclass = (oidvector *) DatumGetPointer(indclassDatum);
703 
704  /* Add quals for all columns from this index. */
705  for (i = 0; i < indnkeyatts; i++)
706  {
707  int attnum = indexStruct->indkey.values[i];
708  Oid opclass = indclass->values[i];
709  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
710  Oid attrtype = attr->atttypid;
711  HeapTuple cla_ht;
712  Form_pg_opclass cla_tup;
713  Oid opfamily;
714  Oid opcintype;
715  Oid op;
716  const char *leftop;
717  const char *rightop;
718 
719  /*
720  * Identify the equality operator associated with this index
721  * column. First we need to look up the column's opclass.
722  */
723  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
724  if (!HeapTupleIsValid(cla_ht))
725  elog(ERROR, "cache lookup failed for opclass %u", opclass);
726  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
727  Assert(cla_tup->opcmethod == BTREE_AM_OID);
728  opfamily = cla_tup->opcfamily;
729  opcintype = cla_tup->opcintype;
730  ReleaseSysCache(cla_ht);
731 
732  op = get_opfamily_member(opfamily, opcintype, opcintype,
734  if (!OidIsValid(op))
735  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
736  BTEqualStrategyNumber, opcintype, opcintype, opfamily);
737 
738  /*
739  * If we find the same column with the same equality semantics
740  * in more than one index, we only need to emit the equality
741  * clause once.
742  *
743  * Since we only remember the last equality operator, this
744  * code could be fooled into emitting duplicate clauses given
745  * multiple indexes with several different opclasses ... but
746  * that's so unlikely it doesn't seem worth spending extra
747  * code to avoid.
748  */
749  if (opUsedForQual[attnum - 1] == op)
750  continue;
751  opUsedForQual[attnum - 1] = op;
752 
753  /*
754  * Actually add the qual, ANDed with any others.
755  */
756  if (foundUniqueIndex)
757  appendStringInfoString(&querybuf, " AND ");
758 
759  leftop = quote_qualified_identifier("newdata",
760  NameStr(attr->attname));
761  rightop = quote_qualified_identifier("mv",
762  NameStr(attr->attname));
763 
764  generate_operator_clause(&querybuf,
765  leftop, attrtype,
766  op,
767  rightop, attrtype);
768 
769  foundUniqueIndex = true;
770  }
771  }
772 
773  /* Keep the locks, since we're about to run DML which needs them. */
774  index_close(indexRel, NoLock);
775  }
776 
777  list_free(indexoidlist);
778 
779  /*
780  * There must be at least one usable unique index on the matview.
781  *
782  * ExecRefreshMatView() checks that after taking the exclusive lock on the
783  * matview. So at least one unique index is guaranteed to exist here
784  * because the lock is still being held; so an Assert seems sufficient.
785  */
786  Assert(foundUniqueIndex);
787 
788  appendStringInfoString(&querybuf,
789  " AND newdata OPERATOR(pg_catalog.*=) mv) "
790  "WHERE newdata IS NULL OR mv IS NULL "
791  "ORDER BY tid");
792 
793  /* Create the temporary "diff" table. */
794  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
795  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
796 
797  SetUserIdAndSecContext(relowner,
798  save_sec_context | SECURITY_RESTRICTED_OPERATION);
799 
800  /*
801  * We have no further use for data from the "full-data" temp table, but we
802  * must keep it around because its type is referenced from the diff table.
803  */
804 
805  /* Analyze the diff table. */
806  resetStringInfo(&querybuf);
807  appendStringInfo(&querybuf, "ANALYZE %s", diffname);
808  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
809  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
810 
812 
813  /* Deletes must come before inserts; do them first. */
814  resetStringInfo(&querybuf);
815  appendStringInfo(&querybuf,
816  "DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY "
817  "(SELECT diff.tid FROM %s diff "
818  "WHERE diff.tid IS NOT NULL "
819  "AND diff.newdata IS NULL)",
820  matviewname, diffname);
821  if (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)
822  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
823 
824  /* Inserts go last. */
825  resetStringInfo(&querybuf);
826  appendStringInfo(&querybuf,
827  "INSERT INTO %s SELECT (diff.newdata).* "
828  "FROM %s diff WHERE tid IS NULL",
829  matviewname, diffname);
830  if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
831  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
832 
833  /* We're done maintaining the materialized view. */
835  table_close(tempRel, NoLock);
836  table_close(matviewRel, NoLock);
837 
838  /* Clean up temp tables. */
839  resetStringInfo(&querybuf);
840  appendStringInfo(&querybuf, "DROP TABLE %s, %s", diffname, tempname);
841  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
842  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
843 
844  /* Close SPI context. */
845  if (SPI_finish() != SPI_OK_FINISH)
846  elog(ERROR, "SPI_finish failed");
847 }
848 
849 /*
850  * Swap the physical files of the target and transient tables, then rebuild
851  * the target's indexes and throw away the transient table. Security context
852  * swapping is handled by the called function, so it is not needed here.
853  */
854 static void
855 refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
856 {
857  finish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,
858  RecentXmin, ReadNextMultiXactId(), relpersistence);
859 }
860 
861 /*
862  * Check whether specified index is usable for match merge.
863  */
864 static bool
866 {
867  Form_pg_index indexStruct = indexRel->rd_index;
868 
869  /*
870  * Must be unique, valid, immediate, non-partial, and be defined over
871  * plain user columns (not expressions). We also require it to be a
872  * btree. Even if we had any other unique index kinds, we'd not know how
873  * to identify the corresponding equality operator, nor could we be sure
874  * that the planner could implement the required FULL JOIN with non-btree
875  * operators.
876  */
877  if (indexStruct->indisunique &&
878  indexStruct->indimmediate &&
879  indexRel->rd_rel->relam == BTREE_AM_OID &&
880  indexStruct->indisvalid &&
881  RelationGetIndexPredicate(indexRel) == NIL &&
882  indexStruct->indnatts > 0)
883  {
884  /*
885  * The point of groveling through the index columns individually is to
886  * reject both index expressions and system columns. Currently,
887  * matviews couldn't have OID columns so there's no way to create an
888  * index on a system column; but maybe someday that wouldn't be true,
889  * so let's be safe.
890  */
891  int numatts = indexStruct->indnatts;
892  int i;
893 
894  for (i = 0; i < numatts; i++)
895  {
896  int attnum = indexStruct->indkey.values[i];
897 
898  if (attnum <= 0)
899  return false;
900  }
901  return true;
902  }
903  return false;
904 }
905 
906 
907 /*
908  * This should be used to test whether the backend is in a context where it is
909  * OK to allow DML statements to modify materialized views. We only want to
910  * allow that for internal code driven by the materialized view definition,
911  * not for arbitrary user-supplied code.
912  *
913  * While the function names reflect the fact that their main intended use is
914  * incremental maintenance of materialized views (in response to changes to
915  * the data in referenced relations), they are initially used to allow REFRESH
916  * without blocking concurrent reads.
917  */
918 bool
920 {
921  return matview_maintenance_depth > 0;
922 }
923 
924 static void
926 {
928 }
929 
930 static void
932 {
935 }
signed short int16
Definition: c.h:416
#define RelationIsPopulated(relation)
Definition: rel.h:613
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:589
Definition: c.h:656
#define SPI_OK_CONNECT
Definition: spi.h:53
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:865
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:15599
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
List * QueryRewrite(Query *parsetree)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1149
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int numLocks
Definition: prs2lock.h:42
EState * estate
Definition: execdesc.h:48
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:1324
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:588
DestReceiver pub
Definition: matview.c:52
int LOCKMODE
Definition: lockdefs.h:26
#define TABLE_INSERT_FROZEN
Definition: tableam.h:134
int SPI_connect(void)
Definition: spi.c:90
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:463
#define ExclusiveLock
Definition: lockdefs.h:44
Oid transientoid
Definition: matview.c:53
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:919
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define SPI_OK_DELETE
Definition: spi.h:60
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:459
int SPI_finish(void)
Definition: spi.c:177
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
#define AccessShareLock
Definition: lockdefs.h:36
SPITupleTable * SPI_tuptable
Definition: spi.c:46
static void CloseMatViewIncrementalMaintenance(void)
Definition: matview.c:931
int errcode(int sqlerrcode)
Definition: elog.c:691
TransactionId RecentXmin
Definition: snapmgr.c:113
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1371
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Form_pg_class rd_rel
Definition: rel.h:110
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:26
#define linitial_node(type, l)
Definition: pg_list.h:177
#define OidIsValid(objectId)
Definition: c.h:706
#define RelationGetTargetBlock(relation)
Definition: rel.h:542
bool isInstead
Definition: prs2lock.h:31
RangeVar * relation
Definition: parsenodes.h:3290
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
uint64 SPI_processed
Definition: spi.c:45
Definition: localtime.c:72
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4862
struct HeapTupleData * rd_indextuple
Definition: rel.h:177
static char * make_temptable_name_n(char *tempname, int n)
Definition: matview.c:544
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1069
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1806
Form_pg_index rd_index
Definition: rel.h:175
void pfree(void *pointer)
Definition: mcxt.c:1057
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:174
#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 ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
ItemPointerData t_self
Definition: htup.h:65
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
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:530
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1138
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:664
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:581
#define RowExclusiveLock
Definition: lockdefs.h:38
CmdType event
Definition: prs2lock.h:27
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5962
int errdetail(const char *fmt,...)
Definition: elog.c:1035
#define SPI_OK_UTILITY
Definition: spi.h:56
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:513
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:485
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
#define RelationGetRelationName(relation)
Definition: rel.h:491
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2212
RewriteRule ** rules
Definition: prs2lock.h:43
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
List * actions
Definition: prs2lock.h:29
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3593
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:855
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11018
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
#define InvalidSnapshot
Definition: snapshot.h:123
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
static struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:124
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1376
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:133
TupleDesc tupdesc
Definition: spi.h:25
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:298
TupleDesc rd_att
Definition: rel.h:111
Relation transientrel
Definition: matview.c:55
#define SPI_OK_SELECT
Definition: spi.h:57
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
#define PG_CATCH()
Definition: elog.h:319
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:800
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1820
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:382
ObjectAddress ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString, ParamListInfo params, QueryCompletion *qc)
Definition: matview.c:138
uint64 es_processed
Definition: execnodes.h:563
RuleLock * rd_rules
Definition: rel.h:114
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define InvalidBlockNumber
Definition: block.h:33
static int list_length(const List *l)
Definition: pg_list.h:149
#define SPI_OK_FINISH
Definition: spi.h:54
static void OpenMatViewIncrementalMaintenance(void)
Definition: matview.c:925
#define PG_RE_THROW()
Definition: elog.h:350
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4515
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:549
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define AccessExclusiveLock
Definition: lockdefs.h:45
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:441
int NewGUCNestLevel(void)
Definition: guc.c:5948
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:2111
int errmsg(const char *fmt,...)
Definition: elog.c:902
static int matview_maintenance_depth
Definition: matview.c:61
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:677
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
#define SPI_OK_INSERT
Definition: spi.h:59
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandId output_cid
Definition: matview.c:56
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
#define copyObject(obj)
Definition: nodes.h:643
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define PG_TRY()
Definition: elog.h:309
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
#define RelationGetRelid(relation)
Definition: rel.h:457
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:334
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:605
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:11342
#define lfirst_oid(lc)
Definition: pg_list.h:171
BulkInsertState bistate
Definition: matview.c:58
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:587
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:497
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723
#define RelationGetNamespace(relation)
Definition: rel.h:498