Postgresql源码(112)plpgsql执行sql时变量何时替换为值

2023-10-21 02:40

本文主要是介绍Postgresql源码(112)plpgsql执行sql时变量何时替换为值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

相关
《Postgresql源码(41)plpgsql函数编译执行流程分析》
《Postgresql源码(46)plpgsql中的变量类型及对应关系》
《Postgresql源码(49)plpgsql函数编译执行流程分析总结》
《Postgresql源码(53)plpgsql语法解析关键流程、函数分析》
《Postgresql源码(112)plpgsql执行sql时变量何时替换为值》

0 用例和问题

drop table d1;
create table d1(a varchar(32));do $$
declarekk varchar(32);
beginkk := 'abcd';insert into d1 values (kk);
end;
$$;select * from d1;

请问:insert执行时,kk变量的值是在哪里换成具体的字符串的。

下文总结:

  1. 在语义分析阶段,走钩子函数plpgsql_post_column_ref确认变量存在,并在Query树上挂Param节点记录变量在PL变量数组中的位置和类型。
  2. 在优化器中,走钩子函数plpgsql_param_fetch拿变量具体的值,然后用Const常量节点替换Param变量节点。

1 _SPI_prepare_plan→语义分析:transform阶段回调plpgsql_post_column_ref得到指向kk的Param

#0  make_datum_param (expr=0x2c508f0, dno=1, location=23) at pl_comp.c:1362
#1  0x00007fbb4f3d4499 in resolve_column_ref (pstate=0x2c56130, expr=0x2c508f0, cref=0x2c55e10, error_if_no_field=true) at pl_comp.c:1279
#2  0x00007fbb4f3d4048 in plpgsql_post_column_ref (pstate=0x2c56130, cref=0x2c55e10, var=0x0) at pl_comp.c:1125
#3  0x000000000063244f in transformColumnRef (pstate=0x2c56130, cref=0x2c55e10) at parse_expr.c:804
#4  0x0000000000631121 in transformExprRecurse (pstate=0x2c56130, expr=0x2c55e10) at parse_expr.c:137
#5  0x00000000006310b3 in transformExpr (pstate=0x2c56130, expr=0x2c55e10, exprKind=EXPR_KIND_VALUES_SINGLE) at parse_expr.c:116
#6  0x000000000064a231 in transformExpressionList (pstate=0x2c56130, exprlist=0x2c55eb0, exprKind=EXPR_KIND_VALUES_SINGLE, allowDefault=true) at parse_target.c:272
#7  0x00000000005e88db in transformInsertStmt (pstate=0x2c56130, stmt=0x2c56060) at analyze.c:889
#8  0x00000000005e79be in transformStmt (pstate=0x2c56130, parseTree=0x2c56060) at analyze.c:344
#9  0x00000000005e792f in transformOptionalSelectInto (pstate=0x2c56130, parseTree=0x2c56060) at analyze.c:306
#10 0x00000000005e77f3 in transformTopLevelStmt (pstate=0x2c56130, parseTree=0x2c560b0) at analyze.c:256
#11 0x00000000005e76de in parse_analyze_withcb (parseTree=0x2c560b0, sourceText=0x2c50980 "insert into d1 values (kk)", parserSetup=0x7fbb4f3d3f1d <plpgsql_parser_setup>, parserSetupArg=0x2c508f0, queryEnv=0x0) at analyze.c:203
#12 0x00000000009b71b6 in pg_analyze_and_rewrite_withcb (parsetree=0x2c560b0, query_string=0x2c50980 "insert into d1 values (kk)", parserSetup=0x7fbb4f3d3f1d <plpgsql_parser_setup>, parserSetupArg=0x2c508f0, queryEnv=0x0) at postgres.c:781
#13 0x000000000079906a in _SPI_prepare_plan (src=0x2c50980 "insert into d1 values (kk)", plan=0x7ffe8928dc90) at spi.c:2265
#14 0x0000000000796df8 in SPI_prepare_extended (src=0x2c50980 "insert into d1 values (kk)", options=0x7ffe8928dd10) at spi.c:925
#15 0x00007fbb4f3de778 in exec_prepare_plan (estate=0x7ffe8928e060, expr=0x2c508f0, cursorOptions=2048) at pl_exec.c:4193
#16 0x00007fbb4f3de898 in exec_stmt_execsql (estate=0x7ffe8928e060, stmt=0x2c509b0) at pl_exec.c:4233
#17 0x00007fbb4f3da092 in exec_stmts (estate=0x7ffe8928e060, stmts=0x2c50840) at pl_exec.c:2091
#18 0x00007fbb4f3d9c68 in exec_stmt_block (estate=0x7ffe8928e060, block=0x2c50a00) at pl_exec.c:1942
#19 0x00007fbb4f3d946d in exec_toplevel_block (estate=0x7ffe8928e060, block=0x2c50a00) at pl_exec.c:1633
#20 0x00007fbb4f3d7415 in plpgsql_exec_function (func=0x2c53de0, fcinfo=0x7ffe8928e2a0, simple_eval_estate=0x2c4b748, simple_eval_resowner=0x2b40478, procedure_resowner=0x2b40478, atomic=false) at pl_exec.c:622
#21 0x00007fbb4f3f1dae in plpgsql_inline_handler (fcinfo=0x7ffe8928e390) at pl_handler.c:368
#22 0x0000000000b80adb in FunctionCall1Coll (flinfo=0x7ffe8928e3f0, collation=0, arg1=46500088) at fmgr.c:1110
#23 0x0000000000b816c1 in OidFunctionCall1Coll (functionId=14272, collation=0, arg1=46500088) at fmgr.c:1388
#24 0x00000000006a6c87 in ExecuteDoStmt (pstate=0x2c587e8, stmt=0x2b45a48, atomic=false) at functioncmds.c:2144
#25 0x00000000009bff91 in standard_ProcessUtility (pstmt=0x2b45ae8, queryString=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;", readOnlyTree=false, context=PROCESS_UTILITY_TOPLEVEL, params=0x0, queryEnv=0x0, dest=0x2b45da8, qc=0x7ffe8928e8a0) at utility.c:714
#26 0x00000000009bfaa8 in ProcessUtility (pstmt=0x2b45ae8, queryString=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;", readOnlyTree=false, context=PROCESS_UTILITY_TOPLEVEL, params=0x0, queryEnv=0x0, dest=0x2b45da8, qc=0x7ffe8928e8a0) at utility.c:530
#27 0x00000000009be6e9 in PortalRunUtility (portal=0x2bf0388, pstmt=0x2b45ae8, isTopLevel=true, setHoldSnapshot=false, dest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:1158
#28 0x00000000009be943 in PortalRunMulti (portal=0x2bf0388, isTopLevel=true, setHoldSnapshot=false, dest=0x2b45da8, altdest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:1315
#29 0x00000000009bde7b in PortalRun (portal=0x2bf0388, count=9223372036854775807, isTopLevel=true, run_once=true, dest=0x2b45da8, altdest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:791
#30 0x00000000009b7962 in exec_simple_query (query_string=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;") at postgres.c:1274
#31 0x00000000009bbfc5 in PostgresMain (dbname=0x2b7c310 "postgres", username=0x2b7c2f8 "mingjie") at postgres.c:4632
#32 0x00000000008f31f6 in BackendRun (port=0x2b70670) at postmaster.c:4461
#33 0x00000000008f2b8f in BackendStartup (port=0x2b70670) at postmaster.c:4189
#34 0x00000000008ef45a in ServerLoop () at postmaster.c:1779
#35 0x00000000008eee2a in PostmasterMain (argc=1, argv=0x2b3ea80) at postmaster.c:1463
#36 0x00000000007b988e in main (argc=1, argv=0x2b3ea80) at main.c:198

注意Param只是一个指针,指向var,并没有存放具体的值:
在这里插入图片描述

2 _SPI_prepare_plan→语义分析:transformColumnRef拿到hook返回的Param

拿到Pl返回的Param

transformColumnRef......if (pstate->p_post_columnref_hook != NULL){Node	   *hookresult;hookresult = pstate->p_post_columnref_hook(pstate, cref, node);if (node == NULL)node = hookresult;else if (hookresult != NULL)ereport(ERROR,(errcode(ERRCODE_AMBIGUOUS_COLUMN),errmsg("column reference \"%s\" is ambiguous",NameListToString(cref->fields)),parser_errposition(pstate, cref->location)));}...

transformInsertStmt流程

transformInsertStmt......exprList = transformExpressionListtransformExprtransformExprRecursetransformColumnRef <- plpgsql_post_column_ref <- resolve_column_ref <- make_datum_param......result = lappend(result, e);exprList = transformInsertRow...transformAssignedExpr...type_id = exprType((Node *) expr);   // 1043coerce_to_target_type                // 类型转换,当前不需要

在这里插入图片描述

transformInsertStmt最后结果:
在这里插入图片描述

3 _SPI_execute_plan→优化器:preprocess_expression根据Param记录的位置走钩子paramFetch→plpgsql_param_fetch拿值

进入优化器:

#0  pg_plan_queries (querytrees=0x2c55798, query_string=0x2c625a0 "insert into d1 values (kk)", cursorOptions=2048, boundParams=0x2c62dc8) at postgres.c:975
#1  0x0000000000b5f6b3 in BuildCachedPlan (plansource=0x2c654d8, qlist=0x2c55798, boundParams=0x2c62dc8, queryEnv=0x0) at plancache.c:937
#2  0x0000000000b5fd69 in GetCachedPlan (plansource=0x2c654d8, boundParams=0x2c62dc8, owner=0x2b7dc00, queryEnv=0x0) at plancache.c:1219
#3  0x00000000007996a4 in _SPI_execute_plan (plan=0x2b6cfb8, options=0x7ffe8928dd00, snapshot=0x0, crosscheck_snapshot=0x0, fire_triggers=true) at spi.c:2555
#4  0x0000000000796997 in SPI_execute_plan_with_paramlist (plan=0x2b6cfb8, params=0x2c62dc8, read_only=false, tcount=0) at spi.c:749
#5  0x00007fbb4f3dea13 in exec_stmt_execsql (estate=0x7ffe8928e060, stmt=0x2c509b0) at pl_exec.c:4292
#6  0x00007fbb4f3da092 in exec_stmts (estate=0x7ffe8928e060, stmts=0x2c50840) at pl_exec.c:2091
#7  0x00007fbb4f3d9c68 in exec_stmt_block (estate=0x7ffe8928e060, block=0x2c50a00) at pl_exec.c:1942
#8  0x00007fbb4f3d946d in exec_toplevel_block (estate=0x7ffe8928e060, block=0x2c50a00) at pl_exec.c:1633
#9  0x00007fbb4f3d7415 in plpgsql_exec_function (func=0x2c53de0, fcinfo=0x7ffe8928e2a0, simple_eval_estate=0x2c4b748, simple_eval_resowner=0x2b40478, procedure_resowner=0x2b40478, atomic=false) at pl_exec.c:622
#10 0x00007fbb4f3f1dae in plpgsql_inline_handler (fcinfo=0x7ffe8928e390) at pl_handler.c:368
#11 0x0000000000b80adb in FunctionCall1Coll (flinfo=0x7ffe8928e3f0, collation=0, arg1=46500088) at fmgr.c:1110
#12 0x0000000000b816c1 in OidFunctionCall1Coll (functionId=14272, collation=0, arg1=46500088) at fmgr.c:1388
#13 0x00000000006a6c87 in ExecuteDoStmt (pstate=0x2c587e8, stmt=0x2b45a48, atomic=false) at functioncmds.c:2144
#14 0x00000000009bff91 in standard_ProcessUtility (pstmt=0x2b45ae8, queryString=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;", readOnlyTree=false, context=PROCESS_UTILITY_TOPLEVEL, params=0x0, queryEnv=0x0, dest=0x2b45da8, qc=0x7ffe8928e8a0) at utility.c:714
#15 0x00000000009bfaa8 in ProcessUtility (pstmt=0x2b45ae8, queryString=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;", readOnlyTree=false, context=PROCESS_UTILITY_TOPLEVEL, params=0x0, queryEnv=0x0, dest=0x2b45da8, qc=0x7ffe8928e8a0) at utility.c:530
#16 0x00000000009be6e9 in PortalRunUtility (portal=0x2bf0388, pstmt=0x2b45ae8, isTopLevel=true, setHoldSnapshot=false, dest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:1158
#17 0x00000000009be943 in PortalRunMulti (portal=0x2bf0388, isTopLevel=true, setHoldSnapshot=false, dest=0x2b45da8, altdest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:1315
#18 0x00000000009bde7b in PortalRun (portal=0x2bf0388, count=9223372036854775807, isTopLevel=true, run_once=true, dest=0x2b45da8, altdest=0x2b45da8, qc=0x7ffe8928e8a0) at pquery.c:791
#19 0x00000000009b7962 in exec_simple_query (query_string=0x2b44e78 "do $$\ndeclare\n kk varchar(32);\nbegin\n  kk := 'abcd';\n  insert into d1 values (kk);\nend;\n$$;") at postgres.c:1274
#20 0x00000000009bbfc5 in PostgresMain (dbname=0x2b7c310 "postgres", username=0x2b7c2f8 "mingjie") at postgres.c:4632
#21 0x00000000008f31f6 in BackendRun (port=0x2b70670) at postmaster.c:4461
#22 0x00000000008f2b8f in BackendStartup (port=0x2b70670) at postmaster.c:4189
#23 0x00000000008ef45a in ServerLoop () at postmaster.c:1779
#24 0x00000000008eee2a in PostmasterMain (argc=1, argv=0x2b3ea80) at postmaster.c:1463
#25 0x00000000007b988e in main (argc=1, argv=0x2b3ea80) at main.c:198

进入时的query树:

优化器preprocess_expression函数执行转换:

pg_plan_queries→pg_plan_query→planner→standard_planner→subquery_planner→preprocess_expression
在这里插入图片描述

preprocess_expressioneval_const_expressionseval_const_expressions_mutator层层递归遍历表达式,因为kk可以写成表达式kk || 'ddd'等等eval_const_expressions_mutatorcase T_Param:钩子拿值prm = paramLI->paramFetch(paramLI, param->paramid,true, &prmdata);进入PL堆栈plpgsql_param_fetch

拿到值后构造const常量,执行时看到的就是Const了。

执行时

plan中的expr已经变成const常量了。代表’abcd’字符串。
在这里插入图片描述

这篇关于Postgresql源码(112)plpgsql执行sql时变量何时替换为值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/251380

相关文章

SQL中的外键约束

外键约束用于表示两张表中的指标连接关系。外键约束的作用主要有以下三点: 1.确保子表中的某个字段(外键)只能引用父表中的有效记录2.主表中的列被删除时,子表中的关联列也会被删除3.主表中的列更新时,子表中的关联元素也会被更新 子表中的元素指向主表 以下是一个外键约束的实例展示

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

如何去写一手好SQL

MySQL性能 最大数据量 抛开数据量和并发数,谈性能都是耍流氓。MySQL没有限制单表最大记录数,它取决于操作系统对文件大小的限制。 《阿里巴巴Java开发手册》提出单表行数超过500万行或者单表容量超过2GB,才推荐分库分表。性能由综合因素决定,抛开业务复杂度,影响程度依次是硬件配置、MySQL配置、数据表设计、索引优化。500万这个值仅供参考,并非铁律。 博主曾经操作过超过4亿行数据

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

MySQL数据库宕机,启动不起来,教你一招搞定!

作者介绍:老苏,10余年DBA工作运维经验,擅长Oracle、MySQL、PG、Mongodb数据库运维(如安装迁移,性能优化、故障应急处理等)公众号:老苏畅谈运维欢迎关注本人公众号,更多精彩与您分享。 MySQL数据库宕机,数据页损坏问题,启动不起来,该如何排查和解决,本文将为你说明具体的排查过程。 查看MySQL error日志 查看 MySQL error日志,排查哪个表(表空间

变量与命名

引言         在前两个课时中,我们已经了解了 Python 程序的基本结构,学习了如何正确地使用缩进来组织代码,并且知道了注释的重要性。现在我们将进一步深入到 Python 编程的核心——变量与命名。变量是我们存储数据的主要方式,而合理的命名则有助于提高代码的可读性和可维护性。 变量的概念与使用         在 Python 中,变量是一种用来存储数据值的标识符。创建变量很简单,

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

MySQL高性能优化规范

前言:      笔者最近上班途中突然想丰富下自己的数据库优化技能。于是在查阅了多篇文章后,总结出了这篇! 数据库命令规范 所有数据库对象名称必须使用小写字母并用下划线分割 所有数据库对象名称禁止使用mysql保留关键字(如果表名中包含关键字查询时,需要将其用单引号括起来) 数据库对象的命名要能做到见名识意,并且最后不要超过32个字符 临时库表必须以tmp_为前缀并以日期为后缀,备份

[MySQL表的增删改查-进阶]

🌈个人主页:努力学编程’ ⛅个人推荐: c语言从初阶到进阶 JavaEE详解 数据结构 ⚡学好数据结构,刷题刻不容缓:点击一起刷题 🌙心灵鸡汤:总有人要赢,为什么不能是我呢 💻💻💻数据库约束 🔭🔭🔭约束类型 not null: 指示某列不能存储 NULL 值unique: 保证某列的每行必须有唯一的值default: 规定没有给列赋值时的默认值.primary key:

Java ArrayList扩容机制 (源码解读)

结论:初始长度为10,若所需长度小于1.5倍原长度,则按照1.5倍扩容。若不够用则按照所需长度扩容。 一. 明确类内部重要变量含义         1:数组默认长度         2:这是一个共享的空数组实例,用于明确创建长度为0时的ArrayList ,比如通过 new ArrayList<>(0),ArrayList 内部的数组 elementData 会指向这个 EMPTY_EL