With just psql I guess @Pavel_Stehule is right (so Not).
With SQLTT you can hack it with the use of hooks.
Example:
// users.sql.js
const sqltt = require("sqltt");
const getUserData = new sqltt({
hooks: {
// Prettier formatting on CLI output:
user_profile: (arg, eng) => eng.match(/(^|_)cli$/) && "jsonb_pretty("+arg+") as "+arg,
},
sql: $=>$`
select id, name, ${$.literal("user_profile")}
from users
where id = ${"userId"}
`,
});
sqltt.publish(module, {getUserData});
Then you can...
Install sqltt:
user@host:~/sqltttest$ npm install sqltt
(...)
List available queries in file:
user@host:~/sqltttest$ node user.sql.js
Available queries:
✓ getUserData: (Undocumented)
Get psql suitable query (with arguments already interpolated):
user@host:~/sqltttest$ node user.sql.js getUserData 'John Smith'
\set userId '''John Smith'''
select id, name, jsonb_pretty(user_profile) as user_profile
from users
where id = :userId
...pipe it directly to psql:
user@host:~/sqltttest$ node user.sql.js getUserData 'John Smith' | psql myDatabase
\set userId '''John Smith'''
select id, name, jsonb_pretty(user_profile) as user_profile
from users
where id = :userId
Use it from Node.js project:
const {getUserData, ...otherSQL} = require("./user.sql.js");
const sql = getUserData.sql();
// select id, name, user_profile
// from users
// where id = $1
Obtain non-cli sql to use with other languages:
user@host:~/sqltttest$ node user.sql.js --engine=_nocli getUserData
select id, name, user_profile
from users
where id = $1
...and, of course, store it in plain sql file:
user@host:~/sqltttest$ node user.sql.js --engine=_nocli getUserData > getUserData.sql