PG在还没有pg_class的时候怎么访问基础系统表?

在没有pg_class的时候,数据库怎么访问系统表?这个问题可以分成两个阶段来看:

  1. 数据库簇初始化,此时一个database都没有,所以怎么构造和访问pg_class等系统表是一个问题
  2. 私有内存初始化系统表。PG的系统表信息是放在backend本地进程上的,backend在初始化的时候又怎么load pg_class?

初始化数据字典

在数据库还没有初始化的时候,明显是不能通过访问数据字典来初始化database、pg_class等等对象的,因为一个库都没有就不能create database,也没有pg_class去查元数据信息。
PG通过bki文件的特殊语言初始化一些数据结构,然后在bootstrap模式初始化一个原始database1

编译阶段:genbki.h & genbki.pl

src/include/catalog/genbki.h

 * genbki.h defines CATALOG(), BKI_BOOTSTRAP and related macros* so that the catalog header files can be read by the C compiler.* (These same words are recognized by genbki.pl to build the BKI* bootstrap file from these header files.)

genbki.h内容很少,主要是为了catalog相关操作的宏定义,以及给KBI bootstrap文件的宏定义。数据字典的头文件基本都包含genbki.h
genbki.pl会在编译过程读取/src/include/catalog目录下的.h表定义文件(不含pg_*_d.h),并创建postgres.bki文件和pg_*_d.h头文件。
以pg_class为例:

[postgres@catalog]$ ll |grep pg_class 
-rw-r----- 1 postgres postgres   3682 Aug  6  2019 pg_class.dat
lrwxrwxrwx 1 postgres postgres     86 Apr  8 20:31 pg_class_d.h -> /lzl/soft/postgresql-11.5/src/backend/catalog/pg_class_d.h
-rw-r----- 1 postgres postgres   5219 Aug  6  2019 pg_class.h

pg_*_d.h头文件就是genbki.pl生成的。pg_*_d.h文件中都包含下面的一段话:

It has been GENERATED by src/backend/catalog/genbki.pl

每个数据字典都有一个结构体typedef struct FormData_*catalogname*用以存储数据字典的行数据2,例如pg_class的FormData_pg_class

CATALOG(pg_class,1259,RelationRelationId) BKI_BOOTSTRAP BKI_ROWTYPE_OID(83,RelationRelation_Rowtype_Id) BKI_SCHEMA_MACRO
{/* oid */Oid			oid;/* class name */NameData	relname;/* OID of namespace containing this class */Oid			relnamespace BKI_DEFAULT(pg_catalog) BKI_LOOKUP(pg_namespace);/* OID of entry in pg_type for relation's implicit row type, if any */Oid			reltype BKI_LOOKUP_OPT(pg_type);/* OID of entry in pg_type for underlying composite type, if any */Oid			reloftype BKI_DEFAULT(0) BKI_LOOKUP_OPT(pg_type);/* class owner */Oid			relowner BKI_DEFAULT(POSTGRES) BKI_LOOKUP(pg_authid);.../* access-method-specific options */text		reloptions[1] BKI_DEFAULT(_null_);/* partition bound node tree */pg_node_tree relpartbound BKI_DEFAULT(_null_);
#endif
} FormData_pg_class;

pg_class的OID写死了1259,所有字段都在FormData_pg_class结构体中。
用户存储数据的结构体初始化后,会使用对应的.dat文件插入基础数据。pg_class中会插入4条数据,可以理解为bootstrap item(pg15中的数据字典表有49个):

{ oid => '1247',relname => 'pg_type', reltype => 'pg_type' },
{ oid => '1249',relname => 'pg_attribute', reltype => 'pg_attribute' },
{ oid => '1255',relname => 'pg_proc', reltype => 'pg_proc' },
{ oid => '1259',relname => 'pg_class', reltype => 'pg_class' },
postgres=#  select oid,relname from  pg_class where oid::int >=1247 and oid::int<=1259;oid  |   relname    
------+--------------1247 | pg_type1249 | pg_attribute1255 | pg_proc1259 | pg_class

把基础数据字典写入后,其他的都可以依赖这些数据生成。

初始化database阶段:initdb&postgres.bki

initdb.c中的注释:

 * To create template1, we run the postgres (backend) program in bootstrap* mode and feed it data from the postgres.bki library file.  After this* initial bootstrap phase, some additional stuff is created by normal* SQL commands fed to a standalone backend. 

以bootstrap模式启动backend并运行postgres.bki脚本,postgres.bki可以在没有任何系统表的情况下,执行相关函数。此后才可以使用正常的SQL文件和启动标准的backend进程。
template1可以称之为bootstrap database了,postgres、template0两个库是在template1建立以后才创建:

void
initialize_data_directory(void)
{
.../* Bootstrap template1 */bootstrap_template1();
...make_template0(cmdfd);make_postgres(cmdfd);PG_CMD_CLOSE;check_ok();
}

有了template1后,make_template0make_postgres创建对应的template0 database和postgres database,直接用一般的SQL语句CREATE DATABASE命令创建:

/** copy template1 to postgres*/
static void
make_postgres(FILE *cmdfd)
{const char *const *line;/** Just as we did for template0, and for the same reasons, assign a fixed* OID to postgres and select the file_copy strategy.*/static const char *const postgres_setup[] = {"CREATE DATABASE postgres OID = " CppAsString2(PostgresDbOid)" STRATEGY = file_copy;\n\n","COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",NULL};for (line = postgres_setup; *line; line++)PG_CMD_PUTS(*line);
}

backend本地缓存数据字典

PG私有内存的基础知识可参考PostgreSQL内存浅析3

PG的数据字典信息存放在本地backend进程中,非共享。数据字典缓存主要关注的是syscache/catcache和relcache,他们分别缓存系统表和表模式信息。
其中syscache/catcache是用于缓存系统表的,syscache相当于catcache的上层结构。syscache是一个数组,数字中的每个元素对应一个catcache,每个catcache对应一个系统表1

//PG15.3 SysCacheSize=35
static CatCache *SysCache[SysCacheSize];

pg在fork backend的时候调用的是InitPostgres,其中会调用syscache/catcache和relcache的初始化函数。下面来看看backend的初始化。

syscache/catcache初始化

struct cachedesc
{Oid			reloid;			/* OID of the relation being cached */Oid			indoid;			/* OID of index relation for this cache */int			nkeys;			/* # of keys needed for cache lookup */int			key[4];			/* attribute numbers of key attrs */int			nbuckets;		/* number of hash buckets for this cache */
};static const struct cachedesc cacheinfo[] = {{
...	{RelationRelationId,		/* RELNAMENSP */ClassNameNspIndexId,2,{Anum_pg_class_relname,Anum_pg_class_relnamespace,0,0},128},{RelationRelationId,		/* RELOID */ClassOidIndexId,1,{Anum_pg_class_oid,0,0,0},128
...
};

例如pg_class,由genbki.pl生成的pg_class_d.h中定义Anum_pg_class_oid

#define Anum_pg_class_oid 1

reloid就是oid

  select oid,relname from  pg_class where oid::int >=1247 and oid::int<=1259;oid  |   relname    
------+--------------1259 | pg_class

InitCatalogCache其实是初始化syscache数组,也就是初始化所有的catcache。InitCatalogCache最终通过InitCatCache全量初始化CatCache(这里其中一个就有pg_class的):

void
InitCatalogCache(void)
{
...for (cacheId = 0; cacheId < SysCacheSize; cacheId++){SysCache[cacheId] = InitCatCache(cacheId,cacheinfo[cacheId].reloid,cacheinfo[cacheId].indoid,cacheinfo[cacheId].nkeys,cacheinfo[cacheId].key,cacheinfo[cacheId].nbuckets);if (!PointerIsValid(SysCache[cacheId]))elog(ERROR, "could not initialize cache %u (%d)",cacheinfo[cacheId].reloid, cacheId);/* Accumulate data for OID lists, too */SysCacheRelationOid[SysCacheRelationOidSize++] =cacheinfo[cacheId].reloid;SysCacheSupportingRelOid[SysCacheSupportingRelOidSize++] =cacheinfo[cacheId].reloid;SysCacheSupportingRelOid[SysCacheSupportingRelOidSize++] =cacheinfo[cacheId].indoid;/* see comments for RelationInvalidatesSnapshotsOnly */Assert(!RelationInvalidatesSnapshotsOnly(cacheinfo[cacheId].reloid));}
...CacheInitialized = true;
}

然后来到catcache.c
InitCatCache会开辟内存,并且放到CacheMemoryContext中管理。它也只是把宏定义的一些oid赋值给对应的catcache,此时还没有open表:

/**		InitCatCache**	This allocates and initializes a cache for a system catalog relation.*	Actually, the cache is only partially initialized to avoid opening the*	relation.  The relation will be opened and the rest of the cache*	structure initialized on the first access.*/
CatCache *
InitCatCache(int id,Oid reloid,Oid indexoid,int nkeys,const int *key,int nbuckets)
{
...oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
...sz = sizeof(CatCache) + PG_CACHE_LINE_SIZE;cp = (CatCache *) CACHELINEALIGN(palloc0(sz));cp->cc_bucket = palloc0(nbuckets * sizeof(dlist_head));/** initialize the cache's relation information for the relation* corresponding to this cache, and initialize some of the new cache's* other internal fields.  But don't open the relation yet.*/cp->id = id;cp->cc_relname = "(not known yet)";cp->cc_reloid = reloid;cp->cc_indexoid = indexoid;cp->cc_relisshared = false; /* temporary */cp->cc_tupdesc = (TupleDesc) NULL;cp->cc_ntup = 0;cp->cc_nbuckets = nbuckets;cp->cc_nkeys = nkeys;for (i = 0; i < nkeys; ++i)cp->cc_keyno[i] = key[i];
...MemoryContextSwitchTo(oldcxt);return cp;
}

id是catcache数组元素的编号,赋值的reloid是已知的cacheinfo中的oid,也赋值了cacheinfo中的key[4],其他信息基本都还不知道,例如relname、tupdesc,因为到这里系统表还没有open。
catcache只有在search的时候才有open的操作,虽然函数名字类似*init*,不过已经不在初始化的过程中了,相关函数不再这里展示。
syscache/catcache初始化完成后,实际上是没有任何元组信息的。

relcache初始化

relcache初始化这篇PostgreSQL内存浅析已经讲的比较好了。
relcache初始化由5个阶段:

  • RelationCacheInitialize - 初始化relcache,初始化为空的
  • RelationCacheInitializePhase2 - 初始化共享的catalog,并加载5个global系统表
  • RelationCacheInitializePhase3 - 完成初始化relcache,并加载4个基础系统表
  • RelationIdGetRelation - 通过relation id获得rel描述
  • RelationClose - 关闭一个relation

其中RelationCacheInitializePhase2 RelationCacheInitializePhase3 都有load系统表,他们有先后顺序的必要。
RelationCacheInitializePhase2有兴趣的可以自行查看函数,也load几个系统表;RelationCacheInitializePhase3 是与我们的问题相关的,我们看这个:

/**		RelationCacheInitializePhase3**		This is called as soon as the catcache and transaction system*		are functional and we have determined MyDatabaseId.  At this point*		we can actually read data from the database's system catalogs.*		We first try to read pre-computed relcache entries from the local*		relcache init file.  If that's missing or broken, make phony entries*		for the minimum set of nailed-in-cache relations.  Then (unless*		bootstrapping) make sure we have entries for the critical system*		indexes.  Once we've done all this, we have enough infrastructure to*		open any system catalog or use any catcache.  The last step is to*		rewrite the cache files if needed.*/
void
RelationCacheInitializePhase3(void)
{
...if (IsBootstrapProcessingMode() ||!load_relcache_init_file(false)){needNewCacheFile = true;formrdesc("pg_class", RelationRelation_Rowtype_Id, false,Natts_pg_class, Desc_pg_class);formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,Natts_pg_attribute, Desc_pg_attribute);formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,Natts_pg_proc, Desc_pg_proc);formrdesc("pg_type", TypeRelation_Rowtype_Id, false,Natts_pg_type, Desc_pg_type);#define NUM_CRITICAL_LOCAL_RELS 4	/* fix if you change list above */}MemoryContextSwitchTo(oldcxt);/* In bootstrap mode, the faked-up formrdesc info is all we'll have */if (IsBootstrapProcessingMode())return;.../* now write the files */write_relcache_init_file(true);write_relcache_init_file(false);}
}

IsBootstrapProcessingMode其实是专门为bootstrap模式定制的判断,一般的backend是不满足这个条件的。
load_relcache_init_file(false)尝试从initfile中加载系统表信息,load_relcache_init_file(false)传入的是false表示是私有initfile,不是共享initfile:

[postgres@16384]$ pwd
/pgdata/lzl/data15_6879/base/16384
--粗糙一点看。strings会忽略一部分信息,但是表和列名可以看到
[postgres@16384]$ strings pg_internal.init |grep pg_class
pg_class_oid_index
pg_class
pg_class_relname_nsp_index
[postgres@16384]$ strings pg_internal.init |grep -E "pg_class|relname"
pg_class_oid_index
pg_class
relname
relnamespace
pg_class_relname_nsp_index
relname
relnamespace

如果initfile损坏或者没有,那么加载initfile失败进入判断,去load 4个基础系统表:

	//跟2阶段差不多,加载更多的系统表描述if (IsBootstrapProcessingMode() ||!load_relcache_init_file(false)){needNewCacheFile = true;formrdesc("pg_class", RelationRelation_Rowtype_Id, false,Natts_pg_class, Desc_pg_class);formrdesc("pg_attribute", AttributeRelation_Rowtype_Id, false,Natts_pg_attribute, Desc_pg_attribute);formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false,Natts_pg_proc, Desc_pg_proc);formrdesc("pg_type", TypeRelation_Rowtype_Id, false,Natts_pg_type, Desc_pg_type);

有了pg_class 4个基础表,后面加载系统表信息一切都很简单了

References


  1. 《PostgreSQL内核分析》第2,3章 ↩︎ ↩︎

  2. https://www.postgresql.org/docs/current/system-catalog-declarations.html ↩︎

  3. PostgreSQL内存浅析 ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/44467.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JavaScript(7)——数组

JavaScript中数组的用法与Java差不多&#xff0c;但还是有一些区别 声明数组 语法: let 数组名 [数据1,数据2,数据...] let arr new Array(数据1,数据2,...数据n) 添加数据 数组.push()方法将一个或多个元素添加到数组末尾&#xff0c;并返回该数组新长度 <script>…

机器学习(五) -- 监督学习(7) --SVM1

系列文章目录及链接 上篇&#xff1a;机器学习&#xff08;五&#xff09; -- 监督学习&#xff08;6&#xff09; --逻辑回归 下篇&#xff1a; 前言 tips&#xff1a;标题前有“***”的内容为补充内容&#xff0c;是给好奇心重的宝宝看的&#xff0c;可自行跳过。文章内容被…

如何写好品牌宣传稿提升品牌曝光?看这篇文章就够了

在这个信息爆炸的时代&#xff0c;一句精炼而富有力量的宣传语&#xff0c;足以让品牌在万千竞争者中脱颖而出。撰写一篇成功的品牌宣传稿&#xff0c;不仅是对文字艺术的驾驭&#xff0c;也是对品牌灵魂的深刻洞察与精准传达&#xff0c;更是连接品牌与消费者情感与认知的桥梁…

2024前端面试真题【Vue篇】

Vue 的虚拟DOM 虚拟DOM 虚拟DOM是真实DOM的JavaScript表示。它是一个轻量级的JavaScript对象&#xff0c;可以表示DOM的结构和属性&#xff0c;虚拟DOM与真实DOM一一对应。 在Vue中&#xff0c;每个Vue组件都会维护一个对应的虚拟DOM树。当组件的数据发生变化时&#xff0c;…

蚁剑编码器编写——php木马免杀

蚁剑编码器编写——php木马免杀 我的想法是 木马要先免杀&#xff0c;能够落地&#xff0c;再去考虑流量层面的问题 举几个例子演示一下 命令执行与代码执行是有比较大的区别&#xff0c;蚁剑执行的是php代码&#xff0c;而system&#xff0c;proc_open,passthru,exec,shell_…

Adobe Illustrator 2021 for mac/Win:专业矢量图形设计的巅峰之作

Adobe Illustrator 2021作为Adobe公司旗下的旗舰矢量图形设计软件&#xff0c;无论是对于Mac还是Windows用户&#xff0c;都提供了强大而灵活的设计工具&#xff0c;让设计师们能够轻松应对各种复杂的图形设计挑战。这款软件以其卓越的性能、丰富的功能和友好的用户界面&#x…

后悔没早点考?揭晓六西格玛证书背后的惊人好处

在这个竞争激烈的时代&#xff0c;不断提升自我价值和专业能力是每个职场人士都需要面对的问题。而六西格玛证书&#xff0c;作为一个备受瞩目的职业资格认证&#xff0c;其背后的好处和价值已经远超出了人们的想象。深圳天行健企业管理咨询公司解析如下&#xff1a; 一、提升职…

镍氢电池性能不减,你敢信?

在科技领域&#xff0c;研究者的探索永无止境&#xff0c;尤其在可再生能源和电动交通工具迅速发展的今天&#xff0c;一种成熟的可充电电池技术——镍氢电池&#xff0c;在多个领域中发挥着至关重要的作用。它不仅环保、高效&#xff0c;还具有出色的循环次数特性&#xff0c;…

MySQL Undo Log

总结自bojiangzhou undo log称为撤销日志或回滚日志。在一个事务中进行增删改操作时&#xff0c;都会记录对应的 undo log。在对数据库进行修改前&#xff0c;会先记录对应的 undo log&#xff0c;然后在事务失败或回滚的时候&#xff0c;就可以用这些 undo log 来将数据回滚到…

除自身以外数组的乘积_前缀和

文章目录 1、描述2、思路4、notes6、code 1、描述 题目链接 238.除自身以外数组的乘积 给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素…

iPhone数据恢复篇:iPhone 数据恢复软件有哪些

问题&#xff1a;iPhone 15 最好的免费恢复软件是什么&#xff1f;我一直在寻找一个恢复程序来恢复从iPhone中意外删除的照片&#xff0c;联系人和消息&#xff0c;但是我有很多选择。 谷歌一下&#xff0c;你会发现许多付费或免费的iPhone数据恢复工具&#xff0c;声称它们可…

数据结构--二叉树相关性质

1.性质 1.满二叉树每层节点个数&#xff1a;等比数列 3.&#xff08;重要&#xff09;任意二叉树&#xff1a;度为0&#xff08;叶子节点&#xff09;的比度为2的永远多一个。。度&#xff1a;就是看有多少孩子 如下图解析&#xff1a;&#xff08;用推到归纳来分析&#xff…

【测开能力提升-fastapi框架】介绍简单使用

0. 前期说明 立了很多flag(开了很多专题)&#xff0c;但坚持下来的没几个。也干了很多测试工作(起初是硬件(Acoustic方向)测试 - 业务功能测试 - 接口测试 - 平台功能测试 - 数据库测试 - py自动化测试 - 性能测试 - 嵌入式测试 - 到最后的python测试开发)&#xff0c;最终还是…

股票分析系统设计方案大纲与细节

股票分析系统设计方案大纲与细节 一、引言 随着互联网和金融行业的迅猛发展,股票市场已成为重要的投资渠道。投资者在追求财富增值的过程中,对股票市场的分析和预测需求日益增加。因此,设计并实现一套高效、精准的股票分析系统显得尤为重要。本设计方案旨在提出一个基于大…

3d已经做好的模型怎么改单位?---模大狮模型网

在展览3D模型设计行业中&#xff0c;经常会遇到需要将已完成的模型进行单位转换的需求。这可能涉及从一种度量单位转换为另一种&#xff0c;例如从英制单位转换为公制单位&#xff0c;或者根据特定的展览场地要求进行尺寸调整。本文将探讨如何有效地修改已完成的3D模型的单位&a…

VS Code 扩展如何发布到私有Nexus的正确姿势

VS Code扩展的发布 VS Code 扩展的发布需要使用到vsce&#xff0c;vsce是一个用于打包、发布和管理 VS Code 扩展的命令行工具。可以通过 npm 来全局安装它&#xff1a; npm install -g vsce发布扩展到微软的应用市场 VS Code 的应用市场基于微软自己的 Azure DevOps。要发布…

redis的部署及基本使用

一、redis部署 1、关闭防火墙 关闭防火墙&#xff1a; systemctl stop firewalld.service 状态&#xff1a; firewall-cmd --state 卸载防火墙 yum remove firewalld 2、CentOS7部署redis 1、检查编译运行环境&#xff0c;是否有 GCC 编译器 检查环境&#xff08;gcc&…

防御---001

一、实验拓扑二、要求 1&#xff0c;DMZ区内的服务器&#xff0c;办公区仅能在办公时间内(9:00 - 18:00)可以访问&#xff0c;生产区的的设备全天可以访问. 2&#xff0c;生产区不允许访问互联网&#xff0c;办公区和游客区允许访问互联网 3,办公区设备10.0.2.10不允许访问DMZ…

Linux的tmp目录占用空间100%问题分析和解决

一、背景 系统运行期间&#xff0c;客户突然反馈上传文档传不上去。研发立马排查日志&#xff0c;发现日志中出现大量的“No space avaliable on disk”&#xff0c;下意识应用服务器磁盘满了&#xff0c;赶快连上服务器查看磁盘空间占用情况&#xff1a; 黑人问号脸&#xff…

前端程序员常用快捷键

一些常用的快捷键 我们在开发时为了提高代码编写效率&#xff0c;通常会使用一些快捷键。我们开发工具自带的快捷比较多&#xff0c;我这里不一一列举了&#xff0c;我把一些常用的快捷键拿出来给大家大致讲一讲&#xff0c;我这里以window电脑为例&#xff0c;如果你mac电脑&a…