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 ;; his used to be without because we didnt track timezones well
29 ;; Now we do, so it should include them
31 "TIMESTAMP WITH TIME ZONE")
33 ;; TODO: the default to CHAR here seems specious as the PG docs claim
34 ;; that char is slower than varchar
36 (format nil "CHAR(~A)" (car args))
40 ((and (consp args) (= (length args) 2))
41 (format nil "NUMERIC(~D,~D)" (first args) (second args)))
42 ((and (consp args) (= (length args) 1))
43 (format nil "NUMERIC(~D)" (first args)))
45 ((tinyint smallint) "INT2")
46 (t (call-next-method))))
50 (defun owner-clause (owner)
55 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
58 (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
61 (defun has-table (name database)
64 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
67 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
71 (defmethod slot-unbound (class (obj generic-postgresql-database)
72 (slot (eql 'has-table-pg_roles)))
73 ;; Lazily cache slot value
74 (declare (ignore class))
75 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
77 (defun database-list-objects-of-type (database type owner)
81 (if (and (has-table-pg_roles database)
82 (not (eq owner :all)))
85 FROM pg_catalog.pg_class c
86 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
87 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
88 WHERE c.relkind IN ('~A','')
89 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
90 AND pg_catalog.pg_table_is_visible(c.oid)
92 "SELECT relname FROM pg_class WHERE (relkind =
98 (defmethod database-list-tables ((database generic-postgresql-database)
100 (database-list-objects-of-type database "r" owner))
102 (defmethod database-list-views ((database generic-postgresql-database)
104 (database-list-objects-of-type database "v" owner))
106 (defmethod database-list-indexes ((database generic-postgresql-database)
108 (database-list-objects-of-type database "i" owner))
111 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
117 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where LOWER(relname)='~A'~A)"
118 (string-downcase (unescaped-database-identifier table))
119 (owner-clause owner))
122 (dolist (indexrelid indexrelids (nreverse result))
124 (caar (database-query
125 (format nil "select relname from pg_class where relfilenode='~A'"
130 (defmethod database-list-attributes ((table %database-identifier)
131 (database generic-postgresql-database)
133 (let* ((table (unescaped-database-identifier table))
135 (cond ((stringp owner)
136 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
137 ((null owner) " AND (not (relowner=1))")
142 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
143 (string-downcase table)
147 (remove-if #'(lambda (it) (member it '("cmin"
153 ;; kmr -- added tableoid
154 "tableoid") :test #'equal))
157 (defmethod database-attribute-type ((attribute %database-identifier)
158 (table %database-identifier)
159 (database generic-postgresql-database)
161 &aux (table (unescaped-database-identifier table))
162 (attribute (unescaped-database-identifier attribute)))
163 (let ((row (car (database-query
164 (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"
165 (string-downcase table)
166 (string-downcase attribute)
167 (owner-clause owner))
170 (destructuring-bind (typname attlen atttypmod attnull) row
171 (setf attlen (%get-int attlen)
172 atttypmod (%get-int atttypmod))
173 (let ((coltype (ensure-keyword typname))
174 (colnull (typecase attnull
175 (string (if (string-equal "f" attnull) 1 0))
180 (setf (values collen colprec)
185 (values (ash (- atttypmod 4) -16)
186 (boole boole-and (- atttypmod 4) #xffff))))
189 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
190 ((= -1 attlen) (- atttypmod 4))
193 (values coltype collen colprec colnull))))))
195 (defmethod database-create-sequence (sequence-name
196 (database generic-postgresql-database))
197 (let ((cmd (concatenate
198 'string "CREATE SEQUENCE " (escaped-database-identifier sequence-name database))))
199 (database-execute-command cmd database)))
201 (defmethod database-drop-sequence (sequence-name
202 (database generic-postgresql-database))
203 (database-execute-command
204 (concatenate 'string "DROP SEQUENCE " (escaped-database-identifier sequence-name database))
207 (defmethod database-list-sequences ((database generic-postgresql-database)
209 (database-list-objects-of-type database "S" owner))
211 (defmethod database-set-sequence-position (name (position integer)
212 (database generic-postgresql-database))
217 (format nil "SELECT SETVAL ('~A', ~A)" (escaped-database-identifier name) position)
218 database nil nil)))))
220 (defmethod database-sequence-next (sequence-name
221 (database generic-postgresql-database))
226 (concatenate 'string "SELECT NEXTVAL ('" (escaped-database-identifier sequence-name) "')")
227 database nil nil)))))
229 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
234 (concatenate 'string "SELECT LAST_VALUE FROM " (escaped-database-identifier sequence-name))
235 database nil nil)))))
237 (defmethod auto-increment-sequence-name (table column (database generic-postgresql-database))
238 (let* ((sequence-name (or (database-identifier (slot-value column 'autoincrement-sequence))
239 (combine-database-identifiers
240 (list table column 'seq)
242 (when (search "'" (escaped-database-identifier sequence-name)
243 :test #'string-equal)
244 (signal-database-too-strange
245 "PG Sequence names shouldnt contain single quotes for the sake of sanity"))
248 (defmethod database-last-auto-increment-id ((database generic-postgresql-database) table column)
249 (let ((seq-name (auto-increment-sequence-name table column database)))
250 (first (clsql:query (format nil "SELECT currval ('~a')"
251 (escaped-database-identifier seq-name))
254 :result-types '(:int)))))
256 (defmethod database-generate-column-definition
257 (class slotdef (database generic-postgresql-database))
258 (when (member (view-class-slot-db-kind slotdef) '(:base :key))
260 (list (sql-expression :attribute (database-identifier slotdef database))
261 (specified-type slotdef)
262 (view-class-slot-db-type slotdef)))
263 (const (listify (view-class-slot-db-constraints slotdef)))
264 (seq (auto-increment-sequence-name class slotdef database)))
266 (setf const (remove :auto-increment const))
267 (unless (member :default const)
268 (let* ((next (format nil " nextval('~a')" (escaped-database-identifier seq))))
269 (setf const (append const (list :default next))))))
270 (append cdef const))))
272 (defmethod database-add-autoincrement-sequence
273 ((self standard-db-class) (database generic-postgresql-database))
274 (let ((ordered-slots (slots-for-possibly-normalized-class self)))
275 (dolist (slotdef ordered-slots)
276 ;; ensure that referenceed sequences actually exist before referencing them
277 (let ((sequence-name (auto-increment-sequence-name self slotdef database)))
278 (when (and sequence-name
279 (not (sequence-exists-p sequence-name :database database)))
280 (create-sequence sequence-name :database database))))))
282 (defmethod database-remove-autoincrement-sequence
283 ((table standard-db-class)
284 (database generic-postgresql-database))
285 (let ((ordered-slots (slots-for-possibly-normalized-class table)))
286 (dolist (slotdef ordered-slots)
287 ;; ensure that referenceed sequences are dropped with the table
288 (let ((sequence-name (auto-increment-sequence-name table slotdef database)))
289 (when sequence-name (drop-sequence sequence-name))))))
291 (defun postgresql-database-list (connection-spec type)
292 (destructuring-bind (host name &rest other-args) connection-spec
293 (declare (ignore name))
294 (let ((database (database-connect (list* host "template1" other-args)
298 (setf (slot-value database 'clsql-sys::state) :open)
299 (mapcar #'car (database-query "select datname from pg_database"
302 (database-disconnect database)
303 (setf (slot-value database 'clsql-sys::state) :closed))))))
305 (defmethod database-list (connection-spec (type (eql :postgresql)))
306 (postgresql-database-list connection-spec type))
308 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
309 (postgresql-database-list connection-spec type))
312 (defmethod database-describe-table ((database generic-postgresql-database) table)
313 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
314 ;; each attribute. It would be more efficient to have a single SQL
315 ;; query return the type data for all attributes. This code is
316 ;; retained as an example of how to do this for PostgreSQL.
318 (format nil "select a.attname, t.typname
319 from pg_class c, pg_attribute a, pg_type t
320 where c.relname = '~a'
322 and a.attrelid = c.oid
323 and a.atttypid = t.oid"
324 (sql-escape (string-downcase table)))
327 ;;; Prepared statements
329 (defvar *next-prepared-id-num* 0)
330 (defun next-prepared-id ()
331 (let ((num (incf *next-prepared-id-num*)))
332 (format nil "CLSQL_PS_~D" num)))
334 (defclass postgresql-stmt ()
335 ((database :initarg :database :reader database)
336 (id :initarg :id :reader id)
337 (bindings :initarg :bindings :reader bindings)
338 (field-names :initarg :field-names :accessor stmt-field-names)
339 (result-types :initarg :result-types :reader result-types)))
341 (defun clsql-type->postgresql-type (type)
343 ((in type :int :integer) "INT4")
344 ((in type :short) "INT2")
345 ((in type :bigint) "INT8")
346 ((in type :float :double :number) "NUMERIC")
347 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
349 (error 'sql-user-error
351 (format nil "Unknown clsql type ~A." type)))))
353 (defun prepared-sql-to-postgresql-sql (sql)
354 ;; FIXME: Convert #\? to "$n". Don't convert within strings
355 (declare (simple-string sql))
356 (with-output-to-string (out)
357 (do ((len (length sql))
362 (declare (fixnum len param pos))
363 (let ((c (schar sql pos)))
364 (declare (character c))
366 ((or (char= c #\") (char= c #\'))
367 (setq in-str (not in-str))
369 ((and (char= c #\?) (not in-str))
371 (write-string (write-to-string (incf param)) out))
373 (write-char c out)))))))
375 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
376 (let ((id (next-prepared-id)))
377 (database-execute-command
378 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
380 (mapcar #'clsql-type->postgresql-type types)
381 (prepared-sql-to-postgresql-sql sql-stmt))
383 (make-instance 'postgresql-stmt
386 :result-types result-types
387 :field-names field-names
388 :bindings (make-list (length types)))))
390 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
391 (setf (nth (1- position) (bindings stmt)) value))
393 (defun binding-to-param (binding)
396 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
400 (defmethod database-run-prepared ((stmt postgresql-stmt))
401 (with-slots (database id bindings field-names result-types) stmt
402 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
403 id (mapcar #'binding-to-param bindings))))
405 ((and field-names (not (consp field-names)))
406 (multiple-value-bind (res names)
407 (database-query query database result-types field-names)
408 (setf field-names names)
411 (values (nth-value 0 (database-query query database result-types nil))
414 (database-query query database result-types field-names))))))
418 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
421 (defmethod db-type-default-case ((db-type (eql :postgresql)))
424 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
427 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
430 (defmethod db-type-has-auto-increment? ((db-type (eql :postgresql)))