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