diff --git a/src/box/lua/sql.lua b/src/box/lua/sql.lua index 7a1df322036fcfa59da74c7a10c33c7b466e7fd6..0a895892728aac2d00ea399f9aa042e2b3c83626 100644 --- a/src/box/lua/sql.lua +++ b/src/box/lua/sql.lua @@ -169,6 +169,11 @@ box.net.sql = { -- quote variable quote = function(self, variable) return self.raw:quote(variable) + end, + + -- quote identifier + quote_ident = function(self, variable) + return self.raw:quote_ident(variable) end } diff --git a/src/lua/pg.cc b/src/lua/pg.cc index 761e59bf4bc0606a8716cdec6dfee2d821294f3f..c155fe85240b38dd001cdd7eafed24b14667854d 100644 --- a/src/lua/pg.cc +++ b/src/lua/pg.cc @@ -296,6 +296,54 @@ self_field(struct lua_State *L, const char *name, int index) } +/** + * quote variable + */ +static int +lua_pg_quote(struct lua_State *L) +{ + if (lua_gettop(L) < 2) { + lua_pushnil(L); + return 1; + } + PGconn *conn = lua_check_pgconn(L, 1); + size_t len; + const char *s = lua_tolstring(L, -1, &len); + + s = PQescapeLiteral(conn, s, len); + + if (!s) + luaL_error(L, "Can't allocate memory"); + lua_pushstring(L, s); + free((void *)s); + return 1; +} + + +/** + * quote identifier + */ +static int +lua_pg_quote_ident(struct lua_State *L) +{ + if (lua_gettop(L) < 2) { + lua_pushnil(L); + return 1; + } + PGconn *conn = lua_check_pgconn(L, 1); + size_t len; + const char *s = lua_tolstring(L, -1, &len); + + s = PQescapeIdentifier(conn, s, len); + + if (!s) + luaL_error(L, "Can't allocate memory"); + lua_pushstring(L, s); + free((void *)s); + return 1; +} + + /** * connect to postgresql */ @@ -352,7 +400,9 @@ lbox_net_pg_connect(struct lua_State *L) lua_newtable(L); static const struct luaL_reg meta [] = { - {"execute", lua_pg_execute}, + {"execute", lua_pg_execute}, + {"quote", lua_pg_quote}, + {"quote_ident", lua_pg_quote_ident}, {NULL, NULL} }; luaL_register(L, NULL, meta); diff --git a/test/box/net_sql.pg.result b/test/box/net_sql.pg.result index 1f836c3f4d578eb0a1d8a65b653822f31d370647..b7b3e0d488e08f75cbf5f26dfb81f1f0648ed169 100644 --- a/test/box/net_sql.pg.result +++ b/test/box/net_sql.pg.result @@ -89,3 +89,7 @@ lua c = box.net.sql.connect('abcd') --- error: '[string "-- sql.lua (internal file)..."]:61: Unknown driver ''abcd''' ... +lua c:quote('abc"cde"def') +--- + - 'abc"cde"def' +... diff --git a/test/box/net_sql.pg.test b/test/box/net_sql.pg.test index 58d885b9833cbf9cb2b5dc23b2d361a400be3fb1..00311e85214843d9b2a3447da3857a31a2a4178d 100644 --- a/test/box/net_sql.pg.test +++ b/test/box/net_sql.pg.test @@ -28,3 +28,5 @@ exec admin "lua c:execute('SELEC T')" exec admin "lua c = box.net.sql.connect('abcd')" + +exec admin "lua c:quote('abc\"cde\"def')"