Quick MySQL Identifier Escaping

A quick code snippet, in Objective Caml, that illustrates escaping an identifier in MySQL. Identifiers are quoted between backticks (`) and backticks within identifiers are escaped by writing two adjacent backticks (“). Escaping identifiers mean turning “Hello`World” into “`Hello“World`”.

This function turns an identifier into a quoted identifier, with a single memory allocation. It uses stack space that is linear in the number of backticks to escape within the identifier (which is at most 256, given traditional MySQL limits).

The code is in the public domain.

let string_of_name name =
  let rec escape c b i =
    try
      let next = String.index_from name i '`' in
      let str = escape (c+1) next (next+1) in
        String.blit name b str (b+c+1) (next-b+1) ;
        str
    with Not_found ->
      let size = String.length name + c + 2 in
      let str = String.create size in
        str.[0] <- '`' ;
        str.[size-1] <- '`' ;
        String.blit name b str (b+c+1) (String.length name - b) ;
        str
  in escape 0 0 0
;;

0 Responses to “Quick MySQL Identifier Escaping”


  1. No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1150 feed subscribers
(readers who polled a feed this week)