PostgreSQL unterminated quoted identifier - postgresql

I have this groovy code which drops a remote postgres schema from commandline:
def dropSchema = "psql --dbname=postgres://$user:$pass#localhost:$port/$targetDb -c \"DROP SCHEMA ${applicationName}_${uid} CASCADE;\"".execute()
This code is working fine when it's run on a windows machine, but when it's on a Linux distribution, it gives me these errors:
psql: warning: extra command-line argument "appName_uid" ignored
psql: warning: extra command-line argument "CASCADE;"" ignored
ERROR: unterminated quoted identifier at or near ""DROP"
LINE 1: "DROP
^
Does anyone know how to fix this ?
Thanks.

Never ever use a string with .execute() like "ls 'my fancy file'".execute(). It splits on whitespace and that is most likely never what you want (same as ["ls", "'my", "fancy", "file'"].execute() for that example).
Also .execute() runs the command via the regular exec of your OS -- not the shell. So quoting or other things, that needs to be done for a shell command actually make things worse - since no shell is involved to interpret your intention.
Instead use an array, where all params are their own (don't quote for a shell, that is never used)
[
"psql",
"--dbname=postgres://$user:$pass#localhost:$port/$targetDb",
"-c", "DROP SCHEMA ${applicationName}_${uid} CASCADE;"
].execute()
If you prefer to reuse an existing shell command, then run it with a shell:
["/bin/sh", "-c", "psql ... -c \"DROP ...\" ..."].execute()
Here you have to quote for the shell, as it is executed like a shell command.

Related

Use variables with --eval in mongodb

I am trying to use the dynamic database name in the below bash script, but it fails with an error saying invalid escape sequence.
#!/bin/bash
...
...
db_name=test
db_existence=$(mongo mongodb+srv://$db_credentials$mongoatlas_host --eval 'db.getMongo().getDBNames().indexOf(\"$db_name\")' --quiet)
I also tried using double quotes with --eval and single quotes for DB name as in the below script, but still, it gives the same invalid escape sequence error.
db_existence=$(mongo mongodb+srv://$db_credentials$mongoatlas_host --eval "db.getMongo().getDBNames().indexOf(\'$db_name\')" --quiet)
It uses the variable name as it is if I don't use \ escape character with db_name.
I can't hardcode the DB name as my database name is coming from another command.
I think that I might be missing something very fundamental in terms of bash scripting.
Please help.
Use one of those:
--eval "db.getMongo().getDBNames().indexOf('$db_name')"
--eval 'db.getMongo().getDBNames().indexOf("'$db_name'")'
--eval "db.getMongo().getDBNames().indexOf(\"$db_name\")"

What does "\unset ON_ERROR_STOP" command do in postgreSQL

I am having this line under psql block.what does it really do?
psql -d ${DBNAME} -h ${HOST} -p ${PORT} -U ${SCHEMA} <
ON_ERROR_STOP
By default, command processing continues after an error. When this variable is set to on, processing will instead stop immediately. In interactive mode, psql will return to the command prompt; otherwise, psql will exit, returning error code 3 to distinguish this case from fatal error conditions, which are reported using error code 1. In either case, any currently running scripts (the top-level script, if any, and any other scripts which it may have in invoked) will be terminated immediately. If the top-level command string contained multiple SQL commands, processing will stop with the current command.
You have to do your research https://www.postgresql.org/docs/9.2/app-psql.html

PostgreSQL encoding issue while executing query from command line

I am trying to execute an SQL query which is stored in the file. I am using following command to execute:
psql -d DB_NAME -a -f QUERY_NAME.sql
I have some non English text in the SQL file like - સુરત
When the query is executed the text in the database looks like - à ª¸à «Âà ª°à ª¤
How do I execute the query from command line so that it runs correctly?
Make sure the client_encoding matches the encoding of your file. Check your system locale. Then use a matching command line argument for psql. Quoting the manual here:
If at least one of standard input or standard output are a terminal,
then psql sets the client encoding to "auto", which will detect the
appropriate client encoding from the locale settings (LC_CTYPE
environment variable on Unix systems). If this doesn't work out as
expected, the client encoding can be overridden using the environment
variable PGCLIENTENCODING.
Example for a Linux shell:
env PGCLIENTENCODING='WIN1258' psql DB_NAME -a -f QUERY_NAME.sql
List of available encodings in the manual.

call postgresql pg_dump.exe from visual basic

Im trying to do a backup of my database from my application made in visual basic (visual studio 2012)
I copy the pg_dump.exe with the necessary dll files to the application root.
Test the pg_dump doing a backup from cmd window and goes ok
This is the code i use to try to call the pg_dump exe but apparently does not receive the parameters i'm trying to send.
' New ProcessStartInfo created
Dim p As New ProcessStartInfo
Dim args As String = "-h serverip -p 5432 -U postgres db_name > " & txtPath.Text.ToString
' Specify the location of the binary
p.FileName = "pg_dump.exe"
' Use these arguments for the process
p.Arguments = args
' Use a hidden window
p.WindowStyle = ProcessWindowStyle.Maximized
' Start the process
Process.Start(p)
When the process start i get this msg:
pd_dump: too many command-line arguments (first is ">")
Try "pg_dump --help" for more information
if i type this in cmd the backup is done ok
pg_dump.exe -h serverip -p 5432 -U postgres db_name > c:\db_bak.backup
But i cant make it work from visual.
First, your command is just plain wrong. You're invoking pg_dump, which wants to read from a file, so you don't want to use >. That'd write to the file and overwrite it in the process. Instead you'd want <, the "read file as standard input" operator.
That's not the immediate cause of your error though. pg_dump doesn't understand >, <, etc. These operations instruct the shell (cmd.exe) to do I/O redirection. If you're not running cmd.exe then they don't work. To get I/O redirection (>, etc) you need to run the process via the cmd shell, not invoke it directly.
In this case it's probably better to use the -f filename option to pg_dump to tell it to write to a file instead of standard output. That way you avoid I/O redirection and don't need the shell anymore. It should be as simple as:
Dim args As String = "-h serverip -p 5432 -U postgres db_name -f " & txtPath.Text.ToString
Alternately, you can use cmd /C to invoke pg_dump via the command shell. Visual Basic might offer a shortcut way to do that; I don't use it, so I can't comment specifically on the mechanics of process invocation in Visual Basic. Check the CreateProcess docs; VB likely uses CreateProcess under the hood.
Personally I recommend that you do

How to use slash commands outside the database?

I tried to use the query outside of the database. That is, without login to data base
I want to get the result. I found the option (-c). Using that option we can execute the query from outside the data base:
test:~$ psql -U sat -c "select * from test.details";
It gives the output. I want to use that query for a crontab entry. So I have tried to store the output in a file:
test:~$ psql -U sat -c "select * from test.details \g sat";
Produced an error:
ERROR: syntax error at or near "\"
LINE 1: select * from test.details \g sat
How to do that?
This is not a slash, but a backslash .
Backslash is an escape character in PostgreSQL string literals, therefore you have to double it to get a single backslash into the actual data.
If you want to store the result of a query into a file from the command line you have to use the -o command line option,so your query will become :
psql -o filename -U sathishkumar -c "select * from hospital_management.patient_details";
There is no such thing as a "query outside of the data base" or "without login to data base".
You are trying to mix meta-commands of the psql client with SQL commands, which is strictly impossible. The backslash meta commands are interpreted by the psql client, SQL queries are interpreted by the database server.
Most meta-commands in psql are actually translated into (a series of) SQL queries to the database server. You can make psql print the commands it sends to the database engine if you start it up with the command option -E in interactive mode. Try:
psql -E mydb
And then execute any backslash command and observe the output. For the rest of your question #aleroot has already given good advice.