基于源码学习PostgreSQL-环境准备
PostgreSQL
开发机环境准备
- 创建一个本地Linux虚拟机或购买一个云主机(我使用的操作系统的版本为
Ubuntu 22.04
) - 创建一个用户
postgres
,赋予执行sudo
和su
的权限 - 配置本机到开发机以及开发机到github的
ssh
免密登录
源码编译与安装
- 下载源码:
git clone git@github.com:postgres/postgres.git
- 安装依赖:
sudo apt update
sudo apt full-upgrade
sudo apt install build-essential libreadline-dev zlib1g-dev flex bison libxml2-dev libxslt-dev libssl-dev libcurl4-openssl-dev
- 创建PostgreSQL安装以及数据的目录:
sudo mkdir -p /usr/local/pgsql
sudo chown -R postgres:postgres /usr/local/pgsql
- 编译安装PostgreSQL:
# 安装pkg-config,不然configure执行可能会报错
sudo apt install pkg-config
# 切换到PostgreSQL源码目录、切换分支
git pull origin REL_16_STABLE
git checkout -b mydev origin/REL_16_STABLE
# 执行configure、编译与安装
export CFLAGS="-O0" && ./configure --enable-debug --enable-cassert --prefix=/usr/local/pgsql
make
sudo make install
- 设置环境变量:
echo 'export PATH=/usr/local/pgsql/bin:$PATH' >> ~/.bashrc source ~/.bashrc
初始化并启动PostgreSQL
- 初始化数据库集群:
sudo mkdir /usr/local/pgsql/data
sudo chown postgres:postgres /usr/local/pgsql/data
initdb -D /usr/local/pgsql/data
- 启动PostgreSQL:
pg_ctl -D /usr/local/pgsql/data -l logfile start
- 连接数据库:
psql -d postgres
- 停止PostgreSQL:
pg_ctl -D /usr/local/pgsql/data stop
gdb调试
- 启动并连接到PostgreSQL后,可以使用两种方法获取当前连接的后台服务进程号:
- 执行查询:
select pg_backend_pid();
- 执行命令:
ps -ef | grep postgres:
(结果中的postgres: postgres postgres [local] idle
表示连接的后台服务进程)
- gdb配置:
# 创建配置文件
vim ~/.config/gdb/gdbinit
# 增加下面的配置内容
set auto-load safe-path /
handle SIGUSR1 nostop noprint pass
- gdb attach调试:
gdb postgres
# 如果没有attach的权限,修改ptrace_scope的值
attach xxx
# 添加断点
b planner
continue
# 执行查询,程序中断在Breakpoint 1 at 0x55feaa57d92c: file planner.c, line 278.
SELECT 1;
使用vscode远程调试看代码更方便,这里暂不说明。
PostGIS
源码编译与安装
- 下载源码:
git clone git@github.com:postgis/postgis.git
- 安装依赖:
sudo apt install libgeos-dev libproj-dev gdal-bin libgdal-dev protobuf-c-compiler libprotobuf-c-dev
- 编译PostGIS扩展:
# 切换到PostGIS源码目录、切换分支(tag)
git checkout -b dev_gist tags/3.5.0rc1
# 执行configure、编译与安装
# configure可能失败,如果是autoconf相关的错误,执行 autoreconf --install --force (命令执行后,恢复该命令对头文件做的修改)后再执行configure
# 还是不行的话,在build-aux目录下执行touch config.rpath
export CFLAGS="-O0" && ./configure --enable-debug --enable-assert --with-pgconfig=/usr/local/pgsql/bin/pg_config
make
sudo make install
- 安装PostGIS扩展:
# 在SQL连接中执行下面的命令
CREATE EXTENSION postgis;
SELECT PostGIS_Version();
# 成功安装PostGIS扩展后,执行扩展相关的查询后,扩展就会被加载,这时就可以在PostGIS相关的代码上打断点
SELECT ST_AsText(ST_Intersection(
ST_GeomFromText('POLYGON((1 1,1 3,3 3,3 1,1 1))'),
ST_GeomFromText('POLYGON((0 0,0 2,2 2,2 0,0 0))')
));