Sign in Join
Wiki copytemporary

postgres: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Overview
22
33You 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|postgres#PostgreSQL_package:_the_low_level_units]] below.
44
55Advantages of PostgreSQL:
66
77- It is very widely used and available
88- Very stable and has a complete feature set
99- Liberal license (no costs) in comparison with MySQL
1010
1111Disadvantage of PostgreSQL:
1212
1313- Some hosters may not offer PostgreSQL)
1414- No embedded version
1515
1616Win64: please see warning [[Windows Programming Tips|here]] on not using certain FPC/Lazarus Win64 versions.
1717
1818## Direct access to PostgreSQL
1919
2020You can connect Lazarus with PostgreSQL by using PostgreSQL Data Access Components (PgDAC). It is a library of components that provides native connectivity to PostgreSQL from Lazarus (and Free Pascal) on Windows, Mac OS X, iOS, Android, Linux, and FreeBSD for both 32-bit and 64-bit platforms. PgDAC is designed to help programmers develop really lightweight, faster and cleaner PostgreSQL database applications without deploying any additional libraries.
2121
2222You can download this [Lazarus component](https://www.devart.com/pgdac/download.html) for free.
2323
2424## Zeos
2525
2626Zeos supports PostgreSQL; please see [[ZeosDBO]]
2727
2828## SQLDB
2929
3030FPC/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:
3131
3232![](/wiki-images/c/c5/Sqldbcomponents.png%E2%80%8E)
3333
3434**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.
3535
3636The CharSet property is used for client encoding.
3737
3838The TPQConnection component does not directly support a Port property, but one can pass the port into the component via the Params parameter:
3939
4040``` pascal
4141PQConnection.Params.Add('port=' + VariableContainingPort);
4242```
4343
4444Also other PostgreSQL specific connection parameters can be specified using the Params property:
4545
4646``` pascal
4747PQConnection.Params.Add('application_name=''yourappname''')
4848```
4949
5050For all supported connection parameters see: [Connection Parameter Key Words](https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS)
5151
5252### Example
5353
5454See [[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).
5555
5656### Event monitoring
5757
5858If you have FPC2.6.2+ and a recent version of Lazarus, you can use the **TPQTEventMonitor** component to monitor events coming from PostgreSQL.
5959
6060It is a thin wrapper around FPC **PQEventMonitor**; please see the FPC pqeventstest.pp example programs for details.
6161
6262### Installation and errors
6363
6464As with all sqldb units, you need to add your driver libraries (**all** required PostgreSQL .dll/.manifest files)
6565
6666- to a directory in the (library search) path (e.g. c:\windows\system32 for Windows)
6767- or (Windows) to the program output directory (e.g. lib/something/ in your project directory, and the project directory
6868
6969#### Windows 64 bit driver
7070
7171If you are developing 64 bit applications, you must use a 64 bit DLL.
7272
7373> **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).
7474
7575A Windows 64 driver is fairly hard to find but can be downloaded here: [1](http://www.enterprisedb.com/products-services-training/pgdownload#windows). The driver library can be installed in c:\windows\system32; 32 bit driver libraries can be installed in the confusingly named c:\windows\syswow64
7676
7777#### Error: "Can not load PostgreSQL client library "libpq.dll""
7878
7979The program cannot find your PostgreSQL driver files.
8080
8181See above on instructions where to install the libraries.
8282
8383A good example that demonstrates how to include drive DLL files when connecting Lazarus with PostgreSQL under Windows is [easyDB](http://paginas.fe.up.pt/~asousa/wiki/doku.php?id=proj:lazarus_projects#easy_db).
8484
8585On Linux/Unix/OSX: make sure the PostgreSQL libraries are in your library search path, e.g.:
8686
8787- 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
8888- It may be necessary to create a symbolic link from a specific library version to a general library name:
8989 ``` bash
9090 ln -s /usr/lib/pqsql.so.5 /usr/lib/pqsql.so
9191 ```
9292
9393 . Alternatively, install the postgresql client -dev package using your distribution's package manager
9494
9595#### Problems clearing parameters
9696
9797> **Note:** Verify this: is .paramtype really necessary?
9898
9999At 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.
100100
101101In that case, explicitly specify the type, e.g.:
102102
103103``` pascal
104104FWriteQuery.Params.ParamByName('LONGITUDE').ParamType:=ptInput; //required for postgresql
105105FWriteQuery.Params.ParamByName('LONGITUDE').Clear
106106```
107107
108108## How To
109109
110110### Use keyword RETURNING for values
111111
112112#### Get Last Inserted ID
113113
114114With PostGres there is no need to run a second query to get the last inserted ID.
115115
116116Use INSERT RETURNING and read the value:
117117
118118``` pascal
119119var
120120 ID: Integer
121121..
122122Query.SQL.Text:= 'INSERT INTO myschema.films(film_name)' +
123123 'VALUES(:film_name) RETURNING film_id;';
124124Query.Open;
125125ID:= Query.FieldByName('film_id').AsInteger;
126126```
127127
128128#### Get multiple fields and expressions
129129
130130RETURNING in PostgreSQL is more flexible than most database engines. It works with INSERT, UPDATE, and DELETE statements and can be any list of fields, constants, or expressions that would be found in a SELECT list.
131131
132132``` SQL
133133INSERT INTO films (film_name) VALUES ('val') RETURNING film_id; -- Returns id's for newly created rows.
134134INSERT INTO films (film_name) VALUES ('val') RETURNING film_id, kind; -- Returns id and kind fields in newly created rows.
135135INSERT INTO films (film_name) VALUES ('val') RETURNING *; -- Returns all fields in newly created rows.
136136
137137UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING film_id; -- Returns id's of updated rows.
138138UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING film_id, film_name; -- Returns id and film names of updated rows.
139139UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING *; -- Returns all fields of updated rows.
140140
141141DELETE FROM films RETURNING film_id; --Returns id's of deleted rows.
142142DELETE FROM films RETURNING film_id, film_name; --Returns id's and film names of deleted rows.
143143DELETE FROM films RETURNING *; -- Returns all fields of deleted rows.
144144```
145145
146146RETURNING using fields, constants, and expressions:
147147
148148``` SQL
149149INSERT INTO films (film_name) VALUES ('val') RETURNING id, 'a' AS a, id*2 AS doubled_id, CASE WHEN id > 100 THEN 'a' ELSE 'b' END AS foo;
150150```
151151
152152## PostgreSQL package: the low level units
153153
154154As 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.
155155
156156Using 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.
157157
158158The main unit is called **postgres**, normally this is the only unit you must include in your uses clause.
159159
160160### Requirements
161161
162162You 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.
163163
164164### Installation
165165
166166The 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:
167167
1681681. The directory where the libpq library resides, usually /usr/local/pgsql/lib
169169
170170Typing
171171
172-`make`
172+```text
173+make
174+```
173175
174176Should compile the units and the program. If compilation was succesfull, you can install with
175177
176-`make install`
178+```text
179+make install
180+```
177181
178182(Remember to set the directory where the units should be installed.)
179183
180184You can then test the program by running
181185
182-`make test`
186+```text
187+make test
188+```
183189
184190This will:
185191
186192- Run the test program testpg. It is a straightforward pascal translation of the example program in the PostGreSQL programmers' guide.
187193- 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.
188194- Run the testprogram testemail
189195- Run a shell script again to remove the created table.
190196
191197You will see a lot of messages on your screen, giving you feedback and results. If something went wrong, make will inform you of this.
192198
193199Go back to [[Package List|Packages List]]
194200
195201## See also
196202
197203- [[TPSQL]] - A different set of PostgreSQL dataset/database components
198204- [[Lazarus DB Faq]] - More about database programming
199205- [[Lazarus Database Tutorial]] - Getting Lazarus working with various databases
200206
201207---
202208*From the Free Pascal wiki, page "postgres", as it stood on 2020-02-23 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history