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