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-output-sql ((self wall-time) (database generic-postgresql-database))
33 (declare (ignore database))
34 (concatenate 'string "'" (format-time nil self :format :iso8601) "'"))
36 (defmethod database-output-sql ((self date) (database generic-postgresql-database))
37 (declare (ignore database))
38 (concatenate 'string "'" (format-time nil (date->time self) :format :iso8601) "'"))
40 (defmethod database-get-type-specifier (type args database
41 (db-type (eql :postgresql)))
42 (declare (ignore type args database))
45 (defmethod database-get-type-specifier ((type (eql 'string)) args database
46 (db-type (eql :postgresql)))
47 (declare (ignore database))
49 (format nil "CHAR(~A)" (car args))
52 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database
53 (db-type (eql :postgresql)))
54 (declare (ignore args database))
57 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database
58 (db-type (eql :postgresql)))
59 (declare (ignore args database))
62 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database
63 (db-type (eql :postgresql)))
64 (declare (ignore args database))
65 "TIMESTAMP WITHOUT TIME ZONE")
67 (defmethod database-get-type-specifier ((type (eql 'number)) args database
68 (db-type (eql :postgresql)))
69 (declare (ignore database))
71 ((and (consp args) (= (length args) 2))
72 (format nil "NUMERIC(~D,~D)" (first args) (second args)))
73 ((and (consp args) (= (length args) 1))
74 (format nil "NUMERIC(~D)" (first args)))
80 (defun owner-clause (owner)
85 " AND (relowner=(SELECT usesysid FROM pg_user WHERE (usename='~A')))"
88 (format nil " AND (relowner<>(SELECT usesysid FROM pg_user WHERE usename='postgres'))"))
91 (defun has-table (name database)
94 (format nil "SELECT relname FROM pg_class WHERE relname='~A'"
97 (if (and (stringp name-retrieved) (plusp (length name-retrieved)))
101 (defmethod slot-unbound (class (obj generic-postgresql-database)
102 (slot (eql 'has-table-pg_roles)))
103 ;; Lazily cache slot value
104 (declare (ignore class))
105 (setf (slot-value obj 'has-table-pg_roles) (has-table "pg_roles" obj)))
107 (defun database-list-objects-of-type (database type owner)
111 (if (and (has-table-pg_roles database)
112 (not (eq owner :all)))
115 FROM pg_catalog.pg_class c
116 LEFT JOIN pg_catalog.pg_roles r ON r.oid = c.relowner
117 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
118 WHERE c.relkind IN ('~A','')
119 AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
120 AND pg_catalog.pg_table_is_visible(c.oid)
122 "SELECT relname FROM pg_class WHERE (relkind =
125 (owner-clause owner))
128 (defmethod database-list-tables ((database generic-postgresql-database)
130 (database-list-objects-of-type database "r" owner))
132 (defmethod database-list-views ((database generic-postgresql-database)
134 (database-list-objects-of-type database "v" owner))
136 (defmethod database-list-indexes ((database generic-postgresql-database)
138 (database-list-objects-of-type database "i" owner))
141 (defmethod database-list-table-indexes (table (database generic-postgresql-database)
147 "select indexrelid from pg_index where indrelid=(select relfilenode from pg_class where relname='~A'~A)"
148 (string-downcase table)
149 (owner-clause owner))
152 (dolist (indexrelid indexrelids (nreverse result))
154 (caar (database-query
155 (format nil "select relname from pg_class where relfilenode='~A'"
160 (defmethod database-list-attributes ((table string)
161 (database generic-postgresql-database)
164 (cond ((stringp owner)
165 (format nil " AND (relowner=(SELECT usesysid FROM pg_user WHERE usename='~A'))" owner))
166 ((null owner) " AND (not (relowner=1))")
171 (format nil "SELECT attname FROM pg_class,pg_attribute WHERE pg_class.oid=attrelid AND attisdropped = FALSE AND relname='~A'~A"
172 (string-downcase table)
176 (remove-if #'(lambda (it) (member it '("cmin"
182 ;; kmr -- added tableoid
183 "tableoid") :test #'equal))
186 (defmethod database-attribute-type (attribute (table string)
187 (database generic-postgresql-database)
189 (let ((row (car (database-query
190 (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"
191 (string-downcase table)
192 (string-downcase attribute)
193 (owner-clause owner))
196 (destructuring-bind (typname attlen atttypmod attnull) row
198 (setf attlen (parse-integer attlen :junk-allowed t)
199 atttypmod (parse-integer atttypmod :junk-allowed t))
201 (let ((coltype (ensure-keyword typname))
202 (colnull (if (string-equal "f" attnull) 1 0))
205 (setf (values collen colprec)
210 (values (ash (- atttypmod 4) -16)
211 (boole boole-and (- atttypmod 4) #xffff))))
214 (cond ((and (= -1 attlen) (= -1 atttypmod)) nil)
215 ((= -1 attlen) (- atttypmod 4))
218 (values coltype collen colprec colnull))))))
220 (defmethod database-create-sequence (sequence-name
221 (database generic-postgresql-database))
222 (database-execute-command
223 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
226 (defmethod database-drop-sequence (sequence-name
227 (database generic-postgresql-database))
228 (database-execute-command
229 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name)) database))
231 (defmethod database-list-sequences ((database generic-postgresql-database)
233 (database-list-objects-of-type database "S" owner))
235 (defmethod database-set-sequence-position (name (position integer)
236 (database generic-postgresql-database))
241 (format nil "SELECT SETVAL ('~A', ~A)" name position)
242 database nil nil)))))
244 (defmethod database-sequence-next (sequence-name
245 (database generic-postgresql-database))
250 (concatenate 'string "SELECT NEXTVAL ('" (sql-escape sequence-name) "')")
251 database nil nil)))))
253 (defmethod database-sequence-last (sequence-name (database generic-postgresql-database))
258 (concatenate 'string "SELECT LAST_VALUE FROM " sequence-name)
259 database nil nil)))))
261 (defun postgresql-database-list (connection-spec type)
262 (destructuring-bind (host name user password) connection-spec
263 (declare (ignore name))
264 (let ((database (database-connect (list host "template1" user password)
268 (setf (slot-value database 'clsql-sys::state) :open)
269 (mapcar #'car (database-query "select datname from pg_database"
272 (database-disconnect database)
273 (setf (slot-value database 'clsql-sys::state) :closed))))))
275 (defmethod database-list (connection-spec (type (eql :postgresql)))
276 (postgresql-database-list connection-spec type))
278 (defmethod database-list (connection-spec (type (eql :postgresql-socket)))
279 (postgresql-database-list connection-spec type))
282 (defmethod database-describe-table ((database generic-postgresql-database) table)
283 ;; MTP: LIST-ATTRIBUTE-TYPES currently executes separate queries for
284 ;; each attribute. It would be more efficient to have a single SQL
285 ;; query return the type data for all attributes. This code is
286 ;; retained as an example of how to do this for PostgreSQL.
288 (format nil "select a.attname, t.typname
289 from pg_class c, pg_attribute a, pg_type t
290 where c.relname = '~a'
292 and a.attrelid = c.oid
293 and a.atttypid = t.oid"
294 (sql-escape (string-downcase table)))
297 ;;; Prepared statements
299 (defvar *next-prepared-id-num* 0)
300 (defun next-prepared-id ()
301 (let ((num (incf *next-prepared-id-num*)))
302 (format nil "CLSQL_PS_~D" num)))
304 (defclass postgresql-stmt ()
305 ((database :initarg :database :reader database)
306 (id :initarg :id :reader id)
307 (bindings :initarg :bindings :reader bindings)
308 (field-names :initarg :field-names :accessor stmt-field-names)
309 (result-types :initarg :result-types :reader result-types)))
311 (defun clsql-type->postgresql-type (type)
313 ((in type :int :integer) "INT4")
314 ((in type :short) "INT2")
315 ((in type :bigint) "INT8")
316 ((in type :float :double :number) "NUMERIC")
317 ((and (consp type) (in (car type) :char :varchar)) "VARCHAR")
319 (error 'sql-user-error
321 (format nil "Unknown clsql type ~A." type)))))
323 (defun prepared-sql-to-postgresql-sql (sql)
324 ;; FIXME: Convert #\? to "$n". Don't convert within strings
325 (declare (simple-string sql))
326 (with-output-to-string (out)
327 (do ((len (length sql))
332 (declare (fixnum len param pos))
333 (let ((c (schar sql pos)))
334 (declare (character c))
336 ((or (char= c #\") (char= c #\'))
337 (setq in-str (not in-str))
339 ((and (char= c #\?) (not in-str))
341 (write-string (write-to-string (incf param)) out))
343 (write-char c out)))))))
345 (defmethod database-prepare (sql-stmt types (database generic-postgresql-database) result-types field-names)
346 (let ((id (next-prepared-id)))
347 (database-execute-command
348 (format nil "PREPARE ~A (~{~A~^,~}) AS ~A"
350 (mapcar #'clsql-type->postgresql-type types)
351 (prepared-sql-to-postgresql-sql sql-stmt))
353 (make-instance 'postgresql-stmt
356 :result-types result-types
357 :field-names field-names
358 :bindings (make-list (length types)))))
360 (defmethod database-bind-parameter ((stmt postgresql-stmt) position value)
361 (setf (nth (1- position) (bindings stmt)) value))
363 (defun binding-to-param (binding)
366 (concatenate 'string "'" (sql-escape-quotes binding) "'"))
370 (defmethod database-run-prepared ((stmt postgresql-stmt))
371 (with-slots (database id bindings field-names result-types) stmt
372 (let ((query (format nil "EXECUTE ~A (~{~A~^,~})"
373 id (mapcar #'binding-to-param bindings))))
375 ((and field-names (not (consp field-names)))
376 (multiple-value-bind (res names)
377 (database-query query database result-types field-names)
378 (setf field-names names)
381 (values (nth-value 0 (database-query query database result-types nil))
384 (database-query query database result-types field-names))))))
388 (defmethod db-type-has-fancy-math? ((db-type (eql :postgresql)))
391 (defmethod db-type-default-case ((db-type (eql :postgresql)))
394 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql)))
397 (defmethod db-type-has-prepared-stmt? ((db-type (eql :postgresql-socket)))