r9519: add prepared statements for postgresql
[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   (case type
232     (:string "VARCHAR")
233     ((:int :integer) "INT4")
234     (:short "INT2")
235     ((:number :numeric :float) "NUMERIC")
236     (:bigint "INT8")))
237
238 (defun prepared-sql-to-postgresql-sql (sql)
239   ;; FIXME: Convert #\? to "$n". Don't convert within strings
240   (declare (simple-string sql))
241   (with-output-to-string (out)
242     (do ((len (length sql))
243          (param 0)
244          (in-str nil)
245          (pos 0 (1+ pos)))
246         ((= len pos))
247       (declare (fixnum len param pos))
248       (let ((c (schar sql pos)))
249         (declare (character c))
250         (cond
251          ((or (char= c #\") (char= c #\'))
252           (setq in-str (not in-str))
253           (write-char c out))
254          ((and (char= c #\?) (not in-str))
255           (write-char #\$ out) 
256           (write-string (write-to-string (incf param)) out))
257          (t
258           (write-char c out)))))))
259
260 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
261   (let ((id (next-prepared-id)))
262     (database-execute-command
263      (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
264              id
265              (mapcar #'clsql-type->postgresql-type types)
266              (prepared-sql-to-postgresql-sql sql-stmt))
267      database)
268     (make-instance 'postgresql-stmt
269                    :id id
270                    :database database
271                    :result-types result-types
272                    :field-names field-names
273                    :bindings (make-list (length types)))))
274
275 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
276   (setf (nth (1- position) (bindings stmt)) value)) 
277
278 (defun binding-to-param (binding)
279   (typecase binding
280     (string
281      (concatenate 'string "'" (sql-escape-quotes binding) "'"))
282     (t
283      binding)))
284
285 (defmethod database-run-prepared ((stmt postgresql-stmt))
286   (with-slots (database id bindings field-names result-types) stmt
287     (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
288                          id (mapcar #'binding-to-param bindings))))
289       (cond
290        ((and field-names (not (consp field-names)))
291         (multiple-value-bind (res names)
292             (database-query query database result-types field-names)
293           (setf field-names names)
294           (values res names)))
295        (field-names
296         (values (nth-value 0 (database-query query database result-types nil))
297                 field-names))
298        (t
299         (database-query query database result-types field-names))))))
300
301 ;;; Capabilities
302
303 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
304   t)
305
306 (defmethod db-type-default-case ((db-type (eql :postgresql)))
307   :lower)
308
309 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
310   t)
311
312 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
313   t)
314