PostgreSQL 未终止的引用标识符

PostgreSQL unterminated quoted identifier

我有这个 groovy 代码,它从命令行删除远程 postgres 模式:

def dropSchema = "psql --dbname=postgres://$user:$pass@localhost:$port/$targetDb -c \"DROP SCHEMA ${applicationName}_${uid} CASCADE;\"".execute()

此代码在 运行 机器上运行良好,但在 Linux 发行版上运行时,出现以下错误:

psql: warning: extra command-line argument "appName_uid" ignored

psql: warning: extra command-line argument "CASCADE;"" ignored

ERROR: unterminated quoted identifier at or near ""DROP"

LINE 1: "DROP ^

有谁知道如何解决这个问题?

谢谢。

永远不要使用带有 .execute() 的字符串,例如 "ls 'my fancy file'".execute()。它在 whitespace 上拆分,这很可能永远不是您想要的(与该示例的 ["ls", "'my", "fancy", "file'"].execute() 相同)。

还有 .execute() 运行 通过 OS 的常规 exec 命令 -- 而不是 shell。因此,引用或其他需要为 shell 命令完成的事情实际上会使事情变得更糟 - 因为没有 shell 参与解释您的意图。

而是使用数组,其中所有参数都是它们自己的(不要引用从未使用过的 shell

[
 "psql", 
 "--dbname=postgres://$user:$pass@localhost:$port/$targetDb", 
 "-c", "DROP SCHEMA ${applicationName}_${uid} CASCADE;"
].execute()

如果您希望重用现有的 shell 命令,则 运行 它带有 shell:

["/bin/sh", "-c", "psql ... -c \"DROP ...\" ..."].execute()

在这里你必须引用shell,因为它像shell命令一样执行。