哪里有做企业网站的/万网创始人
我们前面分析完视图后,这里再继续分析一下物化视图,其实现原理是不相同的,需要注意,物化视图等于是将返回的结果集缓存起来,而视图是查询重写,结果需要重新进行计算。
create materialized view matvt1 as select * from t1
语法解析部分
主流程如下:
exec_simple_query
--> pg_parse_query--> raw_parser--> base_yyparse
--> pg_analyze_and_rewrite--> parse_analyze--> transformStmt--> transformCreateTableAsStmt--> transformStmt // 对查询语句进行语义分析,将其转换为查询树Query--> pg_rewrite_query
--> pg_plan_queries
定义物化视图的语法如下:
/******************************************************************************* QUERY :* CREATE MATERIALIZED VIEW relname AS SelectStmt******************************************************************************/
CreateMatViewStmt:CREATE OptNoLog MATERIALIZED VIEW create_mv_target AS SelectStmt opt_with_data{CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt); ctas->query = $7;ctas->into = $5;ctas->relkind = OBJECT_MATVIEW;ctas->is_select_into = false;ctas->if_not_exists = false;/* cram additional flags into the IntoClause */$5->rel->relpersistence = $2;$5->skipData = !($8);$$ = (Node *) ctas;}
创建物化视图的语法,抽象语法树表示CreateTableAsStmt
,创建物化视图的流程与CREATE TABLE AS
相同,等于新创建一个表(UNLOGGED TABLE),保存查询到的结果集。可以看到SELECT INTO
,与CREATE TABLE AS
也是用此进行表示。
/* ----------------------* CREATE TABLE AS Statement (a/k/a SELECT INTO)** A query written as CREATE TABLE AS will produce this node type natively.* A query written as SELECT ... INTO will be transformed to this form during* parse analysis.* A query written as CREATE MATERIALIZED view will produce this node type,* during parse analysis, since it needs all the same data.** The "query" field is handled similarly to EXPLAIN, though note that it* can be a SELECT or an EXECUTE, but not other DML statements.* ----------------------*/
typedef struct CreateTableAsStmt
{NodeTag type;Node *query; /* the query (see comments above) */IntoClause *into; /* destination table */ObjectType relkind; /* OBJECT_TABLE or OBJECT_MATVIEW */bool is_select_into; /* it was written as SELECT INTO */bool if_not_exists; /* just do nothing if it already exists? */
} CreateTableAsStmt;/** IntoClause - target information for SELECT INTO, CREATE TABLE AS, and* CREATE MATERIALIZED VIEW** For CREATE MATERIALIZED VIEW, viewQuery is the parsed-but-not-rewritten* SELECT Query for the view; otherwise it's NULL. (Although it's actually* Query*, we declare it as Node* to avoid a forward reference.)*/
typedef struct IntoClause
{NodeTag type;RangeVar *rel; /* target relation name */List *colNames; /* column names to assign, or NIL */char *accessMethod; /* table access method */List *options; /* options from WITH clause */OnCommitAction onCommit; /* what do we do at COMMIT? */char *tableSpaceName; /* table space to use, or NULL */Node *viewQuery; /* materialized view's SELECT query */bool skipData; /* true for WITH NO DATA */
} IntoClause;
执行部分——创建物化视图
主流程如下:
exec_simple_query
--> pg_parse_query
--> pg_analyze_and_rewrite
--> pg_plan_queries
--> PortalStart
--> PortalRun--> PortalRunUtility // Execute a utility statement inside a portal.--> ProcessUtility--> standard_ProcessUtility--> ProcessUtilitySlow/** 执行步骤:* 1. 创建表,准备存储结果集* 2. 查询重写(物化视图中的查询语句)* 3. 生成查询的执行计划* 4. 执行获取查询语句的结果集*/--> ExecCreateTableAs // Create the tuple receiver object and insert info it will need--> CreateIntoRelDestReceiver // 结果集输入到IntoRel中,新建的表中--> QueryRewrite--> pg_plan_query--> standard_planner--> subquery_planner--> grouping_planner--> query_planner--> make_one_rel--> create_plan--> create_scan_plan--> CreateQueryDesc /* Create a QueryDesc, redirecting output to our tuple receiver */--> ExecutorStart--> ExecutorRun--> standard_ExecutorRun// 1. 建表--> intorel_startup--> create_ctas_internal //Actually create the target table--> DefineRelation // 建表--> heap_create_with_catalog--> heap_create--> StoreViewQuery // Use the rules system to store the query for the view.--> UpdateRangeTableOfViewParse --> DefineViewRules--> DefineQueryRewrite // Set up the ON SELECT rule.--> InsertRule // 插入的规则,重写为新的物化表,并不是源表--> SetMatViewPopulatedState// 2. 执行查询语句,结果集存入物化的表中--> ExecutePlan--> ExecScan // 扫描获取tuple--> ExecScanFetch--> SeqNext--> table_beginscan--> intorel_receive // receive one tuple--> table_tuple_insert // 将查询到的tuple slot插入到创建的表中--> heapam_tuple_insert--> ExecFetchSlotHeapTuple--> tts_buffer_heap_materialize--> heap_copytuple--> tts_buffer_heap_get_heap_tuple--> heap_insert // 插入到表中,找到指定的page,插入tuple。--> heap_prepare_insert--> RelationPutHeapTuple --> ExecutorEnd--> PortalDrop
对于结果集中如何存入物化的新表中,可查看dest.c、createas.c等源码,查询到的结果可以按照需求发送到不同的地方,可查看下面的枚举,可以看到有个DestIntoRel
的值,即使将结果send to relation
。
/* ----------------* CommandDest is a simplistic means of identifying the desired* destination. Someday this will probably need to be improved.** Note: only the values DestNone, DestDebug, DestRemote are legal for the* global variable whereToSendOutput. The other values may be used* as the destination for individual commands.* ----------------*/
typedef enum
{DestNone, /* results are discarded */DestDebug, /* results go to debugging output */DestRemote, /* results sent to frontend process */DestRemoteExecute, /* sent to frontend, in Execute command */DestRemoteSimple, /* sent to frontend, w/no catalog access */DestSPI, /* results sent to SPI manager */DestTuplestore, /* results sent to Tuplestore */DestIntoRel, /* results sent to relation (SELECT INTO) */DestCopyOut, /* results sent to COPY TO code */DestSQLFunction, /* results sent to SQL-language func mgr */DestTransientRel, /* results sent to transient relation */DestTupleQueue /* results sent to tuple queue */
} CommandDest;
其中还有一个非常重要的函数需要列出来CreateIntoRelDestReceiver
,查询返回的结果输入到IntoClause
节点指定的表中。
/** CreateIntoRelDestReceiver -- create a suitable DestReceiver object** intoClause will be NULL if called from CreateDestReceiver(), in which* case it has to be provided later. However, it is convenient to allow* self->into to be filled in immediately for other callers.*/
DestReceiver *
CreateIntoRelDestReceiver(IntoClause *intoClause)
{DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));self->pub.receiveSlot = intorel_receive;self->pub.rStartup = intorel_startup;self->pub.rShutdown = intorel_shutdown;self->pub.rDestroy = intorel_destroy;self->pub.mydest = DestIntoRel;self->into = intoClause;/* other private fields will be set during intorel_startup */return (DestReceiver *) self;
}typedef struct
{DestReceiver pub; /* publicly-known function pointers */IntoClause *into; /* target relation specification *//* These fields are filled by intorel_startup: */Relation rel; /* relation to write to */ObjectAddress reladdr; /* address of rel, for ExecCreateTableAs */CommandId output_cid; /* cmin to insert in output tuples */int ti_options; /* table_tuple_insert performance options */BulkInsertState bistate; /* bulk insert state */
} DR_intorel;
最后我们看一下系统表pg_class、pg_rewrite中的相关信息:
-- 物化视图matvt1
postgres@postgres=# select oid,relname,relkind,relhasrules from pg_class where relname='matvt1';
-[ RECORD 1 ]-------
oid | 16391
relname | matvt1
relkind | m
relhasrules | t
-- 表t1
postgres@postgres=# select oid,relname,relkind,relhasrules,relrewrite from pg_class where relname='t1';
-[ RECORD 1 ]------
oid | 16384 -- 表OID
relname | t1 -- 表名
relkind | r -- 表示是普通表
relhasrules | f -- 表是否定义了规则
relrewrite | 0
-- 查看系统表pg_rewrite,查看插入的规则
postgres@postgres=# select * from pg_rewrite order by oid desc limit 1;
-[ RECORD 1 ]
oid | 16394
rulename | _RETURN
ev_class | 16391
ev_type | 1
ev_enabled | O
is_instead | t
ev_qual | <>
ev_action | ({QUERY :commandType 1 :querySource 0 :canSetTag true :utilityStmt <> :resultRelation 0 :hasAggs false :hasWindowFuncs false :hasTargetSRFs false :hasSubLinks false :hasDistinctOn false :hasRecursive false :hasModifyingCTE false :hasForUpdate false :hasRowSecurity false :cteList <> :rtable ({RTE :alias {ALIAS :aliasname old :colnames <>} :eref {ALIAS :aliasname old :colnames ("a" "b")} :rtekind 0 :relid 16391 :relkind m :rellockmode 1 :tablesample <> :lateral false :inh false :inFromCl false :requiredPerms 0 :checkAsUser 0 :selectedCols (b) :insertedCols (b) :updatedCols (b) :extraUpdatedCols (b) :securityQuals <>} {RTE :alias {ALIAS :aliasname new :colnames <>} :eref {ALIAS :aliasname new :colnames ("a" "b")} :rtekind 0 :relid 16391 :relkind m :rellockmode 1 :tablesample <> :lateral false :inh false :inFromCl false :requiredPerms 0 :checkAsUser 0 :selectedCols (b) :insertedCols (b) :updatedCols (b) :extraUpdatedCols (b) :securityQuals <>} {RTE :alias <> :eref {ALIAS :aliasname t1 :colnames ("a" "b")} :rtekind 0 :relid 16384 :relkind r :rellockmode 1 :tablesample <> :lateral false :inh true :inFromCl true :requiredPerms 2 :checkAsUser 0 :selectedCols (b 8 9) :insertedCols (b) :updatedCols (b) :extraUpdatedCols (b) :securityQuals <>}) :jointree {FROMEXPR :fromlist ({RANGETBLREF :rtindex 3}) :quals <>} :targetList ({TARGETENTRY :expr {VAR :varno 3 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varlevelsup 0 :varnosyn 3 :varattnosyn 1 :location 42} :resno 1 :resname a :ressortgroupref 0 :resorigtbl 16384 :resorigcol 1 :resjunk false} {TARGETENTRY :expr {VAR :varno 3 :varattno 2 :vartype 23 :vartypmod -1 :varcollid 0 :varlevelsup 0 :varnosyn 3 :varattnosyn 2 :location 42} :resno 2 :resname b :ressortgroupref 0 :resorigtbl 16384 :resorigcol 2 :resjunk false}) :override 0 :onConflict <> :returningList <> :groupClause <> :groupingSets <> :havingQual <> :windowClause <> :distinctClause <> :sortClause <> :limitOffset <> :limitCount <> :limitOption 0 :rowMarks <> :setOperations <> :constraintDeps <> :withCheckOptions <>})
物化视图与普通视图不同的地方在于,创建物化视图时,要建立一张物理表存储查询语句的结果集。
相关文章:

PostgreSQL源码分析——物化视图
我们前面分析完视图后,这里再继续分析一下物化视图,其实现原理是不相同的,需要注意,物化视图等于是将返回的结果集缓存起来,而视图是查询重写,结果需要重新进行计算。 create materialized view matvt1 as…...

操作系统入门系列-MIT6.828(操作系统工程)学习笔记(七)---- 系统调用函数与GDB(Lab: system calls)
系列文章目录 操作系统入门系列-MIT6.828(操作系统工程)学习笔记(一)---- 操作系统介绍与接口示例 操作系统入门系列-MIT6.828(操作系统工程)学习笔记(二)---- 课程实验环境搭建&am…...

ORA-12560: TNS:协议适配器错误
项目场景: 由于最近一直没有连接oracle,然后之前windows也是正常可以启动oracle,正常连接。无论是SQL Developer还是SQL PLUS命令,都能正常连接和操作。 问题描述 这两天刚好用SQL Developer工具连接,然后报错&#…...

不容小觑的“白纸黑字”:银行重空凭证的风险与防控
一、定义与重要性 定义: 银行重空凭证,也称为重要空白凭证,是银行专业术语,指银行印制的无面额、经银行或单位填写金额并签章后,即具有支取款项效力的空白凭证。 重要性: 它是银行资金支付的重要工具&a…...

30v-180V降3.3V100mA恒压WT5107
30v-180V降3.3V100mA恒压WT5107 WT5107是一款恒压单片机供电芯片,它可以30V-180V直流电转换成稳定的3.3V直流电(最大输出电流300mA),为各种单片机供电。WT5107的应用也非常广泛。它可以用于智能家居、LED照明、电子玩具等领域。比…...

Spring Boot 和 Spring Cloud 的区别及选型
Spring Boot 和 Spring Cloud 是现代 Java 开发中非常流行的两个框架,它们分别解决了不同层次的问题。本文将详细介绍 Spring Boot 和 Spring Cloud 的区别,以及在不同场景下如何选择合适的技术。 Spring Boot 什么是 Spring Boot Spring Boot 是一个…...

【神经网络】图像的数字视角
文章目录 图像的数字视角引言直观感受内在剖析图像常用函数图像三维层次 经验总结 图像的数字视角 引言 在机器视觉和目标识别领域,需要处理的对象都是图像,但这些领域的模型都是针对数值进行训练的,那么图像和数值之间是什么关系呢?答案是…...

ChatGPT的问题与回复的内容导出(Chorme)
我给出两种方式,第一种方式无使用要求,第二种方式必须安装Chorme 个人更推荐第二种方式 第一种方式:使用chatgpt自带的数据导出 缺点:会将当前未归档的所有聊天记录导出,发送到你的电子邮箱中 第二种方式:…...

游戏开发中的坑之十四 photoshop的javascript脚本批量修改分辨率
原因:美术提交大量2048x2048的贴图,导致工程臃肿。 方案:使用photoshop的javascript脚本批量把指定的文件夹以及所有子文件夹的贴图进行压缩。 脚本中指定针对2048x2048的贴图进行处理。 // Photoshop JavaScript to resize TGA images with…...

leetcode打卡#day45 携带研究材料(第七期模拟笔试)、518. 零钱兑换 II、377. 组合总和 Ⅳ、爬楼梯(第八期模拟笔试)
携带研究材料(第七期模拟笔试) #include<iostream> #include<algorithm> #include<vector>using namespace std;int main() {int N, V;cin >> N >> V;vector<int> weights(N1);vector<int> values(V1);int w…...

Vite+Vue3安装且自动按需引入Element Plus组件库
一,安装Element Plus npm install element-plus //node环境16二,安装插件 npm install unplugin-auto-import unplugin-vue-components -D三,配置vite.config.ts文件 //按需引入element-plus组件 import AutoImport from unplugin-auto-i…...

敬酒词大全绝对实用 万能敬酒词
举杯共饮,友情初识;再续一杯,情深似海,朋友相伴人生路更宽。酒逢知己千杯少,一饮而尽显真意,浅尝则留情,深情则尽欢。友情到深处,千杯不倒,若情浅则饮少,醉卧…...

【Java】已解决com.mysql.cj.jdbc.exceptions.CommunicationsException异常
文章目录 一、分析问题背景二、可能出错的原因三、错误代码示例四、正确代码示例五、注意事项 已解决com.mysql.cj.jdbc.exceptions.CommunicationsException异常 一、分析问题背景 com.mysql.cj.jdbc.exceptions.CommunicationsException是Java程序在使用MySQL Connector/J与…...

Leetcode 76. 最小覆盖子串
76. 最小覆盖子串 - 力扣(LeetCode) class Solution {/**也是滑动窗口,思路简单,但实现起来容易出错。一个tmap记录目标串t的各个字符出现的次数;一个smap记录原串的某个滑动窗口里字符出现次数。两个指针left&#x…...

JAVAWEB--Mybatis03
Mybatis映射 什么是映射器 MyBatis的映射器就是用来解决这一问题,映射器其实是一个Interface接口,我们通过编写简单的映射器接口,就可以将我们之前在Dao中做的重复的,看起来比较低级的代码给替换掉。也就是说我们以后不用向之前那样写代码&…...

论文学习_Fuzz4All: Universal Fuzzing with Large Language Models
论文名称发表时间发表期刊期刊等级研究单位Fuzz4All: Universal Fuzzing with Large Language Models2024年arXiv-伊利诺伊大学 0.摘要 研究背景模糊测试再发现各种软件系统中的错误和漏洞方面取得了巨大的成功。以编程或形式语言作为输入的被测系统(SUTÿ…...

元数据相关资料整理 metadata
目录 定义和特点 关注点 流程 使用场景 元数据影响分析 元数据冷热度分析 元数据关联度分析 血缘分析 数据地图 元数据接口 相关产品的架构图 定义和特点 元数据(Metadata)是指关于数据的数据,或者说是描述数据的数据。它提供了一…...

【Android面试八股文】谈一谈你对http和https的关系理解
文章目录 HTTPHTTPSSSL/TLS协议HTTPS加密、解密流程HTTP 和 HTTPS 的关系具体的差异实际应用总结扩展阅读HTTP(HyperText Transfer Protocol)和HTTPS(HyperText Transfer Protocol Secure)是用于在网络上进行通信的两种协议。 它们在很多方面是相似的,但关键的区别在于安全…...

Vue3 中 setup 函数与 script setup 用法总结
在 Vue3 中,setup 函数和 script setup 是两种新引入的编写组件的方式,它们都是 Composition API 的一部分。 setup 函数: setup 函数是一个新的组件选项,它作为在组件内使用 Composition API 的入口。在 setup 函数中,我们可以定…...

Springboot 开发之任务调度框架(一)Quartz 简介
一、引言 常见的定时任务框架有 Quartz、elastic-job、xxl-job等等,本文主要介绍 Spirng Boot 集成 Quartz 定时任务框架。 二、Quartz 简介 Quartz 是一个功能强大且灵活的开源作业调度库,广泛用于 Java 应用中。它允许开发者创建复杂的调度任务&…...

企业中面试算法岗时会问什么pytorch问题?看这篇就够了!
如果要面试深度学习相关的岗位,JD上一般会明确要求要熟悉pytorch或tensorflow框架,那么会一般问什么相关问题呢? 文章目录 一. 基础知识与概念1.1 PyTorch与TensorFlow的主要区别是什么? 1.2 解释一下PyTorch中的Tensor是什么&…...

【学习】程序员资源网址
1 书栈网 简介:书栈网是程序员互联网IT开源编程书籍、资源免费阅读的网站,在书栈网你可以找到很多书籍、笔记资源。在这里,你可以根据热门收藏和阅读查看大家都在看什么,也可以根据技术栈分类找到对应模块的编程资源,…...

【3D模型库】机械三维模型库整理
1 开拔网 简介:开拔网是中国较早的机械设计交流平台,广受行业内的各个大学,公司以及行业人士的欢迎。网站有非常丰富的3D模型,CAD图纸,以及各类热门软件的下载。同时我们也为行业搭建一个平台,提供各类设计…...

基于Python-CNN深度学习的物品识别
基于Python-CNN深度学习的物品识别 近年来,深度学习尤其是卷积神经网络(CNN)的快速发展,极大地推动了计算机视觉技术的进步。在物品识别领域,CNN凭借其强大的特征提取和学习能力,成为了主流的技术手段之一…...

Qt | 简单的使用 QStyle 类(风格也称为样式)
01、前言 者在 pro 文件中已添加了正确的 QT+=widgets 语句 02、基础样式 1、QStyle 类继承自 QObject,该类是一个抽像类。 2、QStyle 类描述了 GUI 的界面外观,Qt 的内置部件使用该类执行几乎所有的绘制,以确保 使这些部件看起来与本地部件完全相同。 3、Qt 内置了一系…...

Idea连接GitLab的过程以及创建在gitlab中创建用户和群组
上期讲述了如何部署GitLab以及修复bug,这期我们讲述,如何连接idea。 首先安装gitlab插件 下载安装idea上并重启 配置ssh免密登录 使用管理员打开命令行输入:ssh-keygen -t rsa -C xxxaaa.com 到用户目录下.ssh查看id_rsa.pub文件 打开复制…...

关于glibc-all-in-one下载libc2.35以上报错问题
./download libc版本 下载2.35时报错:原因是缺少解压工具zstd sudo apt-get install zstd 下载后重新输命令就可以了 附加xclibc命令 xclibc -x ./pwn ./libc-版本 ldd pwn文件 xclibc -c libc版本...

C语言之#define #if 预处理器指令
在 C 语言中,预处理器指令用于条件编译代码。你可以使用 #define 和 #if 指令来根据某些条件包含或排除代码块。以下是一个完整的例子,演示了如何使用 #define 和 #if 指令来控制代码的编译: #include <stdio.h>// 定义宏 MERGE_TYPE …...

modbus流量计数据解析(4个字节与float的换算)
通过modbus协议从流量计中读取数据后,需要将获得的字节数据合成float类型。以天信流量计为例: 如何将字节数据合并成float类型呢?这里总结了三种方法。 以温度值41 A0 00 00为例 目录 1、使用char*逐字节解析2、使用memcpy转换2、使用联合体…...

关于element-plus中el-select自定义标签及样式的问题
关于element-plus中el-select自定义标签及样式的问题 我这天天的都遇到各种坑,关于自定义,我直接复制粘贴代码都实现不了,研究了一下午,骂骂咧咧了一下午,服气了。官网代码实现不了,就只能 “ 曲线救国 ”…...