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 (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
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 (declare (ignore class))
90 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
92 (defun database-list-objects-of-type (database type owner)
96 (if (and (has-table-pg_roles database)
97 (not (eq owner :all)))
100 FROM pg_catalog.pg_class c
101 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
102 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
103 WHERE c.relkind IN ('~A','')
104 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
105 AND pg_catalog.pg_table_is_visible(c.oid)
107 "SELECT relname FROM pg_class WHERE (relkind =
110 (owner-clause owner))
113 (defmethod database-list-tables ((database generic-postgresql-database)
115 (database-list-objects-of-type database "r" owner))
117 (defmethod database-list-views ((database generic-postgresql-database)
119 (database-list-objects-of-type database "v" owner))
121 (defmethod database-list-indexes ((database generic-postgresql-database)
123 (database-list-objects-of-type database "i" owner))
126 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
132 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
133 (string-downcase table)
134 (owner-clause owner))
137 (dolist (indexrelid indexrelids (nreverse result))
139 (caar (database-query
140 (format nil "select relname from pg_class where relfilenode='~A'"
145 (defmethod database-list-attributes ((table string)
146 (database generic-postgresql-database)
149 (cond ((stringp owner)
150 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
151 ((null owner) " AND (not (relowner=1))")
156 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
157 (string-downcase table)
161 (remove-if #'(lambda (it) (member it '("cmin"
167 ;; kmr -- added tableoid
168 "tableoid") :test #'equal))
171 (defmethod database-attribute-type (attribute (table string)
172 (database generic-postgresql-database)
174 (let ((row (car (database-query
175 (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"
176 (string-downcase table)
177 (string-downcase attribute)
178 (owner-clause owner))
181 (destructuring-bind (typname attlen atttypmod attnull) row
183 (setf attlen (parse-integer attlen :junk-allowed t)
184 atttypmod (parse-integer atttypmod :junk-allowed t))
186 (let ((coltype (ensure-keyword typname))
187 (colnull (if (string-equal "f" attnull) 1 0))
190 (setf (values collen colprec)
195 (values (ash (- atttypmod 4) -16)
196 (boole boole-and (- atttypmod 4) #xffff))))
199 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
200 ((= -1 attlen) (- atttypmod 4))
203 (values coltype collen colprec colnull))))))
205 (defmethod database-create-sequence (sequence-name
206 (database generic-postgresql-database))
207 (database-execute-command
208 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
211 (defmethod database-drop-sequence (sequence-name
212 (database generic-postgresql-database))
213 (database-execute-command
214 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
216 (defmethod database-list-sequences ((database generic-postgresql-database)
218 (database-list-objects-of-type database "S" owner))
220 (defmethod database-set-sequence-position (name (position integer)
221 (database generic-postgresql-database))
226 (format nil "SELECT SETVAL ('~A', ~A)" name position)
227 database nil nil)))))
229 (defmethod database-sequence-next (sequence-name
230 (database generic-postgresql-database))
235 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
236 database nil nil)))))
238 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
243 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
244 database nil nil)))))
246 (defun postgresql-database-list (connection-spec type)
247 (destructuring-bind (host name &rest other-args) connection-spec
248 (declare (ignore name))
249 (let ((database (database-connect (list* host "template1" other-args)
253 (setf (slot-value database 'clsql-sys::state) :open)
254 (mapcar #'car (database-query "select datname from pg_database"
257 (database-disconnect database)
258 (setf (slot-value database 'clsql-sys::state) :closed))))))
260 (defmethod database-list (connection-spec (type (eql :postgresql)))
261 (postgresql-database-list connection-spec type))
263 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
264 (postgresql-database-list connection-spec type))
267 (defmethod database-describe-table ((database generic-postgresql-database) table)
268 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
269 ;; each attribute. It would be more efficient to have a single SQL
270 ;; query return the type data for all attributes. This code is
271 ;; retained as an example of how to do this for PostgreSQL.
273 (format nil "select a.attname, t.typname
274 from pg_class c, pg_attribute a, pg_type t
275 where c.relname = '~a'
277 and a.attrelid = c.oid
278 and a.atttypid = t.oid"
279 (sql-escape (string-downcase table)))
282 ;;; Prepared statements
284 (defvar *next-prepared-id-num* 0)
285 (defun next-prepared-id ()
286 (let ((num (incf *next-prepared-id-num*)))
287 (format nil "CLSQL_PS_~D" num)))
289 (defclass postgresql-stmt ()
290 ((database :initarg :database :reader database)
291 (id :initarg :id :reader id)
292 (bindings :initarg :bindings :reader bindings)
293 (field-names :initarg :field-names :accessor stmt-field-names)
294 (result-types :initarg :result-types :reader result-types)))
296 (defun clsql-type->postgresql-type (type)
298 ((in type :int :integer) "INT4")
299 ((in type :short) "INT2")
300 ((in type :bigint) "INT8")
301 ((in type :float :double :number) "NUMERIC")
302 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
304 (error 'sql-user-error
306 (format nil "Unknown clsql type ~A." type)))))
308 (defun prepared-sql-to-postgresql-sql (sql)
309 ;; FIXME: Convert #\? to "$n". Don't convert within strings
310 (declare (simple-string sql))
311 (with-output-to-string (out)
312 (do ((len (length sql))
317 (declare (fixnum len param pos))
318 (let ((c (schar sql pos)))
319 (declare (character c))
321 ((or (char= c #\") (char= c #\'))
322 (setq in-str (not in-str))
324 ((and (char= c #\?) (not in-str))
326 (write-string (write-to-string (incf param)) out))
328 (write-char c out)))))))
330 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
331 (let ((id (next-prepared-id)))
332 (database-execute-command
333 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
335 (mapcar #'clsql-type->postgresql-type types)
336 (prepared-sql-to-postgresql-sql sql-stmt))
338 (make-instance 'postgresql-stmt
341 :result-types result-types
342 :field-names field-names
343 :bindings (make-list (length types)))))
345 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
346 (setf (nth (1- position) (bindings stmt)) value))
348 (defun binding-to-param (binding)
351 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
355 (defmethod database-run-prepared ((stmt postgresql-stmt))
356 (with-slots (database id bindings field-names result-types) stmt
357 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
358 id (mapcar #'binding-to-param bindings))))
360 ((and field-names (not (consp field-names)))
361 (multiple-value-bind (res names)
362 (database-query query database result-types field-names)
363 (setf field-names names)
366 (values (nth-value 0 (database-query query database result-types nil))
369 (database-query query database result-types field-names))))))
373 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
376 (defmethod db-type-default-case ((db-type (eql :postgresql)))
379 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
382 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))