Dblink is not accepting the date format of postgressql - postgresql

I am extracting the data from other databases by using dblink but when i put the date condition it is showing below error
ERROR: syntax error at or near "2019"
LINE 5: where date(l.create_date)='2019-01-01'')
^
SQL state: 42601
Character: 562
select cus.* into cus_details from dblink('dbname=dbname user=admin password=admin123',
'select l.id,l.create_date,l.write_date,b.campaign
from rb_lead l
left join rb_campaign b on l.team=b.id
where date(l.create_date)='2019-01-01'')
as cus (id integer,create_date timestamp without time zone,write_date timestamp without time zone,campaign integer)

There are quotes inside your quoted string.
select cus.* into cus_details
from dblink(
'dbname=dbname user=admin password=admin123',
'select ... where date(l.create_date)='2019-01-01''
)
^
You'll need to escape the quotes around 2019-01-01 by doubling them.
select cus.* into cus_details
from dblink(
'dbname=dbname user=admin password=admin123',
'select ... where date(l.create_date)=''2019-01-01'''
)

Related

How to Perform Insert Operation with DbLink in Postgres

I am tying to perform insert with dblink in postgres but it is throwing error
column "Test" does not exist
Select *
from dblink('host=localhost user=postgres password=Test dbname=wb',
'Insert Into tblProducts(AccountNumber,AccountProductNumber,supplierproductnumber)
Values( 2012, 2022,'Test') Returning ProductNumber'
) AS tblProducts(ProductNumber integer)
You have to escape the quotes within the payload, using an additional quote '' (two single quotes):
Select *
from dblink('host=localhost user=postgres password=Test dbname=wb',
'Insert Into tblProducts(AccountNumber,AccountProductNumber,supplierproductnumber)
Values( 2012, 2022,''Test'') Returning ProductNumber'
) AS tblProducts(ProductNumber integer);

How to use unnest argument in "EXECUTE format()" in plpgsql?

Im trying to send an array inside a "unnest" but using it in an a "EXECUTE format()" , how can i do that?
Table
CREATE TABLE IF NOT EXISTS table_xvx(
row_id SERIAL NOT NULL PRIMARY KEY,
open FLOAT(36),
high FLOAT(36),
low FLOAT(36),
close FLOAT(36),
volume FLOAT(36),
capital FLOAT(36),
transactions FLOAT(36)
)
Type
CREATE TYPE type_ohlcvct AS(
type_open float,
type_high float,
type_low float,
type_close float,
type_volume float,
type_capital float,
type_transactions float
);
Function
CREATE OR REPLACE FUNCTION insert_data_ohlcvct(table_name_ varchar(70) , data_list type_ohlcvct[])
RETURNS VOID AS
$$
DECLARE
error_message varchar;
BEGIN
EXECUTE format(
'INSERT INTO %I(open,high,low,close,volume,capital,transactions)
SELECT * FROM unnest(%s)',table_name_ , data_list);
END;
$$ LANGUAGE plpgsql;
Ways to call
SELECT insert_data_ohlcvct('table_xvx' ,'{"(10,10,10,10,10,10,10)","(10,10,10,10,10,10,10)"}'::type_ohlcvct[]);
SELECT insert_data_ohlcvct('table_xvx' , (ARRAY['(10,10,10,10,10,10,10)','(10,10,10,10,10,10,10)'])::type_ohlcvct[]);
SELECT insert_data_ohlcvct('table_xvx' , ARRAY['(10,10,10,10,10,10,10)'::type_ohlcvct,'(10,10,10,10,10,10,10)']);
The error is always the same
ERROR: syntax error at or near "{"
LINE 2: SELECT * FROM unnest({"(10,10,10,10,10,10,10)","(10,10,10,...
^
QUERY: INSERT INTO table_xvx(open,high,low,close,volume,capital,transactions)
SELECT * FROM unnest({"(10,10,10,10,10,10,10)","(10,10,10,10,10,10,10)"})
CONTEXT: PL/pgSQL function insert_data_ohlcvct(character varying,type_ohlcvct[]) line 5 at EXECUTE
SQL state: 42601
Don't pass parameters to dynamic SQL as strings - pass them as parameters:
EXECUTE format(
'INSERT INTO %I(open,high,low,close,volume,capital,transactions)
SELECT * FROM unnest($1)',table_name_)
USING data_list; --<< passes the value to the $1 placeholder

psql passing parameter to sql script

psql version 9.2, server version 12.0.
Trying to pass parameter to sql script ,
Executing the script and passing parameter :
psql --echo-queries -v ON_ERROR_STOP=0 -v TEST=100 postgresql://${curr_connection}<< EOF 1 > ${log_file} 2>&1
\timing
\i sql_script.sql
EOF
Please note I confirm script is working with no issue when using hardcoded value(without the parameter) ,
I guess it may relate that the parameter inside a quote or somthing,
sql_script.sql
INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT
where ACT_HI_COMMENT.TASK_ID_ in (Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK
where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :TEST )')
AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,
user_id_ character varying);
Getting error:
psql:/infadmin/inf/sql_script.sql:2: ERROR: syntax error at or near ":"
CONTEXT: while executing query on unnamed dblink connection
I tried also a single quotes around it as :'TEST'
INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT
where ACT_HI_COMMENT.TASK_ID_ in
(Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK
where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :'TEST' )')
AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,user_id_ character varying);
Getting error:
psql:/infadmin/inf/sql_script.sql:2: ERROR: syntax error at or near "TEST"
LINE 2: ... where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :'TEST' ..
As suspect , it didnt worked as the parameter is inside the single quotes,
I solved it by spliting the whole string inside the quotes into 2 ,
by
' first_part '|| :'TEST'||' <second_part>'
So sql looks like
INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT
where ACT_HI_COMMENT.TASK_ID_ in
(Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK
where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = '|| :'TEST'||' )')
AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,user_id_ character varying);
``

Why I can not use IF in here?

I am trying to remove and drop a table if the the table has no data or empty, so I wrote this Statement in PostgreSQL, but I am encountering an error saying syntax error near IF.
I can divide this to 2 different SQL statements, but I want to run this as one query.
IF (SELECT COUNT(*) FROM ${tableName}) > 0
BEGIN
DROP TABLE ${tableName}
END
I also tried this:
IF (SELECT COUNT(*) FROM zzz > 0) THEN
DROP TABLE zzz
END IF
ERROR: syntax error at or near "SELECT"
LINE 2: SELECT COUNT(*) FROM zzz > 0
^
SQL state: 42601
Character: 7
If you want to do this with SQL, you'll have to use a DO statement:
DO
$$BEGIN
IF (SELECT Count(*) FROM zzz) > 0 THEN
DROP TABLE zzz;
END IF;
END;$$;

function crosstab(unknown, unknown) does not exist but it does

I have a crosstab function that I've used successfully many times in the past, but now it's dumping all the data at the end instead of pivoting it into the output table. It can't seem to find Crosstab. I've researched it doing the following;
create extension if not exists tablefunc; --- answer is: extension "tablefunc" already exists
create extension tablefunc with schema animals; answer is: as above
select count(*) from information_schema.routines where routine_name like 'crosstab%'; ---- answer is 6.
The following is a section of the function code:
BEGIN
str := '" " text,'; -- blanks in A1 cell
FOR rec IN SELECT DISTINCT col_name
FROM an_in_tbl
ORDER BY col_name
LOOP
str := str || '"' || rec.col_name || '" text' ||',';
END LOOP;
str:= substring(str, 0, length(str));
EXECUTE 'CREATE EXTENSION IF NOT EXISTS tablefunc;
DROP TABLE IF EXISTS an_out_tbl;
CREATE TABLE an_out_tbl AS
SELECT *
FROM crosstab(''select row_name, col_name, row_value from an_in_tbl order by 1'',
''SELECT DISTINCT col_name FROM an_in_tbl ORDER BY 1'')
AS final_result ('|| str ||')';
select animal_pivot_fn()
NOTICE: extension "tablefunc" already exists, skipping
NOTICE: table "an_out_tbl" does not exist, skipping
ERROR: function crosstab(unknown, unknown) does not exist
LINE 5: FROM crosstab('select row_name, col_name, row_value from...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
QUERY: CREATE EXTENSION IF NOT EXISTS tablefunc;
DROP TABLE IF EXISTS an_out_tbl;
CREATE TABLE an_out_tbl AS
SELECT *
FROM crosstab('select row_name, col_name, row_value from an_in_tbl order by 1',
'SELECT DISTINCT col_name FROM an_in_tbl ORDER BY 1')
AS final_result (" " text,"CAT" text,"DOG" text,"SNAKE" text,"HORSE" text,"ELEPHANT" text,"MOUSE" text,"MONKEY"... and many more... HERE IS WHERE THE DATA GETS DUMPED AND NO PIVOTED TABLE GETS CREATED.
Need to run below query
Run \dx command .
if result like below need to run following query
CREATE EXTENSION tablefunc;
Run \dx command again,result should be like below.
Now you can run crosstab query it should be solved.