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