Difference between revisions of "postgres"

From Free Pascal wiki
Jump to navigationJump to search
(→‎Installation and errors: clearing parametereized queries)
Line 68: Line 68:
 
* On Linux add the path to the libpq.so file to the libraries section in your /etc/fpc.cfg file. For example : -Fl/usr/local/pgsql/lib
 
* On Linux add the path to the libpq.so file to the libraries section in your /etc/fpc.cfg file. For example : -Fl/usr/local/pgsql/lib
 
* It may be necessary to create a symbolic link from a specific library version to a general library name: <syntaxhighlight lang="bash">ln -s /usr/lib/pqsql.so.5 /usr/lib/pqsql.so</syntaxhighlight>. Alternatively, install the postgresql client -dev package using your distribution's package manager
 
* It may be necessary to create a symbolic link from a specific library version to a general library name: <syntaxhighlight lang="bash">ln -s /usr/lib/pqsql.so.5 /usr/lib/pqsql.so</syntaxhighlight>. Alternatively, install the postgresql client -dev package using your distribution's package manager
 +
 +
==== Problems clearing parameters ====
 +
At least in FPC <= 2.6.2: if you .Clear a parameter (i.e. set it to NULL), PostgreSQL may have difficulty recognizing the parameter type.
 +
 +
In that case, explicitly specify the type, e.g.:
 +
<syntaxhighlight>
 +
FWriteQuery.Params.ParamByName('LONGITUDE').ParamType:=ftFloat; //required for postgresql
 +
FWriteQuery.Params.ParamByName('LONGITUDE').Clear
 +
</syntaxghighlight>
  
 
==PostgreSQL package: the low level units==
 
==PostgreSQL package: the low level units==

Revision as of 13:37, 12 September 2014

Overview

You can use Free Pascal/Lazarus to access a PostgreSQL database server. If you are looking for information on the postgres package in FPC, please see postgres#PostgreSQL_package:_the_low_level_units below.

Advantages of PostgreSQL:

  • It is very widely used and available
  • Very stable and has a complete feature set
  • Liberal license (no costs) in comparison with MySQL

Disadvantage of PostgreSQL:

  • Some hosters may not offer PostgreSQL)
  • No embedded version

Win64: please see warning here on not using certain FPC/Lazarus Win64 versions.

Zeos

Zeos supports PostgreSQL; please see ZeosDBO

SQLDB

FPC/Lazarus supports PostgreSQL out of the box with a PostgreSQL connection component/class. If you are using FPC only or want to manually add PostgreSQL support, add pqconnection to your uses clause. Otherwise, Lazarus provides a component:

sqldbcomponents.png

Note: The libpq C client contains some memory leaks (at least up till version 9.3 of Postgres) when a library is repeatedly loaded/unloaded. SQLDB loads the library when the first connection is made, and unloads it when the last connection closes. This means that whenever the last connection is closed, a small memory leak is created. To prevent this from happening (and speed up the application), you can load the library once at the start of the process with the InitialisePostgres3 call.

The charset property is used for client encoding.

The TPQConnection component does not directly support a Port property, but one can pass the port into the component via the Params parameter:

PQConnection.Params.Add('port=' + VariableContainingPort);

Other PostgreSQL specific connection parameters can be specified using the Params property:

PQConnection.Params.Add('application_name=''yourappname''')

Example

See SQLdb_Tutorial1 for a tutorial on creating a GUI database-enabled program that is written for PostgreSQL/SQLDB, as well as SQLite/SQLDB, Firebird/SQLDB, basically any RDBMS SQLDB supports).

Event monitoring

If you have FPC2.6.2+ and a recent version of Lazarus (note: currently, Oct 2013, Lazarus is set to require FPC2.6.3+ for this to work), you can use the TPQTEventMonitor component to monitor events coming from PostgreSQL.

It is a thin wrapper around FPC PQEventMonitor; please see the FPC pqeventstest.pp example programs for details.


Installation and errors

As with all sqldb units, you need to add your driver libraries (all required PostgreSQL .dll/.manifest files)

  • to a directory in the (library search) path (e.g. c:\windows\system32 for Windows)
  • or (Windows) to the program output directory (e.g. lib/something/ in your project directory, and the project directory

Windows 64 bit driver

If you are developing 64 bit applications, you must use a 64 bit DLL.

Light bulb  Note: FPC 2.6.0 (therefore Lazarus 1.0.4 or lower) does not yet support PostgreSQL on Windows 64 bit (unless you patch and recompile it).

A Windows 64 driver is fairly hard to find but can be downloaded here: [1]. The driver library can be installed in c:\windows\system32; 32 bit driver libraries can be installed in the confusingly named c:\windows\syswow64

Error: "Can not load PostgreSQL client library "libpq.dll""

The program cannot find your PostgreSQL driver files.

See above on instructions where to install the libraries.

A good example that demonstrates how to include drive DLL files when connecting Lazarus with PostgreSQL under Windows is easyDB.

On Linux/Unix/OSX: make sure the PostgreSQL libraries are in your library search path, e.g.:

  • On Linux add the path to the libpq.so file to the libraries section in your /etc/fpc.cfg file. For example : -Fl/usr/local/pgsql/lib
  • It may be necessary to create a symbolic link from a specific library version to a general library name:
    ln -s /usr/lib/pqsql.so.5 /usr/lib/pqsql.so
    
    . Alternatively, install the postgresql client -dev package using your distribution's package manager

Problems clearing parameters

At least in FPC <= 2.6.2: if you .Clear a parameter (i.e. set it to NULL), PostgreSQL may have difficulty recognizing the parameter type.

In that case, explicitly specify the type, e.g.: <syntaxhighlight> FWriteQuery.Params.ParamByName('LONGITUDE').ParamType:=ftFloat; //required for postgresql FWriteQuery.Params.ParamByName('LONGITUDE').Clear </syntaxghighlight>

PostgreSQL package: the low level units

As with all databases, the SQLDB code depends on a lower level PostgreSQL specific unit that wraps around the PostgreSQL driver library (.so/.dll/.dylib). Normally, you would use the higher-level SQLDB code as it allows you to code more quickly, easily switch databases etc.

Using this is very easy, all you need to do is compile some units, and use these units in your program. You need to specify the place of the PostgreSQL client Library (libpq) when compiling, and that is it.

The main unit is called postgres, normally this is the only unit you must include in your uses clause.

Requirements

You need at least version 0.99.5 of Free Pascal (basically any version of FPC except extremely old ones). The headers are translated from PostgreSQL version 6.3.1.

Installation

The postgres unit comes with the Free Pascal packages, and is distributed together with the compiler. This contains a directory postgres with the units, a test program and a makefile. cd to the directory and edit the Makefile to set the variables for your system. You must provide only 1 thing:

  1. The directory where the libpq library resides, usually /usr/local/pgsql/lib

Typing

make

Should compile the units and the program. If compilation was succesfull, you can install with

make install

(Remember to set the directory where the units should be installed.)

You can then test the program by running

make test

This will:

  • Run the test program testpg. It is a straightforward pascal translation of the example program in the PostGreSQL programmers' guide.
  • Run a script to create a table in a database, and fill it with some data. (the psql program should be in your PATH for this) . By default, the used database is testdb.
  • Run the testprogram testemail
  • Run a shell script again to remove the created table.

You will see a lot of messages on your screen, giving you feedback and results. If something went wrong, make will inform you of this.

Go back to Packages List

See also



Return To: LCL Components  — Previous: TSybaseConnection Next: TPQTEventMonitor


LCL Components
Component Tab Components
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TTaskDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TCSVDataSet • TSdfDataSet • TBufDataset • TFixedFormatDataSet • TDbf • TMemDataset
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TJSONPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TLvlGraphControl • TShortPathEdit • TSpinEditEx • TFloatSpinEditEx • TTreeFilterEdit • TExtendedTabControl •
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TMySQL57Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHtmlDataProvider • TIpHttpDataProvider • TIpHtmlPanel
Virtual Controls TVirtualDrawTree • TVirtualStringTree • TVTHeaderPopupMenu