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