├── .gitignore ├── LICENSE ├── Pulumi.dev.yaml ├── Pulumi.yaml ├── README.md ├── index.ts ├── package-lock.json ├── package.json ├── snowflake ├── SnowflakeGenericProvider.ts ├── request_translator.js ├── response_translator.js └── table_function_body.sql └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | .idea 3 | /node_modules/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /Pulumi.dev.yaml: -------------------------------------------------------------------------------- 1 | encryptionsalt: v1:4zyhWwmqQrc=:v1:gynqxJiaBrpbvhJC:KJ+5hm+BoN/2vzA4FR8q8VFUGBpjgw== 2 | config: 3 | aws:region: us-west-2 4 | snowflake:browserAuth: "true" 5 | -------------------------------------------------------------------------------- /Pulumi.yaml: -------------------------------------------------------------------------------- 1 | name: athena 2 | description: A Snowflake to Mysql Query Program (via Athena) 3 | runtime: nodejs 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A Source Connector Framework for Snowflake 2 | 3 | This directory holds a pulumi deployment that allows Snowflake users to query alternative sources (specifically MySQL). You can learn more about this by reading our series of [blog posts](https://www.sundeck.io/blog/creating-a-source-connector-framework-for-snowflake) 4 | 5 | ## Deploy AWS & Snowflake Assets 6 | 1. Ensure you're logged into AWS and your credentials are setup correctly. 7 | 1. Install Pulumi ([instructions](https://www.pulumi.com/docs/get-started/install/)) 8 | 1. Configure pulumi for first use. 9 | ```bash 10 | # Configure with local settings. You could also configure with Pulumi cloud but that takes more time. 11 | pulumi login --local 12 | ``` 13 | 1. Install node/npm ([instructions](https://nodejs.org/en/download/)) 14 | 1. Clone the repository and install the required NPM packages. 15 | ``` 16 | git clone https://github.com/sundeck-io/snowflake-connector-framework.git 17 | npm update 18 | ``` 19 | 20 | 1. Configure your account & username for snowflake: 21 | ``` 22 | cd snowflake-connectors/athena 23 | pulumi config set snowflake:account YOURACCOUNTLOCATOR 24 | pulumi config set snowflake:username YOURSNOWFLAKEUSERNAME 25 | ``` 26 | 1. Setup AWS & Snowflake 27 | ```bash 28 | # During execution, pulumi will prompt you one or more times to login to Snowflake via browser. 29 | # Most of the operations are quick but the following take a while: 30 | # 31 | # * Creation of a MySQL RDS instance takes 2-3 minutes. 32 | # * Deployment of MySQL Athena connector Lambda takes 2-3 minutes. 33 | # 34 | # Unfortunately, since the lambda connector needs info from the RDS instance post 35 | # deploy (connection string), they have to run serially. 36 | # 37 | # Note: If you see any Snowflake operations taking more than a couple seconds, that typically 38 | # means you've missed a login window. Check all your tabs! 39 | # 40 | pulumi up -y 41 | ``` 42 | 43 | ## Query MySQL (or any Athena source) 44 | 1. Go into Snowflake Snowsight (or your preferred SQL tool). 45 | 1. Execute a query in Snowflake against your new MySQL instance. 46 | ```sql 47 | use sundeck_connectors.athena; 48 | select * from table(query_athena($$ 49 | select * from mysql.information_schema.tables 50 | $$, 100)); 51 | ``` 52 | 1. By default, all data comes back as a variant column. This is due to the fact that a UDTF needs to have schema declared at creation time. As such, our declared schema is a single variant column called `data`. If you want to make things more typed, you can create a view on top of your table function invocation. For example: 53 | ```sql 54 | CREATE VIEW mysql_information_schema_tables AS 55 | SELECT 56 | data:table_catalog::text AS table_catalog, 57 | data:table_schema::text AS table_schema, 58 | data:table_name::text AS table_name, 59 | data:table_type::text AS table_type 60 | FROM TABLE(query_athena($$ 61 | SELECT * FROM mysql.information_schema.tables 62 | $$, 100)); 63 | ``` 64 | 65 | ## Frequently Asked Questions 66 |
67 |
How does this all work?
68 |
See our Blog post on the topic!
69 |
What is Pulumi?
70 |
Pulumi is a infrastructure automation tool, similar to Terraform or AWS CloudFormation.
71 |
Why use Pulumi?
72 |
In order to deploy an external function, there is some back and forth between AWS and Snowflake. (You need take information from each and give it to the other). Rather than make people go through a bunch of steps, Pulumi allows us to automatically move the configuration between the two systems to make it easier to setup an external function.
73 |
What if I want to configure things manually?
74 |
Pulumi is largely declarative. Most of the deployment code should readable even if you've never used Pulumi
75 |
What does Sundeck do?
76 |
We're working on some new ways to enhance Snowflake. More coming soon. Go to our website and sign up for our mailing list to hear more as we progress.
77 |
78 | 79 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import * as pulumi from "@pulumi/pulumi"; 2 | import * as aws from "@pulumi/aws"; 3 | import * as snowflake from "@pulumi/snowflake"; 4 | import * as crypto from "crypto"; 5 | import * as fs from "fs"; 6 | import * as awsx from "@pulumi/awsx"; 7 | import * as random from "@pulumi/random"; 8 | import {GenericSnowflake} from "./snowflake/SnowflakeGenericProvider"; 9 | 10 | /////////////////////////////////////////////////////////////////////////// 11 | // Default names for objects. 12 | const functionInvocationRoleName = "SNOWFLAKE_CONNECTOR_INBOUND_REST_ROLE"; 13 | const connectorsDatabaseName = "SUNDECK_CONNECTORS"; 14 | const lambdaFunctionName = "mysql"; 15 | /////////////////////////////////////////////////////////////////////////// 16 | 17 | const identity = aws.getCallerIdentity({}); 18 | const currentRegion = pulumi.output(aws.getRegion()).name; 19 | const currentAccount = identity.then(c => c.accountId); 20 | const vpc = awsx.ec2.Vpc.getDefault(); 21 | const vpcId = vpc.id; 22 | 23 | 24 | // Create an AWS resource (S3 Bucket) !!NOTE!! that this is declared that it will delete on pulumi down. 25 | const athenaResultsBucket = new aws.s3.BucketV2("athena.results", {forceDestroy: true}); 26 | 27 | // Ensure the bucket disables public access 28 | const blockS3PublicAccess = new aws.s3.BucketPublicAccessBlock("athenaResultsBlockPublicAccess", { 29 | bucket: athenaResultsBucket.id, 30 | blockPublicAcls: true, 31 | blockPublicPolicy: true, 32 | ignorePublicAcls: true, 33 | restrictPublicBuckets: true, 34 | }); 35 | 36 | // Create a database for our connector. 37 | const db = new snowflake.Database("snowflake.database", {name: connectorsDatabaseName}); 38 | const schema = new snowflake.Schema("snowflake.schema", {database: db.name, name: "ATHENA"}); 39 | 40 | // Create a role that will be applied to api requests so that they can use Athena 41 | const athenaRole = new aws.iam.Role("athena.role", { 42 | namePrefix: "athenaAssumeRole", 43 | assumeRolePolicy: JSON.stringify({ 44 | Version: "2012-10-17", 45 | Statement: [ { 46 | "Effect": "Allow", 47 | "Principal": { 48 | "Service": "apigateway.amazonaws.com" 49 | }, 50 | "Action": "sts:AssumeRole" 51 | }],}), 52 | managedPolicyArns: ["arn:aws:iam::aws:policy/AmazonAthenaFullAccess"], 53 | inlinePolicies: [{name: "allow-s3-bucket-access", policy: pulumi.all([athenaResultsBucket.arn]).apply((arn) => JSON.stringify({ 54 | Version: "2012-10-17", 55 | Statement: [{ 56 | "Sid": "VisualEditor0", 57 | "Effect": "Allow", 58 | "Action": [ 59 | "s3:ListMultipartUploadParts", 60 | "s3:PutObject", 61 | "s3:GetObject", 62 | "s3:PutBucketNotification", 63 | "s3:ListBucket" 64 | ], 65 | "Resource": arn + "/*" 66 | }], 67 | }))}] 68 | }); 69 | 70 | // Create the api gateway we'll call. 71 | const restApi = new aws.apigateway.RestApi("rest.api", { 72 | endpointConfiguration: { 73 | types: "REGIONAL" 74 | } 75 | } 76 | ); 77 | 78 | // Create a role that will allow Snowflake to access our rest api. We are referring to a role we haven't yet created. 79 | const snowflakeApiIntegration = pulumi.all([restApi.id, currentRegion, currentAccount]).apply(([restApiId, region, accountId]) => new snowflake.ApiIntegration("snowflake.apiIntegration", { 80 | apiAllowedPrefixes: [`https://${restApiId}.execute-api.${region}.amazonaws.com/`], 81 | apiAwsRoleArn: `arn:aws:iam::${accountId}:role/${functionInvocationRoleName}`, 82 | apiProvider: "aws_api_gateway", 83 | enabled: true, 84 | })); 85 | 86 | // Create an athena invocation resource 87 | const athenaResource = new aws.apigateway.Resource("rest.athenaResource", { 88 | restApi: restApi.id, 89 | parentId: restApi.rootResourceId, 90 | pathPart: "athena", 91 | }); 92 | 93 | // Enable the post method for the athena resource. 94 | const postMethod = new aws.apigateway.Method("rest.athenaMethod", { 95 | restApi: restApi.id, 96 | resourceId: athenaResource.id, 97 | httpMethod: "POST", 98 | authorization: "AWS_IAM", 99 | requestParameters: { 100 | "method.request.querystring.action": false 101 | }, 102 | }); 103 | 104 | // Set the default response model to json. 105 | const postMethod200Response = new aws.apigateway.MethodResponse("rest.athena200Response", { 106 | restApi: restApi.id, 107 | resourceId: athenaResource.id, 108 | httpMethod: postMethod.httpMethod, 109 | statusCode: "200", 110 | responseModels: { 111 | "application/json": "Empty" 112 | } 113 | }); 114 | 115 | // define a integration operation that adds a header and converts a query string to a header. 116 | const gatewayIntegration = new aws.apigateway.Integration("rest.requestIntegration", { 117 | restApi: restApi.id, 118 | resourceId: athenaResource.id, 119 | httpMethod: postMethod.httpMethod, 120 | integrationHttpMethod: "POST", 121 | type: "AWS", 122 | uri: pulumi.interpolate `arn:aws:apigateway:${currentRegion}:athena:path//`, 123 | credentials: athenaRole.arn, 124 | requestParameters: { 125 | "integration.request.header.Content-Type": "'application/x-amz-json-1.1'", 126 | "integration.request.header.X-Amz-Target": "method.request.querystring.action" 127 | }, 128 | passthroughBehavior: "WHEN_NO_MATCH" 129 | }); 130 | 131 | const athenaPostIntegrationResponse = new aws.apigateway.IntegrationResponse("rest.athenaPostIntegrationResponse", { 132 | restApi: restApi.id, 133 | resourceId: athenaResource.id, 134 | httpMethod: postMethod.httpMethod, 135 | statusCode: postMethod200Response.statusCode 136 | }, {dependsOn: gatewayIntegration}); 137 | 138 | 139 | // deploy a javascript request translator 140 | const requestTranslator = new snowflake.Function("snowflake.requestTranslator", { 141 | name: "REQUEST_TRANSLATOR", 142 | arguments: [{name: "event", type: "object"}], 143 | database: db.name, 144 | schema: schema.name, 145 | language: "javascript", 146 | statement: pulumi.all( [athenaResultsBucket.bucket]).apply(([bucket]) => 147 | `${file('snowflake/request_translator.js')}\nreturn translate_request(EVENT);` 148 | .replace('INSERTBUCKETNAMEHERE', bucket)), 149 | returnType: "object" 150 | }); 151 | 152 | // deploy a javascript response translator 153 | const responseTranslator = new snowflake.Function("snowflake.responseTranslator", { 154 | name: "RESPONSE_TRANSLATOR", 155 | arguments: [{name: "event", type: "object"}], 156 | database: db.name, 157 | schema: schema.name, 158 | language: "javascript", 159 | statement: `${file('snowflake/response_translator.js')}\nreturn translate_response(EVENT);`, 160 | returnType: "object" 161 | }); 162 | 163 | // generate a mysql password 164 | const mysqlPasswordGenerator = new random.RandomString("mysql.password", {length: 20, upper: true, special: false, lower: true}) 165 | 166 | // export the mysql password to the cli. 167 | export const mysqlPassword = mysqlPasswordGenerator.result; 168 | 169 | // create a mysql rds instance. 170 | const mysql = new aws.rds.Instance("mysql.t3micro", { 171 | identifier: "mysql-snowflake-connector", 172 | allocatedStorage: 10, 173 | dbName: "mydb", 174 | engine: "mysql", 175 | engineVersion: "5.7", 176 | instanceClass: "db.t3.micro", 177 | parameterGroupName: "default.mysql5.7", 178 | password: mysqlPassword, 179 | skipFinalSnapshot: true, 180 | username: "root", 181 | }); 182 | 183 | // create a new role for the lambda that will be used as the 184 | const athenaLambdaRole = new aws.iam.Role("lambda.mysqlConnectorRole", { 185 | namePrefix: "athenaMysqlLambda", 186 | assumeRolePolicy: JSON.stringify({ 187 | "Version": "2012-10-17", 188 | "Statement": [ 189 | { 190 | "Effect": "Allow", 191 | "Principal": { 192 | "Service": "lambda.amazonaws.com" 193 | }, 194 | "Action": "sts:AssumeRole" 195 | } 196 | ] 197 | }), 198 | inlinePolicies: [{name: "athenamysql", policy: pulumi.all([currentRegion, currentAccount, athenaResultsBucket.bucket]).apply(([region, account, bucket]) => JSON.stringify({ 199 | Version: "2012-10-17", 200 | Statement: [ 201 | { 202 | "Effect": "Allow", 203 | "Action": [ 204 | "secretsmanager:GetSecretValue", 205 | ], 206 | "Resource": `arn:aws:secretsmanager:${region}:${account}:secret:AthenaSecret*` 207 | }, 208 | { 209 | "Effect": "Allow", 210 | "Action": [ 211 | "logs:CreateLogGroup", 212 | ], 213 | "Resource": `arn:aws:logs:${region}:${account}*` 214 | }, 215 | { 216 | "Effect": "Allow", 217 | "Action": [ 218 | "logs:CreateLogStream", 219 | "logs:PutLogEvents" 220 | ], 221 | "Resource": `arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambdaFunctionName}:*` 222 | }, 223 | { 224 | "Effect": "Allow", 225 | "Action": [ 226 | "athena:GetQueryExecution", 227 | "s3:ListAllMyBuckets" 228 | ], 229 | "Resource": "*" 230 | }, 231 | { 232 | "Effect": "Allow", 233 | "Action": [ 234 | "s3:GetObject", 235 | "s3:ListBucket", 236 | "s3:GetBucketLocation", 237 | "s3:GetObjectVersion", 238 | "s3:PutObject", 239 | "s3:PutObjectAcl", 240 | "s3:GetLifecycleConfiguration", 241 | "s3:PutLifecycleConfiguration", 242 | "s3:DeleteObject" 243 | ], 244 | "Resource": [ 245 | `arn:aws:s3:::${bucket}`, 246 | `arn:aws:s3:::${bucket}/*` 247 | ] 248 | }, 249 | { 250 | "Effect": "Allow", 251 | "Action": [ 252 | "logs:CreateLogStream", 253 | "logs:PutLogEvents" 254 | ], 255 | "Resource": `arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambdaFunctionName}:*` 256 | }, 257 | { 258 | "Effect": "Allow", 259 | "Action": [ 260 | "ec2:CreateNetworkInterface", 261 | "ec2:DeleteNetworkInterface", 262 | "ec2:DescribeNetworkInterfaces", 263 | "ec2:DetachNetworkInterface" 264 | ], 265 | "Resource": "*" 266 | } 267 | ], 268 | }))}] 269 | }); 270 | 271 | const variables = { 272 | "default": pulumi.interpolate `mysql://jdbc:mysql://root:${mysqlPassword}@${mysql.endpoint}/mydb`, 273 | "disable_spill_encryption": "false", 274 | "spill_bucket": athenaResultsBucket.bucket, 275 | "spill_prefix": "athena-spill", 276 | } 277 | 278 | const envName = `${lambdaFunctionName}_connection_string`; 279 | 280 | // @ts-ignore 281 | variables[envName]= pulumi.interpolate `mysql://jdbc:mysql://root:${mysqlPassword}@${mysql.endpoint}/mydb`; 282 | 283 | const mysqlFunction = new aws.lambda.Function("athena.mysql.connector", { 284 | name: lambdaFunctionName, 285 | handler: "com.amazonaws.athena.connectors.mysql.MySqlMuxCompositeHandler", 286 | runtime: "java11", 287 | role: athenaLambdaRole.arn, 288 | s3Bucket: "awsserverlessrepo-changesets-1f9ifp952i9h0", 289 | s3Key: "577407151357/arn:aws:serverlessrepo:us-east-1:292517598671:applications-AthenaMySQLConnector-versions-2022.42.2/b7e4dd5b-a49b-4769-a1fd-69beb31d0bfc", 290 | timeout: 900, 291 | memorySize: 3008, 292 | ephemeralStorage: { 293 | size: 512 294 | }, 295 | 296 | vpcConfig: { 297 | securityGroupIds: mysql.vpcSecurityGroupIds, 298 | subnetIds: vpc.publicSubnetIds 299 | }, 300 | packageType: "Zip", 301 | environment: { 302 | variables: variables 303 | } 304 | }); 305 | 306 | // Ensure that Athena can invoke the mysql connector. 307 | const allowLambdaInvoke = new aws.iam.RolePolicy("athena.lambda.invoke", { 308 | role: athenaRole, 309 | policy: pulumi.all([mysqlFunction.arn]).apply(([arn]) => JSON.stringify({ 310 | Version: "2012-10-17", 311 | Statement: [{ 312 | Action: ["lambda:InvokeFunction"], 313 | Effect: "Allow", 314 | Resource: arn, 315 | }], 316 | })), 317 | }); 318 | 319 | // Register the mysql connector lambda in the Athena catalog. 320 | const mysqlCatalog = new aws.athena.DataCatalog("athena.lambda.catalog", { 321 | name: mysqlFunction.name, 322 | description: "Mysql connection", 323 | parameters: { 324 | "metadata-function": mysqlFunction.arn, 325 | "record-function": mysqlFunction.arn, 326 | }, 327 | type: "LAMBDA", 328 | }); 329 | 330 | // Create a role that gives Snowflake access to our rest api. 331 | const snowflakeExternalFunctionInvocationRole = new aws.iam.Role("rest.snowflakeInvocationRole", { 332 | name: functionInvocationRoleName, 333 | assumeRolePolicy: pulumi.all([snowflakeApiIntegration.apiAwsIamUserArn, snowflakeApiIntegration.apiAwsExternalId]).apply(([role, externalId]) => JSON.stringify({ 334 | Version: "2012-10-17", 335 | Statement: [{ 336 | "Effect": "Allow", 337 | "Principal": { 338 | "AWS": role 339 | }, 340 | "Action": "sts:AssumeRole", 341 | "Condition": { 342 | "StringEquals": { 343 | "sts:ExternalId": externalId 344 | } 345 | } 346 | }], 347 | })) 348 | }, {dependsOn: snowflakeApiIntegration}); 349 | 350 | // The function that will query Athena 351 | const athenaExternalFunction = new GenericSnowflake("snowflake.athenaExternalFunction", { 352 | type: "EXTERNAL FUNCTION", 353 | name: "ATHENA_EXTERNAL_FUNCTION", 354 | database: db.name, 355 | schema: schema.name, 356 | args: [ 357 | {name: "mode", type: "string"}, 358 | {name: "sql", type: "string"}, 359 | {name: "execution_id", type: "string"}, 360 | {name: "starting_token", type: "string"}, 361 | {name: "max_results_per_page", type: "integer"} 362 | ], 363 | theRest: pulumi.interpolate ` 364 | returns variant 365 | API_INTEGRATION = "${snowflakeApiIntegration.name}" 366 | REQUEST_TRANSLATOR = "${requestTranslator.name}" 367 | RESPONSE_TRANSLATOR = "${responseTranslator.name}" 368 | CONTEXT_HEADERS = (CURRENT_TIMESTAMP) 369 | MAX_BATCH_ROWS = 1 370 | as 'https://${restApi.id}.execute-api.${currentRegion}.amazonaws.com/prod/athena'; 371 | ` 372 | }, {deleteBeforeReplace: true, replaceOnChanges: ["*"]}); 373 | 374 | const queryFunction = new GenericSnowflake("snowflake.athenaQueryUDTF", { 375 | type: "FUNCTION", 376 | name: "QUERY_ATHENA", 377 | database: db.name, 378 | schema: schema.name, 379 | args: [ 380 | {name: "sql", type: "string"}, 381 | {name: "max_results_per_page", type: "integer"} 382 | ], 383 | theRest: pulumi.interpolate `returns table(data object) as $$ 384 | ${file('snowflake/table_function_body.sql')} 385 | $$;` 386 | }, { 387 | dependsOn: [athenaExternalFunction], 388 | deleteBeforeReplace: true, 389 | replaceOnChanges: ["*"] 390 | }); 391 | 392 | const apiPolicy = new aws.apigateway.RestApiPolicy("rest.snowflakePolicy", { 393 | restApiId: restApi.id, 394 | policy: pulumi.all([currentAccount, restApi.id, currentRegion, snowflakeExternalFunctionInvocationRole.name]).apply(([accountId, apiGatewayId, currentRegion, invocationRole]) => JSON.stringify({ 395 | Version: "2012-10-17", 396 | Statement: [{ 397 | "Effect": "Allow", 398 | "Principal": { 399 | "AWS": `arn:aws:sts::${accountId}:assumed-role/${invocationRole}/snowflake` 400 | }, 401 | "Action": "execute-api:Invoke", 402 | "Resource": `arn:aws:execute-api:${currentRegion}:${accountId}:${apiGatewayId}/*` 403 | }] 404 | })) 405 | }, {dependsOn: [mysqlFunction /** add lambda wait here to minimize race problems **/]}); 406 | 407 | // deploy the rest api. 408 | const apiDeployment = new aws.apigateway.Deployment("rest.deployment", { 409 | restApi: restApi.id, 410 | triggers: { 411 | redeployment: restApi.body.apply(body => JSON.stringify(body)).apply(toJSON => crypto.createHash('sha1').update(String(toJSON)).digest('hex')), 412 | }, 413 | }, {dependsOn: [apiPolicy, postMethod200Response, athenaPostIntegrationResponse]}); 414 | 415 | // define a stage to deploy to. 416 | const prodStage :aws.apigateway.Stage = new aws.apigateway.Stage("rest.prodStage", { 417 | deployment: apiDeployment.id, 418 | restApi: restApi.id, 419 | stageName: "prod" 420 | }, {dependsOn: [apiPolicy]}); 421 | 422 | // internal function to read in as a string a file (used for snowflake object imports) 423 | function file(fileName: string): string { 424 | return fs.readFileSync(fileName, 'utf8'); 425 | } 426 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "athena", 3 | "main": "index.ts", 4 | "devDependencies": { 5 | "@types/node": "^14" 6 | }, 7 | "dependencies": { 8 | "@pulumi/aws": "^5.0.0", 9 | "@pulumi/aws-apigateway": "^0.0.11", 10 | "@pulumi/aws-native": "^0.38.0", 11 | "@pulumi/awsx": "^0.40.1", 12 | "@pulumi/pulumi": "^3.0.0", 13 | "@pulumi/random": "^4.8.2", 14 | "@pulumi/snowflake": "^0.14.0", 15 | "@types/snowflake-sdk": "^1.6.8", 16 | "snowflake-promise": "^4.5.0", 17 | "snowflake-sdk": "^1.6.14" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /snowflake/SnowflakeGenericProvider.ts: -------------------------------------------------------------------------------- 1 | import * as pulumi from "@pulumi/pulumi"; 2 | import {ID} from "@pulumi/pulumi/resource"; 3 | import { Snowflake } from 'snowflake-promise'; 4 | 5 | 6 | export interface SnowflakeResourceInputs { 7 | database: pulumi.Input; 8 | schema: pulumi.Input; 9 | name: pulumi.Input; 10 | type: pulumi.Input; 11 | args: pulumi.Input; 12 | theRest: pulumi.Input; 13 | } 14 | 15 | export interface FunctionArgumentInputs { 16 | name: pulumi.Input, 17 | type: pulumi.Input 18 | } 19 | 20 | interface FunctionArgument { 21 | name: string, 22 | type: string 23 | } 24 | 25 | interface SnowflakeInputs { 26 | database: string; 27 | schema: string; 28 | name: string; 29 | type: "FUNCTION" | "EXTERNAL FUNCTION"; 30 | args: FunctionArgument[]; 31 | theRest: string; 32 | } 33 | 34 | function createArgString(inputs: SnowflakeInputs ){ 35 | return inputs.args.map(f => `${f.name} ${f.type}`).join(', '); 36 | } 37 | 38 | function dropArgString(inputs: SnowflakeInputs ){ 39 | return inputs.args.map(f => f.type).join(', '); 40 | } 41 | 42 | function getId(inputs: SnowflakeInputs){ 43 | return `"${inputs.database}"."${inputs.schema}"."${inputs.name}"` 44 | } 45 | 46 | class SnowflakeProvider implements pulumi.dynamic.ResourceProvider { 47 | connection: Snowflake | undefined = undefined; 48 | connected: boolean = false; 49 | 50 | async create(inputs: SnowflakeInputs) { 51 | await this.connectIfNotConnected(); 52 | await runsql(this.connection, inputs.database, inputs.schema, `CREATE ${inputs.type} ${getId(inputs)}(${createArgString(inputs)}) ${inputs.theRest}`); 53 | const output = { id: getId(inputs) , outs: {database: inputs.database, schema: inputs.schema, name: inputs.name, type: inputs.type, theRest: inputs.theRest, args: inputs.args}}; 54 | pulumi.log.debug(JSON.stringify(output)); 55 | return output; 56 | } 57 | 58 | async connectIfNotConnected() { 59 | if(!this.connected) { 60 | pulumi.log.debug("Connecting."); 61 | const config = new pulumi.Config("snowflake"); 62 | const account = config.require("account"); 63 | const username = config.require("username"); 64 | this.connection = new Snowflake({ 65 | account: account, 66 | username: username, 67 | authenticator: "EXTERNALBROWSER" 68 | }); 69 | await this.connection.connectAsync(); 70 | pulumi.log.debug("Connected."); 71 | this.connected = true; 72 | } 73 | } 74 | 75 | async delete(id: ID, inputs: SnowflakeInputs) { 76 | await this.connectIfNotConnected(); 77 | pulumi.log.debug(`database: ${inputs.database} schema: ${inputs.schema}, args: ${(JSON.stringify(inputs.args))}, name: ${inputs.name}`); 78 | await runsql(this.connection, inputs.database, inputs.schema, `DROP FUNCTION ${getId(inputs)}(${dropArgString(inputs)}) `); 79 | } 80 | 81 | } 82 | 83 | const snowflakeGenericProvider= new SnowflakeProvider(); 84 | 85 | interface SnowflakeConfig { 86 | account: string; 87 | username: string; 88 | } 89 | 90 | export class GenericSnowflake extends pulumi.dynamic.Resource { 91 | constructor(name: string, args: SnowflakeResourceInputs, opts?: pulumi.CustomResourceOptions) { 92 | super(snowflakeGenericProvider, name, args, opts); 93 | } 94 | } 95 | 96 | async function runsql(connection: Snowflake | undefined, database: string, schema: string, sql: string) { 97 | pulumi.log.debug("runsql: " + sql ); 98 | await connection?.execute(`USE "${database}"."${schema}"`); 99 | return connection?.execute(sql); 100 | } 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /snowflake/request_translator.js: -------------------------------------------------------------------------------- 1 | 2 | function translate_request(EVENT) { 3 | if(!EVENT.body.data[0][1]) { 4 | throw new Error("Mode must be provided."); 5 | } 6 | let row = EVENT.body.data[0][0]; 7 | let mode = EVENT.body.data[0][1].toLowerCase(); 8 | let sql = EVENT.body.data[0][2]; 9 | let execution_id = EVENT.body.data[0][3]; 10 | let starting_token = EVENT.body.data[0][4]; 11 | let max_results_per_page = EVENT.body.data[0][5]; 12 | 13 | switch(mode) { 14 | 15 | case "submit": 16 | if(!sql || execution_id || starting_token) { 17 | throw new Error("A non-null SQL argument must be passed for Submission."); 18 | } 19 | return { 20 | "translatorData": {"mode" : mode}, 21 | "urlSuffix" : "?action=AmazonAthena.StartQueryExecution", 22 | "body": { "QueryString": sql, 23 | "ClientRequestToken": EVENT.contextHeaders["sf-context-current-timestamp"] + "xxxxxxxxxxxxxxxx", 24 | "ResultConfiguration": {"OutputLocation": "s3://INSERTBUCKETNAMEHERE/"} 25 | }, 26 | }; 27 | case "pending": 28 | if(sql || !execution_id || starting_token) { 29 | throw new Error("Only execution id should be passed for pending." + sql + " " + execution_id + " " + starting_token); 30 | } 31 | return { 32 | "urlSuffix" : "?action=AmazonAthena.GetQueryExecution", 33 | "body": {"QueryExecutionId": execution_id}, 34 | "translatorData": {"mode" : mode, "execution_id": execution_id}, 35 | }; 36 | case "first_page": 37 | if(sql || !execution_id || starting_token) { 38 | throw new Error("First page should have execution id but no sql or starting token."); 39 | } 40 | return { 41 | "urlSuffix" : "?action=AmazonAthena.GetQueryResults", 42 | "translatorData": {"mode" : mode, "execution_id": execution_id}, 43 | "body": { 44 | "QueryExecutionId": execution_id, 45 | "MaxResults": max_results_per_page 46 | }}; 47 | 48 | case "subsequent_page": 49 | if(sql || !execution_id || !starting_token) { 50 | throw new Error("Next page should have execution id and starting token but no sql."); 51 | } 52 | return { 53 | "urlSuffix" : "?action=AmazonAthena.GetQueryResults", 54 | "translatorData": {"mode" : mode, "execution_id": execution_id}, 55 | "body": { 56 | "QueryExecutionId": execution_id, 57 | "MaxResults": max_results_per_page, 58 | "NextToken": starting_token 59 | }, 60 | }; 61 | 62 | default: 63 | throw new Error("Unknown mode submitted."); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /snowflake/response_translator.js: -------------------------------------------------------------------------------- 1 | 2 | function translate_response(EVENT) { 3 | try { 4 | let mode = EVENT.translatorData.mode; 5 | switch(mode) { 6 | case "submit": 7 | return { 8 | "body": { data: [[0, {execution_id: EVENT.body.QueryExecutionId, mode: "pending"}]]} 9 | } 10 | case "pending": 11 | switch(EVENT.body.QueryExecution.Status.State) { 12 | case "SUCCEEDED": 13 | return { 14 | "body": { data: [[0, {execution_id: EVENT.translatorData.execution_id, mode: "first_page"}]]} 15 | } 16 | case "FAILED": 17 | throw new Error(EVENT.body.QueryExecution.Status.StateChangeReason); 18 | } 19 | // let us try again. ideally we would use await here but it is not clear on how to do this inside of snowflake. 20 | //await new Promise(r => setTimeout(r, 75)); 21 | return { 22 | "body": { data: [[0, {execution_id: EVENT.translatorData.execution_id, mode: "pending"}]]} 23 | } 24 | case "first_page": 25 | case "subsequent_page": 26 | const body = EVENT.body; 27 | let records = new Array(); 28 | let columns = body.ResultSet.ColumnInfos; 29 | for (let i = mode == "subsequent_page" ? 0 : 1; i < body.ResultSet.Rows.length; i++) { 30 | let row = body.ResultSet.Rows[i].Data; 31 | let o = new Object(); 32 | for(let h = 0; h < columns.length; h++) { 33 | let name = columns[h].Name; 34 | let value = row[h].VarCharValue; 35 | switch(columns[h].Type) { 36 | case "boolean": 37 | value = Boolean(value); 38 | break; 39 | case "tinyint": 40 | case "smallint": 41 | case "integer": 42 | value = parseInt(value); 43 | break; 44 | } 45 | 46 | o[name] = value; 47 | } 48 | 49 | records.push(o); 50 | } 51 | let data = { 52 | mode: "subsequent_page", 53 | execution_id: EVENT.translatorData.execution_id, 54 | next: body.NextToken, 55 | data: records 56 | }; 57 | return { 58 | "body": { data: [[0, data]]} 59 | }; 60 | default: 61 | return { 62 | "body": { data: [[0, EVENT.body]] } 63 | } 64 | } 65 | } catch(err) { 66 | //throw new Error(err.message + JSON.stringify(EVENT.body)) 67 | throw new Error(err.message) ; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /snowflake/table_function_body.sql: -------------------------------------------------------------------------------- 1 | SELECT f1.value::object FROM ( 2 | WITH paginated(response, data) 3 | AS ( 4 | SELECT 5 | object_construct('sql', sql, 'mode', 'submit')::variant, 6 | cast(null as variant) 7 | UNION ALL 8 | SELECT 9 | athena_external_function(response:mode::text, response:sql::text, response:execution_id::text, response:next::text, max_results_per_page) as tx, 10 | tx:data 11 | FROM paginated 12 | where response:mode::text in ('pending', 'submit', 'first_page') OR response:next::text is not null 13 | ) 14 | SELECT 15 | data 16 | FROM 17 | paginated 18 | WHERE data is not null) f0, 19 | LATERAL FLATTEN(input => f0.data) f1 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "outDir": "bin", 5 | "target": "es2016", 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "sourceMap": true, 9 | "experimentalDecorators": true, 10 | "pretty": true, 11 | "noFallthroughCasesInSwitch": true, 12 | "noImplicitReturns": true, 13 | "forceConsistentCasingInFileNames": true 14 | }, 15 | "files": [ 16 | "index.ts" 17 | ] 18 | } 19 | --------------------------------------------------------------------------------