8

I maintain a legacy application that uses a PostgreSQL database.

The application is heavily dependent on stored procedures (aka functions).

I want to save these functions to files named after the function name so I can then use a VCS (version control system).

I know that I can save the code with the ALTER FUNCTION using PgAdmin but this only allows me to save one function at a time.

I am looking for a way to save all the functions automatically. Is there any way to script this task?

Evan Carroll
65.7k50 gold badges259 silver badges510 bronze badges
asked Sep 17, 2012 at 23:51

3 Answers 3

4

I wrote a simple PHP script using pg_get_functiondef to get the source code and then save it to a file.

$connection = pg_connect("connection string details");
$result = pg_query($connection, "select proname, pg_get_functiondef(oid) from pg_proc where pronamespace=<namespace_oid>");
while ($row = pg_fetch_row($result)) {
 $fp = fopen("{$row[0]}.sql", 'w');
 fwrite($fp, $row[1]);
}
answered Sep 19, 2012 at 1:08
3
  • This is not bad either, but personally I'm in favour of lower level stuff like bash/sed (or any shell, minus standard Windows cmd.exe :) for things like these. Commented Sep 19, 2012 at 6:52
  • @dezso how can you accomplish the same task with bash? why do you prefer lower level stuff? Commented Sep 21, 2012 at 0:28
  • With just psql, dba.stackexchange.com/a/175841/2639 Commented Jun 9, 2017 at 2:00
4

Run the following

  1. mkdir /tmp/foo
  2. chown postgresql:postgresql /tmp/foo

Then in psql, run this command whose inner workings I shamelessly stole from Craig's answer on SO,

SELECT FORMAT(
 'COPY (SELECT pg_get_functiondef(%s)) TO ''/tmp/foo/%s''',
 pp.oid,
 pp.proname
)
from pg_proc pp
inner join pg_namespace pn on (pp.pronamespace = pn.oid)
inner join pg_language pl on (pp.prolang = pl.oid)
where pl.lanname NOT IN ('c','internal') 
 and pn.nspname NOT LIKE 'pg_%'
 and pn.nspname <> 'information_schema';

Then run \gexec

answered Jun 9, 2017 at 1:53
2

I can suggest 2 methods:

  1. Use pg_dump -s to save only the schema of your application. This will create one large file in which you will have to look for the stored procedures and save them to individual files. This may be OK for you.

  2. Query the pg_proc catalog table to create "CREATE FUNCTION" statements. See http://www.postgresql.org/docs/9.1/static/catalog-pg-proc.html for more information about which fields you will need.

answered Sep 18, 2012 at 9:45
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.