LCOV - differential code coverage report
Current view: top level - src/backend/commands - matview.c (source / functions) Coverage Total Hit UBC CBC
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 91.2 % 274 250 24 250
Current Date: 2025-09-06 07:49:51 +0900 Functions: 93.8 % 16 15 1 15
Baseline: lcov-20250906-005545-baseline Branches: 51.7 % 180 93 87 93
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 83.3 % 6 5 1 5
(360..) days: 91.4 % 268 245 23 245
Function coverage date bins:
(360..) days: 93.8 % 16 15 1 15
Branch coverage date bins:
(30,360] days: 25.0 % 4 1 3 1
(360..) days: 52.3 % 176 92 84 92

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * matview.c
                                  4                 :                :  *    materialized view support
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2025, 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 "catalog/indexing.h"
                                 24                 :                : #include "catalog/namespace.h"
                                 25                 :                : #include "catalog/pg_am.h"
                                 26                 :                : #include "catalog/pg_opclass.h"
                                 27                 :                : #include "commands/cluster.h"
                                 28                 :                : #include "commands/matview.h"
                                 29                 :                : #include "commands/tablecmds.h"
                                 30                 :                : #include "commands/tablespace.h"
                                 31                 :                : #include "executor/executor.h"
                                 32                 :                : #include "executor/spi.h"
                                 33                 :                : #include "miscadmin.h"
                                 34                 :                : #include "pgstat.h"
                                 35                 :                : #include "rewrite/rewriteHandler.h"
                                 36                 :                : #include "storage/lmgr.h"
                                 37                 :                : #include "tcop/tcopprot.h"
                                 38                 :                : #include "utils/builtins.h"
                                 39                 :                : #include "utils/lsyscache.h"
                                 40                 :                : #include "utils/rel.h"
                                 41                 :                : #include "utils/snapmgr.h"
                                 42                 :                : #include "utils/syscache.h"
                                 43                 :                : 
                                 44                 :                : 
                                 45                 :                : typedef struct
                                 46                 :                : {
                                 47                 :                :     DestReceiver pub;           /* publicly-known function pointers */
                                 48                 :                :     Oid         transientoid;   /* OID of new heap into which to store */
                                 49                 :                :     /* These fields are filled by transientrel_startup: */
                                 50                 :                :     Relation    transientrel;   /* relation to write to */
                                 51                 :                :     CommandId   output_cid;     /* cmin to insert in output tuples */
                                 52                 :                :     int         ti_options;     /* table_tuple_insert performance options */
                                 53                 :                :     BulkInsertState bistate;    /* bulk insert state */
                                 54                 :                : } DR_transientrel;
                                 55                 :                : 
                                 56                 :                : static int  matview_maintenance_depth = 0;
                                 57                 :                : 
                                 58                 :                : static void transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
                                 59                 :                : static bool transientrel_receive(TupleTableSlot *slot, DestReceiver *self);
                                 60                 :                : static void transientrel_shutdown(DestReceiver *self);
                                 61                 :                : static void transientrel_destroy(DestReceiver *self);
                                 62                 :                : static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query,
                                 63                 :                :                                        const char *queryString, bool is_create);
                                 64                 :                : static char *make_temptable_name_n(char *tempname, int n);
                                 65                 :                : static void refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
                                 66                 :                :                                    int save_sec_context);
                                 67                 :                : static void refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence);
                                 68                 :                : static bool is_usable_unique_index(Relation indexRel);
                                 69                 :                : static void OpenMatViewIncrementalMaintenance(void);
                                 70                 :                : static void CloseMatViewIncrementalMaintenance(void);
                                 71                 :                : 
                                 72                 :                : /*
                                 73                 :                :  * SetMatViewPopulatedState
                                 74                 :                :  *      Mark a materialized view as populated, or not.
                                 75                 :                :  *
                                 76                 :                :  * NOTE: caller must be holding an appropriate lock on the relation.
                                 77                 :                :  */
                                 78                 :                : void
 4506 tgl@sss.pgh.pa.us          79                 :CBC         309 : SetMatViewPopulatedState(Relation relation, bool newstate)
                                 80                 :                : {
                                 81                 :                :     Relation    pgrel;
                                 82                 :                :     HeapTuple   tuple;
                                 83                 :                : 
 4570 kgrittn@postgresql.o       84         [ -  + ]:            309 :     Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
                                 85                 :                : 
                                 86                 :                :     /*
                                 87                 :                :      * Update relation's pg_class entry.  Crucial side-effect: other backends
                                 88                 :                :      * (and this one too!) are sent SI message to make them rebuild relcache
                                 89                 :                :      * entries.
                                 90                 :                :      */
 2420 andres@anarazel.de         91                 :            309 :     pgrel = table_open(RelationRelationId, RowExclusiveLock);
 4506 tgl@sss.pgh.pa.us          92                 :            309 :     tuple = SearchSysCacheCopy1(RELOID,
                                 93                 :                :                                 ObjectIdGetDatum(RelationGetRelid(relation)));
                                 94         [ -  + ]:            309 :     if (!HeapTupleIsValid(tuple))
 4506 tgl@sss.pgh.pa.us          95         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u",
                                 96                 :                :              RelationGetRelid(relation));
                                 97                 :                : 
 4506 tgl@sss.pgh.pa.us          98                 :CBC         309 :     ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
                                 99                 :                : 
 3140 alvherre@alvh.no-ip.      100                 :            309 :     CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
                                101                 :                : 
 4506 tgl@sss.pgh.pa.us         102                 :            309 :     heap_freetuple(tuple);
 2420 andres@anarazel.de        103                 :            309 :     table_close(pgrel, RowExclusiveLock);
                                104                 :                : 
                                105                 :                :     /*
                                106                 :                :      * Advance command counter to make the updated pg_class row locally
                                107                 :                :      * visible.
                                108                 :                :      */
 4506 tgl@sss.pgh.pa.us         109                 :            309 :     CommandCounterIncrement();
 4570 kgrittn@postgresql.o      110                 :            309 : }
                                111                 :                : 
                                112                 :                : /*
                                113                 :                :  * ExecRefreshMatView -- execute a REFRESH MATERIALIZED VIEW command
                                114                 :                :  *
                                115                 :                :  * If WITH NO DATA was specified, this is effectively like a TRUNCATE;
                                116                 :                :  * otherwise it is like a TRUNCATE followed by an INSERT using the SELECT
                                117                 :                :  * statement associated with the materialized view.  The statement node's
                                118                 :                :  * skipData field shows whether the clause was used.
                                119                 :                :  */
                                120                 :                : ObjectAddress
  417 jdavis@postgresql.or      121                 :            134 : ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
                                122                 :                :                    QueryCompletion *qc)
                                123                 :                : {
                                124                 :                :     Oid         matviewOid;
                                125                 :                :     LOCKMODE    lockmode;
                                126                 :                : 
                                127                 :                :     /* Determine strength of lock needed. */
                                128         [ +  + ]:            134 :     lockmode = stmt->concurrent ? ExclusiveLock : AccessExclusiveLock;
                                129                 :                : 
                                130                 :                :     /*
                                131                 :                :      * Get a lock until end of transaction.
                                132                 :                :      */
                                133                 :            134 :     matviewOid = RangeVarGetRelidExtended(stmt->relation,
                                134                 :                :                                           lockmode, 0,
                                135                 :                :                                           RangeVarCallbackMaintainsTable,
                                136                 :                :                                           NULL);
                                137                 :                : 
  402                           138                 :            229 :     return RefreshMatViewByOid(matviewOid, false, stmt->skipData,
                                139                 :            131 :                                stmt->concurrent, queryString, qc);
                                140                 :                : }
                                141                 :                : 
                                142                 :                : /*
                                143                 :                :  * RefreshMatViewByOid -- refresh materialized view by OID
                                144                 :                :  *
                                145                 :                :  * This refreshes the materialized view by creating a new table and swapping
                                146                 :                :  * the relfilenumbers of the new table and the old materialized view, so the OID
                                147                 :                :  * of the original materialized view is preserved. Thus we do not lose GRANT
                                148                 :                :  * nor references to this materialized view.
                                149                 :                :  *
                                150                 :                :  * If skipData is true, this is effectively like a TRUNCATE; otherwise it is
                                151                 :                :  * like a TRUNCATE followed by an INSERT using the SELECT statement associated
                                152                 :                :  * with the materialized view.
                                153                 :                :  *
                                154                 :                :  * Indexes are rebuilt too, via REINDEX. Since we are effectively bulk-loading
                                155                 :                :  * the new heap, it's better to create the indexes afterwards than to fill them
                                156                 :                :  * incrementally while we load.
                                157                 :                :  *
                                158                 :                :  * The matview's "populated" state is changed based on whether the contents
                                159                 :                :  * reflect the result set of the materialized view's query.
                                160                 :                :  *
                                161                 :                :  * This is also used to populate the materialized view created by CREATE
                                162                 :                :  * MATERIALIZED VIEW command.
                                163                 :                :  */
                                164                 :                : ObjectAddress
                                165                 :            312 : RefreshMatViewByOid(Oid matviewOid, bool is_create, bool skipData,
                                166                 :                :                     bool concurrent, const char *queryString,
                                167                 :                :                     QueryCompletion *qc)
                                168                 :                : {
                                169                 :                :     Relation    matviewRel;
                                170                 :                :     RewriteRule *rule;
                                171                 :                :     List       *actions;
                                172                 :                :     Query      *dataQuery;
                                173                 :                :     Oid         tableSpace;
                                174                 :                :     Oid         relowner;
                                175                 :                :     Oid         OIDNewHeap;
 3094 tgl@sss.pgh.pa.us         176                 :            312 :     uint64      processed = 0;
                                177                 :                :     char        relpersistence;
                                178                 :                :     Oid         save_userid;
                                179                 :                :     int         save_sec_context;
                                180                 :                :     int         save_nestlevel;
                                181                 :                :     ObjectAddress address;
                                182                 :                : 
 2420 andres@anarazel.de        183                 :            312 :     matviewRel = table_open(matviewOid, NoLock);
 1216 noah@leadboat.com         184                 :            312 :     relowner = matviewRel->rd_rel->relowner;
                                185                 :                : 
                                186                 :                :     /*
                                187                 :                :      * Switch to the owner's userid, so that any functions are run as that
                                188                 :                :      * user.  Also lock down security-restricted operations and arrange to
                                189                 :                :      * make GUC variable changes local to this command.
                                190                 :                :      */
                                191                 :            312 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
                                192                 :            312 :     SetUserIdAndSecContext(relowner,
                                193                 :                :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
                                194                 :            312 :     save_nestlevel = NewGUCNestLevel();
  551 jdavis@postgresql.or      195                 :            312 :     RestrictSearchPath();
                                196                 :                : 
                                197                 :                :     /* Make sure it is a materialized view. */
 4570 kgrittn@postgresql.o      198         [ -  + ]:            312 :     if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
 4570 kgrittn@postgresql.o      199         [ #  # ]:UBC           0 :         ereport(ERROR,
                                200                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                201                 :                :                  errmsg("\"%s\" is not a materialized view",
                                202                 :                :                         RelationGetRelationName(matviewRel))));
                                203                 :                : 
                                204                 :                :     /* Check that CONCURRENTLY is not specified if not populated. */
 4435 kgrittn@postgresql.o      205   [ +  +  -  + ]:CBC         312 :     if (concurrent && !RelationIsPopulated(matviewRel))
 4435 kgrittn@postgresql.o      206         [ #  # ]:UBC           0 :         ereport(ERROR,
                                207                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                208                 :                :                  errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
                                209                 :                : 
                                210                 :                :     /* Check that conflicting options have not been specified. */
  417 jdavis@postgresql.or      211   [ +  +  +  + ]:CBC         312 :     if (concurrent && skipData)
 4435 kgrittn@postgresql.o      212         [ +  - ]:              3 :         ereport(ERROR,
                                213                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                                214                 :                :                  errmsg("%s and %s options cannot be used together",
                                215                 :                :                         "CONCURRENTLY", "WITH NO DATA")));
                                216                 :                : 
                                217                 :                :     /*
                                218                 :                :      * Check that everything is correct for a refresh. Problems at this point
                                219                 :                :      * are internal errors, so elog is sufficient.
                                220                 :                :      */
 4570                           221         [ +  - ]:            309 :     if (matviewRel->rd_rel->relhasrules == false ||
                                222         [ -  + ]:            309 :         matviewRel->rd_rules->numLocks < 1)
 4570 kgrittn@postgresql.o      223         [ #  # ]:UBC           0 :         elog(ERROR,
                                224                 :                :              "materialized view \"%s\" is missing rewrite information",
                                225                 :                :              RelationGetRelationName(matviewRel));
                                226                 :                : 
 4570 kgrittn@postgresql.o      227         [ -  + ]:CBC         309 :     if (matviewRel->rd_rules->numLocks > 1)
 4570 kgrittn@postgresql.o      228         [ #  # ]:UBC           0 :         elog(ERROR,
                                229                 :                :              "materialized view \"%s\" has too many rules",
                                230                 :                :              RelationGetRelationName(matviewRel));
                                231                 :                : 
 4570 kgrittn@postgresql.o      232                 :CBC         309 :     rule = matviewRel->rd_rules->rules[0];
                                233   [ +  -  -  + ]:            309 :     if (rule->event != CMD_SELECT || !(rule->isInstead))
 4570 kgrittn@postgresql.o      234         [ #  # ]:UBC           0 :         elog(ERROR,
                                235                 :                :              "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
                                236                 :                :              RelationGetRelationName(matviewRel));
                                237                 :                : 
 4570 kgrittn@postgresql.o      238                 :CBC         309 :     actions = rule->actions;
                                239         [ -  + ]:            309 :     if (list_length(actions) != 1)
 4570 kgrittn@postgresql.o      240         [ #  # ]:UBC           0 :         elog(ERROR,
                                241                 :                :              "the rule for materialized view \"%s\" is not a single action",
                                242                 :                :              RelationGetRelationName(matviewRel));
                                243                 :                : 
                                244                 :                :     /*
                                245                 :                :      * Check that there is a unique index with no WHERE clause on one or more
                                246                 :                :      * columns of the materialized view if CONCURRENTLY is specified.
                                247                 :                :      */
 3490 fujii@postgresql.org      248         [ +  + ]:CBC         309 :     if (concurrent)
                                249                 :                :     {
 3376 rhaas@postgresql.org      250                 :             39 :         List       *indexoidlist = RelationGetIndexList(matviewRel);
                                251                 :                :         ListCell   *indexoidscan;
 3490 fujii@postgresql.org      252                 :             39 :         bool        hasUniqueIndex = false;
                                253                 :                : 
  402 jdavis@postgresql.or      254         [ -  + ]:             39 :         Assert(!is_create);
                                255                 :                : 
 3490 fujii@postgresql.org      256   [ +  -  +  +  :             45 :         foreach(indexoidscan, indexoidlist)
                                              +  + ]
                                257                 :                :         {
                                258                 :             42 :             Oid         indexoid = lfirst_oid(indexoidscan);
                                259                 :                :             Relation    indexRel;
                                260                 :                : 
                                261                 :             42 :             indexRel = index_open(indexoid, AccessShareLock);
 2728 tgl@sss.pgh.pa.us         262                 :             42 :             hasUniqueIndex = is_usable_unique_index(indexRel);
 3490 fujii@postgresql.org      263                 :             42 :             index_close(indexRel, AccessShareLock);
 2728 tgl@sss.pgh.pa.us         264         [ +  + ]:             42 :             if (hasUniqueIndex)
                                265                 :             36 :                 break;
                                266                 :                :         }
                                267                 :                : 
 3490 fujii@postgresql.org      268                 :             39 :         list_free(indexoidlist);
                                269                 :                : 
                                270         [ +  + ]:             39 :         if (!hasUniqueIndex)
                                271         [ +  - ]:              3 :             ereport(ERROR,
                                272                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                273                 :                :                      errmsg("cannot refresh materialized view \"%s\" concurrently",
                                274                 :                :                             quote_qualified_identifier(get_namespace_name(RelationGetNamespace(matviewRel)),
                                275                 :                :                                                        RelationGetRelationName(matviewRel))),
                                276                 :                :                      errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
                                277                 :                :     }
                                278                 :                : 
                                279                 :                :     /*
                                280                 :                :      * The stored query was rewritten at the time of the MV definition, but
                                281                 :                :      * has not been scribbled on by the planner.
                                282                 :                :      */
 3071 tgl@sss.pgh.pa.us         283                 :            306 :     dataQuery = linitial_node(Query, actions);
                                284                 :                : 
                                285                 :                :     /*
                                286                 :                :      * Check for active uses of the relation in the current transaction, such
                                287                 :                :      * as open scans.
                                288                 :                :      *
                                289                 :                :      * NB: We count on this to protect us against problems with refreshing the
                                290                 :                :      * data using TABLE_INSERT_FROZEN.
                                291                 :                :      */
  402 jdavis@postgresql.or      292         [ +  + ]:            306 :     CheckTableNotInUse(matviewRel,
                                293                 :                :                        is_create ? "CREATE MATERIALIZED VIEW" :
                                294                 :                :                        "REFRESH MATERIALIZED VIEW");
                                295                 :                : 
                                296                 :                :     /*
                                297                 :                :      * Tentatively mark the matview as populated or not (this will roll back
                                298                 :                :      * if we fail later).
                                299                 :                :      */
  417                           300                 :            306 :     SetMatViewPopulatedState(matviewRel, !skipData);
                                301                 :                : 
                                302                 :                :     /* Concurrent refresh builds new data in temp tablespace, and does diff. */
 4435 kgrittn@postgresql.o      303         [ +  + ]:            306 :     if (concurrent)
                                304                 :                :     {
 2326 alvherre@alvh.no-ip.      305                 :             36 :         tableSpace = GetDefaultTablespace(RELPERSISTENCE_TEMP, false);
 4033                           306                 :             36 :         relpersistence = RELPERSISTENCE_TEMP;
                                307                 :                :     }
                                308                 :                :     else
                                309                 :                :     {
 4435 kgrittn@postgresql.o      310                 :            270 :         tableSpace = matviewRel->rd_rel->reltablespace;
 4033 alvherre@alvh.no-ip.      311                 :            270 :         relpersistence = matviewRel->rd_rel->relpersistence;
                                312                 :                :     }
                                313                 :                : 
                                314                 :                :     /*
                                315                 :                :      * Create the transient table that will receive the regenerated data. Lock
                                316                 :                :      * it against access by any other process until commit (by which time it
                                317                 :                :      * will be gone).
                                318                 :                :      */
 1501 michael@paquier.xyz       319                 :            612 :     OIDNewHeap = make_new_heap(matviewOid, tableSpace,
                                320                 :            306 :                                matviewRel->rd_rel->relam,
                                321                 :                :                                relpersistence, ExclusiveLock);
  239 alvherre@alvh.no-ip.      322         [ -  + ]:            306 :     Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock, false));
                                323                 :                : 
                                324                 :                :     /* Generate the data, if wanted. */
  417 jdavis@postgresql.or      325         [ +  - ]:            306 :     if (!skipData)
                                326                 :                :     {
                                327                 :                :         DestReceiver *dest;
                                328                 :                : 
  402                           329                 :            306 :         dest = CreateTransientRelDestReceiver(OIDNewHeap);
                                330                 :            306 :         processed = refresh_matview_datafill(dest, dataQuery, queryString,
                                331                 :                :                                              is_create);
                                332                 :                :     }
                                333                 :                : 
                                334                 :                :     /* Make the matview match the newly generated data. */
 4435 kgrittn@postgresql.o      335         [ +  + ]:            285 :     if (concurrent)
                                336                 :                :     {
                                337                 :             36 :         int         old_depth = matview_maintenance_depth;
                                338                 :                : 
                                339         [ +  + ]:             36 :         PG_TRY();
                                340                 :                :         {
 4029                           341                 :             36 :             refresh_by_match_merge(matviewOid, OIDNewHeap, relowner,
                                342                 :                :                                    save_sec_context);
                                343                 :                :         }
 4435                           344                 :              6 :         PG_CATCH();
                                345                 :                :         {
                                346                 :              6 :             matview_maintenance_depth = old_depth;
                                347                 :              6 :             PG_RE_THROW();
                                348                 :                :         }
                                349         [ -  + ]:             30 :         PG_END_TRY();
                                350         [ -  + ]:             30 :         Assert(matview_maintenance_depth == old_depth);
                                351                 :                :     }
                                352                 :                :     else
                                353                 :                :     {
 3948 alvherre@alvh.no-ip.      354                 :            249 :         refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
                                355                 :                : 
                                356                 :                :         /*
                                357                 :                :          * Inform cumulative stats system about our activity: basically, we
                                358                 :                :          * truncated the matview and inserted some new data.  (The concurrent
                                359                 :                :          * code path above doesn't need to worry about this because the
                                360                 :                :          * inserts and deletes it issues get counted by lower-level code.)
                                361                 :                :          */
 3094 tgl@sss.pgh.pa.us         362                 :            246 :         pgstat_count_truncate(matviewRel);
  417 jdavis@postgresql.or      363         [ +  - ]:            246 :         if (!skipData)
 3094 tgl@sss.pgh.pa.us         364                 :            246 :             pgstat_count_heap_insert(matviewRel, processed);
                                365                 :                :     }
                                366                 :                : 
 2420 andres@anarazel.de        367                 :            276 :     table_close(matviewRel, NoLock);
                                368                 :                : 
                                369                 :                :     /* Roll back any GUC changes */
 4029 kgrittn@postgresql.o      370                 :            276 :     AtEOXact_GUC(false, save_nestlevel);
                                371                 :                : 
                                372                 :                :     /* Restore userid and security context */
                                373                 :            276 :     SetUserIdAndSecContext(save_userid, save_sec_context);
                                374                 :                : 
 3840 alvherre@alvh.no-ip.      375                 :            276 :     ObjectAddressSet(address, RelationRelationId, matviewOid);
                                376                 :                : 
                                377                 :                :     /*
                                378                 :                :      * Save the rowcount so that pg_stat_statements can track the total number
                                379                 :                :      * of rows processed by REFRESH MATERIALIZED VIEW command. Note that we
                                380                 :                :      * still don't display the rowcount in the command completion tag output,
                                381                 :                :      * i.e., the display_rowcount flag of CMDTAG_REFRESH_MATERIALIZED_VIEW
                                382                 :                :      * command tag is left false in cmdtaglist.h. Otherwise, the change of
                                383                 :                :      * completion tag output might break applications using it.
                                384                 :                :      *
                                385                 :                :      * When called from CREATE MATERIALIZED VIEW command, the rowcount is
                                386                 :                :      * displayed with the command tag CMDTAG_SELECT.
                                387                 :                :      */
 1759 fujii@postgresql.org      388         [ +  + ]:            276 :     if (qc)
  402 jdavis@postgresql.or      389         [ +  + ]:            270 :         SetQueryCompletion(qc,
                                390                 :                :                            is_create ? CMDTAG_SELECT : CMDTAG_REFRESH_MATERIALIZED_VIEW,
                                391                 :                :                            processed);
                                392                 :                : 
 3840 alvherre@alvh.no-ip.      393                 :            276 :     return address;
                                394                 :                : }
                                395                 :                : 
                                396                 :                : /*
                                397                 :                :  * refresh_matview_datafill
                                398                 :                :  *
                                399                 :                :  * Execute the given query, sending result rows to "dest" (which will
                                400                 :                :  * insert them into the target matview).
                                401                 :                :  *
                                402                 :                :  * Returns number of rows inserted.
                                403                 :                :  */
                                404                 :                : static uint64
 4570 kgrittn@postgresql.o      405                 :            306 : refresh_matview_datafill(DestReceiver *dest, Query *query,
                                406                 :                :                          const char *queryString, bool is_create)
                                407                 :                : {
                                408                 :                :     List       *rewritten;
                                409                 :                :     PlannedStmt *plan;
                                410                 :                :     QueryDesc  *queryDesc;
                                411                 :                :     Query      *copied_query;
                                412                 :                :     uint64      processed;
                                413                 :                : 
                                414                 :                :     /* Lock and rewrite, using a copy to preserve the original query. */
 4326                           415                 :            306 :     copied_query = copyObject(query);
 4202 tgl@sss.pgh.pa.us         416                 :            306 :     AcquireRewriteLocks(copied_query, true, false);
 4326 kgrittn@postgresql.o      417                 :            306 :     rewritten = QueryRewrite(copied_query);
                                418                 :                : 
                                419                 :                :     /* SELECT should never rewrite to more or less than one SELECT query */
 4570                           420         [ -  + ]:            306 :     if (list_length(rewritten) != 1)
  402 jdavis@postgresql.or      421   [ #  #  #  # ]:UBC           0 :         elog(ERROR, "unexpected rewrite result for %s",
                                422                 :                :              is_create ? "CREATE MATERIALIZED VIEW " : "REFRESH MATERIALIZED VIEW");
 4570 kgrittn@postgresql.o      423                 :CBC         306 :     query = (Query *) linitial(rewritten);
                                424                 :                : 
                                425                 :                :     /* Check for user-requested abort. */
                                426         [ -  + ]:            306 :     CHECK_FOR_INTERRUPTS();
                                427                 :                : 
                                428                 :                :     /* Plan the query which will generate data for the refresh. */
 1634 tmunro@postgresql.or      429                 :            306 :     plan = pg_plan_query(query, queryString, CURSOR_OPT_PARALLEL_OK, NULL);
                                430                 :                : 
                                431                 :                :     /*
                                432                 :                :      * Use a snapshot with an updated command ID to ensure this query sees
                                433                 :                :      * results of any previously executed queries.  (This could only matter if
                                434                 :                :      * the planner executed an allegedly-stable function that changed the
                                435                 :                :      * database contents, but let's do it anyway to be safe.)
                                436                 :                :      */
 4570 kgrittn@postgresql.o      437                 :            300 :     PushCopiedSnapshot(GetActiveSnapshot());
                                438                 :            300 :     UpdateActiveSnapshotCommandId();
                                439                 :                : 
                                440                 :                :     /* Create a QueryDesc, redirecting output to our tuple receiver */
  107 amitlan@postgresql.o      441                 :            300 :     queryDesc = CreateQueryDesc(plan, queryString,
                                442                 :                :                                 GetActiveSnapshot(), InvalidSnapshot,
                                443                 :                :                                 dest, NULL, NULL, 0);
                                444                 :                : 
                                445                 :                :     /* call ExecutorStart to prepare the plan for execution */
                                446                 :            300 :     ExecutorStart(queryDesc, 0);
                                447                 :                : 
                                448                 :                :     /* run the plan */
  271 tgl@sss.pgh.pa.us         449                 :            300 :     ExecutorRun(queryDesc, ForwardScanDirection, 0);
                                450                 :                : 
 3094                           451                 :            285 :     processed = queryDesc->estate->es_processed;
                                452                 :                : 
                                453                 :                :     /* and clean up */
 4570 kgrittn@postgresql.o      454                 :            285 :     ExecutorFinish(queryDesc);
                                455                 :            285 :     ExecutorEnd(queryDesc);
                                456                 :                : 
                                457                 :            285 :     FreeQueryDesc(queryDesc);
                                458                 :                : 
                                459                 :            285 :     PopActiveSnapshot();
                                460                 :                : 
 3094 tgl@sss.pgh.pa.us         461                 :            285 :     return processed;
                                462                 :                : }
                                463                 :                : 
                                464                 :                : DestReceiver *
 4570 kgrittn@postgresql.o      465                 :            306 : CreateTransientRelDestReceiver(Oid transientoid)
                                466                 :                : {
                                467                 :            306 :     DR_transientrel *self = (DR_transientrel *) palloc0(sizeof(DR_transientrel));
                                468                 :                : 
                                469                 :            306 :     self->pub.receiveSlot = transientrel_receive;
                                470                 :            306 :     self->pub.rStartup = transientrel_startup;
                                471                 :            306 :     self->pub.rShutdown = transientrel_shutdown;
                                472                 :            306 :     self->pub.rDestroy = transientrel_destroy;
                                473                 :            306 :     self->pub.mydest = DestTransientRel;
                                474                 :            306 :     self->transientoid = transientoid;
                                475                 :                : 
                                476                 :            306 :     return (DestReceiver *) self;
                                477                 :                : }
                                478                 :                : 
                                479                 :                : /*
                                480                 :                :  * transientrel_startup --- executor startup
                                481                 :                :  */
                                482                 :                : static void
                                483                 :            300 : transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
                                484                 :                : {
                                485                 :            300 :     DR_transientrel *myState = (DR_transientrel *) self;
                                486                 :                :     Relation    transientrel;
                                487                 :                : 
 2420 andres@anarazel.de        488                 :            300 :     transientrel = table_open(myState->transientoid, NoLock);
                                489                 :                : 
                                490                 :                :     /*
                                491                 :                :      * Fill private fields of myState for use by later routines
                                492                 :                :      */
 4570 kgrittn@postgresql.o      493                 :            300 :     myState->transientrel = transientrel;
                                494                 :            300 :     myState->output_cid = GetCurrentCommandId(true);
 1994 noah@leadboat.com         495                 :            300 :     myState->ti_options = TABLE_INSERT_SKIP_FSM | TABLE_INSERT_FROZEN;
                                496                 :            300 :     myState->bistate = GetBulkInsertState();
                                497                 :                : 
                                498                 :                :     /*
                                499                 :                :      * Valid smgr_targblock implies something already wrote to the relation.
                                500                 :                :      * This may be harmless, but this function hasn't planned for it.
                                501                 :                :      */
 4570 kgrittn@postgresql.o      502   [ -  +  -  - ]:            300 :     Assert(RelationGetTargetBlock(transientrel) == InvalidBlockNumber);
                                503                 :            300 : }
                                504                 :                : 
                                505                 :                : /*
                                506                 :                :  * transientrel_receive --- receive one tuple
                                507                 :                :  */
                                508                 :                : static bool
                                509                 :           2027 : transientrel_receive(TupleTableSlot *slot, DestReceiver *self)
                                510                 :                : {
                                511                 :           2027 :     DR_transientrel *myState = (DR_transientrel *) self;
                                512                 :                : 
                                513                 :                :     /*
                                514                 :                :      * Note that the input slot might not be of the type of the target
                                515                 :                :      * relation. That's supported by table_tuple_insert(), but slightly less
                                516                 :                :      * efficient than inserting with the right slot - but the alternative
                                517                 :                :      * would be to copy into a slot of the right type, which would not be
                                518                 :                :      * cheap either. This also doesn't allow accessing per-AM data (say a
                                519                 :                :      * tuple's xmin), but since we don't do that here...
                                520                 :                :      */
                                521                 :                : 
 2298 andres@anarazel.de        522                 :           2027 :     table_tuple_insert(myState->transientrel,
                                523                 :                :                        slot,
                                524                 :                :                        myState->output_cid,
                                525                 :                :                        myState->ti_options,
                                526                 :                :                        myState->bistate);
                                527                 :                : 
                                528                 :                :     /* We know this is a newly created relation, so there are no indexes */
                                529                 :                : 
 3379 rhaas@postgresql.org      530                 :           2027 :     return true;
                                531                 :                : }
                                532                 :                : 
                                533                 :                : /*
                                534                 :                :  * transientrel_shutdown --- executor end
                                535                 :                :  */
                                536                 :                : static void
 4570 kgrittn@postgresql.o      537                 :            285 : transientrel_shutdown(DestReceiver *self)
                                538                 :                : {
                                539                 :            285 :     DR_transientrel *myState = (DR_transientrel *) self;
                                540                 :                : 
                                541                 :            285 :     FreeBulkInsertState(myState->bistate);
                                542                 :                : 
 2350 andres@anarazel.de        543                 :            285 :     table_finish_bulk_insert(myState->transientrel, myState->ti_options);
                                544                 :                : 
                                545                 :                :     /* close transientrel, but keep lock until commit */
 2420                           546                 :            285 :     table_close(myState->transientrel, NoLock);
 4570 kgrittn@postgresql.o      547                 :            285 :     myState->transientrel = NULL;
                                548                 :            285 : }
                                549                 :                : 
                                550                 :                : /*
                                551                 :                :  * transientrel_destroy --- release DestReceiver object
                                552                 :                :  */
                                553                 :                : static void
 4570 kgrittn@postgresql.o      554                 :UBC           0 : transientrel_destroy(DestReceiver *self)
                                555                 :                : {
                                556                 :              0 :     pfree(self);
                                557                 :              0 : }
                                558                 :                : 
                                559                 :                : 
                                560                 :                : /*
                                561                 :                :  * Given a qualified temporary table name, append an underscore followed by
                                562                 :                :  * the given integer, to make a new table name based on the old one.
                                563                 :                :  * The result is a palloc'd string.
                                564                 :                :  *
                                565                 :                :  * As coded, this would fail to make a valid SQL name if the given name were,
                                566                 :                :  * say, "FOO"."BAR".  Currently, the table name portion of the input will
                                567                 :                :  * never be double-quoted because it's of the form "pg_temp_NNN", cf
                                568                 :                :  * make_new_heap().  But we might have to work harder someday.
                                569                 :                :  */
                                570                 :                : static char *
 4435 kgrittn@postgresql.o      571                 :CBC          36 : make_temptable_name_n(char *tempname, int n)
                                572                 :                : {
                                573                 :                :     StringInfoData namebuf;
                                574                 :                : 
                                575                 :             36 :     initStringInfo(&namebuf);
                                576                 :             36 :     appendStringInfoString(&namebuf, tempname);
 3438 peter_e@gmx.net           577                 :             36 :     appendStringInfo(&namebuf, "_%d", n);
 4435 kgrittn@postgresql.o      578                 :             36 :     return namebuf.data;
                                579                 :                : }
                                580                 :                : 
                                581                 :                : /*
                                582                 :                :  * refresh_by_match_merge
                                583                 :                :  *
                                584                 :                :  * Refresh a materialized view with transactional semantics, while allowing
                                585                 :                :  * concurrent reads.
                                586                 :                :  *
                                587                 :                :  * This is called after a new version of the data has been created in a
                                588                 :                :  * temporary table.  It performs a full outer join against the old version of
                                589                 :                :  * the data, producing "diff" results.  This join cannot work if there are any
                                590                 :                :  * duplicated rows in either the old or new versions, in the sense that every
                                591                 :                :  * column would compare as equal between the two rows.  It does work correctly
                                592                 :                :  * in the face of rows which have at least one NULL value, with all non-NULL
                                593                 :                :  * columns equal.  The behavior of NULLs on equality tests and on UNIQUE
                                594                 :                :  * indexes turns out to be quite convenient here; the tests we need to make
                                595                 :                :  * are consistent with default behavior.  If there is at least one UNIQUE
                                596                 :                :  * index on the materialized view, we have exactly the guarantee we need.
                                597                 :                :  *
                                598                 :                :  * The temporary table used to hold the diff results contains just the TID of
                                599                 :                :  * the old record (if matched) and the ROW from the new table as a single
                                600                 :                :  * column of complex record type (if matched).
                                601                 :                :  *
                                602                 :                :  * Once we have the diff table, we perform set-based DELETE and INSERT
                                603                 :                :  * operations against the materialized view, and discard both temporary
                                604                 :                :  * tables.
                                605                 :                :  *
                                606                 :                :  * Everything from the generation of the new data to applying the differences
                                607                 :                :  * takes place under cover of an ExclusiveLock, since it seems as though we
                                608                 :                :  * would want to prohibit not only concurrent REFRESH operations, but also
                                609                 :                :  * incremental maintenance.  It also doesn't seem reasonable or safe to allow
                                610                 :                :  * SELECT FOR UPDATE or SELECT FOR SHARE on rows being updated or deleted by
                                611                 :                :  * this command.
                                612                 :                :  */
                                613                 :                : static void
 4029                           614                 :             36 : refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
                                615                 :                :                        int save_sec_context)
                                616                 :                : {
                                617                 :                :     StringInfoData querybuf;
                                618                 :                :     Relation    matviewRel;
                                619                 :                :     Relation    tempRel;
                                620                 :                :     char       *matviewname;
                                621                 :                :     char       *tempname;
                                622                 :                :     char       *diffname;
                                623                 :                :     TupleDesc   tupdesc;
                                624                 :                :     bool        foundUniqueIndex;
                                625                 :                :     List       *indexoidlist;
                                626                 :                :     ListCell   *indexoidscan;
                                627                 :                :     int16       relnatts;
                                628                 :                :     Oid        *opUsedForQual;
                                629                 :                : 
 4435                           630                 :             36 :     initStringInfo(&querybuf);
 2420 andres@anarazel.de        631                 :             36 :     matviewRel = table_open(matviewOid, NoLock);
 4435 kgrittn@postgresql.o      632                 :             36 :     matviewname = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(matviewRel)),
 2999 tgl@sss.pgh.pa.us         633                 :             36 :                                              RelationGetRelationName(matviewRel));
 2420 andres@anarazel.de        634                 :             36 :     tempRel = table_open(tempOid, NoLock);
 4435 kgrittn@postgresql.o      635                 :             36 :     tempname = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(tempRel)),
                                636                 :             36 :                                           RelationGetRelationName(tempRel));
                                637                 :             36 :     diffname = make_temptable_name_n(tempname, 2);
                                638                 :                : 
 2709 teodor@sigaev.ru          639                 :             36 :     relnatts = RelationGetNumberOfAttributes(matviewRel);
                                640                 :                : 
                                641                 :                :     /* Open SPI context. */
  362 tgl@sss.pgh.pa.us         642                 :             36 :     SPI_connect();
                                643                 :                : 
                                644                 :                :     /* Analyze the temp table with the new contents. */
 4435 kgrittn@postgresql.o      645                 :             36 :     appendStringInfo(&querybuf, "ANALYZE %s", tempname);
                                646         [ -  + ]:             36 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
 4435 kgrittn@postgresql.o      647         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                648                 :                : 
                                649                 :                :     /*
                                650                 :                :      * We need to ensure that there are not duplicate rows without NULLs in
                                651                 :                :      * the new data set before we can count on the "diff" results.  Check for
                                652                 :                :      * that in a way that allows showing the first duplicated row found.  Even
                                653                 :                :      * after we pass this test, a unique index on the materialized view may
                                654                 :                :      * find a duplicate key problem.
                                655                 :                :      *
                                656                 :                :      * Note: here and below, we use "tablename.*::tablerowtype" as a hack to
                                657                 :                :      * keep ".*" from being expanded into multiple columns in a SELECT list.
                                658                 :                :      * Compare ruleutils.c's get_variable().
                                659                 :                :      */
 4435 kgrittn@postgresql.o      660                 :CBC          36 :     resetStringInfo(&querybuf);
                                661                 :             36 :     appendStringInfo(&querybuf,
                                662                 :                :                      "SELECT newdata.*::%s FROM %s newdata "
                                663                 :                :                      "WHERE newdata.* IS NOT NULL AND EXISTS "
                                664                 :                :                      "(SELECT 1 FROM %s newdata2 WHERE newdata2.* IS NOT NULL "
                                665                 :                :                      "AND newdata2.* OPERATOR(pg_catalog.*=) newdata.* "
                                666                 :                :                      "AND newdata2.ctid OPERATOR(pg_catalog.<>) "
                                667                 :                :                      "newdata.ctid)",
                                668                 :                :                      tempname, tempname, tempname);
                                669         [ -  + ]:             36 :     if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
 4435 kgrittn@postgresql.o      670         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
 4435 kgrittn@postgresql.o      671         [ +  + ]:CBC          36 :     if (SPI_processed > 0)
                                672                 :                :     {
                                673                 :                :         /*
                                674                 :                :          * Note that this ereport() is returning data to the user.  Generally,
                                675                 :                :          * we would want to make sure that the user has been granted access to
                                676                 :                :          * this data.  However, REFRESH MAT VIEW is only able to be run by the
                                677                 :                :          * owner of the mat view (or a superuser) and therefore there is no
                                678                 :                :          * need to check for access to data in the mat view.
                                679                 :                :          */
                                680         [ +  - ]:              3 :         ereport(ERROR,
                                681                 :                :                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
                                682                 :                :                  errmsg("new data for materialized view \"%s\" contains duplicate rows without any null columns",
                                683                 :                :                         RelationGetRelationName(matviewRel)),
                                684                 :                :                  errdetail("Row: %s",
                                685                 :                :                            SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1))));
                                686                 :                :     }
                                687                 :                : 
                                688                 :                :     /*
                                689                 :                :      * Create the temporary "diff" table.
                                690                 :                :      *
                                691                 :                :      * Temporarily switch out of the SECURITY_RESTRICTED_OPERATION context,
                                692                 :                :      * because you cannot create temp tables in SRO context.  For extra
                                693                 :                :      * paranoia, add the composite type column only after switching back to
                                694                 :                :      * SRO context.
                                695                 :                :      */
 4029                           696                 :             33 :     SetUserIdAndSecContext(relowner,
                                697                 :                :                            save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
  579 heikki.linnakangas@i      698                 :             33 :     resetStringInfo(&querybuf);
                                699                 :             33 :     appendStringInfo(&querybuf,
                                700                 :                :                      "CREATE TEMP TABLE %s (tid pg_catalog.tid)",
                                701                 :                :                      diffname);
                                702         [ -  + ]:             33 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
  579 heikki.linnakangas@i      703         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
  579 heikki.linnakangas@i      704                 :CBC          33 :     SetUserIdAndSecContext(relowner,
                                705                 :                :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
                                706                 :             33 :     resetStringInfo(&querybuf);
                                707                 :             33 :     appendStringInfo(&querybuf,
                                708                 :                :                      "ALTER TABLE %s ADD COLUMN newdata %s",
                                709                 :                :                      diffname, tempname);
                                710         [ -  + ]:             33 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
  579 heikki.linnakangas@i      711         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                712                 :                : 
                                713                 :                :     /* Start building the query for populating the diff table. */
 4435 kgrittn@postgresql.o      714                 :CBC          33 :     resetStringInfo(&querybuf);
                                715                 :             33 :     appendStringInfo(&querybuf,
                                716                 :                :                      "INSERT INTO %s "
                                717                 :                :                      "SELECT mv.ctid AS tid, newdata.*::%s AS newdata "
                                718                 :                :                      "FROM %s mv FULL JOIN %s newdata ON (",
                                719                 :                :                      diffname, tempname, matviewname, tempname);
                                720                 :                : 
                                721                 :                :     /*
                                722                 :                :      * Get the list of index OIDs for the table from the relcache, and look up
                                723                 :                :      * each one in the pg_index syscache.  We will test for equality on all
                                724                 :                :      * columns present in all unique indexes which only reference columns and
                                725                 :                :      * include all rows.
                                726                 :                :      */
                                727                 :             33 :     tupdesc = matviewRel->rd_att;
 2728 tgl@sss.pgh.pa.us         728                 :             33 :     opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
 4435 kgrittn@postgresql.o      729                 :             33 :     foundUniqueIndex = false;
                                730                 :                : 
                                731                 :             33 :     indexoidlist = RelationGetIndexList(matviewRel);
                                732                 :                : 
                                733   [ +  +  +  +  :             69 :     foreach(indexoidscan, indexoidlist)
                                              +  + ]
                                734                 :                :     {
                                735                 :             36 :         Oid         indexoid = lfirst_oid(indexoidscan);
                                736                 :                :         Relation    indexRel;
                                737                 :                : 
 4415                           738                 :             36 :         indexRel = index_open(indexoid, RowExclusiveLock);
 2728 tgl@sss.pgh.pa.us         739         [ +  - ]:             36 :         if (is_usable_unique_index(indexRel))
                                740                 :                :         {
                                741                 :             36 :             Form_pg_index indexStruct = indexRel->rd_index;
 2709 teodor@sigaev.ru          742                 :             36 :             int         indnkeyatts = indexStruct->indnkeyatts;
                                743                 :                :             oidvector  *indclass;
                                744                 :                :             Datum       indclassDatum;
                                745                 :                :             int         i;
                                746                 :                : 
                                747                 :                :             /* Must get indclass the hard way. */
  896 dgustafsson@postgres      748                 :             36 :             indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
                                749                 :             36 :                                                    indexRel->rd_indextuple,
                                750                 :                :                                                    Anum_pg_index_indclass);
 2728 tgl@sss.pgh.pa.us         751                 :             36 :             indclass = (oidvector *) DatumGetPointer(indclassDatum);
                                752                 :                : 
                                753                 :                :             /* Add quals for all columns from this index. */
 2709 teodor@sigaev.ru          754         [ +  + ]:             80 :             for (i = 0; i < indnkeyatts; i++)
                                755                 :                :             {
 4415 kgrittn@postgresql.o      756                 :             44 :                 int         attnum = indexStruct->indkey.values[i];
 2728 tgl@sss.pgh.pa.us         757                 :             44 :                 Oid         opclass = indclass->values[i];
 2939 andres@anarazel.de        758                 :             44 :                 Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
 2728 tgl@sss.pgh.pa.us         759                 :             44 :                 Oid         attrtype = attr->atttypid;
                                760                 :                :                 HeapTuple   cla_ht;
                                761                 :                :                 Form_pg_opclass cla_tup;
                                762                 :                :                 Oid         opfamily;
                                763                 :                :                 Oid         opcintype;
                                764                 :                :                 Oid         op;
                                765                 :                :                 const char *leftop;
                                766                 :                :                 const char *rightop;
                                767                 :                : 
                                768                 :                :                 /*
                                769                 :                :                  * Identify the equality operator associated with this index
                                770                 :                :                  * column.  First we need to look up the column's opclass.
                                771                 :                :                  */
                                772                 :             44 :                 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
                                773         [ -  + ]:             44 :                 if (!HeapTupleIsValid(cla_ht))
 2728 tgl@sss.pgh.pa.us         774         [ #  # ]:UBC           0 :                     elog(ERROR, "cache lookup failed for opclass %u", opclass);
 2728 tgl@sss.pgh.pa.us         775                 :CBC          44 :                 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
                                776                 :             44 :                 opfamily = cla_tup->opcfamily;
                                777                 :             44 :                 opcintype = cla_tup->opcintype;
                                778                 :             44 :                 ReleaseSysCache(cla_ht);
                                779                 :                : 
  172 peter@eisentraut.org      780                 :             44 :                 op = get_opfamily_member_for_cmptype(opfamily, opcintype, opcintype, COMPARE_EQ);
 2728 tgl@sss.pgh.pa.us         781         [ -  + ]:             44 :                 if (!OidIsValid(op))
  172 peter@eisentraut.org      782         [ #  # ]:UBC           0 :                     elog(ERROR, "missing equality operator for (%u,%u) in opfamily %u",
                                783                 :                :                          opcintype, opcintype, opfamily);
                                784                 :                : 
                                785                 :                :                 /*
                                786                 :                :                  * If we find the same column with the same equality semantics
                                787                 :                :                  * in more than one index, we only need to emit the equality
                                788                 :                :                  * clause once.
                                789                 :                :                  *
                                790                 :                :                  * Since we only remember the last equality operator, this
                                791                 :                :                  * code could be fooled into emitting duplicate clauses given
                                792                 :                :                  * multiple indexes with several different opclasses ... but
                                793                 :                :                  * that's so unlikely it doesn't seem worth spending extra
                                794                 :                :                  * code to avoid.
                                795                 :                :                  */
 2728 tgl@sss.pgh.pa.us         796         [ -  + ]:CBC          44 :                 if (opUsedForQual[attnum - 1] == op)
 4435 kgrittn@postgresql.o      797                 :UBC           0 :                     continue;
 2728 tgl@sss.pgh.pa.us         798                 :CBC          44 :                 opUsedForQual[attnum - 1] = op;
                                799                 :                : 
                                800                 :                :                 /*
                                801                 :                :                  * Actually add the qual, ANDed with any others.
                                802                 :                :                  */
 4435 kgrittn@postgresql.o      803         [ +  + ]:             44 :                 if (foundUniqueIndex)
                                804                 :             14 :                     appendStringInfoString(&querybuf, " AND ");
                                805                 :                : 
 1491 tgl@sss.pgh.pa.us         806                 :             44 :                 leftop = quote_qualified_identifier("newdata",
 2728                           807                 :             44 :                                                     NameStr(attr->attname));
 1491                           808                 :             44 :                 rightop = quote_qualified_identifier("mv",
 2728                           809                 :             44 :                                                      NameStr(attr->attname));
                                810                 :                : 
                                811                 :             44 :                 generate_operator_clause(&querybuf,
                                812                 :                :                                          leftop, attrtype,
                                813                 :                :                                          op,
                                814                 :                :                                          rightop, attrtype);
                                815                 :                : 
 4435 kgrittn@postgresql.o      816                 :             44 :                 foundUniqueIndex = true;
                                817                 :                :             }
                                818                 :                :         }
                                819                 :                : 
                                820                 :                :         /* Keep the locks, since we're about to run DML which needs them. */
 4190 tgl@sss.pgh.pa.us         821                 :             36 :         index_close(indexRel, NoLock);
                                822                 :                :     }
                                823                 :                : 
 4435 kgrittn@postgresql.o      824                 :             33 :     list_free(indexoidlist);
                                825                 :                : 
                                826                 :                :     /*
                                827                 :                :      * There must be at least one usable unique index on the matview.
                                828                 :                :      *
                                829                 :                :      * ExecRefreshMatView() checks that after taking the exclusive lock on the
                                830                 :                :      * matview. So at least one unique index is guaranteed to exist here
                                831                 :                :      * because the lock is still being held.  (One known exception is if a
                                832                 :                :      * function called as part of refreshing the matview drops the index.
                                833                 :                :      * That's a pretty silly thing to do.)
                                834                 :                :      */
  579 heikki.linnakangas@i      835         [ +  + ]:             33 :     if (!foundUniqueIndex)
  429 michael@paquier.xyz       836         [ +  - ]:              3 :         ereport(ERROR,
                                837                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                838                 :                :                 errmsg("could not find suitable unique index on materialized view \"%s\"",
                                839                 :                :                        RelationGetRelationName(matviewRel)));
                                840                 :                : 
 4435 kgrittn@postgresql.o      841                 :             30 :     appendStringInfoString(&querybuf,
                                842                 :                :                            " AND newdata.* OPERATOR(pg_catalog.*=) mv.*) "
                                843                 :                :                            "WHERE newdata.* IS NULL OR mv.* IS NULL "
                                844                 :                :                            "ORDER BY tid");
                                845                 :                : 
                                846                 :                :     /* Populate the temporary "diff" table. */
  579 heikki.linnakangas@i      847         [ -  + ]:             30 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
 4435 kgrittn@postgresql.o      848         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                849                 :                : 
                                850                 :                :     /*
                                851                 :                :      * We have no further use for data from the "full-data" temp table, but we
                                852                 :                :      * must keep it around because its type is referenced from the diff table.
                                853                 :                :      */
                                854                 :                : 
                                855                 :                :     /* Analyze the diff table. */
 4435 kgrittn@postgresql.o      856                 :CBC          30 :     resetStringInfo(&querybuf);
                                857                 :             30 :     appendStringInfo(&querybuf, "ANALYZE %s", diffname);
                                858         [ -  + ]:             30 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
 4435 kgrittn@postgresql.o      859         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                860                 :                : 
 4435 kgrittn@postgresql.o      861                 :CBC          30 :     OpenMatViewIncrementalMaintenance();
                                862                 :                : 
                                863                 :                :     /* Deletes must come before inserts; do them first. */
                                864                 :             30 :     resetStringInfo(&querybuf);
                                865                 :             30 :     appendStringInfo(&querybuf,
                                866                 :                :                      "DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY "
                                867                 :                :                      "(SELECT diff.tid FROM %s diff "
                                868                 :                :                      "WHERE diff.tid IS NOT NULL "
                                869                 :                :                      "AND diff.newdata IS NULL)",
                                870                 :                :                      matviewname, diffname);
                                871         [ -  + ]:             30 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)
 4435 kgrittn@postgresql.o      872         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                873                 :                : 
                                874                 :                :     /* Inserts go last. */
 4435 kgrittn@postgresql.o      875                 :CBC          30 :     resetStringInfo(&querybuf);
                                876                 :             30 :     appendStringInfo(&querybuf,
                                877                 :                :                      "INSERT INTO %s SELECT (diff.newdata).* "
                                878                 :                :                      "FROM %s diff WHERE tid IS NULL",
                                879                 :                :                      matviewname, diffname);
                                880         [ -  + ]:             30 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
 4435 kgrittn@postgresql.o      881         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                882                 :                : 
                                883                 :                :     /* We're done maintaining the materialized view. */
 4435 kgrittn@postgresql.o      884                 :CBC          30 :     CloseMatViewIncrementalMaintenance();
 2420 andres@anarazel.de        885                 :             30 :     table_close(tempRel, NoLock);
                                886                 :             30 :     table_close(matviewRel, NoLock);
                                887                 :                : 
                                888                 :                :     /* Clean up temp tables. */
 4435 kgrittn@postgresql.o      889                 :             30 :     resetStringInfo(&querybuf);
                                890                 :             30 :     appendStringInfo(&querybuf, "DROP TABLE %s, %s", diffname, tempname);
                                891         [ -  + ]:             30 :     if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
 4435 kgrittn@postgresql.o      892         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_exec failed: %s", querybuf.data);
                                893                 :                : 
                                894                 :                :     /* Close SPI context. */
 4435 kgrittn@postgresql.o      895         [ -  + ]:CBC          30 :     if (SPI_finish() != SPI_OK_FINISH)
 4435 kgrittn@postgresql.o      896         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_finish failed");
 4435 kgrittn@postgresql.o      897                 :CBC          30 : }
                                898                 :                : 
                                899                 :                : /*
                                900                 :                :  * Swap the physical files of the target and transient tables, then rebuild
                                901                 :                :  * the target's indexes and throw away the transient table.  Security context
                                902                 :                :  * swapping is handled by the called function, so it is not needed here.
                                903                 :                :  */
                                904                 :                : static void
 3948 alvherre@alvh.no-ip.      905                 :            249 : refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)
                                906                 :                : {
 4435 kgrittn@postgresql.o      907                 :            249 :     finish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,
                                908                 :                :                      RecentXmin, ReadNextMultiXactId(), relpersistence);
                                909                 :            246 : }
                                910                 :                : 
                                911                 :                : /*
                                912                 :                :  * Check whether specified index is usable for match merge.
                                913                 :                :  */
                                914                 :                : static bool
 2728 tgl@sss.pgh.pa.us         915                 :             78 : is_usable_unique_index(Relation indexRel)
                                916                 :                : {
                                917                 :             78 :     Form_pg_index indexStruct = indexRel->rd_index;
                                918                 :                : 
                                919                 :                :     /*
                                920                 :                :      * Must be unique, valid, immediate, non-partial, and be defined over
                                921                 :                :      * plain user columns (not expressions).
                                922                 :                :      */
                                923         [ +  - ]:             78 :     if (indexStruct->indisunique &&
                                924         [ +  - ]:             78 :         indexStruct->indimmediate &&
 2445 peter_e@gmx.net           925   [ +  -  +  + ]:            156 :         indexStruct->indisvalid &&
 2728 tgl@sss.pgh.pa.us         926                 :             78 :         RelationGetIndexPredicate(indexRel) == NIL &&
                                927         [ +  - ]:             75 :         indexStruct->indnatts > 0)
                                928                 :                :     {
                                929                 :                :         /*
                                930                 :                :          * The point of groveling through the index columns individually is to
                                931                 :                :          * reject both index expressions and system columns.  Currently,
                                932                 :                :          * matviews couldn't have OID columns so there's no way to create an
                                933                 :                :          * index on a system column; but maybe someday that wouldn't be true,
                                934                 :                :          * so let's be safe.
                                935                 :                :          */
                                936                 :             75 :         int         numatts = indexStruct->indnatts;
                                937                 :                :         int         i;
                                938                 :                : 
                                939         [ +  + ]:            163 :         for (i = 0; i < numatts; i++)
                                940                 :                :         {
                                941                 :             91 :             int         attnum = indexStruct->indkey.values[i];
                                942                 :                : 
                                943         [ +  + ]:             91 :             if (attnum <= 0)
                                944                 :              3 :                 return false;
                                945                 :                :         }
                                946                 :             72 :         return true;
                                947                 :                :     }
                                948                 :              3 :     return false;
                                949                 :                : }
                                950                 :                : 
                                951                 :                : 
                                952                 :                : /*
                                953                 :                :  * This should be used to test whether the backend is in a context where it is
                                954                 :                :  * OK to allow DML statements to modify materialized views.  We only want to
                                955                 :                :  * allow that for internal code driven by the materialized view definition,
                                956                 :                :  * not for arbitrary user-supplied code.
                                957                 :                :  *
                                958                 :                :  * While the function names reflect the fact that their main intended use is
                                959                 :                :  * incremental maintenance of materialized views (in response to changes to
                                960                 :                :  * the data in referenced relations), they are initially used to allow REFRESH
                                961                 :                :  * without blocking concurrent reads.
                                962                 :                :  */
                                963                 :                : bool
 4435 kgrittn@postgresql.o      964                 :             60 : MatViewIncrementalMaintenanceIsEnabled(void)
                                965                 :                : {
                                966                 :             60 :     return matview_maintenance_depth > 0;
                                967                 :                : }
                                968                 :                : 
                                969                 :                : static void
 4419                           970                 :             30 : OpenMatViewIncrementalMaintenance(void)
                                971                 :                : {
                                972                 :             30 :     matview_maintenance_depth++;
                                973                 :             30 : }
                                974                 :                : 
                                975                 :                : static void
                                976                 :             30 : CloseMatViewIncrementalMaintenance(void)
                                977                 :                : {
                                978                 :             30 :     matview_maintenance_depth--;
                                979         [ -  + ]:             30 :     Assert(matview_maintenance_depth >= 0);
                                980                 :             30 : }
        

Generated by: LCOV version 2.4-beta