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: psql -X skips your ~/.psqlrc so a script behaves the same everywhere

Database
~/tips/tip-database-psql-no-psqlrc-scripts

psql -X -d appdb -f report.sql

Starts psql without reading startup files, so scripts give the same output on every machine.

My psql settings, such as expanded output or a custom prompt, are nice in the terminal and a trap in a script. The same psql command can print different output on two machines just because one of them has a startup file.

psql -X -d appdb -f report.sql

The docs say that -X (--no-psqlrc) stops psql from reading the startup files: neither the system-wide psqlrc nor your personal ~/.psqlrc. Without it, psql executes those files after connecting and before it takes your commands. The docs explain they are meant for setting up the client or the server to taste, typically with \set and SET commands. That can change output formats or switch autocommit off, to name two examples. In a cron job on another machine, those changes are either missing or different.

Where the file is looked for can be changed. The user file is searched in the home directory and the PSQLRC environment variable can point somewhere else. The docs also say that you can add a version to the name, such as ~/.psqlrc-19, so a file only applies to one PostgreSQL version.

The caveat has to do with the option -c. The notes say that before PostgreSQL 9.6, -c implied -X, and that this is no longer the case. So an old script that relied on this and runs psql -c "..." now reads your startup file too. That is easy to miss when you upgrade.

My habit would be to add -X to every psql call that sits in a script or a cron job, and leave it out for interactive use, where I do want my settings. A script that needs a setting should set it itself, at the top, where the next reader can see it.

Further reading: PostgreSQL documentation: psql

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link