Added some postgres overloads for database-output-sql-as-type so that nullable floati...
[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   ((has-table-pg_roles :type boolean :reader has-table-pg_roles :initform nil))
19   (:documentation "Encapsulate same behavior across postgresql and postgresql-socket backends."))
20
21
22
23 ;; Object functions
24 (defmethod database-output-sql-as-type ((type (eql 'float)) val database (db-type (eql :postgresql)))
25   (declare (ignore database db-type))
26   val)
27
28 (defmethod database-output-sql-as-type ((type (eql 'float)) val database (db-type (eql :postgresql-socket)))
29   (declare (ignore database db-type))
30   val)
31
32 (defmethod database-get-type-specifier (type args database
33                                         (db-type (eql :postgresql)))
34   (declare (ignore type args database))
35   "VARCHAR")
36
37 (defmethod database-get-type-specifier ((type (eql 'string)) args database
38                                         (db-type (eql :postgresql)))
39   (declare (ignore database))
40   (if args
41       (format nil "CHAR(~A)" (car args))
42     "VARCHAR"))
43
44 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
45                                         (db-type (eql :postgresql)))
46   (declare (ignore args database))
47   "INT2")
48
49 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
50                                         (db-type (eql :postgresql)))
51   (declare (ignore args database))
52   "INT2")
53
54 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database
55                                         (db-type (eql :postgresql)))
56   (declare (ignore args database))
57   "TIMESTAMP WITHOUT TIME ZONE")
58
59 (defmethod database-get-type-specifier ((type (eql 'number)) args database
60                                         (db-type (eql :postgresql)))
61   (declare (ignore database))
62   (cond
63    ((and (consp args) (= (length args) 2))
64     (format nil "NUMERIC(~D,~D)" (first args) (second args)))
65    ((and (consp args) (= (length args) 1))
66     (format nil "NUMERIC(~D)" (first args)))
67    (t
68     "NUMERIC")))
69
70 ;;; Backend functions
71
72 (defun owner-clause (owner)
73   (cond
74    ((stringp owner)
75     (format
76      nil
77      " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
78      owner))
79    ((null owner)
80     (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
81    (t "")))
82
83 (defun has-table (name database)
84   (let ((name-retrieved
85          (caar (database-query
86                 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
87                         name)
88                 database nil nil))))
89     (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
90         t
91         nil)))
92
93 (defmethod slot-unbound (class (obj generic-postgresql-database)
94                          (slot (eql 'has-table-pg_roles)))
95   ;; Lazily cache slot value
96   (declare (ignore class))
97   (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
98
99 (defun database-list-objects-of-type (database type owner)
100   (mapcar #'car
101           (database-query
102            (format nil
103                    (if (and (has-table-pg_roles database)
104                             (not (eq owner :all)))
105                        "
106  SELECT c.relname
107  FROM pg_catalog.pg_class c
108       LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
109       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
110  WHERE c.relkind IN ('~A','')
111        AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
112        AND pg_catalog.pg_table_is_visible(c.oid)
113        ~A"
114                        "SELECT relname FROM pg_class WHERE (relkind =
115 '~A')~A")
116                    type
117                    (owner-clause owner))
118            database nil nil)))
119
120 (defmethod database-list-tables ((database generic-postgresql-database)
121                                  &key (owner nil))
122   (database-list-objects-of-type database "r" owner))
123
124 (defmethod database-list-views ((database generic-postgresql-database)
125                                 &key (owner nil))
126   (database-list-objects-of-type database "v" owner))
127
128 (defmethod database-list-indexes ((database generic-postgresql-database)
129                                   &key (owner nil))
130   (database-list-objects-of-type database "i" owner))
131
132
133 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
134                                         &key (owner nil))
135   (let ((indexrelids
136          (database-query
137           (format
138            nil
139            "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
140            (string-downcase table)
141            (owner-clause owner))
142           database :auto nil))
143         (result nil))
144     (dolist (indexrelid indexrelids (nreverse result))
145       (push
146        (caar (database-query
147               (format nil "select relname from pg_class where relfilenode='~A'"
148                       (car indexrelid))
149               database nil nil))
150        result))))
151
152 (defmethod database-list-attributes ((table string)
153                                      (database generic-postgresql-database)
154                                      &key (owner nil))
155   (let* ((owner-clause
156           (cond ((stringp owner)
157                  (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
158                 ((null owner) " AND (not (relowner=1))")
159                 (t "")))
160          (result
161           (mapcar #'car
162                   (database-query
163                    (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
164                            (string-downcase table)
165                            owner-clause)
166                    database nil nil))))
167     (if result
168         (remove-if #'(lambda (it) (member it '("cmin"
169                                                "cmax"
170                                                "xmax"
171                                                "xmin"
172                                                "oid"
173                                                "ctid"
174                                                ;; kmr -- added tableoid
175                                                "tableoid") :test #'equal))
176                    result))))
177
178 (defmethod database-attribute-type (attribute (table string)
179                                     (database generic-postgresql-database)
180                                     &key (owner nil))
181   (let ((row (car (database-query
182                    (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"
183                            (string-downcase table)
184                            (string-downcase attribute)
185                            (owner-clause owner))
186                    database nil nil))))
187     (when row
188       (destructuring-bind (typname attlen atttypmod attnull) row
189
190         (setf attlen (parse-integer attlen :junk-allowed t)
191               atttypmod (parse-integer atttypmod :junk-allowed t))
192
193         (let ((coltype (ensure-keyword typname))
194               (colnull (if (string-equal "f" attnull) 1 0))
195               collen
196               colprec)
197            (setf (values collen colprec)
198                  (case coltype
199                    ((:numeric :decimal)
200                     (if (= -1 atttypmod)
201                         (values nil nil)
202                         (values (ash (- atttypmod 4) -16)
203                                 (boole boole-and (- atttypmod 4) #xffff))))
204                    (otherwise
205                     (values
206                      (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
207                            ((= -1 attlen) (- atttypmod 4))
208                            (t attlen))
209                      nil))))
210            (values coltype collen colprec colnull))))))
211
212 (defmethod database-create-sequence (sequence-name
213                                      (database generic-postgresql-database))
214   (database-execute-command
215    (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
216    database))
217
218 (defmethod database-drop-sequence (sequence-name
219                                    (database generic-postgresql-database))
220   (database-execute-command
221    (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
222
223 (defmethod database-list-sequences ((database generic-postgresql-database)
224                                     &key (owner nil))
225   (database-list-objects-of-type database "S" owner))
226
227 (defmethod database-set-sequence-position (name (position integer)
228                                                 (database generic-postgresql-database))
229   (values
230    (parse-integer
231     (caar
232      (database-query
233       (format nil "SELECT SETVAL ('~A', ~A)" name position)
234       database nil nil)))))
235
236 (defmethod database-sequence-next (sequence-name
237                                    (database generic-postgresql-database))
238   (values
239    (parse-integer
240     (caar
241      (database-query
242       (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
243       database nil nil)))))
244
245 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
246   (values
247    (parse-integer
248     (caar
249      (database-query
250       (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
251       database nil nil)))))
252
253 (defun postgresql-database-list (connection-spec type)
254   (destructuring-bind (host name user password) connection-spec
255     (declare (ignore name))
256     (let ((database (database-connect (list host "template1" user password)
257                                       type)))
258       (unwind-protect
259            (progn
260              (setf (slot-value database 'clsql-sys::state) :open)
261              (mapcar #'car (database-query "select datname from pg_database"
262                                            database nil nil)))
263         (progn
264           (database-disconnect database)
265           (setf (slot-value database 'clsql-sys::state) :closed))))))
266
267 (defmethod database-list (connection-spec (type (eql :postgresql)))
268   (postgresql-database-list connection-spec type))
269
270 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
271   (postgresql-database-list connection-spec type))
272
273 #+nil
274 (defmethod database-describe-table ((database generic-postgresql-database) table)
275   ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
276   ;; each attribute. It would be more efficient to have a single SQL
277   ;; query return the type data for all attributes. This code is
278   ;; retained as an example of how to do this for PostgreSQL.
279   (database-query
280    (format nil "select a.attname, t.typname
281                                from pg_class c, pg_attribute a, pg_type t
282                                where c.relname = '~a'
283                                    and a.attnum > 0
284                                    and a.attrelid = c.oid
285                                    and a.atttypid = t.oid"
286            (sql-escape (string-downcase table)))
287    database :auto nil))
288
289 ;;; Prepared statements
290
291 (defvar *next-prepared-id-num* 0)
292 (defun next-prepared-id ()
293   (let ((num (incf *next-prepared-id-num*)))
294     (format nil "CLSQL_PS_~D" num)))
295
296 (defclass postgresql-stmt ()
297   ((database :initarg :database :reader database)
298    (id :initarg :id :reader id)
299    (bindings :initarg :bindings :reader bindings)
300    (field-names :initarg :field-names :accessor stmt-field-names)
301    (result-types :initarg :result-types :reader result-types)))
302
303 (defun clsql-type->postgresql-type (type)
304   (cond
305     ((in type :int :integer) "INT4")
306     ((in type :short) "INT2")
307     ((in type :bigint) "INT8")
308     ((in type :float :double :number) "NUMERIC")
309     ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
310     (t
311      (error 'sql-user-error
312             :message
313             (format nil "Unknown clsql type ~A." type)))))
314
315 (defun prepared-sql-to-postgresql-sql (sql)
316   ;; FIXME: Convert #\? to "$n". Don't convert within strings
317   (declare (simple-string sql))
318   (with-output-to-string (out)
319     (do ((len (length sql))
320          (param 0)
321          (in-str nil)
322          (pos 0 (1+ pos)))
323         ((= len pos))
324       (declare (fixnum len param pos))
325       (let ((c (schar sql pos)))
326         (declare (character c))
327         (cond
328          ((or (char= c #\") (char= c #\'))
329           (setq in-str (not in-str))
330           (write-char c out))
331          ((and (char= c #\?) (not in-str))
332           (write-char #\$ out)
333           (write-string (write-to-string (incf param)) out))
334          (t
335           (write-char c out)))))))
336
337 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
338   (let ((id (next-prepared-id)))
339     (database-execute-command
340      (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
341              id
342              (mapcar #'clsql-type->postgresql-type types)
343              (prepared-sql-to-postgresql-sql sql-stmt))
344      database)
345     (make-instance 'postgresql-stmt
346                    :id id
347                    :database database
348                    :result-types result-types
349                    :field-names field-names
350                    :bindings (make-list (length types)))))
351
352 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
353   (setf (nth (1- position) (bindings stmt)) value))
354
355 (defun binding-to-param (binding)
356   (typecase binding
357     (string
358      (concatenate 'string "'" (sql-escape-quotes binding) "'"))
359     (t
360      binding)))
361
362 (defmethod database-run-prepared ((stmt postgresql-stmt))
363   (with-slots (database id bindings field-names result-types) stmt
364     (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
365                          id (mapcar #'binding-to-param bindings))))
366       (cond
367        ((and field-names (not (consp field-names)))
368         (multiple-value-bind (res names)
369             (database-query query database result-types field-names)
370           (setf field-names names)
371           (values res names)))
372        (field-names
373         (values (nth-value 0 (database-query query database result-types nil))
374                 field-names))
375        (t
376         (database-query query database result-types field-names))))))
377
378 ;;; Capabilities
379
380 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
381   t)
382
383 (defmethod db-type-default-case ((db-type (eql :postgresql)))
384   :lower)
385
386 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
387   t)
388
389 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
390   t)
391