1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
5 ;;;; Name: postgresql-sql.lisp
6 ;;;; Purpose: High-level PostgreSQL interface using UFFI
7 ;;;; Date Started: Feb 2002
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
16 (in-package #:cl-user)
18 (defpackage #:clsql-postgresql
19 (:use #:common-lisp #:clsql-sys #:postgresql #:clsql-uffi)
20 (:export #:postgresql-database)
21 (:documentation "This is the CLSQL interface to PostgreSQL."))
23 (in-package #:clsql-postgresql)
25 ;;; Field conversion functions
27 (defun make-type-list-for-auto (num-fields res-ptr)
28 (let ((new-types '()))
29 (dotimes (i num-fields)
31 (let* ((type (PQftype res-ptr i)))
40 ((#.pgsql-ftype#float4
46 (nreverse new-types)))
48 (defun canonicalize-types (types num-fields res-ptr)
51 (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
54 (canonicalize-type-list types auto-list))
60 (defun tidy-error-message (message)
61 (unless (stringp message)
62 (setq message (uffi:convert-from-foreign-string message)))
63 (let ((message (string-right-trim '(#\Return #\Newline) message)))
65 ((< (length message) (length "ERROR:"))
67 ((string= message "ERROR:" :end1 6)
68 (string-left-trim '(#\Space) (subseq message 6)))
72 (defmethod database-initialize-database-type ((database-type
76 (uffi:def-type pgsql-conn-def pgsql-conn)
77 (uffi:def-type pgsql-result-def pgsql-result)
80 (defclass postgresql-database (generic-postgresql-database)
81 ((conn-ptr :accessor database-conn-ptr :initarg :conn-ptr
84 :accessor database-lock
85 :initform (make-process-lock "conn"))))
87 (defmethod database-type ((database postgresql-database))
90 (defmethod database-name-from-spec (connection-spec (database-type
92 (check-connection-spec connection-spec database-type
93 (host db user password &optional port options tty))
94 (destructuring-bind (host db user password &optional port options tty)
96 (declare (ignore password options tty))
100 (pathname (namestring host))
106 (integer (write-to-string port))
111 (defmethod database-connect (connection-spec (database-type (eql :postgresql)))
112 (check-connection-spec connection-spec database-type
113 (host db user password &optional port options tty))
114 (destructuring-bind (host db user password &optional port options tty)
116 (uffi:with-cstrings ((host-native host)
118 (password-native password)
121 (options-native options)
123 (let ((connection (PQsetdbLogin host-native port-native
124 options-native tty-native
125 db-native user-native
127 (declare (type pgsql-conn-def connection))
128 (when (not (eq (PQstatus connection)
129 pgsql-conn-status-type#connection-ok))
130 (error 'sql-connection-error
131 :database-type database-type
132 :connection-spec connection-spec
133 :error-id (PQstatus connection)
134 :message (tidy-error-message
135 (PQerrorMessage connection))))
136 (make-instance 'postgresql-database
137 :name (database-name-from-spec connection-spec
139 :database-type :postgresql
140 :connection-spec connection-spec
141 :conn-ptr connection)))))
144 (defmethod database-disconnect ((database postgresql-database))
145 (PQfinish (database-conn-ptr database))
146 (setf (database-conn-ptr database) nil)
149 (defmethod database-query (query-expression (database postgresql-database) result-types field-names)
150 (let ((conn-ptr (database-conn-ptr database)))
151 (declare (type pgsql-conn-def conn-ptr))
152 (uffi:with-cstring (query-native query-expression)
153 (let ((result (PQexec conn-ptr query-native)))
154 (when (uffi:null-pointer-p result)
155 (error 'sql-database-data-error
157 :expression query-expression
158 :message (tidy-error-message (PQerrorMessage conn-ptr))))
160 (case (PQresultStatus result)
161 (#.pgsql-exec-status-type#empty-query
163 (#.pgsql-exec-status-type#tuples-ok
164 (let ((num-fields (PQnfields result)))
166 (canonicalize-types result-types num-fields
169 (loop for tuple-index from 0 below (PQntuples result)
171 (loop for i from 0 below num-fields
173 (if (zerop (PQgetisnull result tuple-index i))
175 (PQgetvalue result tuple-index i)
179 (result-field-names num-fields result)))))
181 (error 'sql-database-data-error
183 :expression query-expression
184 :error-id (PQresultStatus result)
185 :message (tidy-error-message
186 (PQresultErrorMessage result)))))
187 (PQclear result))))))
189 (defun result-field-names (num-fields result)
190 "Return list of result field names."
192 (dotimes (i num-fields (nreverse names))
194 (push (uffi:convert-from-cstring (PQfname result i)) names))))
196 (defmethod database-execute-command (sql-expression
197 (database postgresql-database))
198 (let ((conn-ptr (database-conn-ptr database)))
199 (declare (type pgsql-conn-def conn-ptr))
200 (uffi:with-cstring (sql-native sql-expression)
201 (let ((result (PQexec conn-ptr sql-native)))
202 (when (uffi:null-pointer-p result)
203 (error 'sql-database-data-error
205 :expression sql-expression
206 :message (tidy-error-message (PQerrorMessage conn-ptr))))
208 (case (PQresultStatus result)
209 (#.pgsql-exec-status-type#command-ok
211 ((#.pgsql-exec-status-type#empty-query
212 #.pgsql-exec-status-type#tuples-ok)
213 (warn "Strange result...")
216 (error 'sql-database-data-error
218 :expression sql-expression
219 :error-id (PQresultStatus result)
220 :message (tidy-error-message
221 (PQresultErrorMessage result)))))
222 (PQclear result))))))
224 (defstruct postgresql-result-set
225 (res-ptr (uffi:make-null-pointer 'pgsql-result)
226 :type pgsql-result-def)
228 (num-tuples 0 :type integer)
229 (num-fields 0 :type integer)
230 (tuple-index 0 :type integer))
232 (defmethod database-query-result-set ((query-expression string)
233 (database postgresql-database)
234 &key full-set result-types)
235 (let ((conn-ptr (database-conn-ptr database)))
236 (declare (type pgsql-conn-def conn-ptr))
237 (uffi:with-cstring (query-native query-expression)
238 (let ((result (PQexec conn-ptr query-native)))
239 (when (uffi:null-pointer-p result)
240 (error 'sql-database-data-error
242 :expression query-expression
243 :message (tidy-error-message (PQerrorMessage conn-ptr))))
244 (case (PQresultStatus result)
245 ((#.pgsql-exec-status-type#empty-query
246 #.pgsql-exec-status-type#tuples-ok)
247 (let ((result-set (make-postgresql-result-set
249 :num-fields (PQnfields result)
250 :num-tuples (PQntuples result)
251 :types (canonicalize-types
260 (PQnfields result)))))
263 (error 'sql-database-data-error
265 :expression query-expression
266 :error-id (PQresultStatus result)
267 :message (tidy-error-message
268 (PQresultErrorMessage result)))
269 (PQclear result))))))))
271 (defmethod database-dump-result-set (result-set (database postgresql-database))
272 (let ((res-ptr (postgresql-result-set-res-ptr result-set)))
273 (declare (type pgsql-result-def res-ptr))
277 (defmethod database-store-next-row (result-set (database postgresql-database)
279 (let ((result (postgresql-result-set-res-ptr result-set))
280 (types (postgresql-result-set-types result-set)))
281 (declare (type pgsql-result-def result))
282 (if (>= (postgresql-result-set-tuple-index result-set)
283 (postgresql-result-set-num-tuples result-set))
285 (loop with tuple-index = (postgresql-result-set-tuple-index result-set)
286 for i from 0 below (postgresql-result-set-num-fields result-set)
290 (if (zerop (PQgetisnull result tuple-index i))
292 (PQgetvalue result tuple-index i)
296 (incf (postgresql-result-set-tuple-index result-set))
299 ;;; Large objects support (Marc B)
301 (defmethod database-create-large-object ((database postgresql-database))
302 (lo-create (database-conn-ptr database)
303 (logior postgresql::+INV_WRITE+ postgresql::+INV_READ+)))
307 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
308 (let ((ptr (database-conn-ptr database))
309 (length (length data))
312 (with-transaction (:database database)
315 (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
317 (when (= (lo-write ptr fd data length) length)
320 (when (and fd (>= fd 0))
325 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
326 (let ((ptr (database-conn-ptr database))
327 (length (length data))
330 (database-execute-command "begin" database)
333 (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
335 (when (= (lo-write ptr fd data length) length)
338 (when (and fd (>= fd 0))
340 (database-execute-command (if result "commit" "rollback") database)))
343 ;; (MB) the begin/commit/rollback stuff will be removed when with-transaction wil be implemented
344 ;; (KMR) Can't use with-transaction since that function is in high-level code
345 (defmethod database-read-large-object (object-id (database postgresql-database))
346 (let ((ptr (database-conn-ptr database))
353 (database-execute-command "begin" database)
354 (setf fd (lo-open ptr object-id postgresql::+INV_READ+))
356 (setf length (lo-lseek ptr fd 0 2))
357 (lo-lseek ptr fd 0 0)
359 (setf buffer (uffi:allocate-foreign-string
361 (when (= (lo-read ptr fd buffer length) length)
362 (setf result (uffi:convert-from-foreign-string
363 buffer :length length :null-terminated-p nil))))))
365 (when buffer (uffi:free-foreign-object buffer))
366 (when (and fd (>= fd 0)) (lo-close ptr fd))
367 (database-execute-command (if result "commit" "rollback") database)))
370 (defmethod database-delete-large-object (object-id (database postgresql-database))
371 (lo-unlink (database-conn-ptr database) object-id))
378 (defmethod database-create (connection-spec (type (eql :postgresql)))
379 (destructuring-bind (host name user password) connection-spec
380 (declare (ignore user password))
381 (multiple-value-bind (output status)
382 (clsql-sys:command-output "createdb -h~A ~A"
383 (if host host "localhost")
385 (if (or (not (zerop status))
386 (search "database creation failed: ERROR:" output))
387 (error 'sql-database-error
389 (format nil "createdb failed for postgresql backend with connection spec ~A."
393 (defmethod database-destroy (connection-spec (type (eql :postgresql)))
394 (destructuring-bind (host name user password) connection-spec
395 (declare (ignore user password))
396 (multiple-value-bind (output status)
397 (clsql-sys:command-output "dropdb -h~A ~A"
398 (if host host "localhost")
400 (if (or (not (zerop status))
401 (search "database removal failed: ERROR:" output))
402 (error 'sql-database-error
404 (format nil "dropdb failed for postgresql backend with connection spec ~A."
409 (defmethod database-probe (connection-spec (type (eql :postgresql)))
410 (when (find (second connection-spec) (database-list connection-spec type)
411 :key #'car :test #'string-equal)
415 (defun %pg-database-connection (connection-spec)
416 (check-connection-spec connection-spec :postgresql
417 (host db user password &optional port options tty))
418 (macrolet ((coerce-string (var)
419 `(unless (typep ,var 'simple-base-string)
420 (setf ,var (coerce ,var 'simple-base-string)))))
421 (destructuring-bind (host db user password &optional port options tty)
425 (let ((connection (PQsetdbLogin host port options tty db user password)))
426 (declare (type postgresql::pgsql-conn-ptr connection))
427 (unless (eq (PQstatus connection) :connection-ok)
429 (error 'sql-connection-error
430 :database-type :postgresql
431 :connection-spec connection-spec
432 :error-id (PQstatus connection)
433 :message (PQerrorMessage connection)))
436 (defmethod database-reconnect ((database postgresql-database))
437 (let ((lock (database-lock database)))
438 (with-process-lock (lock "Reconnecting")
439 (with-slots (connection-spec conn-ptr)
441 (setf conn-ptr (%pg-database-connection connection-spec))
444 ;;; Database capabilities
446 (when (clsql-sys:database-type-library-loaded :postgresql)
447 (clsql-sys:initialize-database-type :database-type :postgresql))