如何在psql中包含相对于当前执行脚本的文件?

Gau*_*nia 6 postgresql

我有一个PostgreSQL脚本(例如,MAIN.sqlin ~/sql/),它有类似的行

\i components/helper-functions.sql

如果$ PWD与我的脚本(~/sql/)的目录相同,这包括正常工作,但如果不是,它会查找相对于$ PWD而不是相对于的$ 154包含的文件MAIN.sql.

因此,如果我从中调用脚本~/,它将寻找~/components/helper-functions.sql而不是~/sql/components/helper-functions.sql.

我认为一个新的\ir指令将被包含在9.2中以解决这个问题,但我正在运行8.3

Pet*_*aut 13

将目录名称作为psql变量传递,并使用它来汇编包含文件的绝对路径,例如,

$ cat ./tmp/foo.sql
\echo 'This is foo.'
\set abs_bar_sql :DIR '/bar.sql'
\i :abs_bar_sql

$ cat ./tmp/bar.sql
\echo 'This is bar.'

$ psql -f ./tmp/foo.sql -v DIR=$PWD/tmp
This is foo.
This is bar.
Run Code Online (Sandbox Code Playgroud)

它并不漂亮,但这就是为什么\ir要加入它的原因.