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)
18 ((has-table-pg_roles :type boolean :reader has-table-pg_roles :initform nil))
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 has-table (name database)
79 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
82 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
86 (defmethod slot-unbound (class (obj generic-postgresql-database)
87 (slot (eql 'has-table-pg_roles)))
88 ;; Lazily cache slot value
89 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
91 (defun database-list-objects-of-type (database type owner)
95 (if (and (has-table-pg_roles database)
96 (not (eq owner :all)))
99 FROM pg_catalog.pg_class c
100 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
101 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
102 WHERE c.relkind IN ('~A','')
103 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
104 AND pg_catalog.pg_table_is_visible(c.oid)
106 "SELECT relname FROM pg_class WHERE (relkind =
109 (owner-clause owner))
112 (defmethod database-list-tables ((database generic-postgresql-database)
114 (database-list-objects-of-type database "r" owner))
116 (defmethod database-list-views ((database generic-postgresql-database)
118 (database-list-objects-of-type database "v" owner))
120 (defmethod database-list-indexes ((database generic-postgresql-database)
122 (database-list-objects-of-type database "i" owner))
125 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
131 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
132 (string-downcase table)
133 (owner-clause owner))
136 (dolist (indexrelid indexrelids (nreverse result))
138 (caar (database-query
139 (format nil "select relname from pg_class where relfilenode='~A'"
144 (defmethod database-list-attributes ((table string)
145 (database generic-postgresql-database)
148 (cond ((stringp owner)
149 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
150 ((null owner) " AND (not (relowner=1))")
155 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
156 (string-downcase table)
160 (remove-if #'(lambda (it) (member it '("cmin"
166 ;; kmr -- added tableoid
167 "tableoid") :test #'equal))
170 (defmethod database-attribute-type (attribute (table string)
171 (database generic-postgresql-database)
173 (let ((row (car (database-query
174 (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"
175 (string-downcase table)
176 (string-downcase attribute)
177 (owner-clause owner))
180 (destructuring-bind (typname attlen atttypmod attnull) row
182 (setf attlen (parse-integer attlen :junk-allowed t)
183 atttypmod (parse-integer atttypmod :junk-allowed t))
185 (let ((coltype (ensure-keyword typname))
186 (colnull (if (string-equal "f" attnull) 1 0))
189 (setf (values collen colprec)
194 (values (ash (- atttypmod 4) -16)
195 (boole boole-and (- atttypmod 4) #xffff))))
198 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
199 ((= -1 attlen) (- atttypmod 4))
202 (values coltype collen colprec colnull))))))
204 (defmethod database-create-sequence (sequence-name
205 (database generic-postgresql-database))
206 (database-execute-command
207 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
210 (defmethod database-drop-sequence (sequence-name
211 (database generic-postgresql-database))
212 (database-execute-command
213 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
215 (defmethod database-list-sequences ((database generic-postgresql-database)
217 (database-list-objects-of-type database "S" owner))
219 (defmethod database-set-sequence-position (name (position integer)
220 (database generic-postgresql-database))
225 (format nil "SELECT SETVAL ('~A', ~A)" name position)
226 database nil nil)))))
228 (defmethod database-sequence-next (sequence-name
229 (database generic-postgresql-database))
234 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
235 database nil nil)))))
237 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
242 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
243 database nil nil)))))
245 (defun postgresql-database-list (connection-spec type)
246 (destructuring-bind (host name user password) connection-spec
247 (declare (ignore name))
248 (let ((database (database-connect (list host "template1" user password)
252 (setf (slot-value database 'clsql-sys::state) :open)
253 (mapcar #'car (database-query "select datname from pg_database"
256 (database-disconnect database)
257 (setf (slot-value database 'clsql-sys::state) :closed))))))
259 (defmethod database-list (connection-spec (type (eql :postgresql)))
260 (postgresql-database-list connection-spec type))
262 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
263 (postgresql-database-list connection-spec type))
266 (defmethod database-describe-table ((database generic-postgresql-database) table)
267 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
268 ;; each attribute. It would be more efficient to have a single SQL
269 ;; query return the type data for all attributes. This code is
270 ;; retained as an example of how to do this for PostgreSQL.
272 (format nil "select a.attname, t.typname
273 from pg_class c, pg_attribute a, pg_type t
274 where c.relname = '~a'
276 and a.attrelid = c.oid
277 and a.atttypid = t.oid"
278 (sql-escape (string-downcase table)))
281 ;;; Prepared statements
283 (defvar *next-prepared-id-num* 0)
284 (defun next-prepared-id ()
285 (let ((num (incf *next-prepared-id-num*)))
286 (format nil "CLSQL_PS_~D" num)))
288 (defclass postgresql-stmt ()
289 ((database :initarg :database :reader database)
290 (id :initarg :id :reader id)
291 (bindings :initarg :bindings :reader bindings)
292 (field-names :initarg :field-names :accessor stmt-field-names)
293 (result-types :initarg :result-types :reader result-types)))
295 (defun clsql-type->postgresql-type (type)
297 ((in type :int :integer) "INT4")
298 ((in type :short) "INT2")
299 ((in type :bigint) "INT8")
300 ((in type :float :double :number) "NUMERIC")
301 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
303 (error 'sql-user-error
305 (format nil "Unknown clsql type ~A." type)))))
307 (defun prepared-sql-to-postgresql-sql (sql)
308 ;; FIXME: Convert #\? to "$n". Don't convert within strings
309 (declare (simple-string sql))
310 (with-output-to-string (out)
311 (do ((len (length sql))
316 (declare (fixnum len param pos))
317 (let ((c (schar sql pos)))
318 (declare (character c))
320 ((or (char= c #\") (char= c #\'))
321 (setq in-str (not in-str))
323 ((and (char= c #\?) (not in-str))
325 (write-string (write-to-string (incf param)) out))
327 (write-char c out)))))))
329 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
330 (let ((id (next-prepared-id)))
331 (database-execute-command
332 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
334 (mapcar #'clsql-type->postgresql-type types)
335 (prepared-sql-to-postgresql-sql sql-stmt))
337 (make-instance 'postgresql-stmt
340 :result-types result-types
341 :field-names field-names
342 :bindings (make-list (length types)))))
344 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
345 (setf (nth (1- position) (bindings stmt)) value))
347 (defun binding-to-param (binding)
350 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
354 (defmethod database-run-prepared ((stmt postgresql-stmt))
355 (with-slots (database id bindings field-names result-types) stmt
356 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
357 id (mapcar #'binding-to-param bindings))))
359 ((and field-names (not (consp field-names)))
360 (multiple-value-bind (res names)
361 (database-query query database result-types field-names)
362 (setf field-names names)
365 (values (nth-value 0 (database-query query database result-types nil))
368 (database-query query database result-types field-names))))))
372 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
375 (defmethod db-type-default-case ((db-type (eql :postgresql)))
378 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
381 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))