1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
6 ;;;; Generic postgresql layer, used by db-postgresql and db-postgresql-socket
8 ;;;; This file is part of CLSQL.
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."))
25 (defmethod database-get-type-specifier (type args database
26 (db-type (eql :postgresql)))
27 (declare (ignore type args database))
30 (defmethod database-get-type-specifier ((type (eql 'string)) args database
31 (db-type (eql :postgresql)))
32 (declare (ignore database))
34 (format nil "CHAR(~A)" (car args))
37 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
38 (db-type (eql :postgresql)))
39 (declare (ignore args database))
42 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
43 (db-type (eql :postgresql)))
44 (declare (ignore args database))
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))
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)))
65 (defun owner-clause (owner)
70 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
73 (format nil " AND (NOT (relowner=1))"))
76 (defun database-list-objects-of-type (database type owner)
80 "SELECT relname FROM pg_class WHERE (relkind = '~A')~A"
82 (if (not (eq owner :all))
83 ;; The below query fails on versions of postgresql
84 ;; (such as 7.4) that lack the pg_roles table
87 FROM pg_catalog.pg_class c
88 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
89 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
90 WHERE c.relkind IN ('~A','')
91 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
92 AND pg_catalog.pg_table_is_visible(c.oid)
94 "SELECT relname FROM pg_class WHERE (relkind =
100 (defmethod database-list-tables ((database generic-postgresql-database)
102 (database-list-objects-of-type database "r" owner))
104 (defmethod database-list-views ((database generic-postgresql-database)
106 (database-list-objects-of-type database "v" owner))
108 (defmethod database-list-indexes ((database generic-postgresql-database)
110 (database-list-objects-of-type database "i" owner))
113 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
119 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
120 (string-downcase table)
121 (owner-clause owner))
124 (dolist (indexrelid indexrelids (nreverse result))
126 (caar (database-query
127 (format nil "select relname from pg_class where relfilenode='~A'"
132 (defmethod database-list-attributes ((table string)
133 (database generic-postgresql-database)
136 (cond ((stringp owner)
137 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
138 ((null owner) " AND (not (relowner=1))")
143 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
144 (string-downcase table)
148 (remove-if #'(lambda (it) (member it '("cmin"
154 ;; kmr -- added tableoid
155 "tableoid") :test #'equal))
158 (defmethod database-attribute-type (attribute (table string)
159 (database generic-postgresql-database)
161 (let ((row (car (database-query
162 (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"
163 (string-downcase table)
164 (string-downcase attribute)
165 (owner-clause owner))
168 (destructuring-bind (typname attlen atttypmod attnull) row
170 (setf attlen (parse-integer attlen :junk-allowed t)
171 atttypmod (parse-integer atttypmod :junk-allowed t))
173 (let ((coltype (ensure-keyword typname))
174 (colnull (if (string-equal "f" attnull) 1 0))
177 (setf (values collen colprec)
182 (values (ash (- atttypmod 4) -16)
183 (boole boole-and (- atttypmod 4) #xffff))))
186 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
187 ((= -1 attlen) (- atttypmod 4))
190 (values coltype collen colprec colnull))))))
192 (defmethod database-create-sequence (sequence-name
193 (database generic-postgresql-database))
194 (database-execute-command
195 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
198 (defmethod database-drop-sequence (sequence-name
199 (database generic-postgresql-database))
200 (database-execute-command
201 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
203 (defmethod database-list-sequences ((database generic-postgresql-database)
205 (database-list-objects-of-type database "S" owner))
207 (defmethod database-set-sequence-position (name (position integer)
208 (database generic-postgresql-database))
213 (format nil "SELECT SETVAL ('~A', ~A)" name position)
214 database nil nil)))))
216 (defmethod database-sequence-next (sequence-name
217 (database generic-postgresql-database))
222 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
223 database nil nil)))))
225 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
230 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
231 database nil nil)))))
233 (defun postgresql-database-list (connection-spec type)
234 (destructuring-bind (host name user password) connection-spec
235 (declare (ignore name))
236 (let ((database (database-connect (list host "template1" user password)
240 (setf (slot-value database 'clsql-sys::state) :open)
241 (mapcar #'car (database-query "select datname from pg_database"
244 (database-disconnect database)
245 (setf (slot-value database 'clsql-sys::state) :closed))))))
247 (defmethod database-list (connection-spec (type (eql :postgresql)))
248 (postgresql-database-list connection-spec type))
250 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
251 (postgresql-database-list connection-spec type))
254 (defmethod database-describe-table ((database generic-postgresql-database) table)
255 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
256 ;; each attribute. It would be more efficient to have a single SQL
257 ;; query return the type data for all attributes. This code is
258 ;; retained as an example of how to do this for PostgreSQL.
260 (format nil "select a.attname, t.typname
261 from pg_class c, pg_attribute a, pg_type t
262 where c.relname = '~a'
264 and a.attrelid = c.oid
265 and a.atttypid = t.oid"
266 (sql-escape (string-downcase table)))
269 ;;; Prepared statements
271 (defvar *next-prepared-id-num* 0)
272 (defun next-prepared-id ()
273 (let ((num (incf *next-prepared-id-num*)))
274 (format nil "CLSQL_PS_~D" num)))
276 (defclass postgresql-stmt ()
277 ((database :initarg :database :reader database)
278 (id :initarg :id :reader id)
279 (bindings :initarg :bindings :reader bindings)
280 (field-names :initarg :field-names :accessor stmt-field-names)
281 (result-types :initarg :result-types :reader result-types)))
283 (defun clsql-type->postgresql-type (type)
285 ((in type :int :integer) "INT4")
286 ((in type :short) "INT2")
287 ((in type :bigint) "INT8")
288 ((in type :float :double :number) "NUMERIC")
289 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
291 (error 'sql-user-error
293 (format nil "Unknown clsql type ~A." type)))))
295 (defun prepared-sql-to-postgresql-sql (sql)
296 ;; FIXME: Convert #\? to "$n". Don't convert within strings
297 (declare (simple-string sql))
298 (with-output-to-string (out)
299 (do ((len (length sql))
304 (declare (fixnum len param pos))
305 (let ((c (schar sql pos)))
306 (declare (character c))
308 ((or (char= c #\") (char= c #\'))
309 (setq in-str (not in-str))
311 ((and (char= c #\?) (not in-str))
313 (write-string (write-to-string (incf param)) out))
315 (write-char c out)))))))
317 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
318 (let ((id (next-prepared-id)))
319 (database-execute-command
320 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
322 (mapcar #'clsql-type->postgresql-type types)
323 (prepared-sql-to-postgresql-sql sql-stmt))
325 (make-instance 'postgresql-stmt
328 :result-types result-types
329 :field-names field-names
330 :bindings (make-list (length types)))))
332 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
333 (setf (nth (1- position) (bindings stmt)) value))
335 (defun binding-to-param (binding)
338 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
342 (defmethod database-run-prepared ((stmt postgresql-stmt))
343 (with-slots (database id bindings field-names result-types) stmt
344 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
345 id (mapcar #'binding-to-param bindings))))
347 ((and field-names (not (consp field-names)))
348 (multiple-value-bind (res names)
349 (database-query query database result-types field-names)
350 (setf field-names names)
353 (values (nth-value 0 (database-query query database result-types nil))
356 (database-query query database result-types field-names))))))
360 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
363 (defmethod db-type-default-case ((db-type (eql :postgresql)))
366 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
369 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))