[pg-devel] Escaping SQL.

Erik Enge erik.enge at gmail.com
Fri Sep 15 21:17:27 UTC 2006


On 9/15/06, Eric Marsden <eric.marsden at free.fr> wrote:
>   I would much prefer to keep the core of pg-dot-lisp independent of
>   libpq.so.  Having this available as an extra file in CVS would be
>   fine, though (or it should be pretty easy to implement the escaping
>   in CL ...).

You can write the CL one if you like but I'd personally rather use the
one in libpq.  ;-)

Note that this version only works if you access each connection is
only accessed from one thread, as explained here:
http://www.postgresql.org/docs/8.1/static/libpq-exec.html

Should probably use PQescapeStringConn() though my CFFI knowledge is
lacking and I'm not sure how to pass in a CL-created PG connection to
that function.

(cffi:define-foreign-library libpq
  (t (:default "path-to-libpq")))

(cffi:use-foreign-library libpq)

(cffi:defctype size :unsigned-int)  ; not sure size_t is unsigned-int
everywhere.

;; Note the use of kmrcl code here, replace with whatever you need.
(cffi:defcfun "PQescapeString" size
  (to :string)
  (from :string)
  (length size))

(defun sql-escape (string)
  "SQL escapes a string.

Arguments:
  string: string to escape

Returns:
  new string."
  (let* ((string (kmrcl:ensure-string string))
           (len (length string)))
    (cffi:with-foreign-string (original-string string)
      (cffi:with-foreign-pointer-as-string (buf (1+ (* 2 len)))
        (PQescapeString buf original-string len)))))



More information about the pg-devel mailing list