typedefstruct
{
DestReceiver pub; /* publicly-known function pointers */
Oid transientoid; /* OID of new heap into which to store */ /* These fields are filled by transientrel_startup: */
Relation transientrel; /* relation to write to */
CommandId output_cid; /* cmin to insert in output tuples */ int ti_options; /* table_tuple_insert performance options */
BulkInsertState bistate; /* bulk insert state */
} DR_transientrel;
staticint matview_maintenance_depth = 0;
staticvoid transientrel_startup(DestReceiver *self, int operation, TupleDesc typeinfo); staticbool transientrel_receive(TupleTableSlot *slot, DestReceiver *self); staticvoid transientrel_shutdown(DestReceiver *self); staticvoid transientrel_destroy(DestReceiver *self); static uint64 refresh_matview_datafill(DestReceiver *dest, Query *query, constchar *queryString, bool is_create); staticchar *make_temptable_name_n(char *tempname, int n); staticvoid refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner, int save_sec_context); staticvoid refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence); staticbool is_usable_unique_index(Relation indexRel); staticvoid OpenMatViewIncrementalMaintenance(void); staticvoid CloseMatViewIncrementalMaintenance(void);
/* Make sure it is a materialized view. */ if (matviewRel->rd_rel->relkind != RELKIND_MATVIEW)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("\"%s\" is not a materialized view",
RelationGetRelationName(matviewRel))));
/* Check that CONCURRENTLY is not specified if not populated. */ if (concurrent && !RelationIsPopulated(matviewRel))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("CONCURRENTLY cannot be used when the materialized view is not populated")));
/* Check that conflicting options have not been specified. */ if (concurrent && skipData)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("%s and %s options cannot be used together", "CONCURRENTLY", "WITH NO DATA")));
if (matviewRel->rd_rules->numLocks > 1)
elog(ERROR, "materialized view \"%s\" has too many rules",
RelationGetRelationName(matviewRel));
rule = matviewRel->rd_rules->rules[0]; if (rule->event != CMD_SELECT || !(rule->isInstead))
elog(ERROR, "the rule for materialized view \"%s\" is not a SELECT INSTEAD OF rule",
RelationGetRelationName(matviewRel));
actions = rule->actions; if (list_length(actions) != 1)
elog(ERROR, "the rule for materialized view \"%s\" is not a single action",
RelationGetRelationName(matviewRel));
/* *CheckthatthereisauniqueindexwithnoWHEREclauseononeormore *columnsofthematerializedviewifCONCURRENTLYisspecified.
*/ if (concurrent)
{
List *indexoidlist = RelationGetIndexList(matviewRel);
ListCell *indexoidscan; bool hasUniqueIndex = false;
Assert(!is_create);
foreach(indexoidscan, indexoidlist)
{
Oid indexoid = lfirst_oid(indexoidscan);
Relation indexRel;
if (!hasUniqueIndex)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("cannot refresh materialized view \"%s\" concurrently",
quote_qualified_identifier(get_namespace_name(RelationGetNamespace(matviewRel)),
RelationGetRelationName(matviewRel))),
errhint("Create a unique index with no WHERE clause on one or more columns of the materialized view.")));
}
/* Lock and rewrite, using a copy to preserve the original query. */
copied_query = copyObject(query);
AcquireRewriteLocks(copied_query, true, false);
rewritten = QueryRewrite(copied_query);
/* SELECT should never rewrite to more or less than one SELECT query */ if (list_length(rewritten) != 1)
elog(ERROR, "unexpected rewrite result for %s",
is_create ? "CREATE MATERIALIZED VIEW " : "REFRESH MATERIALIZED VIEW");
query = (Query *) linitial(rewritten);
/* Check for user-requested abort. */
CHECK_FOR_INTERRUPTS();
/* Plan the query which will generate data for the refresh. */
plan = pg_plan_query(query, queryString, CURSOR_OPT_PARALLEL_OK, NULL);
/* Analyze the temp table with the new contents. */
appendStringInfo(&querybuf, "ANALYZE %s", tempname); if (SPI_exec(querybuf.data, 0) != SPI_OK_UTILITY)
elog(ERROR, "SPI_exec failed: %s", querybuf.data);
/* *WeneedtoensurethattherearenotduplicaterowswithoutNULLsin *thenewdatasetbeforewecancountonthe"diff"results.Checkfor *thatinawaythatallowsshowingthefirstduplicatedrowfound.Even *afterwepassthistest,auniqueindexonthematerializedviewmay *findaduplicatekeyproblem. * *Note:hereandbelow,weuse"tablename.*::tablerowtype"asahackto *keep".*"frombeingexpandedintomultiplecolumnsinaSELECTlist. *Compareruleutils.c'sget_variable().
*/
resetStringInfo(&querybuf);
appendStringInfo(&querybuf, "SELECT newdata.*::%s FROM %s newdata " "WHERE newdata.* IS NOT NULL AND EXISTS " "(SELECT 1 FROM %s newdata2 WHERE newdata2.* IS NOT NULL " "AND newdata2.* OPERATOR(pg_catalog.*=) newdata.* " "AND newdata2.ctid OPERATOR(pg_catalog.<>) " "newdata.ctid)",
tempname, tempname, tempname); if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_exec failed: %s", querybuf.data); if (SPI_processed > 0)
{ /* *Notethatthisereport()isreturningdatatotheuser.Generally, *wewouldwanttomakesurethattheuserhasbeengrantedaccessto *thisdata.However,REFRESHMATVIEWisonlyabletoberunbythe *ownerofthematview(orasuperuser)andthereforethereisno *needtocheckforaccesstodatainthematview.
*/
ereport(ERROR,
(errcode(ERRCODE_CARDINALITY_VIOLATION),
errmsg("new data for materialized view \"%s\" contains duplicate rows without any null columns",
RelationGetRelationName(matviewRel)),
errdetail("Row: %s",
SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1))));
}
/* Start building the query for populating the diff table. */
resetStringInfo(&querybuf);
appendStringInfo(&querybuf, "INSERT INTO %s " "SELECT mv.ctid AS tid, newdata.*::%s AS newdata " "FROM %s mv FULL JOIN %s newdata ON (",
diffname, tempname, matviewname, tempname);
foreach(indexoidscan, indexoidlist)
{
Oid indexoid = lfirst_oid(indexoidscan);
Relation indexRel;
indexRel = index_open(indexoid, RowExclusiveLock); if (is_usable_unique_index(indexRel))
{
Form_pg_index indexStruct = indexRel->rd_index; int indnkeyatts = indexStruct->indnkeyatts;
oidvector *indclass;
Datum indclassDatum; int i;
/* Must get indclass the hard way. */
indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
indexRel->rd_indextuple,
Anum_pg_index_indclass);
indclass = (oidvector *) DatumGetPointer(indclassDatum);
/* Add quals for all columns from this index. */ for (i = 0; i < indnkeyatts; i++)
{ int attnum = indexStruct->indkey.values[i];
Oid opclass = indclass->values[i];
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
Oid attrtype = attr->atttypid;
HeapTuple cla_ht;
Form_pg_opclass cla_tup;
Oid opfamily;
Oid opcintype;
Oid op; constchar *leftop; constchar *rightop;
op = get_opfamily_member_for_cmptype(opfamily, opcintype, opcintype, COMPARE_EQ); if (!OidIsValid(op))
elog(ERROR, "missing equality operator for (%u,%u) in opfamily %u",
opcintype, opcintype, opfamily);
/* Deletes must come before inserts; do them first. */
resetStringInfo(&querybuf);
appendStringInfo(&querybuf, "DELETE FROM %s mv WHERE ctid OPERATOR(pg_catalog.=) ANY " "(SELECT diff.tid FROM %s diff " "WHERE diff.tid IS NOT NULL " "AND diff.newdata IS NULL)",
matviewname, diffname); if (SPI_exec(querybuf.data, 0) != SPI_OK_DELETE)
elog(ERROR, "SPI_exec failed: %s", querybuf.data);
/* Inserts go last. */
resetStringInfo(&querybuf);
appendStringInfo(&querybuf, "INSERT INTO %s SELECT (diff.newdata).* " "FROM %s diff WHERE tid IS NULL",
matviewname, diffname); if (SPI_exec(querybuf.data, 0) != SPI_OK_INSERT)
elog(ERROR, "SPI_exec failed: %s", querybuf.data);
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.