fukamachi / cl-dbi

Database independent interface for Common Lisp
202 stars 28 forks source link

with-connection #6

Closed r-moeritz closed 11 years ago

r-moeritz commented 11 years ago

One thing that annoys me when writing db code is having to remember to close connections after I'm done. This has become annoying enough that I wrote a small macro, with-connection, that ensures dbi:disconnect will be called. Here I humbly submit it to you, in the hope that maybe you'll find it useful enough to include in cl-dbi proper.

Definition

(defmacro with-connection ((conn-sym &rest rest) &body body)
  `(let ((,conn-sym (dbi:connect ,@rest)))
     (unwind-protect
          (progn ,@body)
       (dbi:disconnect ,conn-sym))))

Sample usage

    (with-connection (conn :sqlite3 :database-name db-path)
      (let* ((query (dbi:prepare conn "SELECT * FROM People"))
             (result (dbi:execute query)))
        (loop for row = (dbi:fetch result)
           while row
           do (format t "~a~%" row))))))
fukamachi commented 11 years ago

It looks neat. I can't understand why this isn't in CL-DBI.. Would you send me a pull request? (or should I add it by myself?)