brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: \sf+ prints a PostgreSQL function with line numbers so you can find the failing line

Postgresql
~/tips/tip-database-psql-sf-plus-function-source

\sf+ my_function

Shows the source of a PostgreSQL function with numbered lines, to match an error message.

When an error message points at line 14 of a function, it helps to see which line that is. psql can show you the source with the numbers in front.

The \sf command fetches and shows the definition of a function or procedure as a CREATE OR REPLACE FUNCTION or CREATE OR REPLACE PROCEDURE command. With a plus sign, the output lines are numbered, and the first line of the function body is line 1.

\sf+ my_function

Name the function alone or with its argument types, such as \sf+ my_function(integer, text). The docs say the types are only required when more than one function has the same name.

The output goes to the current query output channel, which \o sets. So you can send it to a file and keep the definition in version control or edit it somewhere comfortable.

\o my_function.sql
\sf my_function
\o

Caveat: the rest of the line is taken as the argument, and neither variable interpolation nor backquote expansion is done on it. So you cannot put :name in there and expect it to be replaced. Note too that the line numbers count from the first line of the function body, not from the CREATE line, so they may differ by a line or two from what an editor shows for the whole statement.

Further reading: psql (PostgreSQL documentation)

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link