Инструкция по установке PostgreSQL 17 из исходного кода на Альт Сервер

«Пост-Грэс-Кью-Эл» свободная объектно-реляционная СУБД. Обмениваемся вопросами и ответами о её работе.
Ответить
AntonS
Сообщения: 130
Зарегистрирован: Пт июн 03, 2022 8:51 am

Инструкция по установке PostgreSQL 17 из исходного кода на Альт Сервер

Сообщение AntonS »

В большинстве случаев установка СУБД из двоичных пакетов дистрибутивов Linux или репозиториев postgresql.org предпочтительна.
Но в случае недоступности дистрибутива и пакетов соответвующей версии, возможна установка PostgreSQL из исходного кода.
Установка из исходного кода подробно описана в документации. Есть и краткий вариант установки с использованием Autoconf и Make.
Ранее на форуме опубликована инструкция по установке PostgreSQL из исходного кода на Astra Linux

Данный вариант инструкции включает минимум команд и настроек для установки PostgreSQL 17.5 из исходного кода на Альт Сервер

Выполнение большинства команд от имени sudo и root, отдельные команды от имени пользователя postgres.

Выбор языка системы

Используется en_US.UTF-8

Настройка переменных окружения
В файлах /root/.bashrc для root и /etc/profile для всех пользователей

Код: Выделить всё

LC_CTYPE=en_US.UTF-8
LC_ALL=en_US.UTF-8
PGDATA=/var/lib/postgresql/17/main; export PGDATA;
PATH=$PATH:/usr/local/pgsql/bin; export PATH;
Создание пользователя postgres
При наличии postgres в /etc/passwd, требуется разблокировать вход, заменив /dev/null на /bin/bash
При отсутствии требуется создание:

Код: Выделить всё

useradd -M -d /var/lib/pgsql postgres 
Создание директорий и назначение на них прав

Код: Выделить всё

mkdir /var/lib/pgsql
chown -R postgres:postgres /var/lib/pgsql
mkdir /var/lib/postgresql
mkdir /var/lib/postgresql/17
mkdir /var/lib/postgresql/17/main
chown -R postgres:postgres /var/lib/postgresql
Установка зависимых пакетов
В Альт Сервер по умолчанию могут быть установлены двоичные пакеты postgresql15 и bacula11-director, которые стоит удалить перед установкой PostgreSQL из исходного кода:

Код: Выделить всё

apt-get remove postgresql15

Код: Выделить всё

apt-get update
apt-get install rpm-build
apt-get install libreadline-devel
apt-get install zlib-devel
apt-get install libsystemd-devel
apt-get install libicu-devel
apt-get install flex
Пакеты bison и pkg-config устанавливаются выше в числе зависимостей.

Пакет git может потребоваться для получения исходных кодов дополнительных модулей:

Код: Выделить всё

apt-get install -y git
Загрузка и распаковка дистрибутива
Дистрибутив может быть загружен например отсюда https://www.postgresql.org/ftp/source/

Код: Выделить всё

cd /opt
tar xf postgresql-17.5.tar.bz2
Конфигурирование, сборка, установка

Код: Выделить всё

cd /opt/postgresql-17.5
./configure --with-systemd --enable-debug
make world-bin
make install-world-bin
Создание кластера СУБД
Подключение пользователем postgres

Код: Выделить всё

su - postgres

initdb -k

exit
Создание файла описания и запуска службы

Содержание файла параметров окружения, например /etc/default/postgresql-17
PGDATA=/var/lib/postgresql/17/main

Содержание файла описания службы, например /etc/systemd/system/postgresql.service
# For example, if you want to change the server's port number to 5433,
# create a file named "/etc/systemd/system/postgresql.service" containing:
# .include /lib/systemd/system/postgresql.service
# [Service]
# Environment=PGPORT=5433
# This will override the setting appearing below.

# Note: changing PGPORT or PGDATA will typically require adjusting SELinux
# configuration as well;

# Note: do not use a PGDATA pathname containing spaces, or you will
# break initdb.sh.
[Unit]
Description=PostgreSQL 17 database server
After=syslog.target
After=network.target

[Service]
Type=notify

User=postgres
Group=postgres

# Disable OOM kill on the postmaster
OOMScoreAdjust=-1000
Environment=PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
Environment=PG_OOM_ADJUST_VALUE=0

# Adjust PATH to include ourn binary directory first
Environment=PATH=/usr/local/pgsql/bin:/usr/sbin:/usr/bin:/bin:/sbin:/usr/local/bin
# Location of database directory and other tunable parameters

EnvironmentFile=/etc/default/postgresql-17
# Where to send early-startup messages from the server (before the logging
# options of postgresql.conf take effect)
# This is normally controlled by the global default set by systemd
# StandardOutput=syslog

ExecStart=/usr/local/pgsql/bin/postgres -D ${PGDATA}
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
KillSignal=SIGINT
# Postgres can take long time to start, so set infinite timeout
TimeoutSec=0
TimeoutStartSec=0
TimeoutStopSec=1h

[Install]
WantedBy=multi-user.target

Подобрнее в разделе запуск сервера баз данных

Включение автозапуска службы

Код: Выделить всё

systemctl enable postgresql
systemctl start postgresql
Проверка соединения

Код: Выделить всё

su - postgres

psql

postgres=# SELECT version();
                                         version                                                 
---------------------------------------------------------------------------------------------
 PostgreSQL 17.5 on x86_64-pc-linux-gnu, compiled by x86_64-alt-linux-gcc (GCC), 64-bit
(1 row)
Последний раз редактировалось AntonS Сб фев 21, 2026 9:26 am, всего редактировалось 5 раз.
AntonS
Сообщения: 130
Зарегистрирован: Пт июн 03, 2022 8:51 am

Re: Инструкция по установке PostgreSQL 17 из исходного кода на Альт Сервер

Сообщение AntonS »

Настройка модуля pg_stat_statements для отслеживания статистики SQL-запросов

Поскольку сервер PostgreSQL собран со всем, что может быть собрано, включая дополнительные модули (contrib), такие модули сразу становятся доступны.

Список доступных расширений:

Код: Выделить всё

postgres=# SELECT * FROM pg_available_extensions;
        name        | default_version | installed_version |                                comment
--------------------+-----------------+-------------------+------------------------------------------------------------------------
 amcheck            | 1.4             |                   | functions for verifying relation integrity
 pg_visibility      | 1.2             |                   | examine the visibility map (VM) and page-level visibility info
 pg_surgery         | 1.0             |                   | extension to perform surgery on a damaged relation
 refint             | 1.0             |                   | functions for implementing referential integrity (obsolete)
 pg_prewarm         | 1.2             |                   | prewarm relation data
 file_fdw           | 1.0             |                   | foreign-data wrapper for flat file access
 dict_int           | 1.0             |                   | text search dictionary template for integers
 pg_buffercache     | 1.5             |                   | examine the shared buffer cache
 earthdistance      | 1.2             |                   | calculate great-circle distances on the surface of the Earth
 dblink             | 1.2             |                   | connect to other PostgreSQL databases from within a database
 pgrowlocks         | 1.2             |                   | show row-level locking information
 intarray           | 1.5             |                   | functions, operators, and index support for 1-D arrays of integers
 pg_trgm            | 1.6             |                   | text similarity measurement and index searching based on trigrams
 pageinspect        | 1.12            |                   | inspect the contents of database pages at a low level
 insert_username    | 1.0             |                   | functions for tracking who changed a table
 unaccent           | 1.1             |                   | text search dictionary that removes accents
 dict_xsyn          | 1.0             |                   | text search dictionary template for extended synonym processing
 seg                | 1.4             |                   | data type for representing line segments or floating-point intervals
 tcn                | 1.0             |                   | Triggered change notifications
 bloom              | 1.0             |                   | bloom access method - signature file based index
 lo                 | 1.1             |                   | Large Object maintenance
 ltree              | 1.3             |                   | data type for hierarchical tree-like structures
 plpgsql            | 1.0             | 1.0               | PL/pgSQL procedural language
 tsm_system_time    | 1.0             |                   | TABLESAMPLE method which accepts time in milliseconds as a limit
 pgstattuple        | 1.5             |                   | show tuple-level statistics
 pg_stat_statements | 1.11            |                   | track planning and execution statistics of all SQL statements executed
 postgres_fdw       | 1.1             |                   | foreign-data wrapper for remote PostgreSQL servers
 btree_gin          | 1.3             |                   | support for indexing common datatypes in GIN
 tablefunc          | 1.0             |                   | functions that manipulate whole tables, including crosstab
 autoinc            | 1.0             |                   | functions for autoincrementing fields
 citext             | 1.6             |                   | data type for case-insensitive character strings
 intagg             | 1.1             |                   | integer aggregator and enumerator (obsolete)
 moddatetime        | 1.0             |                   | functions for tracking last modification time
 fuzzystrmatch      | 1.2             |                   | determine similarities and distance between strings
 pg_walinspect      | 1.1             |                   | functions to inspect contents of PostgreSQL Write-Ahead Log
 cube               | 1.5             |                   | data type for multidimensional cubes
 pg_freespacemap    | 1.2             |                   | examine the free space map (FSM)
 hstore             | 1.8             |                   | data type for storing sets of (key, value) pairs
 btree_gist         | 1.7             |                   | support for indexing common datatypes in GiST
 isn                | 1.2             |                   | data types for international product numbering standards
 tsm_system_rows    | 1.0             |                   | TABLESAMPLE method which accepts number of rows as a limit
(41 rows)
Чтобы установить внутри базы данных расширение pg_stat_statements и начать отслеживать статистику SQL-запросов, достаточно
указать параметры в postgresql.conf и затем перезапустить PostgreSQL:

Код: Выделить всё

# postgresql.conf
shared_preload_libraries = 'pg_stat_statements'

compute_query_id = on
pg_stat_statements.max = 10000
pg_stat_statements.track = all
Затем в psql:

Код: Выделить всё

\c postgres
CREATE EXTENSION pg_stat_statements;
Модуль появился в списке расширений, установленных в базе postgres:

Код: Выделить всё

postgres=# \dx
                                            List of installed extensions
        Name        | Version |   Schema   |                              Description
--------------------+---------+------------+------------------------------------------------------------------------
 pg_stat_statements | 1.11    | public     | track planning and execution statistics of all SQL statements executed
 plpgsql            | 1.0     | pg_catalog | PL/pgSQL procedural language
Отслеживаем статистику SQL-запросов через представление pg_stat_statements, приведена пара случайных запросов для примера:

Код: Выделить всё

postgres=# SELECT * FROM pg_stat_statements LIMIT 2 \gx
-[ RECORD 1 ]----------+--------------------------------------------------------------------------
userid                 | 10
dbid                   | 5
toplevel               | f
queryid                | 7388764004403683175
query                  | /* contrib/pg_stat_statements/pg_stat_statements--1.7--1.8.sql */        +
                       |                                                                          +
                       | -- complain if script is sourced in psql, rather than via ALTER EXTENSION+
                       |                                                                          +
                       |                                                                          +
                       | /* First we have to remove them from the extension */                    +
                       | ALTER EXTENSION pg_stat_statements DROP VIEW pg_stat_statements
plans                  | 0
total_plan_time        | 0
min_plan_time          | 0
max_plan_time          | 0
mean_plan_time         | 0
stddev_plan_time       | 0
calls                  | 3
total_exec_time        | 1.227774
min_exec_time          | 0.294614
max_exec_time          | 0.497765
mean_exec_time         | 0.409258
stddev_exec_time       | 0.08497034493280584
rows                   | 0
shared_blks_hit        | 479
shared_blks_read       | 0
shared_blks_dirtied    | 0
shared_blks_written    | 0
local_blks_hit         | 0
local_blks_read        | 0
local_blks_dirtied     | 0
local_blks_written     | 0
temp_blks_read         | 0
temp_blks_written      | 0
shared_blk_read_time   | 0
shared_blk_write_time  | 0
local_blk_read_time    | 0
local_blk_write_time   | 0
temp_blk_read_time     | 0
temp_blk_write_time    | 0
wal_records            | 12
wal_fpi                | 0
wal_bytes              | 648
jit_functions          | 0
jit_generation_time    | 0
jit_inlining_count     | 0
jit_inlining_time      | 0
jit_optimization_count | 0
jit_optimization_time  | 0
jit_emission_count     | 0
jit_emission_time      | 0
jit_deform_count       | 0
jit_deform_time        | 0
stats_since            | 2025-07-15 08:33:42.236148+03
minmax_stats_since     | 2025-07-15 08:33:42.236148+03
-[ RECORD 2 ]----------+--------------------------------------------------------------------------
userid                 | 10
dbid                   | 5
toplevel               | f
queryid                | -6038050342610509136
query                  | GRANT SELECT ON pg_stat_statements_info TO PUBLIC
plans                  | 0
total_plan_time        | 0
min_plan_time          | 0
max_plan_time          | 0
mean_plan_time         | 0
stddev_plan_time       | 0
calls                  | 1
total_exec_time        | 0.152788
min_exec_time          | 0.152788
max_exec_time          | 0.152788
mean_exec_time         | 0.152788
stddev_exec_time       | 0
rows                   | 0
shared_blks_hit        | 20
shared_blks_read       | 0
shared_blks_dirtied    | 0
shared_blks_written    | 0
local_blks_hit         | 0
local_blks_read        | 0
local_blks_dirtied     | 0
local_blks_written     | 0
temp_blks_read         | 0
temp_blks_written      | 0
shared_blk_read_time   | 0
shared_blk_write_time  | 0
local_blk_read_time    | 0
local_blk_write_time   | 0
temp_blk_read_time     | 0
temp_blk_write_time    | 0
wal_records            | 3
wal_fpi                | 0
wal_bytes              | 322
jit_functions          | 0
jit_generation_time    | 0
jit_inlining_count     | 0
jit_inlining_time      | 0
jit_optimization_count | 0
jit_optimization_time  | 0
jit_emission_count     | 0
jit_emission_time      | 0
jit_deform_count       | 0
jit_deform_time        | 0
stats_since            | 2025-07-15 08:33:42.247062+03
minmax_stats_since     | 2025-07-15 08:33:42.247062+03
Ответить