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-2022, 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 relfilenumbers 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  relowner = matviewRel->rd_rel->relowner;
171 
172  /*
173  * Switch to the owner's userid, so that any functions are run as that
174  * user. Also lock down security-restricted operations and arrange to
175  * make GUC variable changes local to this command.
176  */
177  GetUserIdAndSecContext(&save_userid, &save_sec_context);
178  SetUserIdAndSecContext(relowner,
179  save_sec_context | SECURITY_RESTRICTED_OPERATION);
180  save_nestlevel = NewGUCNestLevel();
181 
182  /* Make sure it is a materialized view. */
183  if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
184  ereport(ERROR,
185  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
186  errmsg("\"%s\" is not a materialized view",
187  RelationGetRelationName(matviewRel))));
188 
189  /* Check that CONCURRENTLY is not specified if not populated. */
190  if (concurrent && !RelationIsPopulated(matviewRel))
191  ereport(ERROR,
192  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
193  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
194 
195  /* Check that conflicting options have not been specified. */
196  if (concurrent && stmt->skipData)
197  ereport(ERROR,
198  (errcode(ERRCODE_SYNTAX_ERROR),
199  errmsg("%s and %s options cannot be used together",
200  "CONCURRENTLY", "WITH NO DATA")));
201 
202  /*
203  * Check that everything is correct for a refresh. Problems at this point
204  * are internal errors, so elog is sufficient.
205  */
206  if (matviewRel->rd_rel->relhasrules == false ||
207  matviewRel->rd_rules->numLocks < 1)
208  elog(ERROR,
209  "materialized view \"%s\" is missing rewrite information",
210  RelationGetRelationName(matviewRel));
211 
212  if (matviewRel->rd_rules->numLocks > 1)
213  elog(ERROR,
214  "materialized view \"%s\" has too many rules",
215  RelationGetRelationName(matviewRel));
216 
217  rule = matviewRel->rd_rules->rules[0];
218  if (rule->event != CMD_SELECT || !(rule->isInstead))
219  elog(ERROR,
220  "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
221  RelationGetRelationName(matviewRel));
222 
223  actions = rule->actions;
224  if (list_length(actions) != 1)
225  elog(ERROR,
226  "the rule for materialized view \"%s\" is not a single action",
227  RelationGetRelationName(matviewRel));
228 
229  /*
230  * Check that there is a unique index with no WHERE clause on one or more
231  * columns of the materialized view if CONCURRENTLY is specified.
232  */
233  if (concurrent)
234  {
235  List *indexoidlist = RelationGetIndexList(matviewRel);
236  ListCell *indexoidscan;
237  bool hasUniqueIndex = false;
238 
239  foreach(indexoidscan, indexoidlist)
240  {
241  Oid indexoid = lfirst_oid(indexoidscan);
242  Relation indexRel;
243 
244  indexRel = index_open(indexoid, AccessShareLock);
245  hasUniqueIndex = is_usable_unique_index(indexRel);
246  index_close(indexRel, AccessShareLock);
247  if (hasUniqueIndex)
248  break;
249  }
250 
251  list_free(indexoidlist);
252 
253  if (!hasUniqueIndex)
254  ereport(ERROR,
255  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
256  errmsg("cannot refresh materialized view \"%s\" concurrently",
258  RelationGetRelationName(matviewRel))),
259  errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
260  }
261 
262  /*
263  * The stored query was rewritten at the time of the MV definition, but
264  * has not been scribbled on by the planner.
265  */
266  dataQuery = linitial_node(Query, actions);
267 
268  /*
269  * Check for active uses of the relation in the current transaction, such
270  * as open scans.
271  *
272  * NB: We count on this to protect us against problems with refreshing the
273  * data using TABLE_INSERT_FROZEN.
274  */
275  CheckTableNotInUse(matviewRel, "REFRESH MATERIALIZED VIEW");
276 
277  /*
278  * Tentatively mark the matview as populated or not (this will roll back
279  * if we fail later).
280  */
281  SetMatViewPopulatedState(matviewRel, !stmt->skipData);
282 
283  /* Concurrent refresh builds new data in temp tablespace, and does diff. */
284  if (concurrent)
285  {
286  tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP, false);
287  relpersistence = RELPERSISTENCE_TEMP;
288  }
289  else
290  {
291  tableSpace = matviewRel->rd_rel->reltablespace;
292  relpersistence = matviewRel->rd_rel->relpersistence;
293  }
294 
295  /*
296  * Create the transient table that will receive the regenerated data. Lock
297  * it against access by any other process until commit (by which time it
298  * will be gone).
299  */
300  OIDNewHeap = make_new_heap(matviewOid, tableSpace,
301  matviewRel->rd_rel->relam,
302  relpersistence, ExclusiveLock);
304  dest = CreateTransientRelDestReceiver(OIDNewHeap);
305 
306  /* Generate the data, if wanted. */
307  if (!stmt->skipData)
308  processed = refresh_matview_datafill(dest, dataQuery, queryString);
309 
310  /* Make the matview match the newly generated data. */
311  if (concurrent)
312  {
313  int old_depth = matview_maintenance_depth;
314 
315  PG_TRY();
316  {
317  refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
318  save_sec_context);
319  }
320  PG_CATCH();
321  {
322  matview_maintenance_depth = old_depth;
323  PG_RE_THROW();
324  }
325  PG_END_TRY();
326  Assert(matview_maintenance_depth == old_depth);
327  }
328  else
329  {
330  refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
331 
332  /*
333  * Inform cumulative stats system about our activity: basically, we
334  * truncated the matview and inserted some new data. (The concurrent
335  * code path above doesn't need to worry about this because the
336  * inserts and deletes it issues get counted by lower-level code.)
337  */
338  pgstat_count_truncate(matviewRel);
339  if (!stmt->skipData)
340  pgstat_count_heap_insert(matviewRel, processed);
341  }
342 
343  table_close(matviewRel, NoLock);
344 
345  /* Roll back any GUC changes */
346  AtEOXact_GUC(false, save_nestlevel);
347 
348  /* Restore userid and security context */
349  SetUserIdAndSecContext(save_userid, save_sec_context);
350 
351  ObjectAddressSet(address, RelationRelationId, matviewOid);
352 
353  /*
354  * Save the rowcount so that pg_stat_statements can track the total number
355  * of rows processed by REFRESH MATERIALIZED VIEW command. Note that we
356  * still don't display the rowcount in the command completion tag output,
357  * i.e., the display_rowcount flag of CMDTAG_REFRESH_MATERIALIZED_VIEW
358  * command tag is left false in cmdtaglist.h. Otherwise, the change of
359  * completion tag output might break applications using it.
360  */
361  if (qc)
362  SetQueryCompletion(qc, CMDTAG_REFRESH_MATERIALIZED_VIEW, processed);
363 
364  return address;
365 }
366 
367 /*
368  * refresh_matview_datafill
369  *
370  * Execute the given query, sending result rows to "dest" (which will
371  * insert them into the target matview).
372  *
373  * Returns number of rows inserted.
374  */
375 static uint64
377  const char *queryString)
378 {
379  List *rewritten;
380  PlannedStmt *plan;
381  QueryDesc *queryDesc;
382  Query *copied_query;
383  uint64 processed;
384 
385  /* Lock and rewrite, using a copy to preserve the original query. */
386  copied_query = copyObject(query);
387  AcquireRewriteLocks(copied_query, true, false);
388  rewritten = QueryRewrite(copied_query);
389 
390  /* SELECT should never rewrite to more or less than one SELECT query */
391  if (list_length(rewritten) != 1)
392  elog(ERROR, "unexpected rewrite result for REFRESH MATERIALIZED VIEW");
393  query = (Query *) linitial(rewritten);
394 
395  /* Check for user-requested abort. */
397 
398  /* Plan the query which will generate data for the refresh. */
399  plan = pg_plan_query(query, queryString, CURSOR_OPT_PARALLEL_OK, NULL);
400 
401  /*
402  * Use a snapshot with an updated command ID to ensure this query sees
403  * results of any previously executed queries. (This could only matter if
404  * the planner executed an allegedly-stable function that changed the
405  * database contents, but let's do it anyway to be safe.)
406  */
409 
410  /* Create a QueryDesc, redirecting output to our tuple receiver */
411  queryDesc = CreateQueryDesc(plan, queryString,
413  dest, NULL, NULL, 0);
414 
415  /* call ExecutorStart to prepare the plan for execution */
416  ExecutorStart(queryDesc, 0);
417 
418  /* run the plan */
419  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
420 
421  processed = queryDesc->estate->es_processed;
422 
423  /* and clean up */
424  ExecutorFinish(queryDesc);
425  ExecutorEnd(queryDesc);
426 
427  FreeQueryDesc(queryDesc);
428 
430 
431  return processed;
432 }
433 
434 DestReceiver *
436 {
438 
439  self->pub.receiveSlot = transientrel_receive;
440  self->pub.rStartup = transientrel_startup;
441  self->pub.rShutdown = transientrel_shutdown;
442  self->pub.rDestroy = transientrel_destroy;
443  self->pub.mydest = DestTransientRel;
444  self->transientoid = transientoid;
445 
446  return (DestReceiver *) self;
447 }
448 
449 /*
450  * transientrel_startup --- executor startup
451  */
452 static void
453 transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
454 {
455  DR_transientrel *myState = (DR_transientrel *) self;
456  Relation transientrel;
457 
458  transientrel = table_open(myState->transientoid, NoLock);
459 
460  /*
461  * Fill private fields of myState for use by later routines
462  */
463  myState->transientrel = transientrel;
464  myState->output_cid = GetCurrentCommandId(true);
466  myState->bistate = GetBulkInsertState();
467 
468  /*
469  * Valid smgr_targblock implies something already wrote to the relation.
470  * This may be harmless, but this function hasn't planned for it.
471  */
473 }
474 
475 /*
476  * transientrel_receive --- receive one tuple
477  */
478 static bool
480 {
481  DR_transientrel *myState = (DR_transientrel *) self;
482 
483  /*
484  * Note that the input slot might not be of the type of the target
485  * relation. That's supported by table_tuple_insert(), but slightly less
486  * efficient than inserting with the right slot - but the alternative
487  * would be to copy into a slot of the right type, which would not be
488  * cheap either. This also doesn't allow accessing per-AM data (say a
489  * tuple's xmin), but since we don't do that here...
490  */
491 
493  slot,
494  myState->output_cid,
495  myState->ti_options,
496  myState->bistate);
497 
498  /* We know this is a newly created relation, so there are no indexes */
499 
500  return true;
501 }
502 
503 /*
504  * transientrel_shutdown --- executor end
505  */
506 static void
508 {
509  DR_transientrel *myState = (DR_transientrel *) self;
510 
511  FreeBulkInsertState(myState->bistate);
512 
514 
515  /* close transientrel, but keep lock until commit */
516  table_close(myState->transientrel, NoLock);
517  myState->transientrel = NULL;
518 }
519 
520 /*
521  * transientrel_destroy --- release DestReceiver object
522  */
523 static void
525 {
526  pfree(self);
527 }
528 
529 
530 /*
531  * Given a qualified temporary table name, append an underscore followed by
532  * the given integer, to make a new table name based on the old one.
533  * The result is a palloc'd string.
534  *
535  * As coded, this would fail to make a valid SQL name if the given name were,
536  * say, "FOO"."BAR". Currently, the table name portion of the input will
537  * never be double-quoted because it's of the form "pg_temp_NNN", cf
538  * make_new_heap(). But we might have to work harder someday.
539  */
540 static char *
541 make_temptable_name_n(char *tempname, int n)
542 {
543  StringInfoData namebuf;
544 
545  initStringInfo(&namebuf);
546  appendStringInfoString(&namebuf, tempname);
547  appendStringInfo(&namebuf, "_%d", n);
548  return namebuf.data;
549 }
550 
551 /*
552  * refresh_by_match_merge
553  *
554  * Refresh a materialized view with transactional semantics, while allowing
555  * concurrent reads.
556  *
557  * This is called after a new version of the data has been created in a
558  * temporary table. It performs a full outer join against the old version of
559  * the data, producing "diff" results. This join cannot work if there are any
560  * duplicated rows in either the old or new versions, in the sense that every
561  * column would compare as equal between the two rows. It does work correctly
562  * in the face of rows which have at least one NULL value, with all non-NULL
563  * columns equal. The behavior of NULLs on equality tests and on UNIQUE
564  * indexes turns out to be quite convenient here; the tests we need to make
565  * are consistent with default behavior. If there is at least one UNIQUE
566  * index on the materialized view, we have exactly the guarantee we need.
567  *
568  * The temporary table used to hold the diff results contains just the TID of
569  * the old record (if matched) and the ROW from the new table as a single
570  * column of complex record type (if matched).
571  *
572  * Once we have the diff table, we perform set-based DELETE and INSERT
573  * operations against the materialized view, and discard both temporary
574  * tables.
575  *
576  * Everything from the generation of the new data to applying the differences
577  * takes place under cover of an ExclusiveLock, since it seems as though we
578  * would want to prohibit not only concurrent REFRESH operations, but also
579  * incremental maintenance. It also doesn't seem reasonable or safe to allow
580  * SELECT FOR UPDATE or SELECT FOR SHARE on rows being updated or deleted by
581  * this command.
582  */
583 static void
584 refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
585  int save_sec_context)
586 {
587  StringInfoData querybuf;
588  Relation matviewRel;
589  Relation tempRel;
590  char *matviewname;
591  char *tempname;
592  char *diffname;
593  TupleDesc tupdesc;
594  bool foundUniqueIndex;
595  List *indexoidlist;
596  ListCell *indexoidscan;
597  int16 relnatts;
598  Oid *opUsedForQual;
599 
600  initStringInfo(&querybuf);
601  matviewRel = table_open(matviewOid, NoLock);
603  RelationGetRelationName(matviewRel));
604  tempRel = table_open(tempOid, NoLock);
606  RelationGetRelationName(tempRel));
607  diffname = make_temptable_name_n(tempname, 2);
608 
609  relnatts = RelationGetNumberOfAttributes(matviewRel);
610 
611  /* Open SPI context. */
612  if (SPI_connect() != SPI_OK_CONNECT)
613  elog(ERROR, "SPI_connect failed");
614 
615  /* Analyze the temp table with the new contents. */
616  appendStringInfo(&querybuf, "ANALYZE %s", tempname);
617  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
618  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
619 
620  /*
621  * We need to ensure that there are not duplicate rows without NULLs in
622  * the new data set before we can count on the "diff" results. Check for
623  * that in a way that allows showing the first duplicated row found. Even
624  * after we pass this test, a unique index on the materialized view may
625  * find a duplicate key problem.
626  *
627  * Note: here and below, we use "tablename.*::tablerowtype" as a hack to
628  * keep ".*" from being expanded into multiple columns in a SELECT list.
629  * Compare ruleutils.c's get_variable().
630  */
631  resetStringInfo(&querybuf);
632  appendStringInfo(&querybuf,
633  "SELECT newdata.*::%s FROM %s newdata "
634  "WHERE newdata.* IS NOT NULL AND EXISTS "
635  "(SELECT 1 FROM %s newdata2 WHERE newdata2.* IS NOT NULL "
636  "AND newdata2.* OPERATOR(pg_catalog.*=) newdata.* "
637  "AND newdata2.ctid OPERATOR(pg_catalog.<>) "
638  "newdata.ctid)",
639  tempname, tempname, tempname);
640  if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
641  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
642  if (SPI_processed > 0)
643  {
644  /*
645  * Note that this ereport() is returning data to the user. Generally,
646  * we would want to make sure that the user has been granted access to
647  * this data. However, REFRESH MAT VIEW is only able to be run by the
648  * owner of the mat view (or a superuser) and therefore there is no
649  * need to check for access to data in the mat view.
650  */
651  ereport(ERROR,
652  (errcode(ERRCODE_CARDINALITY_VIOLATION),
653  errmsg("new data for materialized view \"%s\" contains duplicate rows without any null columns",
654  RelationGetRelationName(matviewRel)),
655  errdetail("Row: %s",
657  }
658 
659  SetUserIdAndSecContext(relowner,
660  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
661 
662  /* Start building the query for creating the diff table. */
663  resetStringInfo(&querybuf);
664  appendStringInfo(&querybuf,
665  "CREATE TEMP TABLE %s AS "
666  "SELECT mv.ctid AS tid, newdata.*::%s AS newdata "
667  "FROM %s mv FULL JOIN %s newdata ON (",
668  diffname, tempname, matviewname, tempname);
669 
670  /*
671  * Get the list of index OIDs for the table from the relcache, and look up
672  * each one in the pg_index syscache. We will test for equality on all
673  * columns present in all unique indexes which only reference columns and
674  * include all rows.
675  */
676  tupdesc = matviewRel->rd_att;
677  opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
678  foundUniqueIndex = false;
679 
680  indexoidlist = RelationGetIndexList(matviewRel);
681 
682  foreach(indexoidscan, indexoidlist)
683  {
684  Oid indexoid = lfirst_oid(indexoidscan);
685  Relation indexRel;
686 
687  indexRel = index_open(indexoid, RowExclusiveLock);
688  if (is_usable_unique_index(indexRel))
689  {
690  Form_pg_index indexStruct = indexRel->rd_index;
691  int indnkeyatts = indexStruct->indnkeyatts;
692  oidvector *indclass;
693  Datum indclassDatum;
694  bool isnull;
695  int i;
696 
697  /* Must get indclass the hard way. */
698  indclassDatum = SysCacheGetAttr(INDEXRELID,
699  indexRel->rd_indextuple,
700  Anum_pg_index_indclass,
701  &isnull);
702  Assert(!isnull);
703  indclass = (oidvector *) DatumGetPointer(indclassDatum);
704 
705  /* Add quals for all columns from this index. */
706  for (i = 0; i < indnkeyatts; i++)
707  {
708  int attnum = indexStruct->indkey.values[i];
709  Oid opclass = indclass->values[i];
710  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
711  Oid attrtype = attr->atttypid;
712  HeapTuple cla_ht;
713  Form_pg_opclass cla_tup;
714  Oid opfamily;
715  Oid opcintype;
716  Oid op;
717  const char *leftop;
718  const char *rightop;
719 
720  /*
721  * Identify the equality operator associated with this index
722  * column. First we need to look up the column's opclass.
723  */
724  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
725  if (!HeapTupleIsValid(cla_ht))
726  elog(ERROR, "cache lookup failed for opclass %u", opclass);
727  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
728  Assert(cla_tup->opcmethod == BTREE_AM_OID);
729  opfamily = cla_tup->opcfamily;
730  opcintype = cla_tup->opcintype;
731  ReleaseSysCache(cla_ht);
732 
733  op = get_opfamily_member(opfamily, opcintype, opcintype,
735  if (!OidIsValid(op))
736  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
737  BTEqualStrategyNumber, opcintype, opcintype, opfamily);
738 
739  /*
740  * If we find the same column with the same equality semantics
741  * in more than one index, we only need to emit the equality
742  * clause once.
743  *
744  * Since we only remember the last equality operator, this
745  * code could be fooled into emitting duplicate clauses given
746  * multiple indexes with several different opclasses ... but
747  * that's so unlikely it doesn't seem worth spending extra
748  * code to avoid.
749  */
750  if (opUsedForQual[attnum - 1] == op)
751  continue;
752  opUsedForQual[attnum - 1] = op;
753 
754  /*
755  * Actually add the qual, ANDed with any others.
756  */
757  if (foundUniqueIndex)
758  appendStringInfoString(&querybuf, " AND ");
759 
760  leftop = quote_qualified_identifier("newdata",
761  NameStr(attr->attname));
762  rightop = quote_qualified_identifier("mv",
763  NameStr(attr->attname));
764 
765  generate_operator_clause(&querybuf,
766  leftop, attrtype,
767  op,
768  rightop, attrtype);
769 
770  foundUniqueIndex = true;
771  }
772  }
773 
774  /* Keep the locks, since we're about to run DML which needs them. */
775  index_close(indexRel, NoLock);
776  }
777 
778  list_free(indexoidlist);
779 
780  /*
781  * There must be at least one usable unique index on the matview.
782  *
783  * ExecRefreshMatView() checks that after taking the exclusive lock on the
784  * matview. So at least one unique index is guaranteed to exist here
785  * because the lock is still being held; so an Assert seems sufficient.
786  */
787  Assert(foundUniqueIndex);
788 
789  appendStringInfoString(&querybuf,
790  " AND newdata.* OPERATOR(pg_catalog.*=) mv.*) "
791  "WHERE newdata.* IS NULL OR mv.* IS NULL "
792  "ORDER BY tid");
793 
794  /* Create the temporary "diff" table. */
795  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
796  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
797 
798  SetUserIdAndSecContext(relowner,
799  save_sec_context | SECURITY_RESTRICTED_OPERATION);
800 
801  /*
802  * We have no further use for data from the "full-data" temp table, but we
803  * must keep it around because its type is referenced from the diff table.
804  */
805 
806  /* Analyze the diff table. */
807  resetStringInfo(&querybuf);
808  appendStringInfo(&querybuf, "ANALYZE %s", diffname);
809  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
810  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
811 
813 
814  /* Deletes must come before inserts; do them first. */
815  resetStringInfo(&querybuf);
816  appendStringInfo(&querybuf,
817  "DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY "
818  "(SELECT diff.tid FROM %s diff "
819  "WHERE diff.tid IS NOT NULL "
820  "AND diff.newdata IS NULL)",
821  matviewname, diffname);
822  if (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)
823  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
824 
825  /* Inserts go last. */
826  resetStringInfo(&querybuf);
827  appendStringInfo(&querybuf,
828  "INSERT INTO %s SELECT (diff.newdata).* "
829  "FROM %s diff WHERE tid IS NULL",
830  matviewname, diffname);
831  if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
832  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
833 
834  /* We're done maintaining the materialized view. */
836  table_close(tempRel, NoLock);
837  table_close(matviewRel, NoLock);
838 
839  /* Clean up temp tables. */
840  resetStringInfo(&querybuf);
841  appendStringInfo(&querybuf, "DROP TABLE %s, %s", diffname, tempname);
842  if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
843  elog(ERROR, "SPI_exec failed: %s", querybuf.data);
844 
845  /* Close SPI context. */
846  if (SPI_finish() != SPI_OK_FINISH)
847  elog(ERROR, "SPI_finish failed");
848 }
849 
850 /*
851  * Swap the physical files of the target and transient tables, then rebuild
852  * the target's indexes and throw away the transient table. Security context
853  * swapping is handled by the called function, so it is not needed here.
854  */
855 static void
856 refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
857 {
858  finish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,
859  RecentXmin, ReadNextMultiXactId(), relpersistence);
860 }
861 
862 /*
863  * Check whether specified index is usable for match merge.
864  */
865 static bool
867 {
868  Form_pg_index indexStruct = indexRel->rd_index;
869 
870  /*
871  * Must be unique, valid, immediate, non-partial, and be defined over
872  * plain user columns (not expressions). We also require it to be a
873  * btree. Even if we had any other unique index kinds, we'd not know how
874  * to identify the corresponding equality operator, nor could we be sure
875  * that the planner could implement the required FULL JOIN with non-btree
876  * operators.
877  */
878  if (indexStruct->indisunique &&
879  indexStruct->indimmediate &&
880  indexRel->rd_rel->relam == BTREE_AM_OID &&
881  indexStruct->indisvalid &&
882  RelationGetIndexPredicate(indexRel) == NIL &&
883  indexStruct->indnatts > 0)
884  {
885  /*
886  * The point of groveling through the index columns individually is to
887  * reject both index expressions and system columns. Currently,
888  * matviews couldn't have OID columns so there's no way to create an
889  * index on a system column; but maybe someday that wouldn't be true,
890  * so let's be safe.
891  */
892  int numatts = indexStruct->indnatts;
893  int i;
894 
895  for (i = 0; i < numatts; i++)
896  {
897  int attnum = indexStruct->indkey.values[i];
898 
899  if (attnum <= 0)
900  return false;
901  }
902  return true;
903  }
904  return false;
905 }
906 
907 
908 /*
909  * This should be used to test whether the backend is in a context where it is
910  * OK to allow DML statements to modify materialized views. We only want to
911  * allow that for internal code driven by the materialized view definition,
912  * not for arbitrary user-supplied code.
913  *
914  * While the function names reflect the fact that their main intended use is
915  * incremental maintenance of materialized views (in response to changes to
916  * the data in referenced relations), they are initially used to allow REFRESH
917  * without blocking concurrent reads.
918  */
919 bool
921 {
922  return matview_maintenance_depth > 0;
923 }
924 
925 static void
927 {
929 }
930 
931 static void
933 {
936 }
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1149
#define InvalidBlockNumber
Definition: block.h:33
#define NameStr(name)
Definition: c.h:682
signed short int16
Definition: c.h:429
uint32 CommandId
Definition: c.h:602
#define OidIsValid(objectId)
Definition: c.h:711
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:1423
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod, char relpersistence, LOCKMODE lockmode)
Definition: cluster.c:688
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
@ DestTransientRel
Definition: dest.h:99
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define PG_RE_THROW()
Definition: elog.h:350
#define PG_TRY(...)
Definition: elog.h:309
#define PG_END_TRY(...)
Definition: elog.h:334
#define ERROR
Definition: elog.h:35
#define PG_CATCH(...)
Definition: elog.h:319
#define ereport(elevel,...)
Definition: elog.h:145
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:131
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:300
int NewGUCNestLevel(void)
Definition: guc.c:2183
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2197
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1976
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1990
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_free(List *list)
Definition: list.c:1545
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
#define ExclusiveLock
Definition: lockdefs.h:42
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
static void transientrel_destroy(DestReceiver *self)
Definition: matview.c:524
static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: matview.c:453
static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, const char *queryString)
Definition: matview.c:376
static char * make_temptable_name_n(char *tempname, int n)
Definition: matview.c:541
static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context)
Definition: matview.c:584
DestReceiver * CreateTransientRelDestReceiver(Oid transientoid)
Definition: matview.c:435
static bool is_usable_unique_index(Relation indexRel)
Definition: matview.c:866
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:920
static void CloseMatViewIncrementalMaintenance(void)
Definition: matview.c:932
static void OpenMatViewIncrementalMaintenance(void)
Definition: matview.c:926
void SetMatViewPopulatedState(Relation relation, bool newstate)
Definition: matview.c:84
static int matview_maintenance_depth
Definition: matview.c:61
static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
Definition: matview.c:856
ObjectAddress ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString, ParamListInfo params, QueryCompletion *qc)
Definition: matview.c:138
static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: matview.c:479
static void transientrel_shutdown(DestReceiver *self)
Definition: matview.c:507
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc0(Size size)
Definition: mcxt.c:1230
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:304
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:618
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:625
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:722
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
#define copyObject(obj)
Definition: nodes.h:227
@ CMD_SELECT
Definition: nodes.h:259
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2908
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static int list_length(const List *l)
Definition: pg_list.h:150
#define linitial_node(type, l)
Definition: pg_list.h:179
#define NIL
Definition: pg_list.h:66
#define linitial(l)
Definition: pg_list.h:176
#define lfirst_oid(lc)
Definition: pg_list.h:172
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
void pgstat_count_truncate(Relation rel)
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:853
uintptr_t Datum
Definition: postgres.h:412
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
unsigned int Oid
Definition: postgres_ext.h:31
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
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 struct state * newstate(struct nfa *nfa)
Definition: regc_nfa.c:137
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:507
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RelationGetTargetBlock(relation)
Definition: rel.h:599
#define RelationIsPopulated(relation)
Definition: rel.h:675
#define RelationGetNamespace(relation)
Definition: rel.h:542
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4731
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5078
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
List * QueryRewrite(Query *parsetree)
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11613
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:11937
@ ForwardScanDirection
Definition: sdir.h:26
TransactionId RecentXmin
Definition: snapmgr.c:114
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:747
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:735
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:805
#define InvalidSnapshot
Definition: snapshot.h:123
uint64 SPI_processed
Definition: spi.c:45
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int SPI_connect(void)
Definition: spi.c:95
int SPI_finish(void)
Definition: spi.c:183
int SPI_exec(const char *src, long tcount)
Definition: spi.c:628
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1218
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:594
#define SPI_OK_UTILITY
Definition: spi.h:85
#define SPI_OK_INSERT
Definition: spi.h:88
#define SPI_OK_DELETE
Definition: spi.h:89
#define SPI_OK_CONNECT
Definition: spi.h:82
#define SPI_OK_FINISH
Definition: spi.h:83
#define SPI_OK_SELECT
Definition: spi.h:86
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
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
Relation transientrel
Definition: matview.c:55
BulkInsertState bistate
Definition: matview.c:58
DestReceiver pub
Definition: matview.c:52
CommandId output_cid
Definition: matview.c:56
Oid transientoid
Definition: matview.c:53
int ti_options
Definition: matview.c:57
uint64 es_processed
Definition: execnodes.h:654
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:52
EState * estate
Definition: execdesc.h:48
RangeVar * relation
Definition: parsenodes.h:3515
struct HeapTupleData * rd_indextuple
Definition: rel.h:190
TupleDesc rd_att
Definition: rel.h:111
Form_pg_index rd_index
Definition: rel.h:188
RuleLock * rd_rules
Definition: rel.h:114
Form_pg_class rd_rel
Definition: rel.h:110
RewriteRule ** rules
Definition: prs2lock.h:43
int numLocks
Definition: prs2lock.h:42
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
Definition: c.h:662
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:669
Definition: localtime.c:73
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ INDEXRELID
Definition: syscache.h:66
@ RELOID
Definition: syscache.h:89
@ CLAOID
Definition: syscache.h:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define TABLE_INSERT_FROZEN
Definition: tableam.h:237
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:236
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1566
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1373
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16938
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4004
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void CommandCounterIncrement(void)
Definition: xact.c:1077
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:817