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-base-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 (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 '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
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)
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
157 :expression query-expression
159 :error (tidy-error-message (PQerrorMessage conn-ptr))))
161 (case (PQresultStatus result)
162 (#.pgsql-exec-status-type#empty-query
164 (#.pgsql-exec-status-type#tuples-ok
165 (let ((num-fields (PQnfields result)))
167 (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 (error 'clsql-sql-error
181 :expression query-expression
182 :errno (PQresultStatus result)
183 :error (tidy-error-message
184 (PQresultErrorMessage result)))))
185 (PQclear result))))))
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
196 :expression sql-expression
198 :error (tidy-error-message (PQerrorMessage conn-ptr))))
200 (case (PQresultStatus result)
201 (#.pgsql-exec-status-type#command-ok
203 ((#.pgsql-exec-status-type#empty-query
204 #.pgsql-exec-status-type#tuples-ok)
205 (warn "Strange result...")
208 (error 'clsql-sql-error
210 :expression sql-expression
211 :errno (PQresultStatus result)
212 :error (tidy-error-message
213 (PQresultErrorMessage result)))))
214 (PQclear result))))))
216 (defstruct postgresql-result-set
217 (res-ptr (uffi:make-null-pointer 'pgsql-result)
218 :type pgsql-result-def)
220 (num-tuples 0 :type integer)
221 (num-fields 0 :type integer)
222 (tuple-index 0 :type integer))
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
234 :expression query-expression
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
242 :num-fields (PQnfields result)
243 :num-tuples (PQntuples result)
244 :types (canonicalize-types
253 (PQnfields result)))))
256 (error 'clsql-sql-error
258 :expression query-expression
259 :errno (PQresultStatus result)
260 :error (tidy-error-message
261 (PQresultErrorMessage result)))
262 (PQclear result))))))))
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))
270 (defmethod database-store-next-row (result-set (database postgresql-database)
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))
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)
283 (if (zerop (PQgetisnull result tuple-index i))
285 (PQgetvalue result tuple-index i)
289 (incf (postgresql-result-set-tuple-index result-set))
292 ;;; Large objects support (Marc B)
294 (defmethod database-create-large-object ((database postgresql-database))
295 (lo-create (database-conn-ptr database)
296 (logior postgresql::+INV_WRITE+ postgresql::+INV_READ+)))
300 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
301 (let ((ptr (database-conn-ptr database))
302 (length (length data))
305 (with-transaction (:database database)
308 (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
310 (when (= (lo-write ptr fd data length) length)
313 (when (and fd (>= fd 0))
318 (defmethod database-write-large-object (object-id (data string) (database postgresql-database))
319 (let ((ptr (database-conn-ptr database))
320 (length (length data))
323 (database-execute-command "begin" database)
326 (setf fd (lo-open ptr object-id postgresql::+INV_WRITE+))
328 (when (= (lo-write ptr fd data length) length)
331 (when (and fd (>= fd 0))
333 (database-execute-command (if result "commit" "rollback") database)))
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))
346 (database-execute-command "begin" database)
347 (setf fd (lo-open ptr object-id postgresql::+INV_READ+))
349 (setf length (lo-lseek ptr fd 0 2))
350 (lo-lseek ptr fd 0 0)
352 (setf buffer (uffi:allocate-foreign-string
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))))))
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)))
363 (defmethod database-delete-large-object (object-id (database postgresql-database))
364 (lo-unlink (database-conn-ptr database) object-id))
369 (defmethod database-list-objects-of-type ((database postgresql-database)
372 (cond ((stringp owner)
373 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))" owner))
375 (format nil " AND (NOT (relowner=1))"))
380 "SELECT relname FROM pg_class WHERE (relkind = '~A')~A"
385 (defmethod database-list-tables ((database postgresql-database)
387 (database-list-objects-of-type database "r" owner))
389 (defmethod database-list-views ((database postgresql-database)
391 (database-list-objects-of-type database "v" owner))
393 (defmethod database-list-indexes ((database postgresql-database)
395 (database-list-objects-of-type database "i" owner))
397 (defmethod database-list-attributes ((table string)
398 (database postgresql-database)
401 (cond ((stringp owner)
402 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
403 ((null owner) " AND (not (relowner=1))")
408 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND relname='~A'~A"
409 (string-downcase table)
414 (remove-if #'(lambda (it) (member it '("cmin"
420 ;; kmr -- added tableoid
421 "tableoid") :test #'equal))
424 (defmethod database-attribute-type (attribute (table string)
425 (database postgresql-database)
428 (cond ((stringp owner)
429 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
430 ((null owner) " AND (not (relowner=1))")
435 (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"
436 (string-downcase table)
437 (string-downcase attribute)
441 (intern (string-upcase (car result)) :keyword))))
443 (defmethod database-create-sequence (sequence-name
444 (database postgresql-database))
445 (database-execute-command
446 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
449 (defmethod database-drop-sequence (sequence-name
450 (database postgresql-database))
451 (database-execute-command
452 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
454 (defmethod database-list-sequences ((database postgresql-database)
456 (database-list-objects-of-type database "S" owner))
458 (defmethod database-set-sequence-position (name (position integer)
459 (database postgresql-database))
464 (format nil "SELECT SETVAL ('~A', ~A)" name position)
467 (defmethod database-sequence-next (sequence-name
468 (database postgresql-database))
473 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
476 (defmethod database-sequence-last (sequence-name (database postgresql-database))
481 (concatenate 'string "SELECT LAST_VALUE ('" sequence-name "')")
484 (defmethod database-create (connection-spec (type (eql :postgresql)))
485 (destructuring-bind (host name user password) connection-spec
486 (declare (ignore user password))
487 (multiple-value-bind (output status)
488 (clsql-base-sys:command-output "createdb -h~A ~A"
489 (if host host "localhost")
491 (if (or (not (zerop status))
492 (search "database creation failed: ERROR:" output))
493 (error 'clsql-access-error
494 :connection-spec connection-spec
497 (format nil "database-create failed: ~A"
501 (defmethod database-destroy (connection-spec (type (eql :postgresql)))
502 (destructuring-bind (host name user password) connection-spec
503 (declare (ignore user password))
504 (multiple-value-bind (output status)
505 (clsql-base-sys:command-output "dropdb -h~A ~A"
506 (if host host "localhost")
508 (if (or (not (zerop status))
509 (search "database removal failed: ERROR:" output))
510 (error 'clsql-access-error
511 :connection-spec connection-spec
514 (format nil "database-destory failed: ~A"
519 (defmethod database-probe (connection-spec (type (eql :postgresql)))
520 (when (find (second connection-spec) (database-list connection-spec type)
521 :key #'car :test #'string-equal)
524 (defmethod database-list (connection-spec (type (eql :postgresql)))
525 (destructuring-bind (host name user password) connection-spec
526 (declare (ignore name))
527 (let ((database (database-connect (list host "template1" user password)
531 (setf (slot-value database 'clsql-base-sys::state) :open)
532 (mapcar #'car (database-query "select datname from pg_database"
535 (database-disconnect database)
536 (setf (slot-value database 'clsql-base-sys::state) :closed))))))
538 (defmethod database-describe-table ((database postgresql-database) table)
540 (format nil "select a.attname, t.typname
541 from pg_class c, pg_attribute a, pg_type t
542 where c.relname = '~a'
544 and a.attrelid = c.oid
545 and a.atttypid = t.oid"
546 (sql-escape (string-downcase table)))
549 (defun %pg-database-connection (connection-spec)
550 (check-connection-spec connection-spec :postgresql
551 (host db user password &optional port options tty))
552 (macrolet ((coerce-string (var)
553 `(unless (typep ,var 'simple-base-string)
554 (setf ,var (coerce ,var 'simple-base-string)))))
555 (destructuring-bind (host db user password &optional port options tty)
559 (let ((connection (pqsetdblogin host port options tty db user password)))
560 (declare (type postgresql::pgsql-conn-ptr connection))
561 (unless (eq (pqstatus connection) :connection-ok)
563 (error 'clsql-connect-error
564 :database-type :postgresql
565 :connection-spec connection-spec
566 :errno (pqstatus connection)
567 :error (pqerrormessage connection)))
570 (defmethod database-reconnect ((database postgresql-database))
571 (let ((lock (database-lock database)))
572 (with-process-lock (lock "Reconnecting")
573 (with-slots (connection-spec conn-ptr)
575 (setf conn-ptr (%pg-database-connection connection-spec))
578 (when (clsql-base-sys:database-type-library-loaded :postgresql)
579 (clsql-base-sys:initialize-database-type :database-type :postgresql))