From 60ce25c8830c1dcb00b011dd240f2e7e20b7e288 Mon Sep 17 00:00:00 2001 From: "Dmitry E. Oboukhov" <unera@debian.org> Date: Fri, 7 Jun 2013 18:46:48 +0400 Subject: [PATCH] :quote methods for Pg --- src/box/lua/sql.lua | 5 ++++ src/lua/pg.cc | 52 +++++++++++++++++++++++++++++++++++++- test/box/net_sql.pg.result | 4 +++ test/box/net_sql.pg.test | 2 ++ 4 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/box/lua/sql.lua b/src/box/lua/sql.lua index 7a1df32203..0a89589272 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 761e59bf4b..c155fe8524 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 1f836c3f4d..b7b3e0d488 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 58d885b983..00311e8521 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')" -- GitLab