Postgres command line statement: INSERT complains about non-existing column
I have the following script, which connects through ssh to a remote server and issues an SQL statement on it's Postgresql database:
#!/bin/bash
db_query() {
app_server="$1"
sql_stmt="$2"
psql_cmd="psql -d vdc --pset tuples_only -c '$sql_stmt'"
rows_count=`ssh $app_server "sudo su - postgres -c \"$psql_cmd\""`
echo "DB_QUERY: rows_count = $rows_count"
}
Now I'm trying to issue SELECT and INSERT statements to the following table:
CREATE TABLE pb_properties
(
c_name character varying(255) NOT NULL,
c_value character varying(255),
CONSTRAINT pb_properties_pkey PRIMARY KEY (c_name)
)
This function works fine if I do a SELECT statement:
#!/bin/bash
source db_query.sh
db_query staging "SELECT * FROM pb_properties;"
>> Output: DB_QUERY: rows_count = support-email | test@test.com
But it does not work if I do an INSERT statement:
#!/bin/bash
source db_query.sh
db_query prestaging "INSERT INTO pb_properties (c_name, c_value) VALUES ('support-email', 'test@test.com');"
>> Output:
>>ERROR: column "testname" does not exist
>>LINE 1: ...SERT INTO pb_properties (c_name, c_value) VALUES (testname, ...
^
>>DB_QUERY: rows_count =
Now how can I do a successful INSERT statement开发者_如何学运维 with my db_query function? I already tried masking the values I tried to insert in many several ways, but none of them worked. I guess it has something to do with the combination of running the sql command through SSH and the different quotes i'm using `, " and '.
Here is a code sample you can use that removes the reliance of a tmp file:
echo "$sql_stmt" | ssh $app_server "sudo su - postgres -c '/usr/local/pgsql/bin/psql -A -t -U postgres $database'"
Ok, since I cannot get the SQL statement with single quotes working at all with the db_query method in my question, I'm doing a workaround. On the remote Server, I'm redirecting the SQL statement into a temporary file. Then I can let psql read that file, then I don't have to care about quotes anymore.
This is my new db_query function:
tmpfile=/tmp/pgquery
db_query() {
app_server="$1"
sql_stmt="$2"
ssh $app_server "echo \"$sql_stmt\" > $tmpfile"
psql_cmd="psql -d vdc --pset tuples_only -f $tmpfile"
rows_count=`ssh $app_server "sudo su - postgres -c \"${psql_cmd}\""`
echo "DB_QUERY: rows_count = $rows_count"
}
This now works with my initial statement:
db_query prestaging "INSERT INTO pb_properties (c_name, c_value) VALUES ('testname', 'testvalue');"
Anyway, if anybody has an hint how to get it working without a temporary file, I'd be glad to hear it.
精彩评论