Redshift の UNLOAD でエスケープなしでクエリを書く
書式
unload ($$ ここにクエリを書く $$) to 's3://redshitf-unload/audit_log_' iam_role 'arn:aws:iam::123456789012:role/redshift-spectrum-s3-fullaccess' header format csv gzip parallel off allowoverwrite;
例
unload ($$ /* returned_rows */ select max(d.starttime) as starttime ,max(d.endtime) as endtime ,'Redshift' as servie_type ,max(d.database) as database ,max(d.userid) as userid ,d.query ,max(d.sql) as sql ,max(d.rows) as rows ,max(d.pid) as pid ,max(g.remotehost) as remotehost ,max(g.username) as username from (select c.starttime ,c.endtime ,'Redshift' servie_type ,c.database ,a.userid ,a.query ,a.substring sql ,b.rows ,c.pid from svl_qlog a join stl_return b on a.query=b.query join stl_query c on c.query = a.query where b.slice >= 6411 and a.userid != 1 and c.starttime between '2020-08-08 00:00' and '2020-08-08 23:59' and sql not like '/* returned_rows */%' union all select c.starttime ,c.endtime ,'Redshift' servie_type ,c.database ,a.userid ,a.query ,a.substring sql ,b.rows ,c.pid from svl_qlog a join stl_return b on a.source_query=b.query join stl_query c on c.query = a.query where sql not like '/* returned_rows */%' and c.starttime between '2020-08-08 00:00' and '2020-08-08 23:59') d left outer join (select e.pid, e.remotehost, e.username, f.usesysid, e.recordtime from stl_connection_log e join SVL_USER_INFO f on e.username = f.usename where e.event = 'authenticated' ) g on d.pid = g.pid and d.userid = g.usesysid and d.starttime > g.recordtime group by query $$) to 's3://redshift-unload/audit_log_' iam_role 'arn:aws:iam::123456789012:role/redshift-spectrum-s3-fullaccess' header format csv gzip parallel off allowoverwrite;
参考
4.1.2.4. ドル記号で引用符付けされた文字列定数
4.1. 字句の構造
文字列定数の標準の構文はたいていの場合便利ですが、対象とする文字列内に多くの単一引用符やバックスラッシュがあると、それらを全て二重にしなければなりませんので理解しづらくなります。 こうした状況においても問い合わせの可読性をより高めるためにPostgreSQLは、「ドル引用符付け」という他の文字列定数の指定方法を提供します。 ドル引用符付けされた文字列定数は、ドル記号($)、省略可能な0個以上の文字からなる「タグ」、ドル記号、文字列定数を構成する任意の文字の並び、ドル記号、この引用符付けの始めに指定したものと同じタグ、ドル記号から構成されます。 例えば、「Dianne's horse」という文字列をドル引用符付けを使用して指定する方法を、以下に2つ示します。