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