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."))
24 (defmethod database-output-sql-as-type ((type (eql 'float)) val database (db-type (eql :postgresql)))
25 (declare (ignore database db-type))
28 (defmethod database-output-sql-as-type ((type (eql 'float)) val database (db-type (eql :postgresql-socket)))
29 (declare (ignore database db-type))
32 (defmethod database-get-type-specifier (type args database
33 (db-type (eql :postgresql)))
34 (declare (ignore type args database))
37 (defmethod database-get-type-specifier ((type (eql 'string)) args database
38 (db-type (eql :postgresql)))
39 (declare (ignore database))
41 (format nil "CHAR(~A)" (car args))
44 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
45 (db-type (eql :postgresql)))
46 (declare (ignore args database))
49 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
50 (db-type (eql :postgresql)))
51 (declare (ignore args database))
54 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database
55 (db-type (eql :postgresql)))
56 (declare (ignore args database))
57 "TIMESTAMP WITHOUT TIME ZONE")
59 (defmethod database-get-type-specifier ((type (eql 'number)) args database
60 (db-type (eql :postgresql)))
61 (declare (ignore database))
63 ((and (consp args) (= (length args) 2))
64 (format nil "NUMERIC(~D,~D)" (first args) (second args)))
65 ((and (consp args) (= (length args) 1))
66 (format nil "NUMERIC(~D)" (first args)))
72 (defun owner-clause (owner)
77 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
80 (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
83 (defun has-table (name database)
86 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
89 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
93 (defmethod slot-unbound (class (obj generic-postgresql-database)
94 (slot (eql 'has-table-pg_roles)))
95 ;; Lazily cache slot value
96 (declare (ignore class))
97 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
99 (defun database-list-objects-of-type (database type owner)
103 (if (and (has-table-pg_roles database)
104 (not (eq owner :all)))
107 FROM pg_catalog.pg_class c
108 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
109 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
110 WHERE c.relkind IN ('~A','')
111 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
112 AND pg_catalog.pg_table_is_visible(c.oid)
114 "SELECT relname FROM pg_class WHERE (relkind =
117 (owner-clause owner))
120 (defmethod database-list-tables ((database generic-postgresql-database)
122 (database-list-objects-of-type database "r" owner))
124 (defmethod database-list-views ((database generic-postgresql-database)
126 (database-list-objects-of-type database "v" owner))
128 (defmethod database-list-indexes ((database generic-postgresql-database)
130 (database-list-objects-of-type database "i" owner))
133 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
139 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
140 (string-downcase table)
141 (owner-clause owner))
144 (dolist (indexrelid indexrelids (nreverse result))
146 (caar (database-query
147 (format nil "select relname from pg_class where relfilenode='~A'"
152 (defmethod database-list-attributes ((table string)
153 (database generic-postgresql-database)
156 (cond ((stringp owner)
157 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
158 ((null owner) " AND (not (relowner=1))")
163 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
164 (string-downcase table)
168 (remove-if #'(lambda (it) (member it '("cmin"
174 ;; kmr -- added tableoid
175 "tableoid") :test #'equal))
178 (defmethod database-attribute-type (attribute (table string)
179 (database generic-postgresql-database)
181 (let ((row (car (database-query
182 (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"
183 (string-downcase table)
184 (string-downcase attribute)
185 (owner-clause owner))
188 (destructuring-bind (typname attlen atttypmod attnull) row
190 (setf attlen (parse-integer attlen :junk-allowed t)
191 atttypmod (parse-integer atttypmod :junk-allowed t))
193 (let ((coltype (ensure-keyword typname))
194 (colnull (if (string-equal "f" attnull) 1 0))
197 (setf (values collen colprec)
202 (values (ash (- atttypmod 4) -16)
203 (boole boole-and (- atttypmod 4) #xffff))))
206 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
207 ((= -1 attlen) (- atttypmod 4))
210 (values coltype collen colprec colnull))))))
212 (defmethod database-create-sequence (sequence-name
213 (database generic-postgresql-database))
214 (database-execute-command
215 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
218 (defmethod database-drop-sequence (sequence-name
219 (database generic-postgresql-database))
220 (database-execute-command
221 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
223 (defmethod database-list-sequences ((database generic-postgresql-database)
225 (database-list-objects-of-type database "S" owner))
227 (defmethod database-set-sequence-position (name (position integer)
228 (database generic-postgresql-database))
233 (format nil "SELECT SETVAL ('~A', ~A)" name position)
234 database nil nil)))))
236 (defmethod database-sequence-next (sequence-name
237 (database generic-postgresql-database))
242 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
243 database nil nil)))))
245 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
250 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
251 database nil nil)))))
253 (defun postgresql-database-list (connection-spec type)
254 (destructuring-bind (host name user password) connection-spec
255 (declare (ignore name))
256 (let ((database (database-connect (list host "template1" user password)
260 (setf (slot-value database 'clsql-sys::state) :open)
261 (mapcar #'car (database-query "select datname from pg_database"
264 (database-disconnect database)
265 (setf (slot-value database 'clsql-sys::state) :closed))))))
267 (defmethod database-list (connection-spec (type (eql :postgresql)))
268 (postgresql-database-list connection-spec type))
270 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
271 (postgresql-database-list connection-spec type))
274 (defmethod database-describe-table ((database generic-postgresql-database) table)
275 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
276 ;; each attribute. It would be more efficient to have a single SQL
277 ;; query return the type data for all attributes. This code is
278 ;; retained as an example of how to do this for PostgreSQL.
280 (format nil "select a.attname, t.typname
281 from pg_class c, pg_attribute a, pg_type t
282 where c.relname = '~a'
284 and a.attrelid = c.oid
285 and a.atttypid = t.oid"
286 (sql-escape (string-downcase table)))
289 ;;; Prepared statements
291 (defvar *next-prepared-id-num* 0)
292 (defun next-prepared-id ()
293 (let ((num (incf *next-prepared-id-num*)))
294 (format nil "CLSQL_PS_~D" num)))
296 (defclass postgresql-stmt ()
297 ((database :initarg :database :reader database)
298 (id :initarg :id :reader id)
299 (bindings :initarg :bindings :reader bindings)
300 (field-names :initarg :field-names :accessor stmt-field-names)
301 (result-types :initarg :result-types :reader result-types)))
303 (defun clsql-type->postgresql-type (type)
305 ((in type :int :integer) "INT4")
306 ((in type :short) "INT2")
307 ((in type :bigint) "INT8")
308 ((in type :float :double :number) "NUMERIC")
309 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
311 (error 'sql-user-error
313 (format nil "Unknown clsql type ~A." type)))))
315 (defun prepared-sql-to-postgresql-sql (sql)
316 ;; FIXME: Convert #\? to "$n". Don't convert within strings
317 (declare (simple-string sql))
318 (with-output-to-string (out)
319 (do ((len (length sql))
324 (declare (fixnum len param pos))
325 (let ((c (schar sql pos)))
326 (declare (character c))
328 ((or (char= c #\") (char= c #\'))
329 (setq in-str (not in-str))
331 ((and (char= c #\?) (not in-str))
333 (write-string (write-to-string (incf param)) out))
335 (write-char c out)))))))
337 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
338 (let ((id (next-prepared-id)))
339 (database-execute-command
340 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
342 (mapcar #'clsql-type->postgresql-type types)
343 (prepared-sql-to-postgresql-sql sql-stmt))
345 (make-instance 'postgresql-stmt
348 :result-types result-types
349 :field-names field-names
350 :bindings (make-list (length types)))))
352 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
353 (setf (nth (1- position) (bindings stmt)) value))
355 (defun binding-to-param (binding)
358 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
362 (defmethod database-run-prepared ((stmt postgresql-stmt))
363 (with-slots (database id bindings field-names result-types) stmt
364 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
365 id (mapcar #'binding-to-param bindings))))
367 ((and field-names (not (consp field-names)))
368 (multiple-value-bind (res names)
369 (database-query query database result-types field-names)
370 (setf field-names names)
373 (values (nth-value 0 (database-query query database result-types nil))
376 (database-query query database result-types field-names))))))
380 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
383 (defmethod db-type-default-case ((db-type (eql :postgresql)))
386 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
389 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))