Run SQL files through make and save output

Goal

Use a Make target to:

Why the original version failed

This target is fine for interactive use:

psql:
    docker exec -it $(DB_CONTAINER) psql -U $(DB_USER) -d $(DB_NAME)

But it fails for file input or output redirection because:

Also, psql -f some/path.sql looks for the file inside the container, not on the host.

Best practice

Use two targets:

psql:
    docker exec -it $(DB_CONTAINER) psql -U $(DB_USER) -d $(DB_NAME)

psql-file:
    docker exec -i $(DB_CONTAINER) psql -U $(DB_USER) -d $(DB_NAME)

How to use them

Interactive session

make psql

Execute a host SQL file and save output to a host file

cat backend/db/vendor.sql | make psql-file > ~/etc/tmp/output.txt

Why this works

Rule of thumb

Optional variant with passed arguments

If you want a reusable target for container-side file paths:

psql-args:
    docker exec -i $(DB_CONTAINER) psql -U $(DB_USER) -d $(DB_NAME) $(ARGS)

Example:

make psql-args ARGS="-f /app/backend/db/vendor.sql"

That only works if the file path exists inside the container.

For reliability, prefer the pipe method:

cat backend/db/vendor.sql | make psql-file > ~/etc/tmp/output.txt