|
2 | 2 | from sqlalchemy.engine import reflection |
3 | 3 | from sqlalchemy import util, exc |
4 | 4 | from sqlalchemy.types import VARCHAR, NullType |
| 5 | +from sqlalchemy.ext.compiler import compiles |
| 6 | +from sqlalchemy.sql.expression import Executable, ClauseElement |
| 7 | + |
5 | 8 |
|
6 | 9 | class RedshiftDialect(PGDialect_psycopg2): |
7 | 10 | @reflection.cache |
@@ -51,3 +54,36 @@ def _get_column_info(self, name, format_type, default, |
51 | 54 | if isinstance(column_info['type'], VARCHAR) and column_info['type'].length is None: |
52 | 55 | column_info['type'] = NullType() |
53 | 56 | return column_info |
| 57 | + |
| 58 | + |
| 59 | +class UnloadFromSelect(Executable, ClauseElement): |
| 60 | + ''' Prepares a RedShift unload statement to drop a query to Amazon S3 |
| 61 | + http://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD_command_examples.html |
| 62 | + ''' |
| 63 | + def __init__(self, select, bucket, access_key, secret_key): |
| 64 | + ''' Initializes an UnloadFromSelect instance |
| 65 | +
|
| 66 | + Args: |
| 67 | + self: An instance of UnloadFromSelect |
| 68 | + select: The select statement to be unloaded |
| 69 | + bucket: The Amazon S3 bucket where the result will be stored |
| 70 | + access_key: The Amazon Access Key ID |
| 71 | + secret_key: The Amazon Secret Access Key |
| 72 | + ''' |
| 73 | + self.select = select |
| 74 | + self.bucket = bucket |
| 75 | + self.access_key = access_key |
| 76 | + self.secret_key = secret_key |
| 77 | + |
| 78 | +@compiles(UnloadFromSelect) |
| 79 | +def visit_unload_from_select(element, compiler, **kw): |
| 80 | + ''' Returns the actual sql query for the UnloadFromSelect class |
| 81 | + ''' |
| 82 | + return "unload ('%(query)s') to '%(bucket)s' credentials 'aws_access_key_id=%(access_key)s;aws_secret_access_key=%(secret_key)s'" % { |
| 83 | + 'query': element.select, |
| 84 | + 'bucket': element.bucket, |
| 85 | + 'access_key': element.access_key, |
| 86 | + 'secret_key': element.secret_key, |
| 87 | + } |
| 88 | + |
| 89 | + |
0 commit comments