SQL中是否有一种机制可以对变量进行转义?

时间:2018-12-13 13:53:24

标签: postgresql security escaping sql-injection

我将在PostgreSQL中编写一个存储过程,该存储过程接受一个变量(我的SQL知识接近于零,因此,如果问题很明显,我深表歉意)。由于此变量将在调用中逐字使用,因此我想确保正确地对其进行转义以避免注入。

是否存在可以包装变量的函数,该函数可以正确进行转义?

我特别想在SQL中做到这一点,而不是在调用SQL查询的代码中清理输入(那个变量)(这可能会更容易)。

令我惊讶的是,没有找到有关此功能的重要文档,这使我相信这不是标准做法。我能找到的最接近的是lexer source code of Postgresql,但这超出了我的能力,无法理解这是否是正确的转义符(这将导致string被用作u&’stringuescape’’’ ,这看起来很野蛮)

1 个答案:

答案 0 :(得分:2)

PostgreSQL中有多个引用函数,记录在https://www.postgresql.org/docs/current/functions-string.html

quote_ident(string text)    text    Return the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled. See also Example 40-1.   quote_ident('Foo bar')  "Foo bar"
quote_literal(string text)  text    Return the given string suitably quoted to be used as a string literal in an SQL statement string. Embedded single-quotes and backslashes are properly doubled. Note that quote_literal returns null on null input; if the argument might be null, quote_nullable is often more suitable. See also Example 40-1.    quote_literal(E'O\'Reilly') 'O''Reilly'
quote_literal(value anyelement) text    Coerce the given value to text and then quote it as a literal. Embedded single-quotes and backslashes are properly doubled. quote_literal(42.5) '42.5'
quote_nullable(string text) text    Return the given string suitably quoted to be used as a string literal in an SQL statement string; or, if the argument is null, return NULL. Embedded single-quotes and backslashes are properly doubled. See also Example 40-1.    quote_nullable(NULL)    NULL
quote_nullable(value anyelement)    text    Coerce the given value to text and then quote it as a literal; or, if the argument is null, return NULL. Embedded single-quotes and backslashes are properly doubled.   quote_nullable(42.5)    '42.5'

但是,如果要设计从字符串准备SQL的过程,则应改用查询参数。

PREPARE fooplan (int, text, bool, numeric) AS
    INSERT INTO foo VALUES($1, $2, $3, $4);
EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);

https://www.postgresql.org/docs/current/sql-prepare.html中阅读更多内容