Vzzarr
Vzzarr

Reputation: 5660

Pre-define Redshift table with Keys [Glue]

I want to define manually the Redshift table before of my first write. This is because I want to leverage of distkey and sortkey on defined columns. The SQL query is going to be something like that:

my_sql_command = """
    create table if not exists my_db.my_schema.my_table(
        my_id                     VARCHAR(MAX) NOT NULL DISTKEY,
        type                      VARCHAR(MAX),
        my_timestamp  TIMESTAMP,
    )
    compound sortkey(my_timestamp, my_id);
    """

I'm calling this SQL string as a preactions parameter (mentioned here, could't find any better documentation unfortunately) like this:

my_frame = DynamicFrame.fromDF(my_df, glue_context, "my_frame")

glue_context.write_dynamic_frame.from_jdbc_conf(
        frame=my_frame, catalog_connection=params['db_connection_name'],
        connection_options={"preactions": my_sql_command, "dbtable": "my_schema.my_table", "database": "my_db"},
        redshift_tmp_dir="s3://my_bucket/", transformation_ctx="my_ctx")

But I am getting this error message:

py4j.protocol.Py4JJavaError: An error occurred while calling o227.pyWriteDynamicFrame.
: java.sql.SQLException: [JDBC Driver]String index out of range: 0
at java.lang.String.charAt(String.java:658)

which I really don't know how to interpret.

What's causing this exception?

Upvotes: 1

Views: 712

Answers (1)

Vzzarr
Vzzarr

Reputation: 5660

The reason of the exception is because internally Glue doesn't parse correctly new lines. So rewriting the SQL command as

my_sql_command = "create table if not exists my_db.my_schema.my_table("\
        "my_id         VARCHAR(MAX) NOT NULL DISTKEY, "\
        "type          VARCHAR(MAX), "\
        "my_timestamp  TIMESTAMP) "\
    "compound sortkey(my_timestamp, my_id);"\

resolved the exception that I was getting.

Furthermore analysing the logs, it looks like that the Glue preaction is executed after the Glue auto-generated CREATE TABLE IF NOT EXISTS:

19/11/11 11:11:11 INFO RedshiftWriter: 
CREATE TABLE IF NOT EXISTS my_schema.my_table (my_id VARCHAR(MAX), my_timestamp TIMESTAMP, type VARCHAR(MAX)) DISTSTYLE EVEN
19/11/11 11:11:11 INFO RedshiftWriter: Executing preAction: 
create table if not exists my_schema.my_table(my_id VARCHAR(MAX) NOT NULL DISTKEY, my_timestamp TIMESTAMP, type VARCHAR(MAX)) sortkey(id)

So the approach that I used to sort this inconvenience is create a connection using psycopg2 and execute the SQL command through this library (here's explained how to import it in a Glue Job)

Upvotes: 2

Related Questions