/*
 * call-seq:
 *    PGconn.quote_ident( str ) -> String
 *    conn.quote_ident( str ) -> String
 *
 * Returns a string that is safe for inclusion in a SQL query as an
 * identifier. Note: this is not a quote function for values, but for
 * identifiers.
 * 
 * For example, in a typical SQL query: <tt>SELECT FOO FROM MYTABLE</tt>
 * The identifier <tt>FOO</tt> is folded to lower case, so it actually
 * means <tt>foo</tt>. If you really want to access the case-sensitive
 * field name <tt>FOO</tt>, use this function like
 * <tt>PGconn.quote_ident('FOO')</tt>, which will return <tt>"FOO"</tt>
 * (with double-quotes). PostgreSQL will see the double-quotes, and
 * it will not fold to lower case.
 * 
 * Similarly, this function also protects against special characters,
 * and other things that might allow SQL injection if the identifier
 * comes from an untrusted source.
 */
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE in_str)
{
    VALUE ret;
    char *str = StringValuePtr(in_str);
    /* result size at most NAMEDATALEN*2 plus surrounding
     * double-quotes. */
    char buffer[NAMEDATALEN*2+2];
    unsigned int i=0,j=0;

    if(strlen(str) >= NAMEDATALEN) {
        rb_raise(rb_eArgError, 
            "Input string is longer than NAMEDATALEN-1 (%d)",
            NAMEDATALEN-1);
    }
    buffer[j++] = '"';
    for(i = 0; i < strlen(str) && str[i]; i++) {
        if(str[i] == '"') 
            buffer[j++] = '"';
        buffer[j++] = str[i];
    }
    buffer[j++] = '"';
    ret = rb_str_new(buffer,j);
    OBJ_INFECT(ret, in_str);
    return ret;
}