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