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