1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
4 ;;;; Generic postgresql layer, used by db-postgresql and db-postgresql-socket
6 ;;;; This file is part of CLSQL.
8 ;;;; CLSQL users are granted the rights to distribute and use this software
9 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
10 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
11 ;;;; *************************************************************************
13 (in-package #:clsql-sys)
15 (defclass generic-postgresql-database (database)
16 ((has-table-pg_roles :type boolean :reader has-table-pg_roles :initform nil))
17 (:documentation "Encapsulate same behavior across postgresql and postgresql-socket backends."))
23 (defmethod database-get-type-specifier ((type symbol) args database
24 (db-type (eql :postgresql)))
25 "Special database types for POSTGRESQL backends"
26 (declare (ignore database db-type))
28 (wall-time ;; TODO: why is this WITHOUT...
29 "TIMESTAMP WITHOUT TIME ZONE")
31 ;; TODO: the default to CHAR here seems specious as the PG docs claim
32 ;; that char is slower than varchar
34 (format nil "CHAR(~A)" (car args))
38 ((and (consp args) (= (length args) 2))
39 (format nil "NUMERIC(~D,~D)" (first args) (second args)))
40 ((and (consp args) (= (length args) 1))
41 (format nil "NUMERIC(~D)" (first args)))
43 ((tinyint smallint) "INT2")
44 (t (call-next-method))))
48 (defun owner-clause (owner)
53 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
56 (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
59 (defun has-table (name database)
62 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
65 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
69 (defmethod slot-unbound (class (obj generic-postgresql-database)
70 (slot (eql 'has-table-pg_roles)))
71 ;; Lazily cache slot value
72 (declare (ignore class))
73 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
75 (defun database-list-objects-of-type (database type owner)
79 (if (and (has-table-pg_roles database)
80 (not (eq owner :all)))
83 FROM pg_catalog.pg_class c
84 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
85 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
86 WHERE c.relkind IN ('~A','')
87 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
88 AND pg_catalog.pg_table_is_visible(c.oid)
90 "SELECT relname FROM pg_class WHERE (relkind =
96 (defmethod database-list-tables ((database generic-postgresql-database)
98 (database-list-objects-of-type database "r" owner))
100 (defmethod database-list-views ((database generic-postgresql-database)
102 (database-list-objects-of-type database "v" owner))
104 (defmethod database-list-indexes ((database generic-postgresql-database)
106 (database-list-objects-of-type database "i" owner))
109 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
115 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where LOWER(relname)='~A'~A)"
116 (string-downcase (unescaped-database-identifier table))
117 (owner-clause owner))
120 (dolist (indexrelid indexrelids (nreverse result))
122 (caar (database-query
123 (format nil "select relname from pg_class where relfilenode='~A'"
128 (defmethod database-list-attributes ((table %database-identifier)
129 (database generic-postgresql-database)
131 (let* ((table (unescaped-database-identifier table))
133 (cond ((stringp owner)
134 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
135 ((null owner) " AND (not (relowner=1))")
140 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
141 (string-downcase table)
145 (remove-if #'(lambda (it) (member it '("cmin"
151 ;; kmr -- added tableoid
152 "tableoid") :test #'equal))
155 (defmethod database-attribute-type ((attribute %database-identifier)
156 (table %database-identifier)
157 (database generic-postgresql-database)
159 &aux (table (unescaped-database-identifier table))
160 (attribute (unescaped-database-identifier attribute)))
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
169 (setf attlen (%get-int attlen)
170 atttypmod (%get-int atttypmod))
171 (let ((coltype (ensure-keyword typname))
172 (colnull (typecase attnull
173 (string (if (string-equal "f" attnull) 1 0))
178 (setf (values collen colprec)
183 (values (ash (- atttypmod 4) -16)
184 (boole boole-and (- atttypmod 4) #xffff))))
187 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
188 ((= -1 attlen) (- atttypmod 4))
191 (values coltype collen colprec colnull))))))
193 (defmethod database-create-sequence (sequence-name
194 (database generic-postgresql-database))
195 (let ((cmd (concatenate
196 'string "CREATE SEQUENCE " (escaped-database-identifier sequence-name database))))
197 (database-execute-command cmd database)))
199 (defmethod database-drop-sequence (sequence-name
200 (database generic-postgresql-database))
201 (database-execute-command
202 (concatenate 'string "DROP SEQUENCE " (escaped-database-identifier sequence-name database))
205 (defmethod database-list-sequences ((database generic-postgresql-database)
207 (database-list-objects-of-type database "S" owner))
209 (defmethod database-set-sequence-position (name (position integer)
210 (database generic-postgresql-database))
215 (format nil "SELECT SETVAL ('~A', ~A)" (escaped-database-identifier name) position)
216 database nil nil)))))
218 (defmethod database-sequence-next (sequence-name
219 (database generic-postgresql-database))
224 (concatenate 'string "SELECT NEXTVAL ('" (escaped-database-identifier sequence-name) "')")
225 database nil nil)))))
227 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
232 (concatenate 'string "SELECT LAST_VALUE FROM " (escaped-database-identifier sequence-name))
233 database nil nil)))))
235 (defmethod auto-increment-sequence-name (table column (database generic-postgresql-database))
236 (let* ((sequence-name (or (database-identifier (slot-value column 'autoincrement-sequence))
237 (combine-database-identifiers
238 (list table column 'seq)
240 (when (search "'" (escaped-database-identifier sequence-name)
241 :test #'string-equal)
242 (signal-database-too-strange
243 "PG Sequence names shouldnt contain single quotes for the sake of sanity"))
246 (defmethod database-last-auto-increment-id ((database generic-postgresql-database) table column)
247 (let ((seq-name (auto-increment-sequence-name table column database)))
248 (first (clsql:query (format nil "SELECT currval ('~a')"
249 (escaped-database-identifier seq-name))
252 :result-types '(:int)))))
254 (defmethod database-generate-column-definition
255 (class slotdef (database generic-postgresql-database))
256 (when (member (view-class-slot-db-kind slotdef) '(:base :key))
258 (list (sql-expression :attribute (database-identifier slotdef database))
259 (specified-type slotdef)
260 (view-class-slot-db-type slotdef)))
261 (const (listify (view-class-slot-db-constraints slotdef)))
262 (seq (auto-increment-sequence-name class slotdef database)))
264 (setf const (remove :auto-increment const))
265 (unless (member :default const)
266 (let* ((next (format nil " nextval('~a')" (escaped-database-identifier seq))))
267 (setf const (append const (list :default next))))))
268 (append cdef const))))
270 (defmethod database-add-autoincrement-sequence
271 ((self standard-db-class) (database generic-postgresql-database))
272 (let ((ordered-slots (slots-for-possibly-normalized-class self)))
273 (dolist (slotdef ordered-slots)
274 ;; ensure that referenceed sequences actually exist before referencing them
275 (let ((sequence-name (auto-increment-sequence-name self slotdef database)))
276 (when (and sequence-name
277 (not (sequence-exists-p sequence-name :database database)))
278 (create-sequence sequence-name :database database))))))
280 (defmethod database-remove-autoincrement-sequence
281 ((table standard-db-class)
282 (database generic-postgresql-database))
283 (let ((ordered-slots (slots-for-possibly-normalized-class table)))
284 (dolist (slotdef ordered-slots)
285 ;; ensure that referenceed sequences are dropped with the table
286 (let ((sequence-name (auto-increment-sequence-name table slotdef database)))
287 (when sequence-name (drop-sequence sequence-name))))))
289 (defun postgresql-database-list (connection-spec type)
290 (destructuring-bind (host name &rest other-args) connection-spec
291 (declare (ignore name))
292 (let ((database (database-connect (list* host "template1" other-args)
296 (setf (slot-value database 'clsql-sys::state) :open)
297 (mapcar #'car (database-query "select datname from pg_database"
300 (database-disconnect database)
301 (setf (slot-value database 'clsql-sys::state) :closed))))))
303 (defmethod database-list (connection-spec (type (eql :postgresql)))
304 (postgresql-database-list connection-spec type))
306 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
307 (postgresql-database-list connection-spec type))
310 (defmethod database-describe-table ((database generic-postgresql-database) table)
311 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
312 ;; each attribute. It would be more efficient to have a single SQL
313 ;; query return the type data for all attributes. This code is
314 ;; retained as an example of how to do this for PostgreSQL.
316 (format nil "select a.attname, t.typname
317 from pg_class c, pg_attribute a, pg_type t
318 where c.relname = '~a'
320 and a.attrelid = c.oid
321 and a.atttypid = t.oid"
322 (sql-escape (string-downcase table)))
325 ;;; Prepared statements
327 (defvar *next-prepared-id-num* 0)
328 (defun next-prepared-id ()
329 (let ((num (incf *next-prepared-id-num*)))
330 (format nil "CLSQL_PS_~D" num)))
332 (defclass postgresql-stmt ()
333 ((database :initarg :database :reader database)
334 (id :initarg :id :reader id)
335 (bindings :initarg :bindings :reader bindings)
336 (field-names :initarg :field-names :accessor stmt-field-names)
337 (result-types :initarg :result-types :reader result-types)))
339 (defun clsql-type->postgresql-type (type)
341 ((in type :int :integer) "INT4")
342 ((in type :short) "INT2")
343 ((in type :bigint) "INT8")
344 ((in type :float :double :number) "NUMERIC")
345 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
347 (error 'sql-user-error
349 (format nil "Unknown clsql type ~A." type)))))
351 (defun prepared-sql-to-postgresql-sql (sql)
352 ;; FIXME: Convert #\? to "$n". Don't convert within strings
353 (declare (simple-string sql))
354 (with-output-to-string (out)
355 (do ((len (length sql))
360 (declare (fixnum len param pos))
361 (let ((c (schar sql pos)))
362 (declare (character c))
364 ((or (char= c #\") (char= c #\'))
365 (setq in-str (not in-str))
367 ((and (char= c #\?) (not in-str))
369 (write-string (write-to-string (incf param)) out))
371 (write-char c out)))))))
373 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
374 (let ((id (next-prepared-id)))
375 (database-execute-command
376 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
378 (mapcar #'clsql-type->postgresql-type types)
379 (prepared-sql-to-postgresql-sql sql-stmt))
381 (make-instance 'postgresql-stmt
384 :result-types result-types
385 :field-names field-names
386 :bindings (make-list (length types)))))
388 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
389 (setf (nth (1- position) (bindings stmt)) value))
391 (defun binding-to-param (binding)
394 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
398 (defmethod database-run-prepared ((stmt postgresql-stmt))
399 (with-slots (database id bindings field-names result-types) stmt
400 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
401 id (mapcar #'binding-to-param bindings))))
403 ((and field-names (not (consp field-names)))
404 (multiple-value-bind (res names)
405 (database-query query database result-types field-names)
406 (setf field-names names)
409 (values (nth-value 0 (database-query query database result-types nil))
412 (database-query query database result-types field-names))))))
416 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
419 (defmethod db-type-default-case ((db-type (eql :postgresql)))
422 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
425 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
428 (defmethod db-type-has-auto-increment? ((db-type (eql :postgresql)))