| 1 |
pg.lisp -- socket level interface to the PostgreSQL RDBMS for Common Lisp |
| 2 |
|
| 3 |
Author: Eric Marsden <[email protected]> |
| 4 |
Version: 0.24 |
| 5 |
|
| 6 |
Copyright (C) 1999,2000,2001,2002,2003,2004,2005,2006 Eric Marsden |
| 7 |
|
| 8 |
This library is free software; you can redistribute it and/or |
| 9 |
modify it under the terms of the GNU Library General Public |
| 10 |
License as published by the Free Software Foundation; either |
| 11 |
version 2 of the License, or (at your option) any later version. |
| 12 |
|
| 13 |
This library is distributed in the hope that it will be useful, |
| 14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 16 |
Library General Public License for more details. |
| 17 |
|
| 18 |
You should have received a copy of the GNU Library General Public |
| 19 |
License along with this library; if not, write to the Free |
| 20 |
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
| 21 |
|
| 22 |
For download information, mailing lists for suggestions and bug |
| 23 |
reports, see |
| 24 |
|
| 25 |
<URL:http://www.common-lisp.net/project/pg/> |
| 26 |
|
| 27 |
|
| 28 |
== Overview ========================================================= |
| 29 |
|
| 30 |
This module lets you access the PostgreSQL object-relational DBMS |
| 31 |
from Common Lisp. The code implements the client part of the |
| 32 |
socket-level frontend/backend protocol, rather than providing a |
| 33 |
wrapper around the libpq library. The module is capable of type |
| 34 |
coercions from a range of SQL types to the equivalent Lisp type. |
| 35 |
The only non portable code is the use of 'socket-connect' and |
| 36 |
(optional) some way of accessing the Unix crypt() function. |
| 37 |
|
| 38 |
Works with CMUCL, SBCL, CLISP, OpenMCL, ABCL, ACL, Lispworks, and MCL. |
| 39 |
CormanLisp has socket support but not for binary I/O. |
| 40 |
|
| 41 |
|
| 42 |
== Entry points ======================================================= |
| 43 |
|
| 44 |
(with-pg-connection ((con &rest open-args) &body body) |
| 45 |
A macro which opens a connection to database DBNAME, executes the |
| 46 |
BODY forms then disconnects. See function `pg-connect' for details |
| 47 |
of the connection arguments OPEN-ARGS. |
| 48 |
|
| 49 |
(with-pg-transaction con &body body) |
| 50 |
A macro which executes the BODY forms wrapped in an SQL transaction. |
| 51 |
CON is a connection to the database. If an error occurs during the |
| 52 |
execution of the forms, a ROLLBACK instruction is executed. |
| 53 |
|
| 54 |
(pg-connect dbname user &key password host port) -> connection |
| 55 |
Connect to the database DBNAME on HOST (defaults to localhost) at |
| 56 |
PORT (defaults to 5432), and log in as USER. If HOST designates |
| 57 |
an absolute pathname (its first character is #\/), attempt to |
| 58 |
connect to the localhost using a Unix domain socket that resides |
| 59 |
in that directory (for example "/var/run/postgresql/"); otherwise |
| 60 |
HOST designates a hostname and the connection is established |
| 61 |
using TCP/IP. Connections to unix sockets are not supported on |
| 62 |
all implementations. If the database requires a password, send |
| 63 |
PASSWORD (as clear text unless the backend demands crypt() |
| 64 |
authentication). Set the output date type to 'ISO', and |
| 65 |
initialize our type parser tables. |
| 66 |
|
| 67 |
(pg-exec connection &rest sql) -> pgresult |
| 68 |
Concatenate the SQL strings and send to the backend. Retrieve |
| 69 |
all the information returned by the database and return it in |
| 70 |
an opaque record PGRESULT. |
| 71 |
|
| 72 |
(pg-result pgresult what &rest args) -> info |
| 73 |
Extract information from the PGRESULT. WHAT can be one of |
| 74 |
* :connection |
| 75 |
* :status |
| 76 |
* :attributes |
| 77 |
* :tuples |
| 78 |
* :tuple tupleNumber |
| 79 |
* :oid |
| 80 |
`connection' allows you to retrieve the database connection. |
| 81 |
`status' is a string returned by the backend to indicate the |
| 82 |
status of the command; it is normally "SELECT" for a select |
| 83 |
command, "DELETE 1" if the deletion affected a single row, etc. |
| 84 |
`attributes' is a list of tuples providing metadata: the first |
| 85 |
component of each tuple is the attribute's name as a string, |
| 86 |
the second an integer representing its PostgreSQL type, and the |
| 87 |
third an integer representing the size of that type. `tuples' |
| 88 |
returns all the data retrieved from the database, as a list of |
| 89 |
lists, each list corresponding to one row of data returned by |
| 90 |
the backend. `tuple num' can be used to extract a specific |
| 91 |
tuple. `oid' allows you to retrieve the OID returned by the |
| 92 |
backend if the command was an insertion; the OID is a unique |
| 93 |
identifier for that row in the database (this is |
| 94 |
PostgreSQL-specific, please refer to the documentation for more |
| 95 |
details). |
| 96 |
|
| 97 |
(pg-for-each connection select-form callback) |
| 98 |
Calls CALLBACK on each tuple returned by SELECT-FORM. Declares |
| 99 |
a cursor for SELECT-FORM, then fetches tuples using repeated |
| 100 |
executions of FETCH 1, until no results are left. The cursor is |
| 101 |
then closed. The work is performed within a transaction. When |
| 102 |
you have a large amount of data to handle, this usage is more |
| 103 |
efficient than fetching all the tuples in one go. |
| 104 |
|
| 105 |
(pg-disconnect connection &key abort) -> nil |
| 106 |
Close the database connection. If the keyword argument ABORT is |
| 107 |
non-NIL, the database connection is closed immediately, without |
| 108 |
first attempting to send a disconnect packet to the PostgreSQL |
| 109 |
backend. |
| 110 |
|
| 111 |
|
| 112 |
=== Support for prepared statements ==================================== |
| 113 |
|
| 114 |
(pg-supports-pbe conn) -> boolean |
| 115 |
Returns T iff the connection to the database is able to support |
| 116 |
prepared statements. This is only true of connections using |
| 117 |
version 3 of the frontend/backend protocol. |
| 118 |
|
| 119 |
(pg-prepare conn statement-name sql &optional parameter-types) |
| 120 |
Prepares an execution plan for a query (a prepared statement). |
| 121 |
The prepared statement may contain arguments that are refered to |
| 122 |
as $1, $2 etc; if arguments are present their types must be |
| 123 |
declared via the list PARAMETER-TYPES. Each element of |
| 124 |
PARAMETER-TYPES should be a string that defines the type of its |
| 125 |
corresponding parameter (see PG::*TYPE-PARSERS* for examples of |
| 126 |
type names used by PostgreSQL). |
| 127 |
|
| 128 |
Using execution plans is more efficient than multiple calls to |
| 129 |
PG-EXEC, since the parsing and query optimizing phase only occurs |
| 130 |
once, at preparation time. It also helps to protect against "SQL |
| 131 |
injection" attacks, by ensuring that arguments to an SQL query |
| 132 |
cannot be interpreted as a part of the SQL request. |
| 133 |
|
| 134 |
(pg-bind conn portal-name statement-name typed-arguments) |
| 135 |
Binds the execution plan that was previously prepared as |
| 136 |
STATEMENT-NAME to PORTAL-NAME, with TYPED-ARGUMENTS. |
| 137 |
TYPED-ARGUMENTS is a list of tuples of the form '(type value), |
| 138 |
where TYPE is one of :char, :byte, :int16, :int32, :string. |
| 139 |
|
| 140 |
(pg-execute conn portal-name &optional maximal-return-rows) |
| 141 |
Executes the execution plan that was previously bound to |
| 142 |
PORTAL-NAME. Optionally returns up to MAXIMAL-RETURN-ROWS rows |
| 143 |
(0 means an unlimited number of rows). |
| 144 |
|
| 145 |
(pg-close-statement conn statement-name) |
| 146 |
Releases the command execution plan (prepared statement) |
| 147 |
STATEMENT-NAME. This also releases any open portals for that |
| 148 |
prepared statement. |
| 149 |
|
| 150 |
(pg-close-portal conn portal-name) |
| 151 |
Releases the portal PORTAL-NAME. |
| 152 |
|
| 153 |
Example using prepared statements: |
| 154 |
|
| 155 |
(defun delete-item (db-connection int-value string-value) |
| 156 |
(pg-prepare db-connection "delete-statement" |
| 157 |
"DELETE FROM items WHERE int_column = $1 AND string_column = $2" |
| 158 |
`("int4" "varchar")) |
| 159 |
(unwind-protect |
| 160 |
(progn (pg-bind db-connection "delete-portal" "delete-statement" |
| 161 |
`((:int32 ,int-value) (:string ,string-value))) |
| 162 |
(pg-execute db-connection "delete-portal")) |
| 163 |
;; NB: portal is closed automatically when statement is closed |
| 164 |
(pg-close-statement db-connection "delete-statement"))) |
| 165 |
|
| 166 |
|
| 167 |
=== Introspection support ============================================== |
| 168 |
|
| 169 |
(pg-databases connection) -> list of strings |
| 170 |
Return a list of the databases available at this site (a |
| 171 |
database is a set of tables; in a virgin PostgreSQL |
| 172 |
installation there is a single database named "template1"). |
| 173 |
|
| 174 |
(pg-tables connection) -> list of strings |
| 175 |
Return a list of the tables present in the database to which we |
| 176 |
are currently connected. Only include user tables: system |
| 177 |
tables are excluded. |
| 178 |
|
| 179 |
(pg-columns connection table) -> list of strings |
| 180 |
Return a list of the columns (or attributes) in TABLE, which |
| 181 |
must be a table in the database to which we are currently |
| 182 |
connected. We only include the column names; if you want more |
| 183 |
detailed information (attribute types, for example), it can be |
| 184 |
obtained from `pg-result' on a SELECT statement for that table. |
| 185 |
|
| 186 |
|
| 187 |
=== Support for large objects (BLOBs) ================================= |
| 188 |
|
| 189 |
(pglo-create conn . args) -> oid |
| 190 |
Create a new large object (BLOB, or binary large object in |
| 191 |
other DBMSes parlance) in the database to which we are |
| 192 |
connected via CONN. Returns an OID (which is represented as an |
| 193 |
integer) which will allow you to use the large object. |
| 194 |
Optional ARGS are a Unix-style mode string which determines the |
| 195 |
permissions of the newly created large object, one of "r" for |
| 196 |
read-only permission, "w" for write-only, "rw" for read+write. |
| 197 |
Default is "r". |
| 198 |
|
| 199 |
Large-object functions MUST be used within a transaction (see |
| 200 |
the macro `with-pg-transaction'). |
| 201 |
|
| 202 |
(pglo-open conn oid . args) -> fd |
| 203 |
Open a large object whose unique identifier is OID (an integer) |
| 204 |
in the database to which we are connected via CONN. Optional ARGS |
| 205 |
is a Unix-style mode string as for pglo-create; which defaults to |
| 206 |
"r" read-only permissions. Returns a file descriptor (an integer) |
| 207 |
which can be used in other large-object functions. |
| 208 |
|
| 209 |
(pglo-close conn fd) |
| 210 |
Close the file descriptor FD which was associated with a large |
| 211 |
object. Note that this does not delete the large object; use |
| 212 |
PGLO-UNLINK for that. |
| 213 |
|
| 214 |
(pglo-read conn fd bytes) -> string |
| 215 |
Read BYTES from the file descriptor FD which is associated with a |
| 216 |
large object. Return a string which should be BYTES characters |
| 217 |
long. |
| 218 |
|
| 219 |
(pglo-write connection fd buf) |
| 220 |
Write the bytes contained in the string BUF to the large object |
| 221 |
associated with the file descriptor FD. |
| 222 |
|
| 223 |
(pglo-lseek conn fd offset whence) |
| 224 |
Do the equivalent of a lseek(2) on the file descriptor FD which |
| 225 |
is associated with a large object; ie reposition the read/write |
| 226 |
file offset for that large object to OFFSET (an integer). WHENCE |
| 227 |
has the same significance as in lseek(); it should be one of |
| 228 |
SEEK_SET (set the offset to the absolute position), SEEK_CUR (set |
| 229 |
the offset relative to the current offset) or SEEK_END (set the |
| 230 |
offset relative to the end of the file). WHENCE should be an |
| 231 |
integer whose values can be obtained from the header file |
| 232 |
<unistd.h> (probably 0, 1 and 2 respectively). |
| 233 |
|
| 234 |
(pglo-tell conn oid) -> integer |
| 235 |
Do the equivalent of an ftell(3) on the file associated with |
| 236 |
the large object whose unique identifier is OID. Returns the |
| 237 |
current position of the file offset for the object's associated |
| 238 |
file descriptor, as an integer. |
| 239 |
|
| 240 |
(pglo-unlink conn oid) |
| 241 |
Remove the large object whose unique identifier is OID from the |
| 242 |
system (in the current implementation of large objects in |
| 243 |
PostgreSQL, each large object is associated with an object in |
| 244 |
the filesystem). |
| 245 |
|
| 246 |
(pglo-import conn filename) -> oid |
| 247 |
Create a new large object and initialize it to the data contained |
| 248 |
in the file whose name is FILENAME. Returns an OID (as an |
| 249 |
integer). Note that is operation is only syntactic sugar around |
| 250 |
the basic large-object operations listed above. |
| 251 |
|
| 252 |
(pglo-export conn oid filename) |
| 253 |
Create a new file named FILENAME and fill it with the contents |
| 254 |
of the large object whose unique identifier is OID. This |
| 255 |
operation is also syntactic sugar. |
| 256 |
|
| 257 |
Boolean variable `*PG-DISABLE-TYPE-COERCION*' which can be set to |
| 258 |
non-nil (before initiating a connection) to disable the library's |
| 259 |
type coercion facility. Default is t. |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
SECURITY NOTE: please note that your postmaster has to be started |
| 264 |
with the `-i' option in order for it to accept TCP/IP connections |
| 265 |
(typically this is not the default setting). See the PostgreSQL |
| 266 |
documentation at <URL:http://www.PostgreSQL.org/> for more |
| 267 |
information. |
| 268 |
|
| 269 |
Setting up PostgreSQL to accept TCP/IP connections has security |
| 270 |
implications; please consult the documentation for details. You can |
| 271 |
connect to the database using Unix domain sockets if you wish to |
| 272 |
avoid setting up PostgreSQL to listen on a TCP socket. |
| 273 |
|
| 274 |
pg.lisp is able to use the crypt authentication method to avoid |
| 275 |
sending the password in cleartext over the wire (this assumes access |
| 276 |
to the `crypt' function via the FFI -- see sysdep.lisp). It can also |
| 277 |
use md5 passwords (which are used with the WITH ENCRYPTED PASSWORD |
| 278 |
form of the CREATE USER command), thanks to Pierre Mai's portable md5 |
| 279 |
library. It does not support the Kerberos authentication method, nor |
| 280 |
OpenSSL connections (though this should not be difficult if your |
| 281 |
Common Lisp implementation is able to open SSL streams). |
| 282 |
|
| 283 |
It is also possible to use the port forwarding capabilities of ssh to |
| 284 |
establish a connection to the backend over TCP/IP, which provides |
| 285 |
both a secure authentication mechanism and encryption (and optionally |
| 286 |
compression) of data passing through the tunnel. Here's how to do it |
| 287 |
(thanks to Gene Selkov, Jr. <[email protected]> for the |
| 288 |
description): |
| 289 |
|
| 290 |
1. Establish a tunnel to the backend machine, like this: |
| 291 |
|
| 292 |
ssh -L 3333:backend.dom:5432 [email protected] |
| 293 |
|
| 294 |
The first number in the -L argument, 3333, is the port number of |
| 295 |
your end of the tunnel. The second number, 5432, is the remote |
| 296 |
end of the tunnel -- the port number your backend is using. The |
| 297 |
name or the address in between the port numbers belongs to the |
| 298 |
server machine, as does the last argument to ssh that also includes |
| 299 |
the optional user name. Without the user name, ssh will try the |
| 300 |
name you are currently logged on as on the client machine. You can |
| 301 |
use any user name the server machine will accept, not necessarily |
| 302 |
those related to postgres. |
| 303 |
|
| 304 |
2. Now that you have a running ssh session, you can point pg.lisp to |
| 305 |
the local host at the port number which you specified in step 1. |
| 306 |
For example, |
| 307 |
|
| 308 |
(pg-connect "dbname" "user" :port 3333) |
| 309 |
|
| 310 |
You can omit the port argument if you chose 5432 as the local |
| 311 |
end of the tunnel, since pg.lisp defaults to this value. |
| 312 |
|
| 313 |
|
| 314 |
At various times, this code has been tested or reported to work with |
| 315 |
|
| 316 |
* CMUCL 18d, 18e, 19a, 19c on Solaris/SPARC and Linux/x86 |
| 317 |
* SBCL 0.9.2 to 0.9.16 on Linux/x86 |
| 318 |
* CLISP 2.30 on LinuxPPC and SPARC |
| 319 |
* OpenMCL 0.13.x and 0.14.x on LinuxPPC |
| 320 |
* Armed Bear Common Lisp |
| 321 |
* ACL 6.1 trial/x86 |
| 322 |
* Lispworks 4.3 on Linux and Windows |
| 323 |
* PostgreSQL versions 6.5, 7.0, 7.1.2, 7.2, 7.3, 7.4, 8.0, 8.1 |
| 324 |
|
| 325 |
|
| 326 |
You may be interested in using "pg-psql" by Harley Gorrell, which |
| 327 |
provides a psql-like listener interface to PostgreSQL (together with |
| 328 |
tabulated output), on top of this library. See |
| 329 |
|
| 330 |
<URL:http://www.mahalito.net/~harley/cl/pg-psql.lisp> |
| 331 |
|
| 332 |
|