Error using select statement in psql command - postgresql

I try to perform follow command
psql -c '\\COPY (SELECT file_name, status, reported, operator_id, load_dt AT TIME ZONE GMT FROM mytable) TO STDOUT' > myfile
I receive an error
ERROR: column "gmt" does not exist
LINE 1: ...atus, reported, operator_id, load_dt AT TIME ZONE GMT FROM p...

Can this be of help for you? This is on windows machine. Consider that query command might need modification, depending of what your PC operating system is.
psql -U postgres -d aambackend_dev -c "SELECT \"createdAt\"::timestamp without time zone FROM \"User\" limit(2)" -H -o "D:\xxx1.html"
-U postgres - user
-d typeorm - my database to which i want to connect
-c ... - my query command
-H format html, -o output file
For more info you can refer to: https://www.postgresql.org/docs/13/app-psql.html
Note 1: depending of column i want to select, for majority of columns i don't need escape backslash character. Only for columns of type timestamp with/out time zone i needed to add backslash for quotes.
Note 2: semicolon at the end was not needed in this case (in some other commands and cases it is necessary)
This is my exported file:
If you wish CSV format:
psql -U postgres -d aambackend_dev -c "SELECT "email",\"createdAt\"::timestamp without time zone FROM \"User\" limit(2)" -o "D:\xx2212.csv"

Related

Update a PostgreSQL field from the content of a file

I have a file containing a value which should go into a field of a PostgreSQL table.
By searching a little, I found many answers, e.g. How can I update column values with the content of a file without interpreting it? or https://stackoverflow.com/a/14123513/6630397, with this kind of snippet, but it has to be run in a psql terminal:
\set content `cat /home/username/file.txt`
UPDATE table SET field = :'content' WHERE id=1;
It works, but is it possible to programmatically execute it in one shot, directly from a bash prompt, without manually entering the psql command line, e.g. something like:
$ psql -d postgres://postgres#localhost/mydatabase -c \
"UPDATE table SET field = :'the_file_content' WHERE id=1;"
?
There is also the -v argument that seems promising but I'm not successful when using it:
$ psql -d postgres://postgres#localhost/mydatabase \
-v content=`cat ${HOME}/file.txt` \
-c "UPDATE table SET field = :'content' WHERE id=1;"
I've got thousands of psql: warning: extra command-line argument where psql actually seems to "execute" each comma separated strings of the file as pg commands, where it shouldn't of course; the file content, which consists of a single line, must be treated as a whole.
Doc PostgreSQL 14:
https://www.postgresql.org/docs/current/app-psql.html
How about reading the file content into a variable first and then use it?
content=$(<integer_infile); psql -p 5434 -c "update table set field = $content where id = 1;"
content=$(<text_infile); psql -p 5434 -c "update table set field = '$content' where id = 1;"
This at least works for me if the file contains an integer or text including spaces on a single line.

Syntax error in "psql" , command not get executed

I am using timescaledb.
The doumentation I am following is Using PostgreSQL's COPY to migrate data from a csv file to timescale db. The name of csv file is test.csv.
I created the db named test , the name of table is test1. Table is a hypertable as per the timescaledb documentation.
The table's structure and csv files structure are the same.
While executing the following command in cmd I am not getting a result other than an addition of - symbol in the console command test-#
psql -d test -c "\COPY test1 FROM C:\Users\DEGEJOS\Downloads\test.csv CSV"
If I put ; after the command
psql -d test -c "\COPY test1 FROM C:\Users\DEGEJOS\Downloads\test.csv CSV"; I am getting a syntax error at Line 1.
How can I solve this error and insert data from csv file to db.?
You are trying to run psql with \COPY inside psql session, thus you get an error in the second call, since psql keyword does not exist in SQL. psql is an executable.
To follow the instructions from Timescale, you need to call the command directly in CMD. I.e, call:
psql -d test -c "\COPY test1 FROM C:\Users\DEGEJOS\Downloads\test.csv CSV"
If you are in C:\Users\DEGEJOS as in your screenshoot, it will look like:
C:\Users\DEGEJOS\psql -d test -c "\COPY test1 FROM C:\Users\DEGEJOS\Downloads\test.csv CSV"

migrating from Postgres to MonetDB

I need to know how to migrate from Postgres to MonetDB. Postgres is getting slow and we are trying to change to Monet. Someone now if already exists a script or another thing to migrate to Monet?
exist something equivalent to plpgsql on MonetDB?
exist materialized view on MonetDB?
The following booklet may be relevant to quickly identify some syntactic feature differences. https://en.wikibooks.org/wiki/SQL_Dialects_Reference
And the citrus performance is covered in a blogpost
https://www.monetdb.org/content/citusdb-postgresql-column-store-vs-monetdb-tpc-h-shootout
firstly: You can export data from postgres like:
psql -h xxxxx -U xx -p xx -d postgres -c "copy (select * from db40.xxx) to '/tmp/xxx.csv' delimiter ';'"
secondly: You must replace the NULL like:
sed 's/\\N/NULL/g' xxx.csv >newxxx.csv
last: You can use this to copy data into monetdb like:
mclient -u monetdb -d voc -h 192.168.205.8 -p 50000 -s "COPY INTO newxxx from '/tmp/newxxx.csv' using delimiters ';';"

error syntax ( execute psql query from shell script )

i got this query want to to be executed remotely on my 2nd server and
#!/bin/bash
QUERY=`psql -h my2ndserverip -d testdb -U testuser 'select count(*) as result
from testdb.user where last_logged_date > (clock_timestamp() -interval '90 minutes)
echo "users = $QUERY" > tmp.txt
any tips to fix syntax ?
Use a here document (heredocuments preserve quotes AND allow shell-variable subtitution, as illustrated by the parameter 90 which is used inside single quotes):
#!/bin/bash
limit=${1:-90}
psql -h my2ndserverip -d testdb -U testuser -t -A <<EOFEOF > tmp.txt
SELECT count(*) AS result
FROM "user"
WHERE last_logged_date > clock_timestamp()-interval '${limit} minutes'
;
EOFEOF
exitcode=$?
result=`cat tmp.txt`
echo "Limit=${limit} Exitcode=${exitcode} Result=${result}"
#Eof
I suppose you want psql to omit the column headers etc, so I added the -t -A flags to the psql commandline.
BTW I changed from testdb.user, to FROM user, I don't think you have a schema named 'testdb'.
there are more than one issue
instead quotes in SQL query, you can use $$
postgres=# select interval $$90 min$$;
interval
──────────
01:30:00
(1 row)

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.