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 args database
24 (db-type (eql :postgresql)))
25 (declare (ignore type args database))
28 (defmethod database-get-type-specifier ((type (eql 'string)) args database
29 (db-type (eql :postgresql)))
30 (declare (ignore database))
32 (format nil "CHAR(~A)" (car args))
35 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
36 (db-type (eql :postgresql)))
37 (declare (ignore args database))
40 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
41 (db-type (eql :postgresql)))
42 (declare (ignore args database))
45 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database
46 (db-type (eql :postgresql)))
47 (declare (ignore args database))
48 "TIMESTAMP WITHOUT TIME ZONE")
50 (defmethod database-get-type-specifier ((type (eql 'number)) args database
51 (db-type (eql :postgresql)))
52 (declare (ignore database))
54 ((and (consp args) (= (length args) 2))
55 (format nil "NUMERIC(~D,~D)" (first args) (second args)))
56 ((and (consp args) (= (length args) 1))
57 (format nil "NUMERIC(~D)" (first args)))
63 (defun owner-clause (owner)
68 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
71 (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
74 (defun has-table (name database)
77 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
80 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
84 (defmethod slot-unbound (class (obj generic-postgresql-database)
85 (slot (eql 'has-table-pg_roles)))
86 ;; Lazily cache slot value
87 (declare (ignore class))
88 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
90 (defun database-list-objects-of-type (database type owner)
94 (if (and (has-table-pg_roles database)
95 (not (eq owner :all)))
98 FROM pg_catalog.pg_class c
99 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
100 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
101 WHERE c.relkind IN ('~A','')
102 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
103 AND pg_catalog.pg_table_is_visible(c.oid)
105 "SELECT relname FROM pg_class WHERE (relkind =
108 (owner-clause owner))
111 (defmethod database-list-tables ((database generic-postgresql-database)
113 (database-list-objects-of-type database "r" owner))
115 (defmethod database-list-views ((database generic-postgresql-database)
117 (database-list-objects-of-type database "v" owner))
119 (defmethod database-list-indexes ((database generic-postgresql-database)
121 (database-list-objects-of-type database "i" owner))
124 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
130 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
131 (string-downcase table)
132 (owner-clause owner))
135 (dolist (indexrelid indexrelids (nreverse result))
137 (caar (database-query
138 (format nil "select relname from pg_class where relfilenode='~A'"
143 (defmethod database-list-attributes ((table string)
144 (database generic-postgresql-database)
147 (cond ((stringp owner)
148 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
149 ((null owner) " AND (not (relowner=1))")
154 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
155 (string-downcase table)
159 (remove-if #'(lambda (it) (member it '("cmin"
165 ;; kmr -- added tableoid
166 "tableoid") :test #'equal))
169 (defmethod database-attribute-type (attribute (table string)
170 (database generic-postgresql-database)
172 (let ((row (car (database-query
173 (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"
174 (string-downcase table)
175 (string-downcase attribute)
176 (owner-clause owner))
179 (destructuring-bind (typname attlen atttypmod attnull) row
181 (setf attlen (parse-integer attlen :junk-allowed t)
182 atttypmod (parse-integer atttypmod :junk-allowed t))
184 (let ((coltype (ensure-keyword typname))
185 (colnull (if (string-equal "f" attnull) 1 0))
188 (setf (values collen colprec)
193 (values (ash (- atttypmod 4) -16)
194 (boole boole-and (- atttypmod 4) #xffff))))
197 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
198 ((= -1 attlen) (- atttypmod 4))
201 (values coltype collen colprec colnull))))))
203 (defmethod database-create-sequence (sequence-name
204 (database generic-postgresql-database))
205 (database-execute-command
206 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
209 (defmethod database-drop-sequence (sequence-name
210 (database generic-postgresql-database))
211 (database-execute-command
212 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
214 (defmethod database-list-sequences ((database generic-postgresql-database)
216 (database-list-objects-of-type database "S" owner))
218 (defmethod database-set-sequence-position (name (position integer)
219 (database generic-postgresql-database))
224 (format nil "SELECT SETVAL ('~A', ~A)" name position)
225 database nil nil)))))
227 (defmethod database-sequence-next (sequence-name
228 (database generic-postgresql-database))
233 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
234 database nil nil)))))
236 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
241 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
242 database nil nil)))))
244 (defmethod database-last-auto-increment-id ((database generic-postgresql-database) table column)
246 (sql-ident (setf table (slot-value table 'name)))
247 (standard-db-class (setf table (view-table table))))
249 (sql-ident (setf column (slot-value column 'name)))
250 (view-class-slot-definition-mixin
251 (setf column (view-class-slot-column column))))
252 (let ((seq-name (format nil "~a_~a_seq" table column)))
253 (first (clsql:query (format nil "SELECT currval ('~a')" seq-name)
256 :result-types '(integer)))))
258 (defun postgresql-database-list (connection-spec type)
259 (destructuring-bind (host name &rest other-args) connection-spec
260 (declare (ignore name))
261 (let ((database (database-connect (list* host "template1" other-args)
265 (setf (slot-value database 'clsql-sys::state) :open)
266 (mapcar #'car (database-query "select datname from pg_database"
269 (database-disconnect database)
270 (setf (slot-value database 'clsql-sys::state) :closed))))))
272 (defmethod database-list (connection-spec (type (eql :postgresql)))
273 (postgresql-database-list connection-spec type))
275 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
276 (postgresql-database-list connection-spec type))
279 (defmethod database-describe-table ((database generic-postgresql-database) table)
280 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
281 ;; each attribute. It would be more efficient to have a single SQL
282 ;; query return the type data for all attributes. This code is
283 ;; retained as an example of how to do this for PostgreSQL.
285 (format nil "select a.attname, t.typname
286 from pg_class c, pg_attribute a, pg_type t
287 where c.relname = '~a'
289 and a.attrelid = c.oid
290 and a.atttypid = t.oid"
291 (sql-escape (string-downcase table)))
294 ;;; Prepared statements
296 (defvar *next-prepared-id-num* 0)
297 (defun next-prepared-id ()
298 (let ((num (incf *next-prepared-id-num*)))
299 (format nil "CLSQL_PS_~D" num)))
301 (defclass postgresql-stmt ()
302 ((database :initarg :database :reader database)
303 (id :initarg :id :reader id)
304 (bindings :initarg :bindings :reader bindings)
305 (field-names :initarg :field-names :accessor stmt-field-names)
306 (result-types :initarg :result-types :reader result-types)))
308 (defun clsql-type->postgresql-type (type)
310 ((in type :int :integer) "INT4")
311 ((in type :short) "INT2")
312 ((in type :bigint) "INT8")
313 ((in type :float :double :number) "NUMERIC")
314 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
316 (error 'sql-user-error
318 (format nil "Unknown clsql type ~A." type)))))
320 (defun prepared-sql-to-postgresql-sql (sql)
321 ;; FIXME: Convert #\? to "$n". Don't convert within strings
322 (declare (simple-string sql))
323 (with-output-to-string (out)
324 (do ((len (length sql))
329 (declare (fixnum len param pos))
330 (let ((c (schar sql pos)))
331 (declare (character c))
333 ((or (char= c #\") (char= c #\'))
334 (setq in-str (not in-str))
336 ((and (char= c #\?) (not in-str))
338 (write-string (write-to-string (incf param)) out))
340 (write-char c out)))))))
342 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
343 (let ((id (next-prepared-id)))
344 (database-execute-command
345 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
347 (mapcar #'clsql-type->postgresql-type types)
348 (prepared-sql-to-postgresql-sql sql-stmt))
350 (make-instance 'postgresql-stmt
353 :result-types result-types
354 :field-names field-names
355 :bindings (make-list (length types)))))
357 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
358 (setf (nth (1- position) (bindings stmt)) value))
360 (defun binding-to-param (binding)
363 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
367 (defmethod database-run-prepared ((stmt postgresql-stmt))
368 (with-slots (database id bindings field-names result-types) stmt
369 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
370 id (mapcar #'binding-to-param bindings))))
372 ((and field-names (not (consp field-names)))
373 (multiple-value-bind (res names)
374 (database-query query database result-types field-names)
375 (setf field-names names)
378 (values (nth-value 0 (database-query query database result-types nil))
381 (database-query query database result-types field-names))))))
385 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
388 (defmethod db-type-default-case ((db-type (eql :postgresql)))
391 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
394 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))
397 (defmethod db-type-has-auto-increment? ((db-type (eql :postgresql)))