Remove CVS $Id$ keyword
[clsql.git] / db-postgresql / postgresql-sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          postgresql-sql.lisp
6 ;;;; Purpose:       High-level PostgreSQL interface using UFFI
7 ;;;; Date Started:  Feb 2002
8 ;;;;
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 ;;;; *************************************************************************
13
14 (in-package #:cl-user)
15
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."))
20
21 (in-package #:clsql-postgresql)
22
23 ;;; Field conversion functions
24
25 (defun make-type-list-for-auto (num-fields res-ptr)
26   (let ((new-types '()))
27     (dotimes (i num-fields)
28       (declare (fixnum i))
29       (let* ((type (PQftype res-ptr i)))
30         (push
31          (case type
32            ((#.pgsql-ftype#bytea
33              #.pgsql-ftype#int2
34              #.pgsql-ftype#int4)
35             :int32)
36            (#.pgsql-ftype#int8
37             :int64)
38            ((#.pgsql-ftype#float4
39              #.pgsql-ftype#float8)
40             :double)
41            (otherwise
42             t))
43          new-types)))
44       (nreverse new-types)))
45
46 (defun canonicalize-types (types num-fields res-ptr)
47   (if (null types)
48       nil
49       (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
50         (cond
51           ((listp types)
52            (canonicalize-type-list types auto-list))
53           ((eq types :auto)
54            auto-list)
55           (t
56            nil)))))
57
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)))
62     (cond
63       ((< (length message) (length "ERROR:"))
64        message)
65       ((string= message "ERROR:" :end1 6)
66        (string-left-trim '(#\Space) (subseq message 6)))
67       (t
68        message))))
69
70 (defmethod database-initialize-database-type ((database-type
71                                                (eql :postgresql)))
72   t)
73
74 (uffi:def-type pgsql-conn-def pgsql-conn)
75 (uffi:def-type pgsql-result-def pgsql-result)
76
77
78 (defclass postgresql-database (generic-postgresql-database)
79   ((conn-ptr :accessor database-conn-ptr :initarg :conn-ptr
80              :type pgsql-conn-def)
81    (lock
82     :accessor database-lock
83     :initform (make-process-lock "conn"))))
84
85 (defmethod database-type ((database postgresql-database))
86   :postgresql)
87
88 (defmethod database-name-from-spec (connection-spec (database-type
89                                                      (eql :postgresql)))
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)
93       connection-spec
94     (declare (ignore password options tty))
95     (concatenate 'string
96       (etypecase host
97         (null "localhost")
98         (pathname (namestring host))
99         (string host))
100       (when port
101         (concatenate 'string
102                      ":"
103                      (etypecase port
104                        (integer (write-to-string port))
105                        (string port))))
106       "/" db "/" user)))
107
108
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)
113       connection-spec
114     (uffi:with-cstrings ((host-native host)
115                          (user-native user)
116                          (password-native password)
117                          (db-native db)
118                          (port-native port)
119                          (options-native options)
120                          (tty-native tty))
121       (let ((connection (PQsetdbLogin host-native port-native
122                                       options-native tty-native
123                                       db-native user-native
124                                       password-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
134                    :error-id pqstatus
135                    :message  pqmessage)))
136         (make-instance 'postgresql-database
137                        :name (database-name-from-spec connection-spec
138                                                       database-type)
139                        :database-type :postgresql
140                        :connection-spec connection-spec
141                        :conn-ptr connection)))))
142
143
144 (defmethod database-disconnect ((database postgresql-database))
145   (PQfinish (database-conn-ptr database))
146   (setf (database-conn-ptr database) nil)
147   t)
148
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
156                  :database database
157                  :expression query-expression
158                  :message (tidy-error-message (PQerrorMessage conn-ptr))))
159         (unwind-protect
160             (case (PQresultStatus result)
161               ;; User gave a command rather than a query
162               (#.pgsql-exec-status-type#command-ok
163                nil)
164               (#.pgsql-exec-status-type#empty-query
165                nil)
166               (#.pgsql-exec-status-type#tuples-ok
167                (let ((num-fields (PQnfields result)))
168                  (when result-types
169                    (setq result-types
170                      (canonicalize-types result-types num-fields
171                                          result)))
172                  (let ((res (loop for tuple-index from 0 below (PQntuples result)
173                                 collect
174                                   (loop for i from 0 below num-fields
175                                       collect
176                                         (if (zerop (PQgetisnull result tuple-index i))
177                                             (convert-raw-field
178                                              (PQgetvalue result tuple-index i)
179                                              result-types i)
180                                           nil)))))
181                    (if field-names
182                        (values res (result-field-names num-fields result))
183                      res))))
184               (t
185                (error 'sql-database-data-error
186                       :database database
187                       :expression query-expression
188                       :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
189                       :message (tidy-error-message
190                                 (PQresultErrorMessage result)))))
191           (PQclear result))))))
192
193 (defun result-field-names (num-fields result)
194   "Return list of result field names."
195   (let ((names '()))
196     (dotimes (i num-fields (nreverse names))
197       (declare (fixnum i))
198       (push (uffi:convert-from-cstring (PQfname result i)) names))))
199
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
208                  :database database
209                  :expression sql-expression
210                  :message (tidy-error-message (PQerrorMessage conn-ptr))))
211         (unwind-protect
212             (case (PQresultStatus result)
213               (#.pgsql-exec-status-type#command-ok
214                t)
215               ((#.pgsql-exec-status-type#empty-query
216                 #.pgsql-exec-status-type#tuples-ok)
217                (warn "Strange result...")
218                t)
219               (t
220                (error 'sql-database-data-error
221                       :database database
222                       :expression sql-expression
223                       :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
224                       :message (tidy-error-message
225                                 (PQresultErrorMessage result)))))
226           (PQclear result))))))
227
228 (defstruct postgresql-result-set
229   (res-ptr (uffi:make-null-pointer 'pgsql-result)
230            :type pgsql-result-def)
231   (types nil)
232   (num-tuples 0 :type integer)
233   (num-fields 0 :type integer)
234   (tuple-index 0 :type integer))
235
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
245                  :database database
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
252                         :res-ptr result
253                         :num-fields (PQnfields result)
254                         :num-tuples (PQntuples result)
255                         :types (canonicalize-types
256                                       result-types
257                                       (PQnfields result)
258                                       result))))
259              (if full-set
260                  (values result-set
261                          (PQnfields result)
262                          (PQntuples result))
263                  (values result-set
264                          (PQnfields result)))))
265           (t
266            (unwind-protect
267                (error 'sql-database-data-error
268                       :database database
269                       :expression query-expression
270                       :error-id (PQresultErrorField result +PG-DIAG-SQLSTATE+)
271                       :message (tidy-error-message
272                                 (PQresultErrorMessage result)))
273              (PQclear result))))))))
274
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))
278     (PQclear res-ptr)
279     t))
280
281 (defmethod database-store-next-row (result-set (database postgresql-database)
282                                     list)
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))
288         nil
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)
291           for rest on list
292           do
293             (setf (car rest)
294               (if (zerop (PQgetisnull result tuple-index i))
295                   (convert-raw-field
296                    (PQgetvalue result tuple-index i)
297                    types i)
298                 nil))
299           finally
300             (incf (postgresql-result-set-tuple-index result-set))
301             (return list)))))
302
303 ;;; Large objects support (Marc B)
304
305 (defmethod database-create-large-object ((database postgresql-database))
306   (lo-create (database-conn-ptr database)
307              (logior pgsql::+INV_WRITE+ pgsql::+INV_READ+)))
308
309
310 #+mb-original
311 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
312   (let ((ptr (database-conn-ptr database))
313         (length (length data))
314         (result nil)
315         (fd nil))
316     (with-transaction (:database database)
317        (unwind-protect
318           (progn
319             (setf fd (lo-open ptr object-id pgsql::+INV_WRITE+))
320             (when (>= fd 0)
321               (when (= (lo-write ptr fd data length) length)
322                 (setf result t))))
323          (progn
324            (when (and fd (>= fd 0))
325              (lo-close ptr fd))
326            )))
327     result))
328
329 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
330   (let ((ptr (database-conn-ptr database))
331         (length (length data))
332         (result nil)
333         (fd nil))
334     (database-execute-command "begin" database)
335     (unwind-protect
336         (progn
337           (setf fd (lo-open ptr object-id pgsql::+INV_WRITE+))
338           (when (>= fd 0)
339             (when (= (lo-write ptr fd data length) length)
340               (setf result t))))
341       (progn
342         (when (and fd (>= fd 0))
343           (lo-close ptr fd))
344         (database-execute-command (if result "commit" "rollback") database)))
345     result))
346
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))
351         (buffer nil)
352         (result nil)
353         (length 0)
354         (fd nil))
355     (unwind-protect
356        (progn
357          (database-execute-command "begin" database)
358          (setf fd (lo-open ptr object-id pgsql::+INV_READ+))
359          (when (>= fd 0)
360            (setf length (lo-lseek ptr fd 0 2))
361            (lo-lseek ptr fd 0 0)
362            (when (> length 0)
363              (setf buffer (uffi:allocate-foreign-string
364                            length :unsigned t))
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))))))
368       (progn
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)))
372     result))
373
374 (defmethod database-delete-large-object (object-id (database postgresql-database))
375   (lo-unlink (database-conn-ptr database) object-id))
376
377
378 ;;; Object listing
379
380
381
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)
385                                       type)))
386       (setf (slot-value database 'clsql-sys::state) :open)
387       (unwind-protect
388            (database-execute-command (format nil "create database ~A" name) database)
389         (database-disconnect database)))))
390
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)
394                                       type)))
395       (setf (slot-value database 'clsql-sys::state) :open)
396       (unwind-protect
397            (database-execute-command (format nil "drop database ~A" name) database)
398         (database-disconnect database)))))
399
400
401 (defmethod database-probe (connection-spec (type (eql :postgresql)))
402   (when (find (second connection-spec) (database-list connection-spec type)
403               :test #'string-equal)
404     t))
405
406
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)
414         connection-spec
415       (coerce-string db)
416       (coerce-string user)
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)
421           ;; Connect failed
422           (error 'sql-connection-error
423                  :database-type :postgresql
424                  :connection-spec connection-spec
425                  :error-id (PQstatus connection)
426                  :message (PQerrorMessage connection)))
427         connection))))
428
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)
433           database
434         (setf conn-ptr (%pg-database-connection connection-spec))
435         database))))
436
437 ;;; Database capabilities
438
439 (when (clsql-sys:database-type-library-loaded :postgresql)
440   (clsql-sys:initialize-database-type :database-type :postgresql))