如何在psql中包含相对于当前执行脚本的文件? [英] How to include files relative to the current executing script in psql?

查看:75
本文介绍了如何在psql中包含相对于当前执行脚本的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PostgreSQL脚本(例如,〜/ sql / 中的 MAIN.sql

I have a PostgreSQL script (say, MAIN.sql in ~/sql/) which has lines like


\i components/helper-functions.sql

如果$ PWD与我的脚本目录(〜/ sql / )相同,则该include可以正常工作,但是如果不是,则查找相对于$ PWD而不是相对于 MAIN.sql 的包含文件。

This include works fine if the $PWD is the same as the directory of my script (~/sql/), but if it is not, it looks for the included file relative to the $PWD instead of relative to MAIN.sql.

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

So if I call the script from ~/, it would look for ~/components/helper-functions.sql and not for ~/sql/components/helper-functions.sql.

我认为新的 \ir 指令将完全包含在9.2中,但是我正在运行8.3

I think a new \ir directive is going to be included in 9.2 for exactly this problem, but I'm running 8.3

推荐答案

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

Pass the directory name in as a psql variable and use that to assemble the absolute path to included files, e.g.,

$ 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.

虽然不漂亮,但这就是为什么 \ir

It's not pretty, but that's why \ir is being added after all.

这篇关于如何在psql中包含相对于当前执行脚本的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆