在 plpgsql 函数中使用 quote_ident()
the use of quote_ident() in a plpgsql function
我刚开始创建 plpgsql function.I 需要一些关于在函数内执行的动态命令上使用 quote_ident()(甚至 quote_literal())的说明.希望任何人都可以给我一个关于他们如何在函数内部工作的具体解释。 TIA
这是一个例子:
EXECUTE 'UPDATE tbl SET ' || quote_ident(colname) || ' = ' || quote_literal(newvalue) || ' WHERE key = ' || quote_literal(keyvalue);
quote_ident
用于 identifiers 引用。 quote_literal
用于 string 引用。
postgres=# select quote_ident('tablename');
┌─────────────┐
│ quote_ident │
╞═════════════╡
│ tablename │
└─────────────┘
(1 row)
postgres=# select quote_ident('special name');
┌────────────────┐
│ quote_ident │
╞════════════════╡
│ "special name" │
└────────────────┘
(1 row)
postgres=# select quote_literal(e'some text with special char"\'"');
┌───────────────────────────────────┐
│ quote_literal │
╞═══════════════════════════════════╡
│ 'some text with special char"''"' │
└───────────────────────────────────┘
(1 row)
什么是标识符?表名、列名、模式名、序列名……什么是文字? - 通常是一些文本值(但可以是任何类型的值)。两者都具有搜索和替换一些特殊字符的功能,但具有不同的规则 - SQL.
中的标识符和字符串不同
现在 - 这些功能有点过时了。 quote_literal
应替换为子句 USING
(更好的性能),quote_ident
应替换为格式化函数 format
(由于更好的可读性):
EXECUTE format('UPDATE tbl SET %I= WHERE key=', colname)
USING newvalue, keyvalue;
或仅具有格式化功能
EXECUTE format('UPDATE tbls SET %I=%L WHERE key=%L', colname, newvalue, keyvalue);
不引用你的动态 SQL a) 不应该工作(语法错误失败),b) 对 sql 注入不安全 .
我刚开始创建 plpgsql function.I 需要一些关于在函数内执行的动态命令上使用 quote_ident()(甚至 quote_literal())的说明.希望任何人都可以给我一个关于他们如何在函数内部工作的具体解释。 TIA
这是一个例子:
EXECUTE 'UPDATE tbl SET ' || quote_ident(colname) || ' = ' || quote_literal(newvalue) || ' WHERE key = ' || quote_literal(keyvalue);
quote_ident
用于 identifiers 引用。 quote_literal
用于 string 引用。
postgres=# select quote_ident('tablename');
┌─────────────┐
│ quote_ident │
╞═════════════╡
│ tablename │
└─────────────┘
(1 row)
postgres=# select quote_ident('special name');
┌────────────────┐
│ quote_ident │
╞════════════════╡
│ "special name" │
└────────────────┘
(1 row)
postgres=# select quote_literal(e'some text with special char"\'"');
┌───────────────────────────────────┐
│ quote_literal │
╞═══════════════════════════════════╡
│ 'some text with special char"''"' │
└───────────────────────────────────┘
(1 row)
什么是标识符?表名、列名、模式名、序列名……什么是文字? - 通常是一些文本值(但可以是任何类型的值)。两者都具有搜索和替换一些特殊字符的功能,但具有不同的规则 - SQL.
中的标识符和字符串不同现在 - 这些功能有点过时了。 quote_literal
应替换为子句 USING
(更好的性能),quote_ident
应替换为格式化函数 format
(由于更好的可读性):
EXECUTE format('UPDATE tbl SET %I= WHERE key=', colname)
USING newvalue, keyvalue;
或仅具有格式化功能
EXECUTE format('UPDATE tbls SET %I=%L WHERE key=%L', colname, newvalue, keyvalue);
不引用你的动态 SQL a) 不应该工作(语法错误失败),b) 对 sql 注入不安全 .