9b73b0d6130cb8dc22cd69eaa3d3ccdbeff7a21d
[clsql.git] / db-postgresql-socket3 / sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     postgresql-socket-sql.sql
6 ;;;; Purpose:  High-level PostgreSQL interface using socket
7 ;;;; Authors:  Kevin M. Rosenberg based on original code by Pierre R. Mai
8 ;;;; Created:  Feb 2002
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002-2007 by Kevin M. Rosenberg
13 ;;;; and Copyright (c) 1999-2001 by Pierre R. Mai
14 ;;;;
15 ;;;; CLSQL users are granted the rights to distribute and use this software
16 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
17 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
18 ;;;; *************************************************************************
19
20 (in-package #:cl-user)
21
22 (defpackage :clsql-postgresql-socket3
23     (:use #:common-lisp #:clsql-sys #:postgresql-socket3)
24     (:export #:postgresql-socket3-database)
25     (:documentation "This is the CLSQL socket interface (protocol version 3) to PostgreSQL."))
26
27 (in-package #:clsql-postgresql-socket3)
28
29 (defvar *sqlreader* (cl-postgres:copy-sql-readtable))
30 (let ((dt-fn (lambda (useconds-since-2000)
31                (let ((sec (truncate
32                            (/ useconds-since-2000
33                               1000000)))
34                      (usec (mod useconds-since-2000
35                                 1000000)))
36                  (clsql:make-time :year 2000 :second sec :usec usec)))))
37   (cl-postgres:set-sql-datetime-readers
38    :table *sqlreader*
39    :date (lambda (days-since-2000)
40            (clsql:make-date :year 2000 :day (+ 1 days-since-2000)))
41    :timestamp dt-fn
42    :timestamp-with-timezone dt-fn))
43
44
45
46 ;; interface foreign library loading routines
47
48 (clsql-sys:database-type-load-foreign :postgresql-socket3)
49
50
51 (defmethod database-initialize-database-type ((database-type
52                                                (eql :postgresql-socket3)))
53   t)
54
55
56 ;; Field type conversion
57 (defun convert-to-clsql-warning (database condition)
58   (ecase *backend-warning-behavior*
59     (:warn
60      (warn 'sql-database-warning :database database
61            :message (cl-postgres:database-error-message condition)))
62     (:error
63      (error 'sql-database-error :database database
64             :message (format nil "Warning upgraded to error: ~A"
65                              (cl-postgres:database-error-message condition))))
66     ((:ignore nil)
67      ;; do nothing
68      )))
69
70 (defun convert-to-clsql-error (database expression condition)
71   (error 'sql-database-data-error
72          :database database
73          :expression expression
74          :error-id (type-of condition)
75          :message (cl-postgres:database-error-message condition)))
76
77 (defmacro with-postgresql-handlers
78     ((database &optional expression)
79      &body body)
80   (let ((database-var (gensym))
81         (expression-var (gensym)))
82     `(let ((,database-var ,database)
83            (,expression-var ,expression))
84        (handler-bind ((postgresql-warning
85                        (lambda (c)
86                          (convert-to-clsql-warning ,database-var c)))
87                       (cl-postgres:database-error
88                        (lambda (c)
89                          (convert-to-clsql-error
90                           ,database-var ,expression-var c))))
91          ,@body))))
92
93
94
95 (defclass postgresql-socket3-database (generic-postgresql-database)
96   ((connection :accessor database-connection :initarg :connection
97                :type cl-postgres:database-connection)))
98
99 (defmethod database-type ((database postgresql-socket3-database))
100   :postgresql-socket3)
101
102 (defmethod database-name-from-spec (connection-spec (database-type (eql :postgresql-socket3)))
103   (check-connection-spec connection-spec database-type
104                          (host db user password &optional port options tty))
105   (destructuring-bind (host db user password &optional port options tty)
106       connection-spec
107     (declare (ignore password options tty))
108     (concatenate 'string
109       (etypecase host
110         (null
111          "localhost")
112         (pathname (namestring host))
113         (string host))
114       (when port
115         (concatenate 'string
116                      ":"
117                      (etypecase port
118                        (integer (write-to-string port))
119                        (string port))))
120       "/" db "/" user)))
121
122 (defmethod database-connect (connection-spec
123                              (database-type (eql :postgresql-socket3)))
124   (check-connection-spec connection-spec database-type
125                          (host db user password &optional port options tty))
126   (destructuring-bind (host db user password &optional
127                             (port +postgresql-server-default-port+)
128                             (options "") (tty ""))
129       connection-spec
130     (declare (ignore options tty))
131     (handler-case
132         (handler-bind ((warning
133                         (lambda (c)
134                           (warn 'sql-warning
135                                 :format-control "~A"
136                                 :format-arguments
137                                 (list (princ-to-string c))))))
138           (cl-postgres:open-database db user password host port))
139       (cl-postgres:database-error (c)
140         ;; Connect failed
141         (error 'sql-connection-error
142                :database-type database-type
143                :connection-spec connection-spec
144                :error-id (type-of c)
145                :message (cl-postgres:database-error-message c)))
146       (:no-error (connection)
147                  ;; Success, make instance
148                  (make-instance 'postgresql-socket3-database
149                                 :name (database-name-from-spec connection-spec database-type)
150                                 :database-type :postgresql-socket3
151                                 :connection-spec connection-spec
152                                 :connection connection)))))
153
154 (defmethod database-disconnect ((database postgresql-socket3-database))
155   (cl-postgres:close-database (database-connection database))
156   t)
157
158 (defmethod clsql-sys::release-to-conn-pool :before ((conn postgresql-socket3-database))
159   ;; This resets the connection to "New" state
160   (database-execute-command "DISCARD ALL;" conn))
161
162 (defvar *include-field-names* nil)
163
164
165 ;; THE FOLLOWING MACRO EXPANDS TO THE FUNCTION BELOW IT,
166 ;; BUT TO GET null CONVENTIONS CORRECT I NEEDED TO TWEAK THE EXPANSION
167 ;;
168 ;; (cl-postgres:def-row-reader clsql-default-row-reader (fields)
169 ;;   (values (loop :while (cl-postgres:next-row)
170 ;;              :collect (loop :for field :across fields
171 ;;                             :collect (cl-postgres:next-field field)))
172 ;;        (when *include-field-names*
173 ;;          (loop :for field :across fields
174 ;;                :collect (cl-postgres:field-name field)))))
175
176
177
178 (defun clsql-default-row-reader (stream fields)
179   (declare (type stream stream)
180            (type (simple-array cl-postgres::field-description) fields))
181   (flet ((cl-postgres:next-row ()
182            (cl-postgres::look-for-row stream))
183          (cl-postgres:next-field (cl-postgres::field)
184            (declare (type cl-postgres::field-description cl-postgres::field))
185            (let ((cl-postgres::size (cl-postgres::read-int4 stream)))
186              (declare (type (signed-byte 32) cl-postgres::size))
187              (if (eq cl-postgres::size -1)
188                  nil
189                  (funcall (cl-postgres::field-interpreter cl-postgres::field)
190                           stream cl-postgres::size)))))
191     (let ((results (loop :while (cl-postgres:next-row)
192                          :collect (loop :for field :across fields
193                                         :collect (cl-postgres:next-field field))))
194           (col-names (when *include-field-names*
195                        (loop :for field :across fields
196                              :collect (cl-postgres:field-name field)))))
197       ;;multiple return values were not working here
198       (list results col-names))))
199
200 (defmethod database-query ((expression string) (database postgresql-socket3-database) result-types field-names)
201   (let ((connection (database-connection database))
202         (cl-postgres:*sql-readtable* *sqlreader*))
203     (with-postgresql-handlers (database expression)
204       (let ((*include-field-names* field-names))
205         (apply #'values (cl-postgres:exec-query connection expression #'clsql-default-row-reader)))
206       )))
207
208 (defmethod query ((obj command-object) &key (database *default-database*)
209                   (result-types :auto) (flatp nil) (field-names t))
210   (clsql-sys::record-sql-command (expression obj) database)
211   (multiple-value-bind (rows names)
212       (database-query obj database result-types field-names)
213     (let ((result (if (and flatp (= 1 (length (car rows))))
214                       (mapcar #'car rows)
215                       rows)))
216       (clsql-sys::record-sql-result result database)
217       (if field-names
218           (values result names)
219           result))))
220
221 (defmethod database-query ((obj command-object) (database postgresql-socket3-database) result-types field-names)
222   (let ((connection (database-connection database))
223         (cl-postgres:*sql-readtable* *sqlreader*))
224     (with-postgresql-handlers (database obj)
225       (let ((*include-field-names* field-names))
226         (unless (has-been-prepared obj)
227           (cl-postgres:prepare-query connection (prepared-name obj) (expression obj))
228           (setf (has-been-prepared obj) T))
229         (apply #'values (cl-postgres:exec-prepared
230                          connection
231                          (prepared-name obj)
232                          (parameters obj)
233                          #'clsql-default-row-reader))))))
234
235 (defmethod database-execute-command
236     ((expression string) (database postgresql-socket3-database))
237   (let ((connection (database-connection database)))
238     (with-postgresql-handlers (database expression)
239       (cl-postgres:exec-query connection expression))))
240
241 ;;;; Cursoring interface
242
243
244 (defmethod database-query-result-set ((expression string)
245                                       (database postgresql-socket3-database)
246                                       &key full-set result-types)
247   (declare (ignore result-types))
248   (declare (ignore full-set))
249   (error "Cursoring interface is not supported for postgresql-socket3-database try cl-postgres:exec-query with a custom row-reader"))
250
251 (defmethod database-dump-result-set (result-set
252                                      (database postgresql-socket3-database))
253   (error "Cursoring interface is not supported for postgresql-socket3-database try cl-postgres:exec-query with a custom row-reader")
254   T)
255
256 (defmethod database-store-next-row (result-set
257                                     (database postgresql-socket3-database)
258                                     list)
259   (error "Cursoring interface is not supported for postgresql-socket3-database try cl-postgres:exec-query with a custom row-reader"))
260
261
262 ;;;;;;;;;;;;;;;;;;;;;;;;;;
263
264
265 (defmethod database-create (connection-spec (type (eql :postgresql-socket3)))
266   (destructuring-bind (host name user password &optional port options tty) connection-spec
267     (declare (ignore port options tty))
268     (let ((database (database-connect (list host "postgres" user password)
269                                       type)))
270       (setf (slot-value database 'clsql-sys::state) :open)
271       (unwind-protect
272            (database-execute-command (format nil "create database ~A" name) database)
273         (database-disconnect database)))))
274
275 (defmethod database-destroy (connection-spec (type (eql :postgresql-socket3)))
276   (destructuring-bind (host name user password &optional port options tty) connection-spec
277     (declare (ignore port options tty))
278     (let ((database (database-connect (list host "postgres" user password)
279                                       type)))
280       (setf (slot-value database 'clsql-sys::state) :open)
281       (unwind-protect
282           (database-execute-command (format nil "drop database ~A" name) database)
283         (database-disconnect database)))))
284
285
286 (defmethod database-probe (connection-spec (type (eql :postgresql-socket3)))
287   (when (find (second connection-spec) (database-list connection-spec type)
288               :test #'string-equal)
289     t))
290
291
292 ;; Database capabilities
293
294 (defmethod db-backend-has-create/destroy-db? ((db-type (eql :postgresql-socket3)))
295   nil)
296
297 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql-socket3)))
298   t)
299
300 (defmethod db-type-default-case ((db-type (eql :postgresql-socket3)))
301   :lower)
302
303 (defmethod database-underlying-type ((database postgresql-socket3-database))
304   :postgresql)
305
306 (when (clsql-sys:database-type-library-loaded :postgresql-socket3)
307   (clsql-sys:initialize-database-type :database-type :postgresql-socket3))
308
309
310 ;; Type munging functions
311
312 (defmethod read-sql-value (val (type (eql 'boolean)) (database postgresql-socket3-database) db-type)
313   (declare (ignore database db-type))
314   val)
315
316 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) (database postgresql-socket3-database) db-type)
317   (declare (ignore database db-type))
318   val)