r8849: fold db-*/*-usql files into db-*/*-sql files
[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
84 (defmethod database-type ((database postgresql-database))
85   :postgresql)
86
87 (defmethod database-name-from-spec (connection-spec (database-type
88                                                      (eql :postgresql)))
89   (check-connection-spec connection-spec database-type
90                          (host db user password &optional port options tty))
91   (destructuring-bind (host db user password &optional port options tty)
92       connection-spec
93     (declare (ignore password options tty))
94     (concatenate 'string 
95       (etypecase host
96         (pathname (namestring host))
97         (string host))
98       (when port 
99         (concatenate 'string
100                      ":"
101                      (etypecase port
102                        (integer (write-to-string port))
103                        (string port))))
104       "/" db "/" user)))
105
106
107 (defmethod database-connect (connection-spec (database-type (eql :postgresql)))
108   (check-connection-spec connection-spec database-type
109                          (host db user password &optional port options tty))
110   (destructuring-bind (host db user password &optional port options tty)
111       connection-spec
112     (uffi:with-cstrings ((host-native host)
113                          (user-native user)
114                          (password-native password)
115                          (db-native db)
116                          (port-native port)
117                          (options-native options)
118                          (tty-native tty))
119       (let ((connection (PQsetdbLogin host-native port-native
120                                       options-native tty-native
121                                       db-native user-native
122                                       password-native)))
123         (declare (type pgsql-conn-def connection))
124         (when (not (eq (PQstatus connection) 
125                        pgsql-conn-status-type#connection-ok))
126           (error 'clsql-connect-error
127                  :database-type database-type
128                  :connection-spec connection-spec
129                  :errno (PQstatus connection)
130                  :error (tidy-error-message 
131                          (PQerrorMessage connection))))
132         (make-instance 'postgresql-database
133                        :name (database-name-from-spec connection-spec
134                                                       database-type)
135                        :connection-spec connection-spec
136                        :conn-ptr connection)))))
137
138
139 (defmethod database-disconnect ((database postgresql-database))
140   (PQfinish (database-conn-ptr database))
141   (setf (database-conn-ptr database) nil)
142   t)
143
144 (defmethod database-query (query-expression (database postgresql-database) types)
145   (let ((conn-ptr (database-conn-ptr database)))
146     (declare (type pgsql-conn-def conn-ptr))
147     (uffi:with-cstring (query-native query-expression)
148       (let ((result (PQexec conn-ptr query-native)))
149         (when (uffi:null-pointer-p result)
150           (error 'clsql-sql-error
151                  :database database
152                  :expression query-expression
153                  :errno nil
154                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
155         (unwind-protect
156             (case (PQresultStatus result)
157               (#.pgsql-exec-status-type#empty-query
158                nil)
159               (#.pgsql-exec-status-type#tuples-ok
160                (let ((num-fields (PQnfields result)))
161                  (setq types
162                    (canonicalize-types types num-fields
163                                              result))
164                  (loop for tuple-index from 0 below (PQntuples result)
165                        collect
166                        (loop for i from 0 below num-fields
167                              collect
168                              (if (zerop (PQgetisnull result tuple-index i))
169                                  (convert-raw-field
170                                   (PQgetvalue result tuple-index i)
171                                   types i)
172                                  nil)))))
173               (t
174                (error 'clsql-sql-error
175                       :database database
176                       :expression query-expression
177                       :errno (PQresultStatus result)
178                       :error (tidy-error-message
179                               (PQresultErrorMessage result)))))
180           (PQclear result))))))
181
182 (defmethod database-execute-command (sql-expression
183                                      (database postgresql-database))
184   (let ((conn-ptr (database-conn-ptr database)))
185     (declare (type pgsql-conn-def conn-ptr))
186     (uffi:with-cstring (sql-native sql-expression)
187       (let ((result (PQexec conn-ptr sql-native)))
188         (when (uffi:null-pointer-p result)
189           (error 'clsql-sql-error
190                  :database database
191                  :expression sql-expression
192                  :errno nil
193                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
194         (unwind-protect
195             (case (PQresultStatus result)
196               (#.pgsql-exec-status-type#command-ok
197                t)
198               ((#.pgsql-exec-status-type#empty-query
199                 #.pgsql-exec-status-type#tuples-ok)
200                (warn "Strange result...")
201                t)
202               (t
203                (error 'clsql-sql-error
204                       :database database
205                       :expression sql-expression
206                       :errno (PQresultStatus result)
207                       :error (tidy-error-message
208                               (PQresultErrorMessage result)))))
209           (PQclear result))))))
210
211 (defstruct postgresql-result-set
212   (res-ptr (uffi:make-null-pointer 'pgsql-result) 
213            :type pgsql-result-def)
214   (types nil) 
215   (num-tuples 0 :type integer)
216   (num-fields 0 :type integer)
217   (tuple-index 0 :type integer))
218
219 (defmethod database-query-result-set (query-expression (database postgresql-database) 
220                                       &key full-set types)
221   (let ((conn-ptr (database-conn-ptr database)))
222     (declare (type pgsql-conn-def conn-ptr))
223     (uffi:with-cstring (query-native query-expression)
224       (let ((result (PQexec conn-ptr query-native)))
225         (when (uffi:null-pointer-p result)
226           (error 'clsql-sql-error
227                  :database database
228                  :expression query-expression
229                  :errno nil
230                  :error (tidy-error-message (PQerrorMessage conn-ptr))))
231         (case (PQresultStatus result)
232           ((#.pgsql-exec-status-type#empty-query
233             #.pgsql-exec-status-type#tuples-ok)
234            (let ((result-set (make-postgresql-result-set
235                         :res-ptr result
236                         :num-fields (PQnfields result)
237                         :num-tuples (PQntuples result)
238                         :types (canonicalize-types 
239                                       types
240                                       (PQnfields result)
241                                       result))))
242              (if full-set
243                  (values result-set
244                          (PQnfields result)
245                          (PQntuples result))
246                  (values result-set
247                          (PQnfields result)))))
248           (t
249            (unwind-protect
250                (error 'clsql-sql-error
251                       :database database
252                       :expression query-expression
253                       :errno (PQresultStatus result)
254                       :error (tidy-error-message
255                               (PQresultErrorMessage result)))
256              (PQclear result))))))))
257   
258 (defmethod database-dump-result-set (result-set (database postgresql-database))
259   (let ((res-ptr (postgresql-result-set-res-ptr result-set))) 
260     (declare (type pgsql-result-def res-ptr))
261     (PQclear res-ptr)
262     t))
263
264 (defmethod database-store-next-row (result-set (database postgresql-database) 
265                                     list)
266   (let ((result (postgresql-result-set-res-ptr result-set))
267         (types (postgresql-result-set-types result-set)))
268     (declare (type pgsql-result-def result))
269     (if (>= (postgresql-result-set-tuple-index result-set)
270             (postgresql-result-set-num-tuples result-set))
271         nil
272       (loop with tuple-index = (postgresql-result-set-tuple-index result-set)
273           for i from 0 below (postgresql-result-set-num-fields result-set)
274           for rest on list
275           do
276             (setf (car rest)
277               (if (zerop (PQgetisnull result tuple-index i))
278                   (convert-raw-field
279                    (PQgetvalue result tuple-index i)
280                    types i)
281                 nil))
282           finally
283             (incf (postgresql-result-set-tuple-index result-set))
284             (return list)))))
285
286 ;;; Large objects support (Marc B)
287
288 (defmethod database-create-large-object ((database postgresql-database))
289   (lo-create (database-conn-ptr database)
290              (logior postgresql::+INV_WRITE+ postgresql::+INV_READ+)))
291
292
293 #+mb-original
294 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
295   (let ((ptr (database-conn-ptr database))
296         (length (length data))
297         (result nil)
298         (fd nil))
299     (with-transaction (:database database)
300        (unwind-protect
301           (progn 
302             (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
303             (when (>= fd 0)
304               (when (= (lo-write ptr fd data length) length)
305                 (setf result t))))
306          (progn
307            (when (and fd (>= fd 0))
308              (lo-close ptr fd))
309            )))
310     result))
311
312 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
313   (let ((ptr (database-conn-ptr database))
314         (length (length data))
315         (result nil)
316         (fd nil))
317     (database-execute-command "begin" database)
318     (unwind-protect
319         (progn 
320           (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
321           (when (>= fd 0)
322             (when (= (lo-write ptr fd data length) length)
323               (setf result t))))
324       (progn
325         (when (and fd (>= fd 0))
326           (lo-close ptr fd))
327         (database-execute-command (if result "commit" "rollback") database)))
328     result))
329
330 ;; (MB) the begin/commit/rollback stuff will be removed when with-transaction wil be implemented
331 ;; (KMR) Can't use with-transaction since that function is in high-level code
332 (defmethod database-read-large-object (object-id (database postgresql-database))
333   (let ((ptr (database-conn-ptr database))
334         (buffer nil)
335         (result nil)
336         (length 0)
337         (fd nil))
338     (unwind-protect
339        (progn
340          (database-execute-command "begin" database)
341          (setf fd (lo-open ptr object-id postgresql::+INV_READ+))
342          (when (>= fd 0)
343            (setf length (lo-lseek ptr fd 0 2))
344            (lo-lseek ptr fd 0 0)
345            (when (> length 0)
346              (setf buffer (uffi:allocate-foreign-string 
347                            length :unsigned t))
348              (when (= (lo-read ptr fd buffer length) length)
349                (setf result (uffi:convert-from-foreign-string
350                              buffer :length length :null-terminated-p nil))))))
351       (progn
352         (when buffer (uffi:free-foreign-object buffer))
353         (when (and fd (>= fd 0)) (lo-close ptr fd))
354         (database-execute-command (if result "commit" "rollback") database)))
355     result))
356
357 (defmethod database-delete-large-object (object-id (database postgresql-database))
358   (lo-unlink (database-conn-ptr database) object-id))
359
360
361 ;;; Object listing
362
363 (defmethod database-list-objects-of-type ((database postgresql-database)
364                                           type owner)
365   (let ((owner-clause
366          (cond ((stringp owner)
367                 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))" owner))
368                ((null owner)
369                 (format nil " AND (NOT (relowner=1))"))
370                (t ""))))
371     (mapcar #'car
372             (database-query
373              (format nil
374                      "SELECT relname FROM pg_class WHERE (relkind = '~A')~A"
375                      type
376                      owner-clause)
377              database nil))))
378     
379 (defmethod database-list-tables ((database postgresql-database)
380                                  &key (owner nil))
381   (database-list-objects-of-type database "r" owner))
382   
383 (defmethod database-list-views ((database postgresql-database)
384                                 &key (owner nil))
385   (database-list-objects-of-type database "v" owner))
386   
387 (defmethod database-list-indexes ((database postgresql-database)
388                                   &key (owner nil))
389   (database-list-objects-of-type database "i" owner))
390   
391 (defmethod database-list-attributes ((table string)
392                                      (database postgresql-database)
393                                      &key (owner nil))
394   (let* ((owner-clause
395           (cond ((stringp owner)
396                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
397                 ((null owner) " AND (not (relowner=1))")
398                 (t "")))
399          (result
400           (mapcar #'car
401                   (database-query
402                    (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND relname='~A'~A"
403                            (string-downcase table)
404                            owner-clause)
405                    database nil))))
406     (if result
407         (reverse
408          (remove-if #'(lambda (it) (member it '("cmin"
409                                                 "cmax"
410                                                 "xmax"
411                                                 "xmin"
412                                                 "oid"
413                                                 "ctid"
414                                                 ;; kmr -- added tableoid
415                                                 "tableoid") :test #'equal)) 
416                     result)))))
417
418 (defmethod database-attribute-type (attribute (table string)
419                                     (database postgresql-database)
420                                     &key (owner nil))
421   (let* ((owner-clause
422           (cond ((stringp owner)
423                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
424                 ((null owner) " AND (not (relowner=1))")
425                 (t "")))
426          (result
427           (mapcar #'car
428                   (database-query
429                    (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"
430                            (string-downcase table)
431                            (string-downcase attribute)
432                            owner-clause)
433                    database nil))))
434     (when result
435       (intern (string-upcase (car result)) :keyword))))
436
437 (defmethod database-create-sequence (sequence-name
438                                      (database postgresql-database))
439   (database-execute-command
440    (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
441    database))
442
443 (defmethod database-drop-sequence (sequence-name
444                                    (database postgresql-database))
445   (database-execute-command
446    (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
447
448 (defmethod database-list-sequences ((database postgresql-database)
449                                     &key (owner nil))
450   (database-list-objects-of-type database "S" owner))
451
452 (defmethod database-set-sequence-position (name (position integer)
453                                                 (database postgresql-database))
454   (values
455    (parse-integer
456     (caar
457      (database-query
458       (format nil "SELECT SETVAL ('~A', ~A)" name position)
459       database nil)))))
460
461 (defmethod database-sequence-next (sequence-name 
462                                    (database postgresql-database))
463   (values
464    (parse-integer
465     (caar
466      (database-query
467       (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
468       database nil)))))
469
470 (defmethod database-sequence-last (sequence-name (database postgresql-database))
471   (values
472    (parse-integer
473     (caar
474      (database-query
475       (concatenate 'string "SELECT LAST_VALUE ('" sequence-name "')")
476       database nil)))))
477   
478
479 ;; Functions depending upon high-level CommonSQL classes/functions
480 #|
481 (defmethod database-output-sql ((expr clsql-sys::sql-typecast-exp) 
482                                 (database postgresql-database))
483   (with-slots (clsql-sys::modifier clsql-sys::components)
484     expr
485     (if clsql-sys::modifier
486         (progn
487           (clsql-sys::output-sql clsql-sys::components database)
488           (write-char #\: clsql-sys::*sql-stream*)
489           (write-char #\: clsql-sys::*sql-stream*)
490           (write-string (symbol-name clsql-sys::modifier) 
491                         clsql-sys::*sql-stream*)))))
492
493 (defmethod database-output-sql-as-type ((type (eql 'integer)) val
494                                         (database postgresql-database))
495   (when val   ;; typecast it so it uses the indexes
496     (make-instance 'clsql-sys::sql-typecast-exp
497                    :modifier 'int8
498                    :components val)))
499 |#
500
501 (when (clsql-base-sys:database-type-library-loaded :postgresql)
502   (clsql-base-sys:initialize-database-type :database-type :postgresql))