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