Первоисточник: https://postgrespro.ru/education/courses/DBA1
Распаковываем архив
Распаковываем архив с исходными кодами PostgreSQL
student$ tar xzf /home/student/postgresql-10.0.tar.gz
student$ ls -ld /home/student/postgres*
drwxr-xr-x 6 student student 4096 окт 3 2017 /home/student/postgresql-10.0 -rw-rw-r-- 1 student student 25830653 окт 3 2017 /home/student/postgresql-10.0.tar.gz
Создание конфигурации
Если требуется повторно выполнить конфигурацию, например с другими параметрами, то предварительно нужно очистить результаты предыдущего запуска:
$ make distclean
В команде configure можно указать различные параметры конфигурации. Например:
- —prefix — каталог установки, по умолчанию /usr/local/pgsql;
- —enable-debug — для включения отладочной информации.
И многие другие, полный список в документации.
Также принимаются во внимание переменные окружения. Например, CC и CFLAGS настраивают компилятор C.
Будем использовать настройки по умолчанию:
student$ (cd /home/student/postgresql-10.0/; ./configure) 2>/dev/null | tail
config.status: src/include/pg_config_ext.h is unchanged config.status: creating src/interfaces/ecpg/include/ecpg_config.h config.status: src/interfaces/ecpg/include/ecpg_config.h is unchanged config.status: linking src/backend/port/tas/dummy.s to src/backend/port/tas.s config.status: linking src/backend/port/dynloader/linux.c to src/backend/port/dynloader.c config.status: linking src/backend/port/posix_sema.c to src/backend/port/pg_sema.c config.status: linking src/backend/port/sysv_shmem.c to src/backend/port/pg_shmem.c config.status: linking src/backend/port/dynloader/linux.h to src/include/dynloader.h config.status: linking src/include/port/linux.h to src/include/pg_config_os.h config.status: linking src/makefiles/Makefile.linux to src/Makefile.port
Сборка PostgreSQL
Возможные варианты:
- make — сборка только сервера
- make world — сборка сервера, всех расширений и документации
Выбираем сборку только сервера. Установку расширений посмотрим дальше.
student$ (cd /home/student/postgresql-10.0; make) | tail
make -C test/perl all make[2]: Entering directory '/home/student/postgresql-10.0/src/test/perl' make[2]: Nothing to be done for 'all'. make[2]: Leaving directory '/home/student/postgresql-10.0/src/test/perl' make[1]: Leaving directory '/home/student/postgresql-10.0/src' make -C config all make[1]: Entering directory '/home/student/postgresql-10.0/config' make[1]: Nothing to be done for 'all'. make[1]: Leaving directory '/home/student/postgresql-10.0/config' All of PostgreSQL successfully made. Ready to install.
Установка
Теперь выполняем установку. Для этого потребуются права суперпользователя:
student$ (cd /home/student/postgresql-10.0; sudo make install) | tail
/usr/bin/install -c -m 644 ./Makefile.shlib '/usr/local/pgsql/lib/pgxs/src/Makefile.shlib' /usr/bin/install -c -m 644 ./nls-global.mk '/usr/local/pgsql/lib/pgxs/src/nls-global.mk' make[1]: Leaving directory '/home/student/postgresql-10.0/src' make -C config install make[1]: Entering directory '/home/student/postgresql-10.0/config' /bin/mkdir -p '/usr/local/pgsql/lib/pgxs/config' /usr/bin/install -c -m 755 ./install-sh '/usr/local/pgsql/lib/pgxs/config/install-sh' /usr/bin/install -c -m 755 ./missing '/usr/local/pgsql/lib/pgxs/config/missing' make[1]: Leaving directory '/home/student/postgresql-10.0/config' PostgreSQL installation complete.
Если бы собирали сервер с расширениями и документацией (make world), то можно было бы установить все вместе командой sudo make install-world.
Пользователь postgres и каталог PGDATA
Пользователь postgres, под которым будет работать СУБД, предварительно уже создан. Теперь необходимо создать каталог для данных и сделать postgres его владельцем:
student$ sudo mkdir /usr/local/pgsql/data
student$ sudo chown postgres /usr/local/pgsql/data
Этот каталог часто называют PGDATA, по имени переменной окружения, которую удобно использовать при работе с утилитами сервера.
В окружении пользователя postgres учтено, куда устанавливается СУБД и где находится каталог с данными:
postgres$ echo $PGDATA
/usr/local/pgsql/data
postgres$ echo $PATH
/usr/local/pgsql/bin:/home/postgres/bin:/home/postgres/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/snap/bin
Команда для подключения под пользователем postgres: sudo su — postgres
Инициализация и запуск кластера
Для инициализации кластера базы данных используется утилита initdb.
Ключ -k включает подсчет контрольной суммы страниц, что позволяет своевременно обнаруживать повреждение данных. В остальном используем настройки по умолчанию:
postgres$ initdb -k
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.
The database cluster will be initialized with locales
COLLATE: en_US.UTF-8
CTYPE: en_US.UTF-8
MESSAGES: en_US.UTF-8
MONETARY: ru_RU.UTF-8
NUMERIC: ru_RU.UTF-8
TIME: ru_RU.UTF-8
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are enabled.
fixing permissions on existing directory /usr/local/pgsql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok
WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
Success. You can now start the database server using:
pg_ctl -D /usr/local/pgsql/data -l logfile start
Теперь все готово к запуску сервера:
postgres$ pg_ctl -w -l /home/postgres/logfile -D /usr/local/pgsql/data start
waiting for server to start.... done server started
Проверяем работу:
postgres$ psql -c 'select now();'
now
-------------------------------
2019-03-31 15:25:15.735019+03
(1 row)
Мы успешно подключились к серверу и выполнили функцию, возвращающую текущее время.
Установка расширений
Собираем и устанавливаем расширение pgcrypto. Для сборки отдельного расширения, нужно перейти в его каталог и выполнить команду make:
student$ (cd ~/postgresql-10.0/contrib/pgcrypto; make) | tail
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-decrypt.o pgp-decrypt.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-encrypt.o pgp-encrypt.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-info.o pgp-info.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-mpi.o pgp-mpi.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-pubdec.o pgp-pubdec.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-pubenc.o pgp-pubenc.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-pubkey.o pgp-pubkey.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-s2k.o pgp-s2k.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I. -I. -I../../src/include -D_GNU_SOURCE -c -o pgp-pgsql.o pgp-pgsql.c gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -shared -o pgcrypto.so pgcrypto.o px.o px-hmac.o px-crypt.o crypt-gensalt.o crypt-blowfish.o crypt-des.o crypt-md5.o md5.o sha1.o internal.o internal-sha2.o blf.o rijndael.o pgp-mpi-internal.o imath.o mbuf.o pgp.o pgp-armor.o pgp-cfb.o pgp-compress.o pgp-decrypt.o pgp-encrypt.o pgp-info.o pgp-mpi.o pgp-pubdec.o pgp-pubenc.o pgp-pubkey.o pgp-s2k.o pgp-pgsql.o -L../../src/port -L../../src/common -Wl,--as-needed -Wl,-rpath,'/usr/local/pgsql/lib',--enable-new-dtags -lz
Устанавливаем расширение:
student$ (cd ~/postgresql-10.0/contrib/pgcrypto; sudo make install)
/bin/mkdir -p '/usr/local/pgsql/lib' /bin/mkdir -p '/usr/local/pgsql/share/extension' /bin/mkdir -p '/usr/local/pgsql/share/extension' /usr/bin/install -c -m 755 pgcrypto.so '/usr/local/pgsql/lib/pgcrypto.so' /usr/bin/install -c -m 644 ./pgcrypto.control '/usr/local/pgsql/share/extension/' /usr/bin/install -c -m 644 ./pgcrypto--1.3.sql ./pgcrypto--1.2--1.3.sql ./pgcrypto--1.1--1.2.sql ./pgcrypto--1.0--1.1.sql ./pgcrypto--unpackaged--1.0.sql '/usr/local/pgsql/share/extension/'
Подобным образом устанавливается большинство расширений. Но для некоторых требуются дополнительные действия, поэтому перед установкой следует проверить документацию к расширению.
Соберем все расширения из каталога contrib:
student$ (cd ~/postgresql-10.0/contrib; make) | tail
make[1]: Nothing to be done for 'all'. make[1]: Leaving directory '/home/student/postgresql-10.0/contrib/tsm_system_time' make -C unaccent all make[1]: Entering directory '/home/student/postgresql-10.0/contrib/unaccent' make[1]: Nothing to be done for 'all'. make[1]: Leaving directory '/home/student/postgresql-10.0/contrib/unaccent' make -C vacuumlo all make[1]: Entering directory '/home/student/postgresql-10.0/contrib/vacuumlo' make[1]: Nothing to be done for 'all'. make[1]: Leaving directory '/home/student/postgresql-10.0/contrib/vacuumlo'
Устанавливаем:
student$ (cd ~/postgresql-10.0/contrib; sudo make install) | tail
/usr/bin/install -c -m 755 unaccent.so '/usr/local/pgsql/lib/unaccent.so' /usr/bin/install -c -m 644 ./unaccent.control '/usr/local/pgsql/share/extension/' /usr/bin/install -c -m 644 ./unaccent--1.1.sql ./unaccent--1.0--1.1.sql ./unaccent--unpackaged--1.0.sql '/usr/local/pgsql/share/extension/' /usr/bin/install -c -m 644 ./unaccent.rules '/usr/local/pgsql/share/tsearch_data/' make[1]: Leaving directory '/home/student/postgresql-10.0/contrib/unaccent' make -C vacuumlo install make[1]: Entering directory '/home/student/postgresql-10.0/contrib/vacuumlo' /bin/mkdir -p '/usr/local/pgsql/bin' /usr/bin/install -c vacuumlo '/usr/local/pgsql/bin' make[1]: Leaving directory '/home/student/postgresql-10.0/contrib/vacuumlo'
Большинство установленных расширений создают новые объекты SQL (функции, представления, таблицы). Перед использованием таких расширений требуется выполнить SQL-команду CREATE EXTENTION.
Список доступных расширений можно посмотреть запросом:
postgres$ psql -c 'SELECT name, comment FROM pg_available_extensions ORDER BY name;'
name | comment
--------------------+----------------------------------------------------------------------
adminpack | administrative functions for PostgreSQL
amcheck | functions for verifying relation integrity
autoinc | functions for autoincrementing fields
bloom | bloom access method - signature file based index
btree_gin | support for indexing common datatypes in GIN
btree_gist | support for indexing common datatypes in GiST
chkpass | data type for auto-encrypted passwords
citext | data type for case-insensitive character strings
cube | data type for multidimensional cubes
dblink | connect to other PostgreSQL databases from within a database
dict_int | text search dictionary template for integers
dict_xsyn | text search dictionary template for extended synonym processing
earthdistance | calculate great-circle distances on the surface of the Earth
file_fdw | foreign-data wrapper for flat file access
fuzzystrmatch | determine similarities and distance between strings
hstore | data type for storing sets of (key, value) pairs
insert_username | functions for tracking who changed a table
intagg | integer aggregator and enumerator (obsolete)
intarray | functions, operators, and index support for 1-D arrays of integers
isn | data types for international product numbering standards
lo | Large Object maintenance
ltree | data type for hierarchical tree-like structures
moddatetime | functions for tracking last modification time
pageinspect | inspect the contents of database pages at a low level
pg_buffercache | examine the shared buffer cache
pg_freespacemap | examine the free space map (FSM)
pg_prewarm | prewarm relation data
pg_stat_statements | track execution statistics of all SQL statements executed
pg_trgm | text similarity measurement and index searching based on trigrams
pg_visibility | examine the visibility map (VM) and page-level visibility info
pgcrypto | cryptographic functions
pgrowlocks | show row-level locking information
pgstattuple | show tuple-level statistics
plpgsql | PL/pgSQL procedural language
postgres_fdw | foreign-data wrapper for remote PostgreSQL servers
refint | functions for implementing referential integrity (obsolete)
seg | data type for representing line segments or floating-point intervals
tablefunc | functions that manipulate whole tables, including crosstab
tcn | Triggered change notifications
timetravel | functions for implementing time travel
tsm_system_rows | TABLESAMPLE method which accepts number of rows as a limit
tsm_system_time | TABLESAMPLE method which accepts time in milliseconds as a limit
unaccent | text search dictionary that removes accents
(43 rows)
Останавливаем сервер
Для останова используется команда pg_ctl stop -m fast|smart|immediate.
В ключе -m можно указать один из трех режимов останова:
- fast — принудительно завершает сеансы и записывает на диск изменения из оперативной памяти;
- smart — ожидает завершения всех сеансов и записывает на диск изменения из оперативной памяти;
- immediate — принудительно завершает сеансы, при запуске потребуется восстановление.
По умолчанию используется режим fast.
postgres$ pg_ctl -w -D /usr/local/pgsql/data stop
waiting for server to shut down.... done server stopped
Конец демонстрации.