clsql-patch.lisp 17.4 KB
Newer Older
hayeah's avatar
hayeah committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
;; expressions.lisp
(in-package :clsql-sys)
(use-package :wisp.util)

(defun make-query (&rest args)
  ;; (pp 'make-query=> args)
  (flet ((select-objects (target-args)
           (and target-args
                (every #'(lambda (arg)
                           (and (symbolp arg)
                                (find-class arg nil)))
                       target-args))))
    (multiple-value-bind (selections arglist)
	(query-get-selections args)
      (if (select-objects selections) 
	  (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
	    (make-instance 'sql-object-query :objects selections
			   :flatp flatp :refresh refresh
			   :exp arglist))
	  (destructuring-bind (&key all flatp set-operation distinct from where
				    group-by having order-by 
				    offset limit inner-join on joins &allow-other-keys)
	      arglist
	    (if (null selections)
		(error "No target columns supplied to select statement."))
	    (if (null from)
		(error "No source tables supplied to select statement."))
	    ;; (pp 'selections=> selections 'from=> from)
	    (make-instance 'sql-query :selections selections
			   :all all :flatp flatp :set-operation set-operation
			   :distinct distinct :from from :where where
			   :limit limit :offset offset
			   :group-by group-by :having having :order-by order-by
			   :inner-join inner-join :joins joins :on on))))))

;;;; Complex Join


;;<join-query> := ( <join-type> <join-table> <join-table>)
;;<join-table> := <table-name> | <join-query>
;;<join-type> := inner | :left | :right | :full | :natural

;; (:full [qux]
;;        (:left (:natural [foo] [bar])
;; 	      [baz] :using '(c d))
;;        :on [= [qux a] [foo b]])

;; (output-joins '(:right [qux]
;; 		      (:left (:natural [foo] [bar])
;; 			     [baz] :using (c d))
;; 		      :on [= [qux a] [foo b]]))

;; qux full join ( (foo natural join bar) left join baz using (c,d)) on (qux.a = foo.b)

    
(defun output-joins (joins)
  (let ((*sql-stream* (make-string-output-stream))
	(database *default-database*))
    (cond ((atom joins) (output-sql joins database))
	  (t (let* ((join-type (car joins))
		    (tab1 (cadr joins))
		    (tab2 (caddr joins))
		    (condition (member-if #'(lambda (x) (member x '(:on :using)))
					  joins))
		    (cond-type (car condition))
		    (cond-clause (sql-output (cadr condition))))
	       (let ((tab1 (if (consp tab1)
			       #?"(${(output-joins tab1)})"
			       (output-joins tab1)))
		     (tab2 (if (consp tab2)
			       #?"(${(output-joins tab2)})"
			       (output-joins tab2))))
		 (when (and (eq join-type :natural)
			    condition)
		   (error "natural join takes no join condition"))
		 (if condition
		     #?"${tab1} ${join-type} join ${tab2} ${cond-type} ${cond-clause}"
		     #?"${tab1} ${join-type} join ${tab2}")))))))


(defmethod output-sql ((query sql-query) database)
  (with-slots (distinct selections from where group-by having order-by
                        limit offset inner-join on all set-operation) 
      query

    ;; (pp 'output=> selections from)
      
    (when *in-subselect*
      (write-string "(" *sql-stream*))
    (write-string "SELECT " *sql-stream*)
    (when all 
      (write-string "ALL " *sql-stream*))
    (when (and distinct (not all))
      (write-string "DISTINCT " *sql-stream*)
      (unless (eql t distinct)
        (write-string "ON " *sql-stream*)
        (output-sql distinct database)
        (write-char #\Space *sql-stream*)))
    (output-sql (apply #'vector selections) database)
    (when from
      (write-string " FROM " *sql-stream*)
      (flet ((ident-table-equal (a b) 
               (and (if (and (eql (type-of a) 'sql-ident-table)
                             (eql (type-of b) 'sql-ident-table))
                        (string-equal (slot-value a 'alias)
                                      (slot-value b 'alias))
                        t)
                    (string-equal (symbol-name (slot-value a 'name))
                                  (symbol-name (slot-value b 'name))))))
        (typecase from 
          (list (output-sql (apply #'vector 
                                   (remove-duplicates from 
                                                      :test #'ident-table-equal))
                            database))
          (string (write-string from *sql-stream*))
          (t (output-sql from database)))))
    (when inner-join
      (write-string " INNER JOIN " *sql-stream*)
      (output-sql inner-join database))
    (when on
      (write-string " ON " *sql-stream*)
      (output-sql on database))
    (when where
      (write-string " WHERE " *sql-stream*)
      (let ((*in-subselect* t))
        (output-sql where database)))
    (when group-by
      (write-string " GROUP BY " *sql-stream*)
      (output-sql group-by database))
    (when having
      (write-string " HAVING " *sql-stream*)
      (output-sql having database))
    (when order-by
      (write-string " ORDER BY " *sql-stream*)
      (if (listp order-by)
          (do ((order order-by (cdr order)))
              ((null order))
            (let ((item (car order)))
              (typecase item 
                (cons 
                 (output-sql (car item) database)
                 (format *sql-stream* " ~A" (cadr item)))
                (t 
                 (output-sql item database)))
              (when (cdr order)
                (write-char #\, *sql-stream*))))
          (output-sql order-by database)))
    (when limit
      (write-string " LIMIT " *sql-stream*)
      (output-sql limit database))
    (when offset
      (write-string " OFFSET " *sql-stream*)
      (output-sql offset database))
    (when *in-subselect*
      (write-string ")" *sql-stream*))
    (when set-operation 
      (write-char #\Space *sql-stream*)
      (output-sql set-operation database)))
  t)



;; syntax.lisp

;; Changed cons to apply
;;;; Want '[= [foo] [bar]] => <#sql-relational>
;;;; Rather then (sql-= foo bar)

(defun sql-reader-open (stream char) 
  (declare (ignore char)) 
  (let ((sqllist (read-delimited-list #\] stream t))) 
    (unless *read-suppress* 
      (handler-case 
	  (cond ((string= (write-to-string (car sqllist)) "||") 
		 (apply (sql-operator 'concat-op) (cdr sqllist))) 
		((and (= (length sqllist) 1) (eql (car sqllist) '*)) 
		 (apply #'generate-sql-reference sqllist)) 
		((sql-operator (car sqllist)) 
		 (apply (sql-operator (car sqllist)) (cdr sqllist))) 
		(t (apply #'generate-sql-reference sqllist))) 
	(sql-user-error (c) 
	  (error 'sql-user-error 
		 :message (format nil "Error ~A occured while attempting to parse '~A' at file position ~A" 
				  (sql-user-error-message c) sqllist (file-position stream))))))))


;; (defun generate-sql-reference (&rest arglist)
;;   (cond ((= (length arglist) 1)	string, table or attribute
;; 	 (if (stringp (car arglist))
;; 	     (sql-expression :string (car arglist))
;;              (sql-expression :attribute (car arglist))))
;; 	what the? When does it ever gets to the error case?
;; 	(t
;; 	 (let* ((attr-alias (cadr (member :as arglist)))
;; 		(table-alias (if (stringp (cadr arglist))
;; 				 (cadr arglist)
;; 			       nil))
;; 		(attr-table (if (keywordp (cadr arglist)) 
;; 				nil
;; 			      (car arglist)))
;; 		(attr-id (if attr-table
;; 			     (cadr arglist)
;; 			   (car arglist)))
;; 		(sqltype (when (keywordp (caddr arglist)) (caddr arglist) nil)))
;; 	  (princ (list 'alias '==> attr-alias))
;; 	   (cond (table-alias
;; 		  (sql-expression :table (car arglist)
;; 				  :alias (cadr arglist)
;; 				  :type sqltype))
;; 		 (t
;; 		  (princ (list 'alias '==> attr-alias 'second))
;; 		  (sql-expression :alias attr-alias
;; 				  :attribute attr-id
;; 				  :type sqltype
;; 				  :table attr-table)))))))


(defun generate-sql-reference (&rest arglist)
  (pprint arglist)
  (cond ((= (length arglist) 1)		;; string, table or attribute
	 (if (stringp (car arglist))
	     (sql-expression :string (car arglist))
             (sql-expression :attribute (car arglist))))
	((<= 2 (length arglist))
	 (let ((sqltype (when (keywordp (caddr arglist)) (caddr arglist) nil)))
           (cond
	     ;; The signature for table alias is [foo "bar"]  => "foo /"bar/"" 
             ((stringp (cadr arglist)) (sql-expression :table (car arglist) :alias (cadr arglist) :type sqltype))
	     ;; This is a very flimsy way to detect field information.
	     ;; ;; The type information has to be on the second position.
	     ;;
	     ;; Just try not to have integer type declared, i think it would be fine.
	     ((keywordp (cadr arglist)) (sql-expression :attribute (car arglist) :type (cadr arglist)))
	     ;; type is forced to nil if I specified a table for the attribute.
	     ;; [foo bar :integer]
	     ;;
	     ;; Bur I still would want to generate something like
	     ;; select foo.bar as boop from foo
	     ;; ;; I wonder how useful it is to allow alias for field?
	     ;; ;; ;; What if I want "select (10*id),(100*id) from foo"?
	     ;; ;; ;; ;; Without alias, I would have to extract data by position.
	     (t (sql-expression :attribute (cadr arglist) :table (car arglist) :type sqltype)))))
	(t (error 'sql-user-error :message "bad expression syntax"))))

(defun sql-expression (&key string table alias attribute type)
  "Returns an SQL expression constructed from the supplied
arguments which may be combined as follows: ATTRIBUTE and TYPE;
ATTRIBUTE; ALIAS or TABLE and ATTRIBUTE and TYPE; ALIAS or TABLE
and ATTRIBUTE; TABLE, ATTRIBUTE and TYPE; TABLE and ATTRIBUTE;
TABLE and ALIAS; TABLE; and STRING. An error of type
SQL-USER-ERROR is signalled if an unsupported combination of
keyword arguments is specified."
  (pprint (list string table alias attribute type))
  (cond
    (string (make-instance 'sql :string string))
    (attribute (make-instance 'sql-ident-attribute
			      :name attribute :qualifier (or table alias) :type type))
    ((and table (not attribute)) (make-instance 'sql-ident-table
						:name table :table-alias alias))))


;; (defvar clsql-function-wrappers
;;   '((create-table (name description &rest rest)
;;      `(create-table (->clsql name) (mapcar #'->clsql description) ,@rest))))

;; (macrolet (wrappers)
;;   (do-list (wrapper
	    
;; 	 (flet ((wrapper)))



;; (defun sexp->clsql (sqllist)
;;   (if (clsql-language-function? (car sexp))
;;       (wrapper sexp)
;;       (->clsql sexp)))


(defun ->clsql (sqllist) 
  (cond
    ((atom sqllist) (if (and (not (keywordp sqllist)) (symbolp sqllist))
			(generate-sql-reference sqllist)
			sqllist))
    ((eq (car sqllist) '||)
     (apply (sql-operator 'concat-op) (mapcar #'->clsql (cdr sqllist))))
    ((and (= (length sqllist) 1) (eql (car sqllist) '*))
     (apply #'generate-sql-reference sqllist))
    ((sql-operator (car sqllist))
     (apply (sql-operator (car sqllist)) (mapcar #'->clsql (cdr sqllist))))
    (t (apply #'generate-sql-reference sqllist))))



;; (sql-output (sexp->clsql-exp '(select (+ foo (baz bar) boo) :from (foo "bar"))))


;; (defun sql-output (sql-expr &optional database)
(defun sql-output (sql-expr &optional (database *default-database*))
  "Top-level call for generating SQL strings. Returns an SQL
  string appropriate for DATABASE which corresponds to the
  supplied lisp expression SQL-EXPR."
  (progv '(*sql-stream*)
      `(,(make-string-output-stream))
    (output-sql sql-expr database)
    (get-output-stream-string *sql-stream*)))



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Constraint Stuff
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; fddl.lisp


(defun create-table (name description &key (database *default-database*)
                          (constraints nil) (transactions t))
  "Creates a table called NAME, which may be a string, symbol or
SQL table identifier, in DATABASE which defaults to
*DEFAULT-DATABASE*. DESCRIPTION is a list whose elements are
lists containing the attribute names, types, and other
constraints such as not-null or primary-key for each column in
the table.  CONSTRAINTS is a string representing an SQL table
constraint expression or a list of such strings. With MySQL
databases, if TRANSACTIONS is t an InnoDB table is created which
supports transactions."
  (let* ((table-name (etypecase name 
                       (symbol (sql-expression :attribute name))
                       (string (sql-expression :attribute name))
                       (sql-ident name)))
         (stmt (make-instance 'sql-create-table
                              :name table-name
                              :columns description
                              :modifiers constraints
			      :transactions transactions)))
    (execute-command stmt :database database)))




;; expression.lisp

;;
;; Column constraint types and conversion to SQL
;;

(defparameter *constraint-types*
  (list
   (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
   (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
   (cons (symbol-name-default-case "NOT") "NOT")
   (cons (symbol-name-default-case "NULL") "NULL")
   (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
   (cons (symbol-name-default-case "KEY") "KEY")
   (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
   (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
   (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
   (cons (symbol-name-default-case "UNIQUE") "UNIQUE")))


;; constraints for postgresql
(defparameter *pg-special-constraint-types*
  (list
   (cons :required  "NOT NULL")
   (cons :primary "PRIMARY KEY") 
;;   (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
;;   (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL") 
   (cons :autoinc "AUTO_INCREMENT")
   (cons :unique "UNIQUE")))


;; (defmethod database-constraint-statement (constraint-list database)
;;   (declare (ignore database))
;;   (make-constraints-description constraint-list)) 

(defmethod database-constraint-statement (constraint-list database)
  (make-constraints-description constraint-list (database-underlying-type database)))

(fmakunbound 'make-constraints-description)

(defgeneric make-constraints-description (constraint-list db-type)) 


(defclass column-spec ()
  ((name :initarg :name)
   (default :initarg :default :initform nil)
   (type :initarg :type)
   (reference :initarg :reference :initform nil)
   (value-consts :initarg :value-consts :initform nil)
   (special-consts :initarg :special-consts :initform nil)))

392
(defclass reference ()
hayeah's avatar
hayeah committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  ((foreign-table :initarg :foreign-table)
   (foreign-field :initarg :foreign-field)
   (trigger :initarg :trigger)
   (trigger-response :initarg :trigger-response)))

(defmethod output-column (col-spec database)
  (destructuring-bind (name type . constraints)
               col-spec
             (let ((type (listify type)))
               (output-sql name database)
               (write-char #\Space *sql-stream*)
               (write-string
		(database-get-type-specifier (car type) (cdr type) database (database-underlying-type database))
		*sql-stream*)
               (let ((constraints (database-constraint-statement constraints database)))
                 (when constraints
                   (write-string " " *sql-stream*)
                   (write-string constraints *sql-stream*))))))


(defmethod output-column ((col-spec column-spec) (database clsql-postgresql:postgresql-database))
  (with-slots (name default reference value-constraints special-constraints) col-spec
    (sql-output name database)
    (when default (write-string " DEFAULTS" *sql-stream*) (sql-output default database))
    (when reference (with-slots (foreign-table foreign-field  trigger trigger-response) reference
		      (write-string " REFERENCES" *sql-stream*)
		      (sql-output foreign-table database)
		      (when foreign-field
			(write-char #\( *sql-stream*)
			(sql-output foreign-field database)
			(write-char #\) *sql-stream*))
		      (when trigger
 			(ecase trigger
			  (:on-delete (write-string " ON DELETE" *sql-stream*))
			  (:on-update (write-string " ON UPDATE" *sql-stream*)))
			(ecase trigger-response
			  (:restrict (write-string " RESTRICT" *sql-stream*))
			  (:cascade (write-string " CASCADE" *sql-stream*))
431 432
			  (:null (write-string " SET NULL" *sql-stream*))
			  (:default (write-string " SET DEFAULT" *sql-stream*))))))
hayeah's avatar
hayeah committed
433 434 435 436 437 438 439 440 441 442 443
    (dolist (key special-constraints)
      (let* ((constraint (assoc key *pg-special-constraint-types*))
	    (constraint-string (cdr constraint)))
	(if constraint
	    (write-string constraint-string *sql-stream*)
	    (error "Unrecognized column constraint ~S" key))))
    (when value-constraints
      (write-string " CHECKS(" *sql-stream*)
      (sql-output (->clsql (cons 'and value-constraints)) database)
      (write-char #\) *sql-stream*))))

444
;; (sql-output (->clsql '(> 2 3)))
hayeah's avatar
hayeah committed
445

446
;; (create-table 'foo (list (make-instance 'column-spec 
hayeah's avatar
hayeah committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

(defmethod output-sql ((stmt sql-create-table) (database clsql-postgresql:postgresql-database))
  (with-slots (name columns modifiers transactions)
      stmt
    (write-string "CREATE TABLE " *sql-stream*)
    (output-sql name database)
    (write-string " (" *sql-stream*)
    (do ((column columns (cdr column)))
	((null (cdr column))
	 (output-column (car column) database))
      (output-column (car column) database)
      (write-string ", " *sql-stream*))
    (when modifiers
      (do ((modifier (listify modifiers) (cdr modifier)))
	  ((null modifier))
	(write-string ", " *sql-stream*)
	(write-string (car modifier) *sql-stream*)))
    (write-char #\) *sql-stream*)
    (when (and (eq :mysql (database-underlying-type database))
	       transactions
	       (db-type-transaction-capable? :mysql database))
      (write-string " Type=InnoDB" *sql-stream*)))
  t)





(export '->clsql) 
(export 'column-spec)
(export 'foreign-key)