r9138: add generics
[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 ;;;; $Id$
10 ;;;;
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 ;;;; *************************************************************************
15
16 (in-package #:cl-user)
17
18 (defpackage #:clsql-postgresql
19     (:use #:common-lisp #:clsql-base-sys #:postgresql #:clsql-uffi)
20     (:export #:postgresql-database)
21     (:documentation "This is the CLSQL interface to PostgreSQL."))
22
23 (in-package #:clsql-postgresql)
24
25 ;;; Field conversion functions
26
27 (defun make-type-list-for-auto (num-fields res-ptr)
28   (let ((new-types '()))
29     (dotimes (i num-fields)
30       (declare (fixnum i))
31       (let* ((type (PQftype res-ptr i)))
32         (push
33          (case type
34            ((#.pgsql-ftype#bytea
35              #.pgsql-ftype#int2
36              #.pgsql-ftype#int4)
37             :int32)
38            (#.pgsql-ftype#int8
39             :int64)
40            ((#.pgsql-ftype#float4
41              #.pgsql-ftype#float8)
42             :double)
43            (otherwise
44             t))
45          new-types)))
46       (nreverse new-types)))
47
48 (defun canonicalize-types (types num-fields res-ptr)
49   (if (null types)
50       nil
51       (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
52         (cond
53           ((listp types)
54            (canonicalize-type-list types auto-list))
55           ((eq types :auto)
56            auto-list)
57           (t
58            nil)))))
59
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)))
64     (cond
65       ((< (length message) (length "ERROR:"))
66        message)
67       ((string= message "ERROR:" :end1 6)
68        (string-left-trim '(#\Space) (subseq message 6)))
69       (t
70        message))))
71
72 (defmethod database-initialize-database-type ((database-type
73                                                (eql :postgresql)))
74   t)
75
76 (uffi:def-type pgsql-conn-def pgsql-conn)
77 (uffi:def-type pgsql-result-def pgsql-result)
78
79
80 (defclass postgresql-database (database)
81   ((conn-ptr :accessor database-conn-ptr :initarg :conn-ptr
82              :type pgsql-conn-def)
83    (lock
84     :accessor database-lock
85     :initform (make-process-lock "conn"))))
86
87 (defmethod database-type ((database postgresql-database))
88   :postgresql)
89
90 (defmethod database-name-from-spec (connection-spec (database-type
91                                                      (eql :postgresql)))
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)
95       connection-spec
96     (declare (ignore password options tty))
97     (concatenate 'string 
98       (etypecase host
99         (null "localhost")
100         (pathname (namestring host))
101         (string host))
102       (when port 
103         (concatenate 'string
104                      ":"
105                      (etypecase port
106                        (integer (write-to-string port))
107                        (string port))))
108       "/" db "/" user)))
109
110
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)
115       connection-spec
116     (uffi:with-cstrings ((host-native host)
117                          (user-native user)
118                          (password-native password)
119                          (db-native db)
120                          (port-native port)
121                          (options-native options)
122                          (tty-native tty))
123       (let ((connection (PQsetdbLogin host-native port-native
124                                       options-native tty-native
125                                       db-native user-native
126                                       password-native)))
127         (declare (type pgsql-conn-def connection))
128         (when (not (eq (PQstatus connection) 
129                        pgsql-conn-status-type#connection-ok))
130           (error 'clsql-connect-error
131                  :database-type database-type
132                  :connection-spec connection-spec
133                  :errno (PQstatus connection)
134                  :error (tidy-error-message 
135                          (PQerrorMessage connection))))
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)
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 'clsql-sql-error
156                  :database database
157                  :expression query-expression
158                  :errno nil
159                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
160         (unwind-protect
161             (case (PQresultStatus result)
162               (#.pgsql-exec-status-type#empty-query
163                nil)
164               (#.pgsql-exec-status-type#tuples-ok
165                (let ((num-fields (PQnfields result)))
166                  (setq result-types
167                    (canonicalize-types result-types num-fields
168                                              result))
169                  (loop for tuple-index from 0 below (PQntuples result)
170                        collect
171                        (loop for i from 0 below num-fields
172                              collect
173                              (if (zerop (PQgetisnull result tuple-index i))
174                                  (convert-raw-field
175                                   (PQgetvalue result tuple-index i)
176                                   result-types i)
177                                  nil)))))
178               (t
179                (error 'clsql-sql-error
180                       :database database
181                       :expression query-expression
182                       :errno (PQresultStatus result)
183                       :error (tidy-error-message
184                               (PQresultErrorMessage result)))))
185           (PQclear result))))))
186
187 (defmethod database-execute-command (sql-expression
188                                      (database postgresql-database))
189   (let ((conn-ptr (database-conn-ptr database)))
190     (declare (type pgsql-conn-def conn-ptr))
191     (uffi:with-cstring (sql-native sql-expression)
192       (let ((result (PQexec conn-ptr sql-native)))
193         (when (uffi:null-pointer-p result)
194           (error 'clsql-sql-error
195                  :database database
196                  :expression sql-expression
197                  :errno nil
198                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
199         (unwind-protect
200             (case (PQresultStatus result)
201               (#.pgsql-exec-status-type#command-ok
202                t)
203               ((#.pgsql-exec-status-type#empty-query
204                 #.pgsql-exec-status-type#tuples-ok)
205                (warn "Strange result...")
206                t)
207               (t
208                (error 'clsql-sql-error
209                       :database database
210                       :expression sql-expression
211                       :errno (PQresultStatus result)
212                       :error (tidy-error-message
213                               (PQresultErrorMessage result)))))
214           (PQclear result))))))
215
216 (defstruct postgresql-result-set
217   (res-ptr (uffi:make-null-pointer 'pgsql-result) 
218            :type pgsql-result-def)
219   (types nil) 
220   (num-tuples 0 :type integer)
221   (num-fields 0 :type integer)
222   (tuple-index 0 :type integer))
223
224 (defmethod database-query-result-set ((query-expression string)
225                                       (database postgresql-database) 
226                                       &key full-set result-types)
227   (let ((conn-ptr (database-conn-ptr database)))
228     (declare (type pgsql-conn-def conn-ptr))
229     (uffi:with-cstring (query-native query-expression)
230       (let ((result (PQexec conn-ptr query-native)))
231         (when (uffi:null-pointer-p result)
232           (error 'clsql-sql-error
233                  :database database
234                  :expression query-expression
235                  :errno nil
236                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
237         (case (PQresultStatus result)
238           ((#.pgsql-exec-status-type#empty-query
239             #.pgsql-exec-status-type#tuples-ok)
240            (let ((result-set (make-postgresql-result-set
241                         :res-ptr result
242                         :num-fields (PQnfields result)
243                         :num-tuples (PQntuples result)
244                         :types (canonicalize-types 
245                                       result-types
246                                       (PQnfields result)
247                                       result))))
248              (if full-set
249                  (values result-set
250                          (PQnfields result)
251                          (PQntuples result))
252                  (values result-set
253                          (PQnfields result)))))
254           (t
255            (unwind-protect
256                (error 'clsql-sql-error
257                       :database database
258                       :expression query-expression
259                       :errno (PQresultStatus result)
260                       :error (tidy-error-message
261                               (PQresultErrorMessage result)))
262              (PQclear result))))))))
263   
264 (defmethod database-dump-result-set (result-set (database postgresql-database))
265   (let ((res-ptr (postgresql-result-set-res-ptr result-set))) 
266     (declare (type pgsql-result-def res-ptr))
267     (PQclear res-ptr)
268     t))
269
270 (defmethod database-store-next-row (result-set (database postgresql-database) 
271                                     list)
272   (let ((result (postgresql-result-set-res-ptr result-set))
273         (types (postgresql-result-set-types result-set)))
274     (declare (type pgsql-result-def result))
275     (if (>= (postgresql-result-set-tuple-index result-set)
276             (postgresql-result-set-num-tuples result-set))
277         nil
278       (loop with tuple-index = (postgresql-result-set-tuple-index result-set)
279           for i from 0 below (postgresql-result-set-num-fields result-set)
280           for rest on list
281           do
282             (setf (car rest)
283               (if (zerop (PQgetisnull result tuple-index i))
284                   (convert-raw-field
285                    (PQgetvalue result tuple-index i)
286                    types i)
287                 nil))
288           finally
289             (incf (postgresql-result-set-tuple-index result-set))
290             (return list)))))
291
292 ;;; Large objects support (Marc B)
293
294 (defmethod database-create-large-object ((database postgresql-database))
295   (lo-create (database-conn-ptr database)
296              (logior postgresql::+INV_WRITE+ postgresql::+INV_READ+)))
297
298
299 #+mb-original
300 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
301   (let ((ptr (database-conn-ptr database))
302         (length (length data))
303         (result nil)
304         (fd nil))
305     (with-transaction (:database database)
306        (unwind-protect
307           (progn 
308             (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
309             (when (>= fd 0)
310               (when (= (lo-write ptr fd data length) length)
311                 (setf result t))))
312          (progn
313            (when (and fd (>= fd 0))
314              (lo-close ptr fd))
315            )))
316     result))
317
318 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
319   (let ((ptr (database-conn-ptr database))
320         (length (length data))
321         (result nil)
322         (fd nil))
323     (database-execute-command "begin" database)
324     (unwind-protect
325         (progn 
326           (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
327           (when (>= fd 0)
328             (when (= (lo-write ptr fd data length) length)
329               (setf result t))))
330       (progn
331         (when (and fd (>= fd 0))
332           (lo-close ptr fd))
333         (database-execute-command (if result "commit" "rollback") database)))
334     result))
335
336 ;; (MB) the begin/commit/rollback stuff will be removed when with-transaction wil be implemented
337 ;; (KMR) Can't use with-transaction since that function is in high-level code
338 (defmethod database-read-large-object (object-id (database postgresql-database))
339   (let ((ptr (database-conn-ptr database))
340         (buffer nil)
341         (result nil)
342         (length 0)
343         (fd nil))
344     (unwind-protect
345        (progn
346          (database-execute-command "begin" database)
347          (setf fd (lo-open ptr object-id postgresql::+INV_READ+))
348          (when (>= fd 0)
349            (setf length (lo-lseek ptr fd 0 2))
350            (lo-lseek ptr fd 0 0)
351            (when (> length 0)
352              (setf buffer (uffi:allocate-foreign-string 
353                            length :unsigned t))
354              (when (= (lo-read ptr fd buffer length) length)
355                (setf result (uffi:convert-from-foreign-string
356                              buffer :length length :null-terminated-p nil))))))
357       (progn
358         (when buffer (uffi:free-foreign-object buffer))
359         (when (and fd (>= fd 0)) (lo-close ptr fd))
360         (database-execute-command (if result "commit" "rollback") database)))
361     result))
362
363 (defmethod database-delete-large-object (object-id (database postgresql-database))
364   (lo-unlink (database-conn-ptr database) object-id))
365
366
367 ;;; Object listing
368
369 (defun owner-clause (owner)
370   (cond 
371    ((stringp owner)
372     (format
373      nil
374      " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))" 
375      owner))
376    ((null owner)
377     (format nil " AND (NOT (relowner=1))"))
378    (t "")))
379
380 (defun database-list-objects-of-type (database type owner)
381   (mapcar #'car
382           (database-query
383            (format nil
384                    "SELECT relname FROM pg_class WHERE (relkind = '~A')~A"
385                    type
386                    (owner-clause owner))
387            database nil)))
388
389 (defmethod database-list-tables ((database postgresql-database)
390                                  &key (owner nil))
391   (database-list-objects-of-type database "r" owner))
392   
393 (defmethod database-list-views ((database postgresql-database)
394                                 &key (owner nil))
395   (database-list-objects-of-type database "v" owner))
396   
397 (defmethod database-list-indexes ((database postgresql-database)
398                                   &key (owner nil))
399   (database-list-objects-of-type database "i" owner))
400
401
402 (defmethod database-list-table-indexes (table (database postgresql-database)
403                                         &key (owner nil))
404   (let ((indexrelids
405          (database-query
406           (format 
407            nil
408            "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
409            (string-downcase table)
410            (owner-clause owner))
411           database :auto))
412         (result nil))
413     (dolist (indexrelid indexrelids (nreverse result))
414       (push 
415        (caar (database-query
416               (format nil "select relname from pg_class where relfilenode='~A'"
417                       (car indexrelid))
418               database
419               nil))
420        result))))
421
422 (defmethod database-list-attributes ((table string)
423                                      (database postgresql-database)
424                                      &key (owner nil))
425   (let* ((owner-clause
426           (cond ((stringp owner)
427                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
428                 ((null owner) " AND (not (relowner=1))")
429                 (t "")))
430          (result
431           (mapcar #'car
432                   (database-query
433                    (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND relname='~A'~A"
434                            (string-downcase table)
435                            owner-clause)
436                    database nil))))
437     (if result
438         (reverse
439          (remove-if #'(lambda (it) (member it '("cmin"
440                                                 "cmax"
441                                                 "xmax"
442                                                 "xmin"
443                                                 "oid"
444                                                 "ctid"
445                                                 ;; kmr -- added tableoid
446                                                 "tableoid") :test #'equal)) 
447                     result)))))
448
449 (defmethod database-attribute-type (attribute (table string)
450                                     (database postgresql-database)
451                                     &key (owner nil))
452   (let* ((owner-clause
453           (cond ((stringp owner)
454                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
455                 ((null owner) " AND (not (relowner=1))")
456                 (t "")))
457          (result
458           (mapcar #'car
459                   (database-query
460                    (format nil "SELECT pg_type.typname FROM pg_type,pg_class,pg_attribute WHERE pg_class.oid=pg_attribute.attrelid AND pg_class.relname='~A' AND pg_attribute.attname='~A' AND pg_attribute.atttypid=pg_type.oid~A"
461                            (string-downcase table)
462                            (string-downcase attribute)
463                            owner-clause)
464                    database nil))))
465     (when result
466       (intern (string-upcase (car result)) :keyword))))
467
468 (defmethod database-create-sequence (sequence-name
469                                      (database postgresql-database))
470   (database-execute-command
471    (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
472    database))
473
474 (defmethod database-drop-sequence (sequence-name
475                                    (database postgresql-database))
476   (database-execute-command
477    (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
478
479 (defmethod database-list-sequences ((database postgresql-database)
480                                     &key (owner nil))
481   (database-list-objects-of-type database "S" owner))
482
483 (defmethod database-set-sequence-position (name (position integer)
484                                                 (database postgresql-database))
485   (values
486    (parse-integer
487     (caar
488      (database-query
489       (format nil "SELECT SETVAL ('~A', ~A)" name position)
490       database nil)))))
491
492 (defmethod database-sequence-next (sequence-name 
493                                    (database postgresql-database))
494   (values
495    (parse-integer
496     (caar
497      (database-query
498       (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
499       database nil)))))
500
501 (defmethod database-sequence-last (sequence-name (database postgresql-database))
502   (values
503    (parse-integer
504     (caar
505      (database-query
506       (concatenate 'string "SELECT LAST_VALUE ('" sequence-name "')")
507       database nil)))))
508   
509 (defmethod database-create (connection-spec (type (eql :postgresql)))
510   (destructuring-bind (host name user password) connection-spec
511     (declare (ignore user password))
512     (multiple-value-bind (output status)
513         (clsql-base-sys:command-output "createdb -h~A ~A"
514                                        (if host host "localhost")
515                                        name)
516       (if (or (not (zerop status))
517               (search "database creation failed: ERROR:" output))
518           (error 'clsql-access-error
519                  :connection-spec connection-spec
520                  :database-type type
521                  :error 
522                  (format nil "database-create failed: ~A" 
523                          output))
524         t))))
525
526 (defmethod database-destroy (connection-spec (type (eql :postgresql)))
527   (destructuring-bind (host name user password) connection-spec
528     (declare (ignore user password))
529     (multiple-value-bind (output status)
530         (clsql-base-sys:command-output "dropdb -h~A ~A"
531                                        (if host host "localhost")
532                                        name)
533       (if (or (not (zerop status))
534               (search "database removal failed: ERROR:" output))
535           (error 'clsql-access-error
536                  :connection-spec connection-spec
537                  :database-type type
538                  :error 
539                  (format nil "database-destory failed: ~A" 
540                          output))
541         t))))
542
543
544 (defmethod database-probe (connection-spec (type (eql :postgresql)))
545   (when (find (second connection-spec) (database-list connection-spec type)
546               :key #'car :test #'string-equal)
547     t))
548
549 (defmethod database-list (connection-spec (type (eql :postgresql)))
550   (destructuring-bind (host name user password) connection-spec
551     (declare (ignore name))
552     (let ((database (database-connect (list host "template1" user password)
553                                       type)))
554       (unwind-protect
555            (progn
556              (setf (slot-value database 'clsql-base-sys::state) :open)
557              (mapcar #'car (database-query "select datname from pg_database" 
558                                            database nil)))
559         (progn
560           (database-disconnect database)
561           (setf (slot-value database 'clsql-base-sys::state) :closed))))))
562
563 (defmethod database-describe-table ((database postgresql-database) table)
564   (database-query 
565    (format nil "select a.attname, t.typname
566                                from pg_class c, pg_attribute a, pg_type t
567                                where c.relname = '~a'
568                                    and a.attnum > 0
569                                    and a.attrelid = c.oid
570                                    and a.atttypid = t.oid"
571            (sql-escape (string-downcase table)))
572    database :auto))
573
574 (defun %pg-database-connection (connection-spec)
575   (check-connection-spec connection-spec :postgresql
576                          (host db user password &optional port options tty))
577   (macrolet ((coerce-string (var)
578                `(unless (typep ,var 'simple-base-string)
579                  (setf ,var (coerce ,var 'simple-base-string)))))
580     (destructuring-bind (host db user password &optional port options tty)
581         connection-spec
582       (coerce-string db)
583       (coerce-string user)
584       (let ((connection (pqsetdblogin host port options tty db user password)))
585         (declare (type postgresql::pgsql-conn-ptr connection))
586         (unless (eq (pqstatus connection) :connection-ok)
587           ;; Connect failed
588           (error 'clsql-connect-error
589                  :database-type :postgresql
590                  :connection-spec connection-spec
591                  :errno (pqstatus connection)
592                  :error (pqerrormessage connection)))
593         connection))))
594
595 (defmethod database-reconnect ((database postgresql-database))
596   (let ((lock (database-lock database)))
597     (with-process-lock (lock "Reconnecting")
598       (with-slots (connection-spec conn-ptr)
599           database
600         (setf conn-ptr (%pg-database-connection connection-spec))
601         database))))
602
603 ;;; Database capabilities
604
605 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
606   t)
607
608 (defmethod db-type-default-case ((db-type (eql :postgresql)))
609   :lower)
610
611 (when (clsql-base-sys:database-type-library-loaded :postgresql)
612   (clsql-base-sys:initialize-database-type :database-type :postgresql))