1

I have a directory with at least 6 function files.

I'm using psql and I need to be able to source (initialize ?) all function files at once.

I'm sure making a single function and call all others like SELECT fn1, fn2 isn't going to work.

Doing \i functions_folder/fn1.sql 6 times isn't ideal either.

So is there a way I can (maybe) \i functions/*.sql? Doing that currently gives me

functions/*.sql: No such file or directory

I'm using psql on postgresql 9.6.2

ArchNoob
  • 3,946
  • 5
  • 32
  • 59

2 Answers2

2

Create a wrapper that contains the \i commands, and \i the wrapper.

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
  • "wrapper that contains the` \i` commands" you mean the wrapper that contains the functions filenames? Or contains `\i filename.sql \n \i filaname2.sql` ? – ArchNoob May 06 '17 at 04:50
  • 1
    The latter; use a file that includes other files. – Craig Ringer May 06 '17 at 13:21
  • Oh, kinda like what Abelisto said in his answer? `cat` ing the contents of the function files. I wouldn't have known that trick. Thanks. :D – ArchNoob May 06 '17 at 16:46
  • @ArchNoob Yes, it is yet another alternative: `ls ./functions/*.sql | sed -e 's/^/\\i /g' > wrapper.sql` But we are talking not about PostgreSQL but about shell :o) – Abelisto May 06 '17 at 17:31
  • Sure, I could tell. Someone in irc (ningu) got me to something like `cat ./functions/* | psql ...` but I wanted something more psql-*ish* .. @Abelisto ;) – ArchNoob May 06 '17 at 18:05
2

If you are using *nix OS:

postgres=# \! cat ./functions/*.sql > all_functions.sql
postgres=# \i all_functions.sql

For Windows try to find the analogue of the cat (as I remember it is copy command with some flags)

PS I have the feeling that it could be done by using backquotes:

Within an argument, text that is enclosed in backquotes (`) is taken as a command line that is passed to the shell. The output of the command (with any trailing newline removed) replaces the backquoted text.

Documentation

But still have no idea how. Probably somebody more experienced will provide a hint...

Abelisto
  • 14,826
  • 2
  • 33
  • 41
  • 1
    Thanks, I'm using Linux and this worked perfectly. No backquotes/backticks. Also it's `type` command not cat see [Windows Alternative to cat command](http://stackoverflow.com/a/60254/2405689) – ArchNoob May 06 '17 at 12:28
  • 1
    @ArchNoob You provided the link to exactly that question where I found info about the Windows alternative for POSIX `cat` :o) Look at the comments for the accepted answer (about unnecessary lines) and to the next answer with `copy /b`. Good luck. – Abelisto May 06 '17 at 15:02
  • It surely is quite a thread to read but yeah I've seen the problems with `type` in it. Thanks for correction and the good luck man. – ArchNoob May 06 '17 at 16:54