### AWS Credentials File Example Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Example content for the AWS credentials file (~/.aws/credentials) used for IAM authentication. ```bash # ~/.aws/credentials [default] aws_access_key_id="my_aws_access_key_id" aws_secret_access_key="my_aws_secret_access_key" aws_session_token="my_aws_session_token" ``` -------------------------------- ### Connect using JumpCloud SAML Browser Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb This example demonstrates connecting to Redshift using JumpCloud for authentication via the BrowserSamlCredentialsProvider. The login_url specific to your JumpCloud setup is required. ```python import redshift_connector conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', cluster_identifier='my-testing-cluster', credentials_provider='BrowserSamlCredentialsProvider', user='brooke@myjumpcloud.org', password='', login_url='https://sso.jumpcloud.com/saml2/plustwo_melody' ) ``` -------------------------------- ### Install Redshift Connector via Pip Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Use this command to install the redshift_connector package from PyPi. ```sh pip install redshift_connector ``` -------------------------------- ### Install Redshift Connector from Source Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Clone the repository and install the connector from source. This is useful for development or if you need the latest unreleased changes. ```sh $ git clone https://github.com/aws/amazon-redshift-python-driver.git $ cd redshift_connector $ pip install . ``` -------------------------------- ### Install Redshift Connector via Conda Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Use this command to install the redshift_connector package from the conda-forge channel. ```sh conda install -c conda-forge redshift_connector ``` -------------------------------- ### Connect to Redshift using Database Credentials Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Establishes a connection to an Amazon Redshift cluster using raw database credentials. It demonstrates the use of 'with' statements for automatic resource cleanup and includes examples for creating a table, inserting data, and querying it. ```python import redshift_connector # establish a connection to an Amazon Redshift cluster # here we use "with" statements to ensure connection # and cursor resources are cleaned up once we are finished # with them with redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' # port value of 5439 is specified by default ) as conn: with conn.cursor() as cursor: # Please note: autocommit is disabled by default, per DB-API specification # If you'd like to commit your changes, manually commit or enable autocommit # on the cursor object # conn.commit() # manually commits # conn.autocommit = True # enables autocommit for subsequent SQL statements cursor.execute("create table book(bookname varchar,author varchar)") cursor.executemany("insert into book (bookname, author) values (%s, %s)", [ ('One Hundred Years of Solitude', 'Gabriel García Márquez'), ('A Brief History of Time', 'Stephen Hawking') ] ) cursor.execute("select * from book") result: tuple = cursor.fetchall() print(result) ``` -------------------------------- ### Fetch Data as pandas DataFrame Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/002 - Data Science Library Integrations.ipynb Use fetch_dataframe() to retrieve query results directly into a pandas DataFrame. Ensure pandas is installed and imported. ```python import pandas import redshift_connector with redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' ) as conn: with conn.cursor() as cursor: cursor.execute("create Temp table book(bookname varchar,author‎ varchar)") cursor.executemany("insert into book (bookname, author‎) values (%s, %s)", [ ('One Hundred Years of Solitude', 'Gabriel García Márquez'), ('A Brief History of Time', 'Stephen Hawking') ]) cursor.execute("select * from book") result: pandas.DataFrame = cursor.fetch_dataframe() print(result) ``` -------------------------------- ### Fetch Data as numpy ndarray Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/002 - Data Science Library Integrations.ipynb Use fetch_numpy_array() to retrieve query results directly into a numpy ndarray. Ensure numpy is installed and imported. ```python import numpy import redshift_connector with redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' ) as conn: with conn.cursor() as cursor: cursor.execute("create Temp table book(bookname varchar,author‎ varchar)") cursor.executemany("insert into book (bookname, author‎) values (%s, %s)", [ ('One Hundred Years of Solitude', 'Gabriel García Márquez'), ('A Brief History of Time', 'Stephen Hawking') ]) cursor.execute("select * from book") result: numpy.ndarray = cursor.fetch_numpy_array() print(result) ``` -------------------------------- ### Insert pandas DataFrame into Redshift Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/002 - Data Science Library Integrations.ipynb Use write_dataframe() to insert data from a pandas DataFrame into an Amazon Redshift table. Ensure pandas and numpy are installed and imported. ```python import numpy as np import pandas as pd import redshift_connector df: pd.DataFrame = pd.DataFrame( np.array( [ ["One Hundred Years of Solitude", "Gabriel García Márquez"], ["A Brief History of Time", "Stephen Hawking"], ] ), columns=["bookname", "author‎"], ) with redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' ) as conn: with conn.cursor() as cursor: cursor.execute("create Temp table book(bookname varchar,author‎ varchar)") cursor.write_dataframe(df, "book") cursor.execute("select * from book;") result = cursor.fetchall() print(result) ``` -------------------------------- ### Get Computed Element Style Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html A utility function to retrieve the computed style property of a given DOM element. It supports both IE's currentStyle and the standard getComputedStyle. ```javascript function getStyle(element, styleProp) { var propStyle = null; if (element && element.currentStyle) { propStyle = element.currentStyle[styleProp]; } else if (element && window.getComputedStyle) { propStyle = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProp); } return propStyle; } ``` -------------------------------- ### Using Various Paramstyles with Redshift Connector Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Illustrates how to use different paramstyles ('qmark', 'numeric', 'named', 'format', 'pyformat') for executing SQL statements with parameters. Parameter format depends on the paramstyle. ```python # qmark cursor.paramstyle = 'qmark' sql = 'insert into foo(bar, jar) VALUES(?, ?)' cursor.execute(sql, (1, "hello world")) # numeric cursor.paramstyle = 'numeric' sql = 'insert into foo(bar, jar) VALUES(:1, :2)' cursor.execute(sql, (1, "hello world")) # named cursor.paramstyle = 'named' sql = 'insert into foo(bar, jar) VALUES(:p1, :p2)' cursor.execute(sql, {"p1":1, "p2":"hello world"}) # format cursor.paramstyle = 'format' sql = 'insert into foo(bar, jar) VALUES(%s, %s)' cursor.execute(sql, (1, "hello world")) # pyformat cursor.paramstyle = 'pyformat' sql = 'insert into foo(bar, jar) VALUES(%(bar)s, %(jar)s)' cursor.execute(sql, {"bar": 1, "jar": "hello world"}) ``` -------------------------------- ### Connect using Okta Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connect to Redshift using Okta for authentication with the OktaCredentialsProvider. You will need to provide your Okta host, app ID, and app name. ```python import redshift_connector conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', region='us-east-1', cluster_identifier='my-testing-cluster', credentials_provider='OktaCredentialsProvider', user='brooke@myazure.org', password='hunter2', idp_host='my_idp_host', app_id='my_first_appetizer', app_name='dinner_party' ) ``` -------------------------------- ### Basic Redshift Connection and Data Manipulation Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Connects to a Redshift cluster using standard credentials, creates a temporary table, inserts data using executemany, and fetches results. ```python import redshift_connector # Connects to Redshift cluster using AWS credentials conn = redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' ) cursor: redshift_connector.Cursor = conn.cursor() cursor.execute("create Temp table book(bookname varchar,author varchar)") cursor.executemany("insert into book (bookname, author) values (%s, %s)", [ ('One Hundred Years of Solitude', 'Gabriel García Márquez'), ('A Brief History of Time', 'Stephen Hawking') ] ) cursor.execute("select * from book") result: tuple = cursor.fetchall() print(result) >> (['One Hundred Years of Solitude', 'Gabriel García Márquez'], ['A Brief History of Time', 'Stephen Hawking']) ``` -------------------------------- ### Connect to Redshift Using Authentication Profile Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Establish a connection to Amazon Redshift using a previously created authentication profile. Ensure the region specified in the connect call matches the region where the profile was created. ```python import redshift_connector import os with redshift_connector.connect( iam=True, region='us-west-2', access_key_id=os.environ["AWS_ACCESS_KEY_ID"], secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"], session_token=os.environ["AWS_SESSION_TOKEN"], auth_profile="QAProfile", db_user="bobby_tables" ) as conn: pass ``` -------------------------------- ### Connect using Azure Native OAuth2 Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Establish a connection to Redshift using the native Azure AD OAuth2 flow. This requires specifying the host, scope, tenant ID, client ID, and other relevant parameters. ```python import redshift_connector with redshift_connector.connect( iam=True, credentials_provider='BrowserAzureOAuth2CredentialsProvider', host='test-cluster.abcdefghijkl.us-east-1.redshift.amazonaws.com', scope='api://123456-7891-j3jk3-9dd2-c423434f0037/jdbc_login', idp_tenant='e42343b2-1234-5678-8768-5db01232131d72', cluster_identifier='test-cluster', region='us-east-1', listen_port=7890, idp_response_timeout=50, client_id='343432-492d-j3jk3-9dd2-c423434f0037', database='dev', ssl=True, sslmode='verify-ca', #ssl_insecure=False # port value of 5439 is specified by default ) as conn: pass ``` -------------------------------- ### ADFS Sign-In Error Handling and Input Utilities (JavaScript) Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Provides utility functions for managing error messages and input focus on the ADFS sign-in page. It includes a constructor for error messages and methods to check, set, and display errors, as well as manage initial focus. ```javascript function LoginErrors(){this.userNameFormatError = 'Enter your user ID in the format \u0026quot;domain\\user\u0026quot; or \u0026quot;user@domain\u0026quot;.'; this.passwordEmpty = 'Enter your password.'; this.passwordTooLong = 'Password is too long (\u0026gt; 128 characters).';}; var maxPasswordLength = 128; ``` ```javascript function InputUtil(errTextElementID, errDisplayElementID) { if (!errTextElementID) errTextElementID = 'errorText'; if (!errDisplayElementID) errDisplayElementID = 'error'; this.hasFocus = false; this.errLabel = document.getElementById(errTextElementID); this.errDisplay = document.getElementById(errDisplayElementID); }; InputUtil.prototype.canDisplayError = function () { return this.errLabel && this.errDisplay; } InputUtil.prototype.checkError = function () { if (!this.canDisplayError){ throw new Error ('Error element not present'); } if (this.errLabel && this.errLabel.innerHTML) { this.errDisplay.style.display = ''; var cause = this.errLabel.getAttribute('for'); if (cause) { var causeNode = document.getElementById(cause); if (causeNode && causeNode.value) { causeNode.focus(); this.hasFocus = true; } } } else { this.errDisplay.style.display = 'none'; } }; InputUtil.prototype.setInitialFocus = function (input) { if (this.hasFocus) return; var node = document.getElementById(input); if (node) { if ((/^\s\*$/).test(node.value)) { node.focus(); this.hasFocus = true; } } }; InputUtil.prototype.setError = function (input, errorMsg) { if (!this.canDisplayError) { throw new Error('Error element not present'); } input.focus(); if (errorMsg) { this.errLabel.innerHTML = errorMsg; } this.errLabel.setAttribute('for', input.id); this.errDisplay.style.display = ''; }; ``` -------------------------------- ### Connect to Redshift with IAM Credentials Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Connects to a Redshift cluster using IAM credentials. Ensure your AWS credentials and region are configured in `~/.aws/config` or `~/.aws/credentials`, or provide them directly. ```python import redshift_connector # Connects to Redshift cluster using IAM credentials from default profile defined in ~/.aws/credentials conn = redshift_connector.connect( iam=True, database='dev', db_user='awsuser', password='', user='', cluster_identifier='examplecluster', access_key_id="my_aws_access_key_id", secret_access_key="my_aws_secret_access_key", session_token="my_aws_session_token", region="us-east-2" ) ``` -------------------------------- ### Configuring Paramstyle on Module and Cursor Levels Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Shows how to set the paramstyle for Redshift cursors, either globally on the module or individually on a cursor object. The default module-level paramstyle is 'format'. ```python # setting paramstyle to qmark on a module level redshift_connector.paramstyle = 'qmark' with redshift_connector.connect() as conn1: with conn1.cursor() as cursor1: # this cursor will use qmark paramstyle as it's been set on the module level pass with conn1.cursor() as cursor2: # setting paramstyle to numeric on the cursor level only this cursor will use numeric paramstyle cursor.paramstyle = 'numeric' with conn1.cursor() as cursor3: # this cursor will use qmark paramstyle as it's been set on the module level pass with redshift_connector.connect() as conn2: with conn2.cursor() as cursor1: # this cursor will use qmark paramstyle as it's been set on the module level pass ``` -------------------------------- ### Connect using Azure Browser Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Use this snippet to connect to Redshift when authenticating via Azure AD using the BrowserAzureCredentialsProvider. Ensure the user and idp_tenant are correctly specified. ```python import redshift_connector conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', cluster_identifier='my-testing-cluster', credentials_provider='BrowserAzureCredentialsProvider', user='brooke@myazure.org', password='', idp_tenant='my_idp_tenant', client_id='my_client_id', ) ``` -------------------------------- ### Enabling Autocommit in Redshift Connector Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Demonstrates how to enable and disable autocommit for Redshift connections. Autocommit is off by default. ```py3 # Make sure we're not in a transaction conn.rollback() conn.autocommit = True conn.run("VACUUM") conn.autocommit = False ``` -------------------------------- ### Send Geometry Data in WKB Format Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Demonstrates sending geometry data in Well-Known Binary (WKB) format to an Amazon Redshift table. Ensure the table schema includes a geometry column. ```python import redshift_connector with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute("create table datatype_test (c1 geometry);") cursor.execute( "insert into datatype_test (c1) values (%s);", ( '0103000020E61000000100000005000000000000000000000000000000000000000000000000000000000000000000F03F000000000000F03F000000000000F03F000000000000F03F000000000000000000000000000000000000000000000000', # using WKB format ) ) cursor.execute("select c1 from datatype_test;") result = cursor.fetchone() print("c1={}\n".format(result[0],)) ``` -------------------------------- ### JavaScript for Option Selection Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Handles the selection of options and submits a form. It also displays a waiting wheel during submission. ```javascript function SelectOption(option) { var w = document.getElementById('waitingWheelDiv'); if(w) w.style.display = 'inline'; var i = document.getElementById('optionSelection'); i.value = option; document.forms\[\'options\'\]\.submit(); return false; } ``` -------------------------------- ### Placeholder and UI Helper Functions for Older Browsers (JavaScript) Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Includes functions to create and manage input placeholders, specifically for older Internet Explorer versions (7, 8, 9). It also provides general utility functions for DOM manipulation like focusing elements, adding/removing CSS classes, and showing/hiding hint text. ```javascript InputUtil.makePlaceholder = function (input) { var ua = navigator.userAgent; if (ua != null && (ua.match(/MSIE 9.0/) != null || ua.match(/MSIE 8.0/) != null || ua.match(/MSIE 7.0/) != null)) { var node = document.getElementById(input); if (node) { var placeholder = node.getAttribute("placeholder"); if (placeholder != null && placeholder != '') { var label = document.createElement('input'); label.type = "text"; label.value = placeholder; label.readOnly = true; label.style.position = 'absolute'; label.style.borderColor = 'transparent'; label.className = node.className + ' hint'; label.tabIndex = -1; label.onfocus = function () { this.nextSibling.focus(); }; node.style.position = 'relative'; node.parentNode.style.position = 'relative'; node.parentNode.insertBefore(label, node); node.onkeyup = function () { InputUtil.showHint(this); }; node.onblur = function () { InputUtil.showHint(this); }; node.style.background = 'transparent'; node.setAttribute("placeholder", ""); InputUtil.showHint(node); } } } }; InputUtil.focus = function (inputField) { var node = document.getElementById(inputField); if (node) node.focus(); }; InputUtil.hasClass = function(node, clsName) { return node.className.match(new RegExp('(\\s|^)' + clsName + '(\\s|$)')); }; InputUtil.addClass = function(node, clsName) { if (!this.hasClass(node, clsName)) node.className += " " + clsName; }; InputUtil.removeClass = function(node, clsName) { if (this.hasClass(node, clsName)) { var reg = new RegExp('(\\s|^)' + clsName + '(\\s|$)'); node.className = node.className.replace(reg, ' '); } }; InputUtil.showHint = function (node, gotFocus) { if (node.value && node.value != '') { node.previousSibling.style.display = 'none'; } else { node.previousSibling.style.display = ''; } }; InputUtil.updatePlaceholder = function (input, placeholderText) { var node = document.getElementById(input); if (node) { var ua = navigator.userAgent; if (ua != null && (ua.match(/MSIE 9.0/) != null || ua.match(/MSIE 8.0/) != null || ua.match(/MSIE 7.0/) != null)) { var label = node.previousSibling; if (label != null) { label.value = placeholderText; } } else { node.placeholder = placeholderText; } } }; ``` -------------------------------- ### Compute and Load Illustration Image Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Attaches event listeners to 'load' and 'resize' to dynamically add an 'illustrationClass' to the branding element when it's displayed. This class is used to apply a background image. ```javascript var computeLoadIllustration = function () { var branding = document.getElementById("branding"); var brandingDisplay = getStyle(branding, "display"); var brandingWrapperDisplay = getStyle(document.getElementById("brandingWrapper"), "display"); if (brandingDisplay && brandingDisplay !== "none" && brandingWrapperDisplay && brandingWrapperDisplay !== "none") { var newClass = "illustrationClass"; if (branding.classList && branding.classList.add) { branding.classList.add(newClass); } else if (branding.className !== undefined) { branding.className += " " + newClass; } if (window.removeEventListener) { window.removeEventListener('load', computeLoadIllustration, false); window.removeEventListener('resize', computeLoadIllustration, false); } else if (window.detachEvent) { window.detachEvent('onload', computeLoadIllustration); window.detachEvent('onresize', computeLoadIllustration); } } }; if (window.addEventListener) { window.addEventListener('resize', computeLoadIllustration, false); window.addEventListener('load', computeLoadIllustration, false); } else if (window.attachEvent) { window.attachEvent('onresize', computeLoadIllustration); window.attachEvent('onload', computeLoadIllustration); } ``` -------------------------------- ### Connect to Redshift Serverless using Database Credentials Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connect to a Redshift Serverless endpoint using native database credentials. Provide the serverless endpoint to the 'host' parameter. The default port is 5439. ```python import redshift_connector with redshift_connector.connect( host='mytest_workgroup.123456789012.us-west-1.redshift-serverless.amazonaws.com', database='dev', user='awsuser', password='my_password' # port value of 5439 is specified by default ) as conn: pass ``` -------------------------------- ### Authenticate with ADFS Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connect to Amazon Redshift using the AdfsCredentialsProvider. This requires specifying user credentials, IdP host, and other connection details. ```python import redshift_connector conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', cluster_identifier='my-testing-cluster', credentials_provider='AdfsCredentialsProvider', user='brooke@myadfshostname.com', password='Hunter2', idp_host='myadfshostname.com' ) ``` -------------------------------- ### Authenticate with Azure Identity Provider Plugin Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connect to Amazon Redshift using the AzureCredentialsProvider. This method requires Azure-specific details such as client ID, client secret, and IdP tenant. ```python import redshift_connector conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', region='us-east-1', cluster_identifier='my-testing-cluster', credentials_provider='AzureCredentialsProvider', user='brooke@myazure.org', password='Hunter2', idp_tenant='my_idp_tenant', client_id='my_client_id', client_secret='my_client_secret', preferred_role='arn:aws:iam:123:role/MyFirstDinnerRoll' ) ``` -------------------------------- ### Connect to Redshift using IAM Credentials with AWS Profile Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connects to a Redshift cluster using IAM credentials from a specified AWS profile. Requires the 'iam' parameter to be set to True and the 'profile' to be defined in your AWS configuration. ```python import redshift_connector # Connects to Redshift cluster using IAM credentials from default profile defined in ~/.aws/credentials conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', db_user='awsuser', password='', user='', cluster_identifier='examplecluster', profile='default' ) ``` -------------------------------- ### Connect to Redshift using IAM Credentials with Explicit AWS Keys Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connects to a Redshift cluster using IAM credentials provided directly as parameters. This method requires explicit provision of access key ID, secret access key, and optionally a session token and region. ```python import redshift_connector # Connects to Redshift cluster using IAM credentials from default profile defined in ~/.aws/credentials conn: redshift_connector.Connection = redshift_connector.connect( iam=True, database='dev', db_user='awsuser', password='', user='', cluster_identifier='examplecluster', access_key_id="my_aws_access_key_id", secret_access_key="my_aws_secret_access_key", session_token="my_aws_session_token", region="us-east-2" ) ``` -------------------------------- ### Connect to Redshift Serverless using IAM Credentials Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Connect to a Redshift Serverless endpoint using IAM credentials. Specify the serverless endpoint in the 'host' parameter and provide your AWS access key, secret access key, and session token. ```python import redshift_connector with redshift_connector.connect( iam=True, host='mytest_workgroup.123456789012.us-west-1.redshift-serverless.amazonaws.com', database='dev', access_key_id='my_aws_access_key_id', secret_access_key='my_aws_secret_access_key', session_token='my_aws_session_token', region='us-east-2' ) as conn: pass ``` -------------------------------- ### Insert and Select VARBYTE Data Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Demonstrates inserting string, bytes, and byte sequences into a VARBYTE column in Amazon Redshift and then selecting the data. The VARBYTE datatype can accept string, bytes, or hexadecimal representations. ```python import redshift_connector with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute("create table t (v varbyte);") cursor.execute("insert into t values (%s), (%s);", ('aa', 'abc', )) cursor.execute("insert into t values (%s), (%s);", (b'aa', b'abc',)) cursor.execute("insert into t values (%s), (%s);", (b'\x00\x01\x02\x03',b'\x00\x0a\x0b\x0c')) cursor.execute("select v from t;") result = cursor.fetchall() print(result) ``` -------------------------------- ### COPY and UNLOAD Data with Amazon S3 Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/003 - Amazon Redshift Feature Support.ipynb Use this snippet to copy data from an S3 bucket into a Redshift table and then unload data from a Redshift table back to an S3 bucket. Ensure the IAM role has the necessary S3 permissions. ```text 12,Shows,Musicals,Musical theatre 13,Shows,Plays,"All ""non-musical"" theatre" 14,Shows,Opera,"All opera, light, and ""rock"" opera" 15,Concerts,Classical,"All symphony, concerto, and choir concerts" ``` ```python import redshift_connector with redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', user='awsuser', password='my_password' ) as conn: with conn.cursor() as cursor: cursor.execute("create table category (catid int, cargroup varchar, catname varchar, catdesc varchar)") cursor.execute("copy category from 's3://testing/category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") cursor.execute("select * from category") print(cursor.fetchall()) cursor.execute("unload ('select * from category') to 's3://testing/unloaded_category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") print('done') ``` -------------------------------- ### Fetch Query Results as Pandas DataFrame Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Retrieves query results and loads them into a pandas DataFrame. This is useful for data analysis and manipulation. ```python import pandas cursor.execute("create Temp table book(bookname varchar,author varchar)") cursor.executemany("insert into book (bookname, author) values (%s, %s)", [ ('One Hundred Years of Solitude', 'Gabriel García Márquez'), ('A Brief History of Time', 'Stephen Hawking') ]) cursor.execute("select * from book") result: pandas.DataFrame = cursor.fetch_dataframe() print(result) ``` -------------------------------- ### Send Geometry Data in WKT Format Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Demonstrates sending geometry data in Well-Known Text (WKT) format to an Amazon Redshift table using the ST_GeomFromText function. Ensure the table schema includes a geometry column. ```python import redshift_connector with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute("create table datatype_test (c1 geometry);") cursor.execute( "insert into datatype_test (c1) values (ST_GeomFromText(%s));", ( 'LINESTRING(1 2,3 4,5 6,7 8,9 10,11 12,13 14,15 16,17 18,19 20)', # using WKT format ) ) cursor.execute("select c1, c2 from datatype_test;") result = cursor.fetchone() print("c1={}\nc2={}".format(result[0], result[1])) ``` -------------------------------- ### Execute Query and Fetch Single Row Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Executes a SQL query and fetches a single row from the result set. This is commonly used for retrieving single values or status information. ```python cursor.execute("SELECT CURRENT_TIMESTAMP") print(cursor.fetchone()) ``` -------------------------------- ### Create Amazon Redshift Authentication Profile Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Use boto3 to create an Amazon Redshift authentication profile. This profile stores connection details like host and cluster identifier, improving code portability and security. ```python import boto3 from botocore.exceptions import ClientError import json authentication_profile_contents = { 'host': 'examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', 'region': 'us-west-1', 'cluster_identifier': 'examplecluster', 'db_name': 'dev' } try: client = boto3.client("redshift", "us-east-2") client.create_authentication_profile( AuthenticationProfileName="QAProfile", AuthenticationProfileContent=json.dumps(authentication_profile_contents) ) except ClientError: raise ``` -------------------------------- ### CSS for Floating Circles Animation Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Defines the CSS for a 'floating circles' loading animation, including keyframes for fading effects. ```css #floatingCirclesG { position: relative; width: 125px; height: 125px; margin: auto; transform: scale(0.4); -o-transform: scale(0.4); -ms-transform: scale(0.4); -webkit-transform: scale(0.4); -moz-transform: scale(0.4); } .f_circleG { position: absolute; height: 22px; width: 22px; border-radius: 12px; -o-border-radius: 12px; -ms-border-radius: 12px; -webkit-border-radius: 12px; -moz-border-radius: 12px; animation-name: f_fadeG; -o-animation-name: f_fadeG; -ms-animation-name: f_fadeG; -webkit-animation-name: f_fadeG; -moz-animation-name: f_fadeG; animation-duration: 1.2s; -o-animation-duration: 1.2s; -ms-animation-duration: 1.2s; -webkit-animation-duration: 1.2s; -moz-animation-duration: 1.2s; animation-iteration-count: infinite; -o-animation-iteration-count: infinite; -ms-animation-iteration-count: infinite; -webkit-animation-iteration-count: infinite; -moz-animation-iteration-count: infinite; animation-direction: normal; -o-animation-direction: normal; -ms-animation-direction: normal; -webkit-animation-direction: normal; -moz-animation-direction: normal; } #frotateG_01 { left: 0; top: 51px; animation-delay: 0.45s; -o-animation-delay: 0.45s; -ms-animation-delay: 0.45s; -webkit-animation-delay: 0.45s; -moz-animation-delay: 0.45s; } #frotateG_02 { left: 15px; top: 15px; animation-delay: 0.6s; -o-animation-delay: 0.6s; -ms-animation-delay: 0.6s; -webkit-animation-delay: 0.6s; -moz-animation-delay: 0.6s; } #frotateG_03 { left: 51px; top: 0; animation-delay: 0.75s; -o-animation-delay: 0.75s; -ms-animation-delay: 0.75s; -webkit-animation-delay: 0.75s; -moz-animation-delay: 0.75s; } #frotateG_04 { right: 15px; top: 15px; animation-delay: 0.9s; -o-animation-delay: 0.9s; -ms-animation-delay: 0.9s; -webkit-animation-delay: 0.9s; -moz-animation-delay: 0.9s; } #frotateG_05 { right: 0; top: 51px; animation-delay: 1.05s; -o-animation-delay: 1.05s; -ms-animation-delay: 1.05s; -webkit-animation-delay: 1.05s; -moz-animation-delay: 1.05s; } #frotateG_06 { right: 15px; bottom: 15px; animation-delay: 1.2s; -o-animation-delay: 1.2s; -ms-animation-delay: 1.2s; -webkit-animation-delay: 1.2s; -moz-animation-delay: 1.2s; } #frotateG_07 { left: 51px; bottom: 0; animation-delay: 1.35s; -o-animation-delay: 1.35s; -ms-animation-delay: 1.35s; -webkit-animation-delay: 1.35s; -moz-animation-delay: 1.35s; } #frotateG_08 { left: 15px; bottom: 15px; animation-delay: 1.5s; -o-animation-delay: 1.5s; -ms-animation-delay: 1.5s; -webkit-animation-delay: 1.5s; -moz-animation-delay: 1.5s; } @keyframes f_fadeG { 0% { background-color: rgb(47, 146, 212); } 100% { background-color: rgb(255, 255, 255); } } @-o-keyframes f_fadeG { 0% { background-color: rgb(47, 146, 212); } 100% { background-color: rgb(255, 255, 255); } } @-ms-keyframes f_fadeG { 0% { background-color: rgb(47, 146, 212); } 100% { background-color: rgb(255, 255, 255); } } @-webkit-keyframes f_fadeG { 0% { background-color: rgb(47, 146, 212); } 100% { background-color: rgb(255, 255, 255); } } @-moz-keyframes f_fadeG { 0% { background-color: rgb(47, 146, 212); } 100% { background-color: rgb(255, 255, 255); } } ``` -------------------------------- ### JavaScript for Login Form Validation Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Handles ADFS login form validation, checking for valid username format, non-empty password, and password length constraints before submission. ```javascript // maxPasswordLength) { u.setError(password, e.passwordTooLong); return false; } document.forms['loginForm'].submit(); return false; }; InputUtil.makePlaceholder(Login.userNameInput); InputUtil.makePlaceholder(Login.passwordInput); //]]> ``` -------------------------------- ### Querying Nested JSON Arrays with SUPER Datatype Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Shows how to create a table with a SUPER datatype column populated by JSON data and then query nested arrays within it. The json_parse function is used to convert the JSON string into a SUPER type. ```python import redshift_connector with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute( "CREATE TABLE foo AS SELECT json_parse(%s) AS multi_level_array;", ('[[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]', ) ) cursor.execute("SELECT array, element FROM foo AS f, f.multi_level_array AS array, array AS element;") result = cursor.fetchall() print(result) ``` -------------------------------- ### Insert and Select Data from SUPER Datatype Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Illustrates inserting both JSON array and JSON object data into a SUPER datatype column and then selecting the data. The json_parse function is used to convert JSON strings into the SUPER type. ```python import redshift_connector import json with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute("create table t (s super);") cursor.execute("insert into t values (json_parse(%s));", ('[10001,10002,"abc"]',)) cursor.execute("insert into t values (json_parse(%s));", (json.dumps({"x": [1,2,3,4]}),)) cursor.execute("select s from t;") result = cursor.fetchall() print(result) ``` -------------------------------- ### Set Custom Illustration Image Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Dynamically creates and injects a CSS style rule to set a background image for elements with the 'illustrationClass'. This function is used to change the illustration image on ADFS pages. ```javascript function SetIllustrationImage(imageUri) { var illustrationImageClass = '.illustrationClass {background-image:url(' + imageUri + ');}'; var css = document.createElement('style'); css.type = 'text/css'; if (css.styleSheet) css.styleSheet.cssText = illustrationImageClass; else css.appendChild(document.createTextNode(illustrationImageClass)); document.getElementsByTagName("head")[0].appendChild(css); } ``` -------------------------------- ### Windows 8 Phone Viewport Adjustment Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Applies a CSS workaround for Windows 8 phones to ensure correct viewport dimensions. This is necessary due to specific browser behavior on that platform. ```javascript if (navigator.userAgent.match(/IEMobile\/10\.0/)) { var msViewportStyle = document.createElement("style"); msViewportStyle.appendChild( document.createTextNode( "@-ms-viewport{width:auto!important}" ) ); msViewportStyle.appendChild( document.createTextNode( "@-ms-viewport{height:auto!important}" ) ); document.getElementsByTagName("head")[0].appendChild(msViewportStyle); } ``` -------------------------------- ### Set Viewport Width Based on Inner Width Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Adjusts the viewport meta tag to use the window's innerWidth if it differs from outerWidth. This ensures better responsiveness on certain devices. ```javascript if (window.innerWidth && window.outerWidth && window.innerWidth !== window.outerWidth) { var viewport = document.querySelector("meta\[name=viewport\]"); viewport.setAttribute('content', 'width=' + window.innerWidth + ', initial-scale=1.0, user-scalable=1'); } ``` -------------------------------- ### Retrieve Array Elements from SUPER Datatype Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/004 - Amazon Redshift Datatypes.ipynb Demonstrates storing a JSON object with an array in a SUPER datatype column and then retrieving specific array elements. The json.dumps function is used to serialize the Python dictionary to a JSON string. ```python import redshift_connector import json with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute( "CREATE TABLE foo AS SELECT json_parse(%s) AS vals;", (json.dumps({"x": [1,2,3,4], "y": [5,6,7,8], "z": [9,10,11,12]}),) ) cursor.execute("SELECT vals.x FROM foo;") result = cursor.fetchall() print(result) ``` -------------------------------- ### JavaScript Requirement Message (HTML/JavaScript) Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Displays a message to the user indicating that JavaScript is required for the page to function correctly. This is shown when JavaScript is either not supported by the browser or is disabled. ```javascript document.getElementById("noScript").style.display = "none"; ``` -------------------------------- ### Insert Pandas DataFrame into Redshift Table Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/README.rst Writes data from a pandas DataFrame into an Amazon Redshift table. This method is efficient for bulk inserts. ```python import numpy as np import pandas as pd df = pd.DataFrame( np.array( [ ["One Hundred Years of Solitude", "Gabriel García Márquez"], ["A Brief History of Time", "Stephen Hawking"], ] ), columns=["bookname", "author‎"], ) with conn.cursor() as cursor: cursor.write_dataframe(df, "book") cursor.execute("select * from book; ") result = cursor.fetchall() ``` -------------------------------- ### Delete Amazon Redshift Authentication Profile Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/tutorials/001 - Connecting to Amazon Redshift.ipynb Remove an Amazon Redshift authentication profile using boto3. This is useful for cleanup after demonstration or testing. ```python try: client = boto3.client("redshift") client.delete_authentication_profile( AuthenticationProfileName="QAProfile", ) except ClientError: raise ``` -------------------------------- ### Adjust iPhone Email Input Type Source: https://github.com/aws/amazon-redshift-python-driver/blob/master/test/unit/plugin/data/mock_adfs_sign_in.html Modifies email input fields to 'text' on iPhones to ensure the correct keyboard is displayed. This is a workaround for inconsistent browser behavior. ```javascript if (navigator.userAgent.match(/iPhone/i) != null) { var emails = document.querySelectorAll("input\[type='email'\ ]"); if (emails) { for (var i = 0; i < emails.length; i++) { emails[i].type = 'text'; } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.