- Delphi+PostgreSQL
- Connect to PostgreSQL (FireDAC)
- Contents
- Supported Versions
- Client Software
- Windows Client Software
- OS X Client Software
- iOS Client Software
- Linux Client Software
- Driver Linkage
- Additional Setup
- Connection Definition Parameters
- Connect to PostgreSQL (FireDAC)
- Contents
- Supported Versions
- Client Software
- Windows Client Software
- OS X Client Software
- iOS Client Software
- Linux Client Software
- Driver Linkage
- Additional Setup
- Connection Definition Parameters
- DataBind Controls to PostgreSQL Data in Delphi
- Ready to get started?
- Create a FireDAC Connection to PostgreSQL Data
- Create VCL Applications with Connectivity to PostgreSQL Data
- Execute Commands to PostgreSQL with FireDAC Components
- Connect to PostgreSQL Data
- Create Parameterized Queries
- Execute a Query
Delphi+PostgreSQL
В одном из проектов понадобилось получить доступ к БД PostgreSQL из Delphi и, в частности, читать BLOB поля из этой БД. Разумеется, дабы не изобретать велосипед, решил поискать готовые компоненты. Нашлось два решения:
Производительность была ключевым моментом, поэтому я решил их сравнить.
Тестирование производилось на базе PostgreSQL 8.2.5, в обоих компонентах использовалась dll той же версии. Предварительно запрос был выполнен пару раз, для того, чтобы база его закэшировала.
В скобках указано усреднённое значение для следующих трёх попыток, которые были выполнены без закрытия программы. Запрос был вида «select * from table», где table — таблица с 450 тысячами неодинаковых записей, не обработанная с помощью vacuum. Позиционирование представляло из себя код:
Query.First;
repeat
Query.Next;
until Query.Eof;
Результаты:
PostgresDAC
Соединение с базой: 170 мс (65 мс)*.
Выполнение запроса: 5900 мс (5900 мс).
Позиционирование: 4150 мс (4150 мс)
ZeosLib
Соединение с базой: 60 мс (60 мс).
Выполнение запроса: 5200 мс (5200 мс).
Позиционирование: 8100 мс (1900 мс)
Но самое интересное, как оказалось, ждало меня дальше.
При попытке получить данные из BLOB поля, оба компонента возвращали nil. Недолгие и несложные эксперименты показали, что так происходит при превышении Binary Object’ом размера в 20 килобайт.
Гугл проблему решить не помог, пришлось браться за напильник самому. Я конвертировал libpq.h из поставки PostgreSQL в pas, при помощи замечательной утилиты и стал проверять.
Действительно, стандартная функция PQexec отдавала nil вместо данных. Проблема решилась только использованием асинхронного запроса.
Вот такой код, со стандартными функциями из libpq.dll, получает из базы поле BLOB любой длинны (разумеется, для этого нужен unit с определёнными функциями и предварительно установленное соединение myConnection):
PQsendQuery(myСonnection, pchar(myQuery));
myResult:=PQGetResult(myConnection);
buf:=PQunescapeBytea(PQgetvalue(myResult, 0, 0), resultKey);
PS: Первый мой топик на хабре. Надеюсь, написаное действительно кому-нибудь поможет.
PPS: Ах да, есть ещё способ доступа через ADO, но он по всем показателям где-то в 2-2,5 раза медленнее Zeos’а и DAC’а. Да и искал я именно специализированные компоненты, так что в тестах ADO не присутствует.
Connect to PostgreSQL (FireDAC)
This topic describes how to connect to PostgreSQL.
Contents
Supported Versions
The FireDAC native driver supports PostgreSQL Server and PostgreSQL Advanced Server version 7.4 and later, because it requires a PG protocol 3.0 connection.
Client Software
Windows Client Software
FireDAC requires the LIBPQ.DLL x86 or x64 client library for connecting to the PostgreSQL server. Using libpq.dll also requires the «Microsoft Visual C++ 2010 Redistributable Package» installed. You can get this package from http://www.microsoft.com/en-us/download/details.aspx?id=8328. Ideally, the libpq.dll version should be equal to the server version. The full set of the v 9.0 client files:
- libpq.dll
- ssleay32.dll
- libeay32.dll
- libintl-8.dll
- libiconv-2.dll
You can take them from the server (details) installation Bin folder and place them in:
- a folder listed in your PATH environment variable
- your application EXE folder
Alternatively you may put the required files in any other folder, and specify their path in FDDrivers.ini:
If the PostgreSQL client library has not been installed properly, an exception is raised when you try to connect:
OS X Client Software
- the libpq.dylib x86 client library.
It comes pre-installed on OS X or can be installed separately (more).
iOS Client Software
The article (more) explains how to build libpq.dylib for iOS.
Note, Embarcadero Technologies has not tested this and does not provide assistance with it.
Linux Client Software
To install the PostgreSQL client library:
- On Ubuntu Server 16.04 LTS, run:
Driver Linkage
To link the driver:
- drop a TFDPhysPgDriverLink component from the «FireDAC Links» palette page
- or include the FireDAC.Phys.PG unit in a uses clause.
Additional Setup
If an application is using the
- DATE
- TIMESTAMP
- TIMESTAMP WITH TIME ZONE
The function template:
Connection Definition Parameters
To connect to a PostgreSQL DBMS, most applications require that you specify DriverID, Server, Database, User_Name, Password, and CharacterSet (see Defining Connection (FireDAC) for details).
Parameter | Description | Example value | ||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Server | The TCP/IP address or host name of the server running a PostgreSQL server. | 127.0.0.1 | ||||||||||||||||||||||||||||||
Port | The TCP/IP port on which PostgreSQL server is listening. | 5432 | ||||||||||||||||||||||||||||||
Database | Name of the current database for the connection. If the Database is not specified, no current database is set up. | MyDB | ||||||||||||||||||||||||||||||
User_Name | The PostgreSQL user ID. | postgres | ||||||||||||||||||||||||||||||
Password | The PostgreSQL user password. | |||||||||||||||||||||||||||||||
CharacterSet | The default character set for the connection. For details, see the Character Set Support chapter. | WIN1251 | ||||||||||||||||||||||||||||||
LoginTimeout | Controls the amount of time, in seconds, before an application times out while attempting to establish a connection. | 30 | ||||||||||||||||||||||||||||||
ExtendedMetadata | False | |||||||||||||||||||||||||||||||
OidAsBlob | Yes | |||||||||||||||||||||||||||||||
UnknownFormat | BYTEA | |||||||||||||||||||||||||||||||
ArrayScanSample | Determines whether the constrained arrays are mapped to ftArray or ftDataSet . To specify this connection parameter use ArrayScanSample= [; ]. Connect to PostgreSQL (FireDAC)This topic describes how to connect to PostgreSQL. ContentsSupported VersionsThe FireDAC native driver supports PostgreSQL Server and PostgreSQL Advanced Server version 7.4 and later, because it requires a PG protocol 3.0 connection. Client SoftwareWindows Client SoftwareFireDAC requires the LIBPQ.DLL x86 or x64 client library for connecting to the PostgreSQL server. Using libpq.dll also requires the «Microsoft Visual C++ 2010 Redistributable Package» installed. You can get this package from http://www.microsoft.com/en-us/download/details.aspx?id=8328. Ideally, the libpq.dll version should be equal to the server version. The full set of the v 9.0 client files:
You can take them from the server (details) installation Bin folder and place them in:
Alternatively you may put the required files in any other folder, and specify their path in FDDrivers.ini: If the PostgreSQL client library has not been installed properly, an exception is raised when you try to connect: OS X Client Software
It comes pre-installed on OS X or can be installed separately (more). iOS Client SoftwareThe article (more) explains how to build libpq.dylib for iOS. Note, Embarcadero Technologies has not tested this and does not provide assistance with it. Linux Client SoftwareTo install the PostgreSQL client library:
Driver LinkageTo link the driver:
Additional SetupIf an application is using the
The function template: Connection Definition ParametersTo connect to a PostgreSQL DBMS, most applications require that you specify DriverID, Server, Database, User_Name, Password, and CharacterSet (see Defining Connection (FireDAC) for details).
|