r9530: updates for mysql prepared statements
[clsql.git] / sql / generic-postgresql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; Generic postgresql layer, used by db-postgresql and db-postgresql-socket
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
14
15 (in-package #:clsql-sys)
16
17 (defclass generic-postgresql-database (database)
18   ()
19   (:documentation "Encapsulate same behavior across postgresql and postgresql-socket backends."))
20
21
22
23 ;; Object functions
24
25 (defmethod database-get-type-specifier (type args database
26                                         (db-type (eql :postgresql)))
27   (declare (ignore type args database))
28   "VARCHAR")
29
30 (defmethod database-get-type-specifier ((type (eql 'string)) args database
31                                         (db-type (eql :postgresql)))
32   (declare (ignore database))
33   (if args
34       (format nil "CHAR(~A)" (car args))
35       "VARCHAR"))
36
37 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database
38                                         (db-type (eql :postgresql)))
39   (declare (ignore args database))
40   "TIMESTAMP WITHOUT TIME ZONE")
41
42
43 ;;; Backend functions
44
45 (defun owner-clause (owner)
46   (cond 
47    ((stringp owner)
48     (format
49      nil
50      " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))" 
51      owner))
52    ((null owner)
53     (format nil " AND (NOT (relowner=1))"))
54    (t "")))
55
56 (defun database-list-objects-of-type (database type owner)
57   (mapcar #'car
58           (database-query
59            (format nil
60                    "SELECT relname FROM pg_class WHERE (relkind = '~A')~A"
61                    type
62                    (owner-clause owner))
63            database nil nil)))
64
65 (defmethod database-list-tables ((database generic-postgresql-database)
66                                  &key (owner nil))
67   (database-list-objects-of-type database "r" owner))
68   
69 (defmethod database-list-views ((database generic-postgresql-database)
70                                 &key (owner nil))
71   (database-list-objects-of-type database "v" owner))
72   
73 (defmethod database-list-indexes ((database generic-postgresql-database)
74                                   &key (owner nil))
75   (database-list-objects-of-type database "i" owner))
76
77
78 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
79                                         &key (owner nil))
80   (let ((indexrelids
81          (database-query
82           (format 
83            nil
84            "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
85            (string-downcase table)
86            (owner-clause owner))
87           database :auto nil))
88         (result nil))
89     (dolist (indexrelid indexrelids (nreverse result))
90       (push 
91        (caar (database-query
92               (format nil "select relname from pg_class where relfilenode='~A'"
93                       (car indexrelid))
94               database nil nil))
95        result))))
96
97 (defmethod database-list-attributes ((table string)
98                                      (database generic-postgresql-database)
99                                      &key (owner nil))
100   (let* ((owner-clause
101           (cond ((stringp owner)
102                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
103                 ((null owner) " AND (not (relowner=1))")
104                 (t "")))
105          (result
106           (mapcar #'car
107                   (database-query
108                    (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND relname='~A'~A"
109                            (string-downcase table)
110                            owner-clause)
111                    database nil nil))))
112     (if result
113         (remove-if #'(lambda (it) (member it '("cmin"
114                                                "cmax"
115                                                "xmax"
116                                                "xmin"
117                                                "oid"
118                                                "ctid"
119                                                ;; kmr -- added tableoid
120                                                "tableoid") :test #'equal)) 
121                    result))))
122
123 (defmethod database-attribute-type (attribute (table string)
124                                     (database generic-postgresql-database)
125                                     &key (owner nil))
126   (let ((row (car (database-query
127                    (format nil "SELECT pg_type.typname,pg_attribute.attlen,pg_attribute.atttypmod,pg_attribute.attnotnull 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"
128                            (string-downcase table)
129                            (string-downcase attribute)
130                            (owner-clause owner))
131                    database nil nil))))
132     (when row
133       (values
134        (ensure-keyword (first row))
135        (if (string= "-1" (second row))
136            (- (parse-integer (third row) :junk-allowed t) 4)
137          (parse-integer (second row)))
138        nil
139        (if (string-equal "f" (fourth row))
140            1
141          0)))))
142
143 (defmethod database-create-sequence (sequence-name
144                                      (database generic-postgresql-database))
145   (database-execute-command
146    (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
147    database))
148
149 (defmethod database-drop-sequence (sequence-name
150                                    (database generic-postgresql-database))
151   (database-execute-command
152    (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
153
154 (defmethod database-list-sequences ((database generic-postgresql-database)
155                                     &key (owner nil))
156   (database-list-objects-of-type database "S" owner))
157
158 (defmethod database-set-sequence-position (name (position integer)
159                                                 (database generic-postgresql-database))
160   (values
161    (parse-integer
162     (caar
163      (database-query
164       (format nil "SELECT SETVAL ('~A', ~A)" name position)
165       database nil nil)))))
166
167 (defmethod database-sequence-next (sequence-name 
168                                    (database generic-postgresql-database))
169   (values
170    (parse-integer
171     (caar
172      (database-query
173       (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
174       database nil nil)))))
175
176 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
177   (values
178    (parse-integer
179     (caar
180      (database-query
181       (concatenate 'string "SELECT LAST_VALUE ('" sequence-name "')")
182       database nil nil)))))
183
184 (defun postgresql-database-list (connection-spec type)
185   (destructuring-bind (host name user password) connection-spec
186     (declare (ignore name))
187     (let ((database (database-connect (list host "template1" user password)
188                                       type)))
189       (unwind-protect
190            (progn
191              (setf (slot-value database 'clsql-sys::state) :open)
192              (mapcar #'car (database-query "select datname from pg_database" 
193                                            database nil nil)))
194         (progn
195           (database-disconnect database)
196           (setf (slot-value database 'clsql-sys::state) :closed))))))
197
198 (defmethod database-list (connection-spec (type (eql :postgresql)))
199   (postgresql-database-list connection-spec type))
200
201 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
202   (postgresql-database-list connection-spec type))
203
204
205 (defmethod database-describe-table ((database generic-postgresql-database) table)
206   (database-query 
207    (format nil "select a.attname, t.typname
208                                from pg_class c, pg_attribute a, pg_type t
209                                where c.relname = '~a'
210                                    and a.attnum > 0
211                                    and a.attrelid = c.oid
212                                    and a.atttypid = t.oid"
213            (sql-escape (string-downcase table)))
214    database :auto nil))
215
216 ;;; Prepared statements
217
218 (defvar *next-prepared-id-num* 0)
219 (defun next-prepared-id ()
220   (let ((num (incf *next-prepared-id-num*)))
221     (format nil "CLSQL_PS_~D" num)))
222
223 (defclass postgresql-stmt ()
224   ((database :initarg :database :reader database)
225    (id :initarg :id :reader id)
226    (bindings :initarg :bindings :reader bindings)
227    (field-names :initarg :field-names :accessor stmt-field-names)
228    (result-types :initarg :result-types :reader result-types)))
229
230 (defun clsql-type->postgresql-type (type)
231   (cond
232     ((in type :int :integer) "INT4")
233     ((in type :short) "INT2")
234     ((in type :bigint) "INT8")
235     ((in type :float :double :number) "NUMERIC")
236     ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
237     (t
238      (error 'sql-user-error 
239             :message 
240             (format nil "Unknown clsql type ~A." type)))))
241
242 (defun prepared-sql-to-postgresql-sql (sql)
243   ;; FIXME: Convert #\? to "$n". Don't convert within strings
244   (declare (simple-string sql))
245   (with-output-to-string (out)
246     (do ((len (length sql))
247          (param 0)
248          (in-str nil)
249          (pos 0 (1+ pos)))
250         ((= len pos))
251       (declare (fixnum len param pos))
252       (let ((c (schar sql pos)))
253         (declare (character c))
254         (cond
255          ((or (char= c #\") (char= c #\'))
256           (setq in-str (not in-str))
257           (write-char c out))
258          ((and (char= c #\?) (not in-str))
259           (write-char #\$ out) 
260           (write-string (write-to-string (incf param)) out))
261          (t
262           (write-char c out)))))))
263
264 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
265   (let ((id (next-prepared-id)))
266     (database-execute-command
267      (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
268              id
269              (mapcar #'clsql-type->postgresql-type types)
270              (prepared-sql-to-postgresql-sql sql-stmt))
271      database)
272     (make-instance 'postgresql-stmt
273                    :id id
274                    :database database
275                    :result-types result-types
276                    :field-names field-names
277                    :bindings (make-list (length types)))))
278
279 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
280   (setf (nth (1- position) (bindings stmt)) value)) 
281
282 (defun binding-to-param (binding)
283   (typecase binding
284     (string
285      (concatenate 'string "'" (sql-escape-quotes binding) "'"))
286     (t
287      binding)))
288
289 (defmethod database-run-prepared ((stmt postgresql-stmt))
290   (with-slots (database id bindings field-names result-types) stmt
291     (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
292                          id (mapcar #'binding-to-param bindings))))
293       (cond
294        ((and field-names (not (consp field-names)))
295         (multiple-value-bind (res names)
296             (database-query query database result-types field-names)
297           (setf field-names names)
298           (values res names)))
299        (field-names
300         (values (nth-value 0 (database-query query database result-types nil))
301                 field-names))
302        (t
303         (database-query query database result-types field-names))))))
304
305 ;;; Capabilities
306
307 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
308   t)
309
310 (defmethod db-type-default-case ((db-type (eql :postgresql)))
311   :lower)
312
313 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
314   t)
315
316 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
317   t)
318