1- /* $PostgreSQL: pgsql/src/interfaces/ecpg/ecpglib/execute.c,v 1.63 2007/02/02 08:58:23 meskes Exp $ */
1+ /* $PostgreSQL: pgsql/src/interfaces/ecpg/ecpglib/execute.c,v 1.64 2007/02/11 15:18:17 meskes Exp $ */
22
33/*
44 * The aim is to get a simpler inteface to the database routines.
3838static char *
3939quote_postgres (char * arg ,bool quote ,int lineno )
4040{
41- char * res ;
42- int i ,
43- ri = 0 ;
41+ char * res ;
42+ int error ;
43+ size_t length ;
44+ size_t escaped_len ;
45+ size_t buffer_len ;
4446
4547/*
4648 * if quote is false we just need to store things in a descriptor they
@@ -50,29 +52,35 @@ quote_postgres(char *arg, bool quote, int lineno)
5052return res = ECPGstrdup (arg ,lineno );
5153else
5254{
53- res = (char * )ECPGalloc (2 * strlen (arg )+ 3 ,lineno );
55+ length = strlen (arg );
56+ buffer_len = 2 * length + 1 ;
57+ res = (char * )ECPGalloc (buffer_len + 3 ,lineno );
5458if (!res )
5559return (res );
5660
57- /*
58- * We don't know if the target database is using
59- * standard_conforming_strings, so we always use E'' strings.
60- */
61- if (strchr (arg ,'\\' )!= NULL )
62- res [ri ++ ]= ESCAPE_STRING_SYNTAX ;
63-
64- res [ri ++ ]= '\'' ;
65-
66- for (i = 0 ;arg [i ];i ++ ,ri ++ )
61+ error = 0 ;
62+ escaped_len = PQescapeString (res + 1 ,arg ,buffer_len );
63+ if (error )
6764{
68- if (SQL_STR_DOUBLE (arg [i ], true))
69- res [ri ++ ]= arg [i ];
70- res [ri ]= arg [i ];
65+ ECPGfree (res );
66+ return NULL ;
67+ }
68+ if (length == escaped_len )
69+ {
70+ res [0 ]= res [escaped_len + 1 ]= '\'' ;
71+ res [escaped_len + 2 ]= '\0' ;
72+ }
73+ else
74+ {
75+ /*
76+ * We don't know if the target database is using
77+ * standard_conforming_strings, so we always use E'' strings.
78+ */
79+ memmove (res + 2 ,res + 1 ,escaped_len );
80+ res [0 ]= ESCAPE_STRING_SYNTAX ;
81+ res [1 ]= res [escaped_len + 2 ]= '\'' ;
82+ res [escaped_len + 3 ]= '\0' ;
7183}
72-
73- res [ri ++ ]= '\'' ;
74- res [ri ]= '\0' ;
75-
7684ECPGfree (arg );
7785return res ;
7886}