Skip to content

Instantly share code, notes, and snippets.

@mpeteuil
Last active October 1, 2019 17:10
Show Gist options
  • Save mpeteuil/40247f4991e137c290d00499b488fe06 to your computer and use it in GitHub Desktop.
Save mpeteuil/40247f4991e137c290d00499b488fe06 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from airflow.hooks.postgres_hook import PostgresHook
from airflow.hooks.S3_hook import S3Hook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class RedshiftToS3QueryTransfer(BaseOperator):
"""
Executes an UNLOAD command to s3 as a CSV with headers
:param schema: reference to a specific schema in redshift database
:type schema: string
:param table: reference to a specific table in redshift database
:type table: string
:param s3_bucket: reference to a specific S3 bucket
:type s3_bucket: string
:param s3_key: reference to a specific S3 key
:type s3_key: string
:param redshift_conn_id: reference to a specific redshift database
:type redshift_conn_id: string
:param s3_conn_id: reference to a specific S3 connection
:type s3_conn_id: string
:param options: reference to a list of UNLOAD options
:type options: list
"""
template_fields = ('s3_key', 'query',)
template_ext = ()
ui_color = '#ededed'
@apply_defaults
def __init__(
self,
s3_key,
s3_bucket=None,
query=None,
schema=None,
table=None,
redshift_conn_id='redshift_default',
s3_conn_id='s3_default',
unload_options=tuple(),
autocommit=False,
parameters=None,
*args, **kwargs):
super(RedshiftToS3QueryTransfer, self).__init__(*args, **kwargs)
self.query = query
self.schema = schema
self.table = table
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.redshift_conn_id = redshift_conn_id
self.s3_conn_id = s3_conn_id
self.unload_options = unload_options
self.autocommit = autocommit
self.parameters = parameters
def execute(self, context):
self.hook = PostgresHook(postgres_conn_id=self.redshift_conn_id)
self.s3 = S3Hook(s3_conn_id=self.s3_conn_id)
a_key, s_key = self.s3.get_credentials()
s3_bucket = self.s3_bucket if self.s3_bucket else self.s3.extra_params['bucket']
unload_options = ('\n\t\t\t').join(self.unload_options)
if self.query is None and self.schema and self.table:
logging.info("Retrieving headers from %s.%s..." % (self.schema, self.table))
columns_query = """SELECT column_name
FROM information_schema.columns
WHERE table_schema = '{0}'
AND table_name = '{1}'
ORDER BY ordinal_position
""".format(self.schema, self.table)
cursor = self.hook.get_conn().cursor()
cursor.execute(columns_query)
rows = cursor.fetchall()
columns = map(lambda row: row[0], rows)
column_names = (', ').join(map(lambda c: "\\'{0}\\'".format(c), columns))
column_castings = (', ').join(map(lambda c: "CAST({0} AS text) AS {0}".format(c),
columns))
unload_query = """
UNLOAD ('SELECT {0}
UNION ALL
SELECT {1} FROM {2}.{3}')
TO 's3://{4}/{5}/{3}_'
with
credentials 'aws_access_key_id={6};aws_secret_access_key={7}'
{8};
""".format(column_names, column_castings, self.schema, self.table,
s3_bucket, self.s3_key, a_key, s_key, unload_options)
else:
unload_query = """
UNLOAD ('{query}')
TO 's3://{s3_bucket}/{s3_key}'
with
credentials 'aws_access_key_id={access_key};aws_secret_access_key={secret_key}'
{unload_options};
""".format(
query=self.query.replace("'",r'\''),
s3_bucket=s3_bucket,
s3_key=self.s3_key,
access_key=a_key,
secret_key=s_key,
unload_options=unload_options
)
logging.info('Executing UNLOAD command...')
self.hook.run(unload_query, self.autocommit)
logging.info("UNLOAD command complete...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment