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
9 ;;;; CLSQL users are granted the rights to distribute and use this software
10 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
11 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
12 ;;;; *************************************************************************
14 (in-package #:cl-user)
16 (defpackage #:clsql-postgresql
17 (:use #:common-lisp #:clsql-sys #:pgsql #:clsql-uffi)
18 (:export #:postgresql-database)
19 (:documentation "This is the CLSQL interface to PostgreSQL."))
21 (in-package #:clsql-postgresql)
23 ;;; Field conversion functions
25 (defun make-type-list-for-auto (num-fields res-ptr)
26 (let ((new-types '()))
27 (dotimes (i num-fields)
29 (let* ((type (PQftype res-ptr i)))
38 ((#.pgsql-ftype#float4
44 (nreverse new-types)))
46 (defun canonicalize-types (types num-fields res-ptr)
49 (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
52 (canonicalize-type-list types auto-list))
58 (defun tidy-error-message (message)
59 (unless (stringp message)
60 (setq message (uffi:convert-from-foreign-string message)))
61 (let ((message (string-right-trim '(#\Return #\Newline) message)))
63 ((< (length message) (length "ERROR:"))
65 ((string= message "ERROR:" :end1 6)
66 (string-left-trim '(#\Space) (subseq message 6)))
70 (defmethod database-initialize-database-type ((database-type
74 (uffi:def-type pgsql-conn-def pgsql-conn)
75 (uffi:def-type pgsql-result-def pgsql-result)
78 (defclass postgresql-database (generic-postgresql-database)
79 ((conn-ptr :accessor database-conn-ptr :initarg :conn-ptr
82 :accessor database-lock
83 :initform (make-process-lock "conn"))))
85 (defmethod database-type ((database postgresql-database))
88 (defmethod database-name-from-spec (connection-spec (database-type
90 (check-connection-spec connection-spec database-type
91 (host db user password &optional port options tty))
92 (destructuring-bind (host db user password &optional port options tty)
94 (declare (ignore password options tty))
98 (pathname (namestring host))
104 (integer (write-to-string port))
109 (defmethod database-connect (connection-spec (database-type (eql :postgresql)))
110 (check-connection-spec connection-spec database-type
111 (host db user password &optional port options tty))
112 (destructuring-bind (host db user password &optional port options tty)
114 (uffi:with-cstrings ((host-native host)
116 (password-native password)
119 (options-native options)
121 (let ((connection (PQsetdbLogin host-native port-native
122 options-native tty-native
123 db-native user-native
125 (declare (type pgsql-conn-def connection))
126 (when (not (eq (PQstatus connection)
127 pgsql-conn-status-type#connection-ok))
128 (let ((pqstatus (PQstatus connection))
129 (pqmessage (tidy-error-message (PQerrorMessage connection))))
130 (PQfinish connection)
131 (error 'sql-connection-error
132 :database-type database-type
133 :connection-spec connection-spec
135 :message pqmessage)))
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 ;; User gave a command rather than a query
162 (#.pgsql-exec-status-type#command-ok
164 (#.pgsql-exec-status-type#empty-query
166 (#.pgsql-exec-status-type#tuples-ok
167 (let ((num-fields (PQnfields result)))
170 (canonicalize-types result-types num-fields
172 (let ((res (loop for tuple-index from 0 below (PQntuples result)
174 (loop for i from 0 below num-fields
176 (if (zerop (PQgetisnull result tuple-index i))
178 (PQgetvalue result tuple-index i)
182 (values res (result-field-names num-fields result))
185 (error 'sql-database-data-error
187 :expression query-expression
188 :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
189 :message (tidy-error-message
190 (PQresultErrorMessage result)))))
191 (PQclear result))))))
193 (defun result-field-names (num-fields result)
194 "Return list of result field names."
196 (dotimes (i num-fields (nreverse names))
198 (push (uffi:convert-from-cstring (PQfname result i)) names))))
200 (defmethod database-execute-command (sql-expression
201 (database postgresql-database))
202 (let ((conn-ptr (database-conn-ptr database)))
203 (declare (type pgsql-conn-def conn-ptr))
204 (uffi:with-cstring (sql-native sql-expression)
205 (let ((result (PQexec conn-ptr sql-native)))
206 (when (uffi:null-pointer-p result)
207 (error 'sql-database-data-error
209 :expression sql-expression
210 :message (tidy-error-message (PQerrorMessage conn-ptr))))
212 (case (PQresultStatus result)
213 (#.pgsql-exec-status-type#command-ok
215 ((#.pgsql-exec-status-type#empty-query
216 #.pgsql-exec-status-type#tuples-ok)
217 (warn "Strange result...")
220 (error 'sql-database-data-error
222 :expression sql-expression
223 :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
224 :message (tidy-error-message
225 (PQresultErrorMessage result)))))
226 (PQclear result))))))
228 (defstruct postgresql-result-set
229 (res-ptr (uffi:make-null-pointer 'pgsql-result)
230 :type pgsql-result-def)
232 (num-tuples 0 :type integer)
233 (num-fields 0 :type integer)
234 (tuple-index 0 :type integer))
236 (defmethod database-query-result-set ((query-expression string)
237 (database postgresql-database)
238 &key full-set result-types)
239 (let ((conn-ptr (database-conn-ptr database)))
240 (declare (type pgsql-conn-def conn-ptr))
241 (uffi:with-cstring (query-native query-expression)
242 (let ((result (PQexec conn-ptr query-native)))
243 (when (uffi:null-pointer-p result)
244 (error 'sql-database-data-error
246 :expression query-expression
247 :message (tidy-error-message (PQerrorMessage conn-ptr))))
248 (case (PQresultStatus result)
249 ((#.pgsql-exec-status-type#empty-query
250 #.pgsql-exec-status-type#tuples-ok)
251 (let ((result-set (make-postgresql-result-set
253 :num-fields (PQnfields result)
254 :num-tuples (PQntuples result)
255 :types (canonicalize-types
264 (PQnfields result)))))
267 (error 'sql-database-data-error
269 :expression query-expression
270 :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
271 :message (tidy-error-message
272 (PQresultErrorMessage result)))
273 (PQclear result))))))))
275 (defmethod database-dump-result-set (result-set (database postgresql-database))
276 (let ((res-ptr (postgresql-result-set-res-ptr result-set)))
277 (declare (type pgsql-result-def res-ptr))
281 (defmethod database-store-next-row (result-set (database postgresql-database)
283 (let ((result (postgresql-result-set-res-ptr result-set))
284 (types (postgresql-result-set-types result-set)))
285 (declare (type pgsql-result-def result))
286 (if (>= (postgresql-result-set-tuple-index result-set)
287 (postgresql-result-set-num-tuples result-set))
289 (loop with tuple-index = (postgresql-result-set-tuple-index result-set)
290 for i from 0 below (postgresql-result-set-num-fields result-set)
294 (if (zerop (PQgetisnull result tuple-index i))
296 (PQgetvalue result tuple-index i)
300 (incf (postgresql-result-set-tuple-index result-set))
303 ;;; Large objects support (Marc B)
305 (defmethod database-create-large-object ((database postgresql-database))
306 (lo-create (database-conn-ptr database)
307 (logior pgsql::+INV_WRITE+ pgsql::+INV_READ+)))
311 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
312 (let ((ptr (database-conn-ptr database))
313 (length (length data))
316 (with-transaction (:database database)
319 (setf fd (lo-open ptr object-id pgsql::+INV_WRITE+))
321 (when (= (lo-write ptr fd data length) length)
324 (when (and fd (>= fd 0))
329 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
330 (let ((ptr (database-conn-ptr database))
331 (length (length data))
334 (database-execute-command "begin" database)
337 (setf fd (lo-open ptr object-id pgsql::+INV_WRITE+))
339 (when (= (lo-write ptr fd data length) length)
342 (when (and fd (>= fd 0))
344 (database-execute-command (if result "commit" "rollback") database)))
347 ;; (MB) the begin/commit/rollback stuff will be removed when with-transaction wil be implemented
348 ;; (KMR) Can't use with-transaction since that function is in high-level code
349 (defmethod database-read-large-object (object-id (database postgresql-database))
350 (let ((ptr (database-conn-ptr database))
357 (database-execute-command "begin" database)
358 (setf fd (lo-open ptr object-id pgsql::+INV_READ+))
360 (setf length (lo-lseek ptr fd 0 2))
361 (lo-lseek ptr fd 0 0)
363 (setf buffer (uffi:allocate-foreign-string
365 (when (= (lo-read ptr fd buffer length) length)
366 (setf result (uffi:convert-from-foreign-string
367 buffer :length length :null-terminated-p nil))))))
369 (when buffer (uffi:free-foreign-object buffer))
370 (when (and fd (>= fd 0)) (lo-close ptr fd))
371 (database-execute-command (if result "commit" "rollback") database)))
374 (defmethod database-delete-large-object (object-id (database postgresql-database))
375 (lo-unlink (database-conn-ptr database) object-id))
382 (defmethod database-create (connection-spec (type (eql :postgresql)))
383 (destructuring-bind (host name user password) connection-spec
384 (let ((database (database-connect (list host "postgres" user password)
386 (setf (slot-value database 'clsql-sys::state) :open)
388 (database-execute-command (format nil "create database ~A" name) database)
389 (database-disconnect database)))))
391 (defmethod database-destroy (connection-spec (type (eql :postgresql)))
392 (destructuring-bind (host name user password) connection-spec
393 (let ((database (database-connect (list host "postgres" user password)
395 (setf (slot-value database 'clsql-sys::state) :open)
397 (database-execute-command (format nil "drop database ~A" name) database)
398 (database-disconnect database)))))
401 (defmethod database-probe (connection-spec (type (eql :postgresql)))
402 (when (find (second connection-spec) (database-list connection-spec type)
403 :test #'string-equal)
407 (defun %pg-database-connection (connection-spec)
408 (check-connection-spec connection-spec :postgresql
409 (host db user password &optional port options tty))
410 (macrolet ((coerce-string (var)
411 `(unless (typep ,var 'simple-base-string)
412 (setf ,var (coerce ,var 'simple-base-string)))))
413 (destructuring-bind (host db user password &optional port options tty)
417 (let ((connection (PQsetdbLogin host port options tty db user password)))
418 (declare (type pgsql::pgsql-conn-ptr connection))
419 (unless (eq (PQstatus connection)
420 pgsql-conn-status-type#connection-ok)
422 (error 'sql-connection-error
423 :database-type :postgresql
424 :connection-spec connection-spec
425 :error-id (PQstatus connection)
426 :message (PQerrorMessage connection)))
429 (defmethod database-reconnect ((database postgresql-database))
430 (let ((lock (database-lock database)))
431 (with-process-lock (lock "Reconnecting")
432 (with-slots (connection-spec conn-ptr)
434 (setf conn-ptr (%pg-database-connection connection-spec))
437 ;;; Database capabilities
439 (when (clsql-sys:database-type-library-loaded :postgresql)
440 (clsql-sys:initialize-database-type :database-type :postgresql))