How to customise the PostgreSQL/psql prompt? - postgresql

How can I customize the prompt in the PostgreSQL command line tool psql (ideally in a per-user start-up script)?
In particular, I'd like to be able to change it while still including the character that indicates whether the command is multi-line (eg. =, -, ', etc.).
I'm running Ubuntu 10.04 (Lucid), PostgreSQL 8.4.4.

You can certainly customize the prompt.
From the documentation:
The prompts psql issues can be
customized to your preference. The
three variables PROMPT1, PROMPT2, and
PROMPT3 contain strings and special
escape sequences that describe the
appearance of the prompt. Prompt 1 is
the normal prompt that is issued when
psql requests a new command. Prompt 2
is issued when more input is expected
during command input because the
command was not terminated with a
semicolon or a quote was not closed.
Prompt 3 is issued when you run an SQL COPY command and you are expected to
type in the row values on the
terminal.
If you want to set the prompt on a per user basis, you can add the \set commands to the user's .psqlrc file.
So, your $HOME/.psqlrc would be something like this:
\set PROMPT1 '(%n#%M:%>) %`date +%H:%M:%S` [%/] \n%x%# '

Related

Postgres: Run some hard-coded SQLs then drop to interactive terminal

When you start interactive bash, it runs .bashrc first and then it gives you an interactive prompt. Very handy to setup bash in the right way.
I'm trying to do the same with Postgres client (psql). I want to set some session configuration parameters before I run SQL statements interactively. Does psql let me do that?
The -c option and the -f option are the standard ways to run a pre-canned SQL statements, but the man page clearly states that those options are incompatible with the interactive mode.
The analogy to .bashrc extend to the name as well. You want .psqlrc

Difference between psql command and psql interactive terminal

I've tried various combinations of search terms and I can't find an answer to this...
I'm new to Postgres, and I'm enjoying using the psql interactive terminal to run SQL commands. But often when I look things up, I find people using psql as a command rather than as a terminal.
For instance, you can restore a database using this command:
psql database-name < path/to/backup.dmp
My question is, are they the same thing or different things? When I run psql as a standalone command, am I effectively running up an interactive terminal for just that one command? And if so, does that mean that anything which goes after psql will also work as a command typed into the psql terminal? So in the example above, I could also just start up a psql terminal and then run the following command?
postgres=# database-name < path/to/backup.dmp
This is actually basic bash stuff. You should read up on Unix shells to understand that better.
Each process has a standard input, a standard output and a standard error.
By default, the interactive terminal where you started a program will be used for these, so the text you type will be the input of the program, and the output of the program will be shown on your screen.
Bot you can also redirect standard input with
command < file
Then the input for the program will be taken from file rather than from the interactive terminal.
That's one of the ideas in Unix: the user is just another file from which you can read and to which you can write.
So everything before the < is part of the command invocation, and everything after the < is the file to read.
If you want to read and execute an SQL script while in a psql interactive session, use
\i file.sql

Execute many db2 commands in one command

can I run multiple db2 commands in one command?
i.e: from cmd:
db2cmd /c db2 /c connect to sample user sample_user using sample_pwd /c
"SELECT * FROM table;"
I also tried the following:
db2 connect to sample user db2admin using pwd; EXPORT TO result.csv OF DEL
MODIFIED BY NOCHARDEL SELECT * FROM alarms;
but didn't work with the following error:
SQL0104N An unexpected token "EXPORT" was found following
"". Expected tokens may include: "NEW". SQLSTATE=42601
as an example, for VERTICA, vsql tool, this can be done this way:
vsql -h localhost -U user -w pwd -c "SELECT * FROM alarms" -A -o
"alarms.csv" -F "|" -P footer=off -q
You appear to be using Microsoft Windows db2cmd.exe .
Your question has nothing to do with Db2 per se, but it is instead more about CMD (cmd.exe) scripting syntax, a legacy scripting language for batch files by Microsoft that still works on Windows-10, and which also works in db2cmd.exe.
In a db2cmd.exe shell you can use the "&&" sequence between distinct Db2 commands (and each such command must have the db2 prefix). Additionally each such command line has to escape any of the characters that are special characters to the shell itself. By default the escape character is a caret (^) symbol.
For example db2 connect to dbname && db2 ^"export to alarms.csv of del ... select ^* from alarms^" && db2 connect reset
( I show the ^ before any " that you might want to pass to Db2-CLP ).
But that && will require that each command returns a zero exit code, which might not be what you want, although it is usually the safest option. If a previous command fails then subsequent commands will not run.
If you want to tolerate some non-zero exit codes, use bracketing ( ... ) to group commands, and then use the && or & outside the brackets depending on your requirements. You can read about CMD scripting in any good book, plenty of examples online.
However, when scripting for Db2 on Windows , it can be much wiser to append all of the commands (without the Db2 prefix) into a plain text file, and then ask the Db2 clp to execute the text file via the syntax db2 -tvf texfile. Doing it this way lets you add conditional logic inside the textfile, handle exceptions , avoid shell escaping requirements, etc. If you encapsulate all your logic inside a script, it makes it easier to test, and also easier to run from a single db2cmd /c .... command-line.
If you want to make a batch file (*.bat or *.cmd) that does not need the db2cmd prefix to be invoked, you can alter your batch file to have a few lines at the start of the batch file to re-execute itself via db2cmd.exe. This works better if your db2cmd.exe is already on the PATH environment variable, but if that is not the case then you can fully-qualify the absolute pathname to your db2cmd.exe inside the batch file. The lines to add at the start of the batch file are:
#rem re-execute via db2cmd if running from cmd.exe
#echo off
if "%DB2CLP%"=="" db2cmd /c /i /w "%0" %* & goto :EOF
db2 connect to sample user db2admin using pwd
if errorlevel 1 #echo "Failed to connect to database " && #goto :EOF
db2 "EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL SELECT * FROM alarms"
if errorlevel 3 #echo "Export from Db2 failed" && #goto :EOF
Additionally on Windows, you can use Powershell scripting to maniuplate Db2 databases, and you can also use Windows subsystem for unix to run Unix-style shell scripts in some configuration.
Your example's most direct comparison in Db2-land would be clpplus which lets you specify the database but you also have to provide login information (including a password or you can be prompted for it).
Within the db2cmd and db2 framework you have a couple options but most likely will want to use a script file.
One option: Set the registry variable DB2DBDFT to your default database. Personally, I dislike this option because it causes an implicit connection to a database that you may not have intended.
One option: Put your series of commands into a file and run that file. This is the more traditional way of running multiple commands. Commands can be terminated with a semi-colon and newline (it understands DOS and Unix differences here). You can use a different terminator by using -td # (for example). You would then invoke db2 -tf file.sql.
One option: A batch file. It's similar to above but you'd use the db2cmd environment to execute a batch that has the db2 commands in it. db2cmd gets you an appropriate environment for working with Db2. If you connect to a database in this environment you stay connected until you issue a CONNECT RESET, a TERMINATE, are forcibly disconnected, or your environment exits. So your batch file would simply have:
db2 connect to sample user db2admin using pwd
db2 "EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL SELECT * FROM alarms"
(note the quotes to keep the command line from substituting all the filenames in the current working directory where the * is)
Two options.
1-st:
db2cmd /i /w /c "db2 ^"connect to sample^" & db2 ^"values 1^" & db2 connect reset"
2-nd:
You may set the following Windows system environment variable DB2CLP to the value **$$** and run db2 commands from windows cmd directly afterwards like this:
db2 "connect to sample" & db2 "values 1" & db2 connect reset

Ending Postgres Query without leaving the command line - Get back to command line automatically

Whenever I run a Postgres query it appears that you have to completely quit out of the command line.
I have seen it done where you can press CTRL-C and you are taken back to the PSQL command line i.e., databasename=>. Additionally, if I am in the middle of viewing results and I press CTRL-C, how can I have Postgres send me back to databasename=>?
Bonus:
Is there a way to script is so if I type usedb databasename folllwed by psql, Postgres will know which database I am referring to and automatically connect me to it so I dont have to type \connect databasename ?
Once a postgres query has run and has returned its table of results in the 'psql' command line environment it should drop you back in to the same database that you ran the previous command from.
If you want to connect directly to a database from your terminal :
psql -d nameofdatabase
If you want to connect using a script you can access postgres by url :
postgres://username:password#localhost/nameofdatabase
where 'localhost' could be replaced by the ip of the database you are trying to connect to if its not on the same machine.
Instead of pressing Ctrl-C, press Ctrl-D. In Unix, Ctrl-D is the End-of-File (EOF) character. That is what will make psql quit---just like if you fed it a script on stdin and it got to the end. It works in many other REPLs too, like irb, rails console, python, R, bash, etc.
The reason Ctrl-C doesn't exit is so that you can use it to abort an individual command, e.g. a long-running query.
EDIT: Also, if you are viewing results and they are paged (they appear on a new screen and you can scroll up and down), you can get back to the psql prompt by typing q. That's because by default the pager used is just less. You can say man less to read more about it. Or experiment with it on any text file: less /etc/services.
Personally I find paging in psql annoying, so I turn it off by creating a file named ~/.psqlrc with this line:
\pset pager
(Also, sorry if you know this already: ~ is just an abbreviation for "my home directory". So ~/.psqlrc is the same as /home/whatever/.psqlrc.)
Bonus: If you want to connect to a specific database, you can say psql -d foo or even just psql foo.
just enter \q or q in the psql terminal

Permanently set DB2CLP environment variable

I have a problem with DB2CLP environment variable, on Windows 7 64, IBM_client64_V97 (to be connected with DB2).
Every time when i try to DB2 in Windows command prompt window, I receive this error:
DB21061E Command line environment not initialized.
and per this document using just this step:
2. at the prompt enter these commands:
db2cmd -i -w db2clpsetcp
echo %DB2CLP%
I fix that error, and "db2" command opens Command Line Processor for DB2 Client.
But it lasts only until windows CMD is open. As soon as I close it and reopen, I have to repeat process.
My question (being absolute novice to DB2) is:
How should I make that change permanent and
How this happened at the first place as I installed and setup everything according to the manual (including adding local user to DB2USERS and DB2ADMINS) groups?
When DB2 client is installed, it should have installed a functional window to the command line processor. Check here:
Start / All Programs / IBM DB2 / DB2copy1/ Command Line Processor
Note that DB2copy1 is the default location for the first db2 instance. The name may be different if user select the non-default name.
Shortcut to the CLP can be copied on the desktop.
Regarding the typing "DB2 ..some command..." in windows command prompt which causes described error explanation is as follows:
That's because the normal DOS (or Windows) prompt doesn't
automatically run the setup script that enables the DB2 commands.
When the setup runs, it puts the DB2 items first in the PATH variable.
That could conflict with other tools that also want to be first on the
search list.
If you've got both the DOS (Windows) and DB2 command line prompts on
your desktop, right click them and select Properties. You'll notice
that the system (DOS) prompt runs cmd.exe.
The DB2 prompt runs DB2CMD.exe from the DB2 libraries. The DB2 script
then runs DB2SETCP.BAT and finally DB2.EXE. (All of the DB2
executables should be in C:\Program Files\IBM\SQLLIB\BIN.)
So there are differences in the two prompts. For you purposes, try
running DB2SETCP.BAT from the normal DOS prompt. That may be
sufficient for your needs.
For my purposes I always have the DOS and DB2 prompts on my desktop
and just select the one that I need.