How to include files in current current script in psql?

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

  \ i components / helper-functions.sql

This works fine if $ PWD matches the directory of my script ( ~/sql/ ), but if it doesn’t, it searches for the included file relative to $ PWD instead of the relative MAIN.sql .

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

I think the new \ir directive will be included in 9.2 for this problem, but I am running 8.3

+6
source share
1 answer

Pass the directory name as the psql variable and use this to collect the absolute path to the 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. 

This is not very, but that's why \ir added in the end.

+13
source

Source: https://habr.com/ru/post/898335/


All Articles