r10783: 11 Oct 2005 Kevin Rosenberg <kevin@rosenberg.net>
[clsql/s11.git] / sql / generic-postgresql.lisp
blobc196a4568d46106e58d75dbf4a61429c1181759b
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 ;;;; *************************************************************************
15 (in-package #:clsql-sys)
17 (defclass generic-postgresql-database (database)
19 (:documentation "Encapsulate same behavior across postgresql and postgresql-socket backends."))
23 ;; Object functions
25 (defmethod database-get-type-specifier (type args database
26 (db-type (eql :postgresql)))
27 (declare (ignore type args database))
28 "VARCHAR")
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"))
37 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
38 (db-type (eql :postgresql)))
39 (declare (ignore args database))
40 "INT2")
42 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
43 (db-type (eql :postgresql)))
44 (declare (ignore args database))
45 "INT2")
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")
52 (defmethod database-get-type-specifier ((type (eql 'number)) args database
53 (db-type (eql :postgresql)))
54 (declare (ignore database db-type))
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)))
61 "NUMERIC")))
63 ;;; Backend functions
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 "")))
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)))
85 (defmethod database-list-tables ((database generic-postgresql-database)
86 &key (owner nil))
87 (database-list-objects-of-type database "r" owner))
89 (defmethod database-list-views ((database generic-postgresql-database)
90 &key (owner nil))
91 (database-list-objects-of-type database "v" owner))
93 (defmethod database-list-indexes ((database generic-postgresql-database)
94 &key (owner nil))
95 (database-list-objects-of-type database "i" owner))
98 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
99 &key (owner nil))
100 (let ((indexrelids
101 (database-query
102 (format
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))))
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))))
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 (values
154 (ensure-keyword (first row))
155 (if (string= "-1" (second row))
156 (- (parse-integer (third row) :junk-allowed t) 4)
157 (parse-integer (second row)))
159 (if (string-equal "f" (fourth row))
161 0)))))
163 (defmethod database-create-sequence (sequence-name
164 (database generic-postgresql-database))
165 (database-execute-command
166 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
167 database))
169 (defmethod database-drop-sequence (sequence-name
170 (database generic-postgresql-database))
171 (database-execute-command
172 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
174 (defmethod database-list-sequences ((database generic-postgresql-database)
175 &key (owner nil))
176 (database-list-objects-of-type database "S" owner))
178 (defmethod database-set-sequence-position (name (position integer)
179 (database generic-postgresql-database))
180 (values
181 (parse-integer
182 (caar
183 (database-query
184 (format nil "SELECT SETVAL ('~A', ~A)" name position)
185 database nil nil)))))
187 (defmethod database-sequence-next (sequence-name
188 (database generic-postgresql-database))
189 (values
190 (parse-integer
191 (caar
192 (database-query
193 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
194 database nil nil)))))
196 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
197 (values
198 (parse-integer
199 (caar
200 (database-query
201 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
202 database nil nil)))))
204 (defun postgresql-database-list (connection-spec type)
205 (destructuring-bind (host name user password) connection-spec
206 (declare (ignore name))
207 (let ((database (database-connect (list host "template1" user password)
208 type)))
209 (unwind-protect
210 (progn
211 (setf (slot-value database 'clsql-sys::state) :open)
212 (mapcar #'car (database-query "select datname from pg_database"
213 database nil nil)))
214 (progn
215 (database-disconnect database)
216 (setf (slot-value database 'clsql-sys::state) :closed))))))
218 (defmethod database-list (connection-spec (type (eql :postgresql)))
219 (postgresql-database-list connection-spec type))
221 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
222 (postgresql-database-list connection-spec type))
224 #+nil
225 (defmethod database-describe-table ((database generic-postgresql-database) table)
226 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
227 ;; each attribute. It would be more efficient to have a single SQL
228 ;; query return the type data for all attributes. This code is
229 ;; retained as an example of how to do this for PostgreSQL.
230 (database-query
231 (format nil "select a.attname, t.typname
232 from pg_class c, pg_attribute a, pg_type t
233 where c.relname = '~a'
234 and a.attnum > 0
235 and a.attrelid = c.oid
236 and a.atttypid = t.oid"
237 (sql-escape (string-downcase table)))
238 database :auto nil))
240 ;;; Prepared statements
242 (defvar *next-prepared-id-num* 0)
243 (defun next-prepared-id ()
244 (let ((num (incf *next-prepared-id-num*)))
245 (format nil "CLSQL_PS_~D" num)))
247 (defclass postgresql-stmt ()
248 ((database :initarg :database :reader database)
249 (id :initarg :id :reader id)
250 (bindings :initarg :bindings :reader bindings)
251 (field-names :initarg :field-names :accessor stmt-field-names)
252 (result-types :initarg :result-types :reader result-types)))
254 (defun clsql-type->postgresql-type (type)
255 (cond
256 ((in type :int :integer) "INT4")
257 ((in type :short) "INT2")
258 ((in type :bigint) "INT8")
259 ((in type :float :double :number) "NUMERIC")
260 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
262 (error 'sql-user-error
263 :message
264 (format nil "Unknown clsql type ~A." type)))))
266 (defun prepared-sql-to-postgresql-sql (sql)
267 ;; FIXME: Convert #\? to "$n". Don't convert within strings
268 (declare (simple-string sql))
269 (with-output-to-string (out)
270 (do ((len (length sql))
271 (param 0)
272 (in-str nil)
273 (pos 0 (1+ pos)))
274 ((= len pos))
275 (declare (fixnum len param pos))
276 (let ((c (schar sql pos)))
277 (declare (character c))
278 (cond
279 ((or (char= c #\") (char= c #\'))
280 (setq in-str (not in-str))
281 (write-char c out))
282 ((and (char= c #\?) (not in-str))
283 (write-char #\$ out)
284 (write-string (write-to-string (incf param)) out))
286 (write-char c out)))))))
288 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
289 (let ((id (next-prepared-id)))
290 (database-execute-command
291 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
293 (mapcar #'clsql-type->postgresql-type types)
294 (prepared-sql-to-postgresql-sql sql-stmt))
295 database)
296 (make-instance 'postgresql-stmt
297 :id id
298 :database database
299 :result-types result-types
300 :field-names field-names
301 :bindings (make-list (length types)))))
303 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
304 (setf (nth (1- position) (bindings stmt)) value))
306 (defun binding-to-param (binding)
307 (typecase binding
308 (string
309 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
311 binding)))
313 (defmethod database-run-prepared ((stmt postgresql-stmt))
314 (with-slots (database id bindings field-names result-types) stmt
315 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
316 id (mapcar #'binding-to-param bindings))))
317 (cond
318 ((and field-names (not (consp field-names)))
319 (multiple-value-bind (res names)
320 (database-query query database result-types field-names)
321 (setf field-names names)
322 (values res names)))
323 (field-names
324 (values (nth-value 0 (database-query query database result-types nil))
325 field-names))
327 (database-query query database result-types field-names))))))
329 ;;; Capabilities
331 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
334 (defmethod db-type-default-case ((db-type (eql :postgresql)))
335 :lower)
337 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
340 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))