17.1. Сборка с помощью Visual C++ или Microsoft Windows SDK

PostgreSQL может быть собран с помощью компилятора Visual C++ от Microsoft. Этот компилятор есть в пакетах Visual Studio, Visual Studio Express и в некоторых версиях Microsoft Windows SDK. Если у вас ещё не установлена среда Visual Studio, проще всего будет использовать компиляторы из Visual Studio 2022 или из Windows SDK 10, которые Microsoft распространяет бесплатно.

С применением инструментария Microsoft Compiler возможна и 32-, и 64-битная сборка. 32-битную сборку PostgreSQL можно произвести с использованием Visual Studio 2013 — Visual Studio 2022, а также отдельных выпусков Windows SDK версии с 8.1a по 10. Для 64-битных сборок также можно использовать Microsoft Windows SDK версии с 8.1a по 10 или Visual Studio 2013 и новее. При сборке с Visual Studio 2013 — Visual Studio 2022 поддерживаются системы, начиная с Windows 7 и Windows Server 2008 R2 SP1.

Инструменты для компиляции с помощью Visual C++ или Platform SDK находятся в каталоге src/tools/msvc. При сборке убедитесь, что в системном пути PATH не подключаются инструменты из набора MinGW или Cygwin. Также убедитесь, что в пути PATH указаны каталоги всех необходимых инструментов Visual C++. Если вы используете Visual Studio, запустите Visual Studio Command Prompt. Если вы хотите собрать 64-битную версию, вы должны выбрать 64-битную версию данной оболочки, и наоборот. Начиная с Visual Studio 2017, это можно сделать в командной строке, воспользовавшись скриптом VsDevCmd.bat. О его параметрах и их значениях по умолчанию можно узнать, запустив его с ключом -help. Вы можете выбрать целевую архитектуру процессора, тип сборки и целевую ОС в приглашении Visual Studio Command Prompt с помощью скрипта vcvarsall.bat. Например, выполнив vcvarsall.bat x64 10.0.10240.0, вы подготовитесь к сборке выпускаемой 64-битной версии для Windows 10. О других параметрах vcvarsall.bat можно узнать, запустив его с ключом -help. Все эти скрипты должны запускаться из каталога src\tools\msvc.

До начала сборки можно создать файл config.pl и изменить в нём желаемые параметры конфигурации или пути к сторонним библиотекам, которые будут использоваться. Для получения конфигурации сначала считывается и разбирается файл config_default.pl, а затем применяются все изменения из config.pl. Например, чтобы указать, куда установлен Python, следует добавить в config.pl:

$config->{python} = 'c:\python26';

Вам нужно задать только те параметры, которые отличаются от заданных в config_default.pl.

Если вам необходимо установить какие-либо другие переменные окружения, создайте файл с именем buildenv.pl и поместите в него требуемые команды. Например, чтобы добавить путь к bison, которого нет в PATH, создайте файл следующего содержания:

$ENV{PATH}=$ENV{PATH} . ';c:\some\where\bison\bin';

Передать дополнительные аргументы командной строки команде сборки Visual Studio (msbuild или vcbuild) можно так:

$ENV{MSBFLAGS}="/m";

17.1.1. Требования

Для сборки PostgreSQL требуется следующее дополнительное ПО. Укажите каталоги, в которых находятся соответствующие библиотеки, в файле конфигурации config.pl.

Microsoft Windows SDK

Если с вашим инструментарием для разработки не поставляется поддерживаемая версия Microsoft Windows SDK, рекомендуется установить последнюю версию SDK (в настоящее время 10), которую можно загрузить с https://www.microsoft.com/download.

Устанавливая SDK, вы всегда должны выбирать для установки пункт Windows Headers and Libraries (Заголовочные файлы и библиотеки Windows). Если вы установили Windows SDK, включая Visual C++ Compilers, Visual Studio для сборки вам не нужна. Обратите внимание, что с версии 8.0a в SDK для Windows не включается полное окружение для сборки в командной строке.

Strawberry Perl

Strawberry Perl требуется для запуска скриптов, управляющих сборкой. Perl из MinGW или Cygwin работать не будет. ActiveState Perl также должен находиться по пути в PATH. Готовый двоичный пакет можно загрузить с https://www.strawberryperl.com.

Следующее дополнительное ПО не требуется для базовой сборки, но требуется для сборки полного пакета. Укажите каталоги, в которых находятся соответствующие библиотеки, в файле конфигурации config.pl.

Magicsplat Tcl

Требуется для сборки PL/Tcl. Двоичные пакеты можно загрузить с https://www.magicsplat.com/tcl-installer/index.html.

Bison и Flex

Для компиляции из Git требуются Bison и Flex, хотя они не нужны для компиляции из дистрибутивного пакета исходного кода. Bison должен быть версии 1.875 или 2.2, либо новее, а Flex — версии 2.5.31 или новее.

И Bison, и Flex входят в комплект утилит msys, который можно загрузить с http://www.mingw.org/wiki/MSYS в качестве компонента набора MinGW.

Вам потребуется добавить каталог, содержащий flex.exe и bison.exe, в путь, задаваемый переменной PATH, в buildenv.pl, если она его ещё не включает. В случае с MinGW, это будет подкаталог \msys\1.0\bin в каталоге вашей инсталляции MinGW.

Примечание

Bison, поставляемый в составе GnuWin32, может работать некорректно, когда он установлен в каталог с именем, содержащим пробелы, например, C:\Program Files\GnuWin32 (целевой каталог по умолчанию в англоязычной системе). В таком случае, возможно, стоит установить его в C:\GnuWin32 или задать в переменной окружения PATH короткий путь NTFS к GnuWin32 (например, C:\PROGRA~1\GnuWin32).

Примечание

Старые программы winflex, которые раньше размещались на FTP-сайте PostgreSQL и упоминались в старой документации, не будут работать в 64-битной Windows, выдавая ошибку «flex: fatal internal error, exec failed». Используйте Flex из набора MSYS.

Diff

Diff требуется для запуска регрессионных тестов, его можно загрузить с http://gnuwin32.sourceforge.net.

Gettext

Gettext требуется для сборки с поддержкой NLS, его можно загрузить с http://gnuwin32.sourceforge.net. Обратите внимание, что для сборки потребуются и исполняемые файлы, и зависимости, и файлы для разработки.

MIT Kerberos

Требуется для поддержки проверки подлинности GSSAPI. MIT Kerberos можно загрузить с https://web.mit.edu/Kerberos/dist/index.html.

libxml2 и libxslt

Требуется для поддержки XML. Двоичный пакет можно загрузить с https://zlatkovic.com/pub/libxml, а исходный код с http://xmlsoft.org. Учтите, что для libxml2 требуется iconv, который можно загрузить там же.

OpenSSL

Требуется для поддержки SSL. Двоичные пакеты можно загрузить с https://slproweb.com/products/Win32OpenSSL.html, а исходный код с https://www.openssl.org.

ossp-uuid

Требуется для поддержки UUID-OSSP (только для contrib). Исходный код можно загрузить с http://www.ossp.org/pkg/lib/uuid/.

Python

Требуется для сборки PL/Python. Двоичные пакеты можно загрузить с https://www.python.org.

zlib

Требуется для поддержки сжатия в pg_dump и pg_restore. Двоичные пакеты можно загрузить с https://www.zlib.net.

17.1.2. Специальные замечания для 64-битной Windows

PostgreSQL для архитектуры x64 можно собрать только в 64-битной Windows, процессоры Itanium не поддерживаются.

Совместная сборка 32- и 64-битных версий в одном дереве не поддерживается. Система сборки автоматически определит, в каком окружении (32- или 64-битном) она запущена, и соберёт соответствующий вариант PostgreSQL. Поэтому сборку важно запускать в командной оболочке, предоставляющей нужное окружение.

Для использования на стороне сервера сторонних библиотек, таких как python или OpenSSL, эти библиотеки также должны быть 64-битными. 64-битный сервер не поддерживает загрузку 32-битных библиотек. Некоторые библиотеки сторонних разработчиков, предназначенные для PostgreSQL, могут быть доступны только в 32-битных версиях и в таком случае их нельзя будет использовать с 64-битной версией PostgreSQL.

17.1.3. Сборка

Чтобы собрать весь PostgreSQL в конфигурации выпуска (по умолчанию), запустите команду:

build

Чтобы собрать весь PostgreSQL в конфигурации отладки, запустите команду:

build DEBUG

Для сборки отдельного проекта, например psql, выполните, соответственно:

build psql
build DEBUG psql

Чтобы сменить конфигурацию по умолчанию на отладочную, поместите в файл buildenv.pl следующую строку:

$ENV{CONFIG}="Debug";

Также возможна сборка из графической среды Visual Studio. В этом случае вам нужно запустить в командной строке:

perl mkvcbuild.pl

и затем открыть в Visual Studio полученный pgsql.sln в корневом каталоге дерева исходных кодов.

17.1.4. Очистка и установка

В большинстве случаев за изменением файлов будет следить автоматическая система отслеживания зависимостей в Visual Studio. Но если изменений было слишком много, может понадобиться очистка установки. Чтобы её выполнить, просто запустите команду clean.bat, которая автоматически очистит все сгенерированные файлы. Вы также можете запустить эту команду с параметром dist, в этом случае она отработает подобно make distclean и удалит также выходные файлы flex/bison.

По умолчанию все файлы сохраняются в подкаталогах debug или release. Чтобы установить эти файлы стандартным образом, а также сгенерировать файлы, требуемые для инициализации и использования базы данных, запустите команду:

install c:\destination\directory

Если вы хотите установить только клиентские приложения и интерфейсные библиотеки, выполните команду:

install c:\destination\directory client

17.1.5. Запуск регрессионных тестов

Чтобы запустить регрессионные тесты, важно сначала собрать все необходимые для них компоненты. Также убедитесь, что в системном пути могут быть найдены все DLL, требуемые для загрузки всех подсистем СУБД (например, DLL Perl и Python для процедурных языков). Если их каталоги в пути поиска отсутствуют, задайте их в файле buildenv.pl. Чтобы запустить тесты, выполните одну из следующих команд в каталоге src\tools\msvc:

vcregress check
vcregress installcheck
vcregress plcheck
vcregress contribcheck
vcregress modulescheck
vcregress ecpgcheck
vcregress isolationcheck
vcregress bincheck
vcregress recoverycheck
vcregress taptest
vcregress upgradecheck

Чтобы выбрать другой планировщик выполнения тестов (по умолчанию выбран параллельный), укажите его в командной строке, например:

vcregress check serial

Команду vcregress taptest можно использовать для запуска TAP-тестов целевого каталога, например:

vcregress taptest src\bin\initdb\

За дополнительными сведениями о регрессионных тестах обратитесь к Главе 32.

Для запуска регрессионных тестов клиентских программ с применением команды vcregress bincheck, тестов восстановления с применением vcregress recoverycheck или TAP-тестов с применением vcregress taptest должен быть установлен дополнительный модуль Perl:

IPC::Run

На момент написания документации модуль IPC::Run не включается ни в инсталляцию Perl ActiveState, ни в библиотеку ActiveState PPM (Perl Package Manager, Менеджер пакетов Perl). Чтобы установить его, загрузите архив исходного кода IPC-Run-<version>.tar.gz из CPAN, по адресу https://metacpan.org/release/IPC-Run, и распакуйте его. Откройте файл buildenv.pl и добавьте в него переменную PERL5LIB, указывающую на подкаталог lib из извлечённого архива. Например:

$ENV{PERL5LIB}=$ENV{PERL5LIB} . ';c:\IPC-Run-0.94\lib';

Некоторые TAP-тесты зависят от набора внешних команд, при наличии которых могут быть запущены связанные с этими командами тесты. Переопределить эти команды или сбросить их можно в следующих переменных в buildenv.pl:

GZIP_PROGRAM

Команда или путь для запуска программы gzip. По умолчанию — gzip, то есть для поиска этой команды будет использоваться PATH.

TAR

Команда или путь для запуска программы tar. По умолчанию — tar, то есть для поиска этой команды будет использоваться PATH.

17.1. Building with Visual C++ or the Microsoft Windows SDK

PostgreSQL can be built using the Visual C++ compiler suite from Microsoft. These compilers can be either from Visual Studio, Visual Studio Express or some versions of the Microsoft Windows SDK. If you do not already have a Visual Studio environment set up, the easiest ways are to use the compilers from Visual Studio 2022 or those in the Windows SDK 10, which are both free downloads from Microsoft.

Both 32-bit and 64-bit builds are possible with the Microsoft Compiler suite. 32-bit PostgreSQL builds are possible with Visual Studio 2013 to Visual Studio 2022, as well as standalone Windows SDK releases 8.1a to 10. 64-bit PostgreSQL builds are supported with Microsoft Windows SDK version 8.1a to 10 or Visual Studio 2013 and above. Compilation is supported down to Windows 7 and Windows Server 2008 R2 SP1 when building with Visual Studio 2013 to Visual Studio 2022.

The tools for building using Visual C++ or Platform SDK are in the src/tools/msvc directory. When building, make sure there are no tools from MinGW or Cygwin present in your system PATH. Also, make sure you have all the required Visual C++ tools available in the PATH. In Visual Studio, start the Visual Studio Command Prompt. If you wish to build a 64-bit version, you must use the 64-bit version of the command, and vice versa. Starting with Visual Studio 2017 this can be done from the command line using VsDevCmd.bat, see -help for the available options and their default values. vsvars32.bat is available in Visual Studio 2015 and earlier versions for the same purpose. From the Visual Studio Command Prompt, you can change the targeted CPU architecture, build type, and target OS by using the vcvarsall.bat command, e.g., vcvarsall.bat x64 10.0.10240.0 to target Windows 10 with a 64-bit release build. See -help for the other options of vcvarsall.bat. All commands should be run from the src\tools\msvc directory.

Before you build, you can create the file config.pl to reflect any configuration options you want to change, or the paths to any third party libraries to use. The complete configuration is determined by first reading and parsing the file config_default.pl, and then apply any changes from config.pl. For example, to specify the location of your Python installation, put the following in config.pl:

$config->{python} = 'c:\python26';

You only need to specify those parameters that are different from what's in config_default.pl.

If you need to set any other environment variables, create a file called buildenv.pl and put the required commands there. For example, to add the path for bison when it's not in the PATH, create a file containing:

$ENV{PATH}=$ENV{PATH} . ';c:\some\where\bison\bin';

To pass additional command line arguments to the Visual Studio build command (msbuild or vcbuild):

$ENV{MSBFLAGS}="/m";

17.1.1. Requirements

The following additional products are required to build PostgreSQL. Use the config.pl file to specify which directories the libraries are available in.

Microsoft Windows SDK

If your build environment doesn't ship with a supported version of the Microsoft Windows SDK it is recommended that you upgrade to the latest version (currently version 10), available for download from https://www.microsoft.com/download.

You must always include the Windows Headers and Libraries part of the SDK. If you install a Windows SDK including the Visual C++ Compilers, you don't need Visual Studio to build. Note that as of Version 8.0a the Windows SDK no longer ships with a complete command-line build environment.

Strawberry Perl

Strawberry Perl is required to run the build generation scripts. MinGW or Cygwin Perl will not work. It must also be present in the PATH. Binaries can be downloaded from https://strawberryperl.com.

The following additional products are not required to get started, but are required to build the complete package. Use the config.pl file to specify which directories the libraries are available in.

Magicsplat Tcl

Required for building PL/Tcl. Binaries can be downloaded from https://www.magicsplat.com/tcl-installer/index.html.

Bison and Flex

Bison and Flex are required to build from Git, but not required when building from a release file. Only Bison 1.875 or versions 2.2 and later will work. Flex must be version 2.5.31 or later.

Both Bison and Flex are included in the msys tool suite, available from http://www.mingw.org/wiki/MSYS as part of the MinGW compiler suite.

You will need to add the directory containing flex.exe and bison.exe to the PATH environment variable in buildenv.pl unless they are already in PATH. In the case of MinGW, the directory is the \msys\1.0\bin subdirectory of your MinGW installation directory.

Note

The Bison distribution from GnuWin32 appears to have a bug that causes Bison to malfunction when installed in a directory with spaces in the name, such as the default location on English installations C:\Program Files\GnuWin32. Consider installing into C:\GnuWin32 or use the NTFS short name path to GnuWin32 in your PATH environment setting (e.g., C:\PROGRA~1\GnuWin32).

Note

The obsolete winflex binaries distributed on the PostgreSQL FTP site and referenced in older documentation will fail with “flex: fatal internal error, exec failed” on 64-bit Windows hosts. Use Flex from MSYS instead.

Diff

Diff is required to run the regression tests, and can be downloaded from http://gnuwin32.sourceforge.net.

Gettext

Gettext is required to build with NLS support, and can be downloaded from http://gnuwin32.sourceforge.net. Note that binaries, dependencies and developer files are all needed.

MIT Kerberos

Required for GSSAPI authentication support. MIT Kerberos can be downloaded from https://web.mit.edu/Kerberos/dist/index.html.

libxml2 and libxslt

Required for XML support. Binaries can be downloaded from https://zlatkovic.com/pub/libxml or source from http://xmlsoft.org. Note that libxml2 requires iconv, which is available from the same download location.

OpenSSL

Required for SSL support. Binaries can be downloaded from https://slproweb.com/products/Win32OpenSSL.html or source from https://www.openssl.org.

ossp-uuid

Required for UUID-OSSP support (contrib only). Source can be downloaded from http://www.ossp.org/pkg/lib/uuid/.

Python

Required for building PL/Python. Binaries can be downloaded from https://www.python.org.

zlib

Required for compression support in pg_dump and pg_restore. Binaries can be downloaded from https://www.zlib.net.

17.1.2. Special Considerations for 64-Bit Windows

PostgreSQL will only build for the x64 architecture on 64-bit Windows, there is no support for Itanium processors.

Mixing 32- and 64-bit versions in the same build tree is not supported. The build system will automatically detect if it's running in a 32- or 64-bit environment, and build PostgreSQL accordingly. For this reason, it is important to start the correct command prompt before building.

To use a server-side third party library such as python or OpenSSL, this library must also be 64-bit. There is no support for loading a 32-bit library in a 64-bit server. Several of the third party libraries that PostgreSQL supports may only be available in 32-bit versions, in which case they cannot be used with 64-bit PostgreSQL.

17.1.3. Building

To build all of PostgreSQL in release configuration (the default), run the command:

build

To build all of PostgreSQL in debug configuration, run the command:

build DEBUG

To build just a single project, for example psql, run the commands:

build psql
build DEBUG psql

To change the default build configuration to debug, put the following in the buildenv.pl file:

$ENV{CONFIG}="Debug";

It is also possible to build from inside the Visual Studio GUI. In this case, you need to run:

perl mkvcbuild.pl

from the command prompt, and then open the generated pgsql.sln (in the root directory of the source tree) in Visual Studio.

17.1.4. Cleaning and Installing

Most of the time, the automatic dependency tracking in Visual Studio will handle changed files. But if there have been large changes, you may need to clean the installation. To do this, simply run the clean.bat command, which will automatically clean out all generated files. You can also run it with the dist parameter, in which case it will behave like make distclean and remove the flex/bison output files as well.

By default, all files are written into a subdirectory of the debug or release directories. To install these files using the standard layout, and also generate the files required to initialize and use the database, run the command:

install c:\destination\directory

If you want to install only the client applications and interface libraries, then you can use these commands:

install c:\destination\directory client

17.1.5. Running the Regression Tests

To run the regression tests, make sure you have completed the build of all required parts first. Also, make sure that the DLLs required to load all parts of the system (such as the Perl and Python DLLs for the procedural languages) are present in the system path. If they are not, set it through the buildenv.pl file. To run the tests, run one of the following commands from the src\tools\msvc directory:

vcregress check
vcregress installcheck
vcregress plcheck
vcregress contribcheck
vcregress modulescheck
vcregress ecpgcheck
vcregress isolationcheck
vcregress bincheck
vcregress recoverycheck
vcregress taptest
vcregress upgradecheck

To change the schedule used (default is parallel), append it to the command line like:

vcregress check serial

vcregress taptest can be used to run the TAP tests of a target directory, like:

vcregress taptest src\bin\initdb\

For more information about the regression tests, see Chapter 32.

Running the regression tests on client programs with vcregress bincheck, on recovery tests with vcregress recoverycheck, or TAP tests specified with vcregress taptest requires an additional Perl module to be installed:

IPC::Run

As of this writing, IPC::Run is not included in the ActiveState Perl installation, nor in the ActiveState Perl Package Manager (PPM) library. To install, download the IPC-Run-<version>.tar.gz source archive from CPAN, at https://metacpan.org/release/IPC-Run, and uncompress. Edit the buildenv.pl file, and add a PERL5LIB variable to point to the lib subdirectory from the extracted archive. For example:

$ENV{PERL5LIB}=$ENV{PERL5LIB} . ';c:\IPC-Run-0.94\lib';

Some of the TAP tests depend on a set of external commands that would optionally trigger tests related to them. Each one of those variables can be set or unset in buildenv.pl:

GZIP_PROGRAM

Path to a gzip command. The default is gzip, that would be the command found in PATH.

TAR

Path to a tar command. The default is tar, that would be the command found in PATH.

FAQ