Next: , Previous: , Up: Query Construction   [Contents][Index]


9.4 Quoting

Ideally, the tree construction procedures in the following section would be powerful enough to do the right thing given a well-formed prefix-style expression. However, sometimes reality intrudes and you need to craft SQL directly. In these cases, it still may be a good idea to use the tree construction procedures for most of the work and tweak only the small parts that need it. This selective use of varying expression construction approaches is known prosaically as quoting.

Procedure: sql-pre string

Return string marked as preformatted. This inhibits certain types of processing when passed through the other procedures defined in this module. Repeated calls do not nest.

Procedure: sql-pre? string

Return #t if string is marked as preformatted.

Procedure: sql-unpre string

Return string, undoing the effect of sql-pre.

Procedure: sql-quote string

Return a new string made by doubling each single-quote in string, and prefixing and suffixing with single-quote. The returned string will also have backslash characters #\\ replaced with \134 (i.e., the string of four characters: #\\, #\1, #\3, #\4). The returned string is marked by sql-pre. For example:

(define bef "ab'c\\d")
(define aft (sql-quote bef))
(define (both proc)
  (map proc (list bef aft)))

(display aft)        -| 'ab''c\134d'
(both string-length) ⇒ (6 12)
(both sql-pre?)      ⇒ (#f #t)

Note that this procedure used to return internal single-quote characters prefixed with a backslash, which is acceptable by PostgreSQL (given certain runtime parameter settings), but not standards conforming. The current (as of Guile-PG 0.38) behavior is standards-conforming, upward compatible, and avoids futzing with the runtime parameters.

Procedure: idquote id

Return the quoted identifier form of id, a string or symbol. The returned string is marked by sql-pre. For example:

(define (try x)
  (display (idquote x))
  (newline))

(try 'abcd)       -| "abcd"
(try 'ab.cd)      -| "ab"."cd"
(try 'abcd[xyz])  -| "abcd"[xyz]
(try 'ab.cd[xyz]) -| "ab"."cd"[xyz]

;; Special case: only * after dot.
(try 'ab.*)       -| "ab".*

Note that PostgreSQL case-folding for non-quoted identifiers is nonstandard. The PostgreSQL documentation says:

If you want to write portable applications you are advised to always quote a particular name or never quote it. Section 4.1.1, Identifiers and Keywords

The qcons module (see Query Construction) uses idquote internally extensively.


Next: Strings, Previous: Lookup Tables Extension, Up: Query Construction   [Contents][Index]