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