]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/quote.c
Add E'' to internally created SQL strings that contain backslashes.
[postgresql] / src / backend / utils / adt / quote.c
1 /*-------------------------------------------------------------------------
2  *
3  * quote.c
4  *        Functions for quoting identifiers and literals
5  *
6  * Portions Copyright (c) 2000-2005, PostgreSQL Global Development Group
7  *
8  *
9  * IDENTIFICATION
10  *        $PostgreSQL: pgsql/src/backend/utils/adt/quote.c,v 1.16 2005/07/02 17:01:50 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "utils/builtins.h"
17
18
19 /*
20  * quote_ident -
21  *        returns a properly quoted identifier
22  */
23 Datum
24 quote_ident(PG_FUNCTION_ARGS)
25 {
26         text       *t = PG_GETARG_TEXT_P(0);
27         text       *result;
28         const char *qstr;
29         char       *str;
30         int                     len;
31
32         /* We have to convert to a C string to use quote_identifier */
33         len = VARSIZE(t) - VARHDRSZ;
34         str = (char *) palloc(len + 1);
35         memcpy(str, VARDATA(t), len);
36         str[len] = '\0';
37
38         qstr = quote_identifier(str);
39
40         len = strlen(qstr);
41         result = (text *) palloc(len + VARHDRSZ);
42         VARATT_SIZEP(result) = len + VARHDRSZ;
43         memcpy(VARDATA(result), qstr, len);
44
45         PG_RETURN_TEXT_P(result);
46 }
47
48 /*
49  * quote_literal -
50  *        returns a properly quoted literal
51  */
52 Datum
53 quote_literal(PG_FUNCTION_ARGS)
54 {
55         text       *t = PG_GETARG_TEXT_P(0);
56         text       *result;
57         char       *cp1;
58         char       *cp2;
59         int                     len;
60
61         len = VARSIZE(t) - VARHDRSZ;
62         /* We make a worst-case result area; wasting a little space is OK */
63         result = (text *) palloc(len * 2 + 3 + VARHDRSZ);
64
65         cp1 = VARDATA(t);
66         cp2 = VARDATA(result);
67
68         for(; len-- > 0; cp1++)
69                 if (*cp1 == '\\')
70                 {
71                         *cp2++ = ESCAPE_STRING_SYNTAX;
72                         break;
73                 }
74         
75         len = VARSIZE(t) - VARHDRSZ;
76         cp1 = VARDATA(t);
77         *cp2++ = '\'';
78         while (len-- > 0)
79         {
80                 if (SQL_STR_DOUBLE(*cp1))
81                         *cp2++ = *cp1;
82                 *cp2++ = *cp1++;
83         }
84         *cp2++ = '\'';
85
86         VARATT_SIZEP(result) = cp2 - ((char *) result);
87
88         PG_RETURN_TEXT_P(result);
89 }