athenadriver

athenadriver

功能完善的AWS Athena Go语言数据库驱动

athenadriver是功能完善的AWS Athena数据库Go语言驱动程序。该项目支持多种AWS授权方式,兼容全部Athena数据类型和查询语句,提供工作组和标签管理、查询取消、只读模式等高级特性。内置的日志和指标功能有助于简化Athena查询代码。作为开源项目,athenadriver为Go开发者提供了便捷的AWS Athena数据库查询方案。

athenadriverAWS AthenaGo数据库驱动SQL查询Github开源项目

[![CodeCov][cov-img]][cov] [![GoDoc][doc-img]][doc] [![Github release][release-img]][release] [![Go Report Card][report-card-img]][report-card] [![lic][license-img]][license] [![made][made-img]][made]


:package: athenadriver - A fully-featured AWS Athena database driver for Go
:shell: athenareader - A moneywise command line utililty to query athena in command line.


Overview

(This project is a sandbox project and the development status is STABLE.)

athenadriver is a fully-featured AWS Athena database driver for Go developed at Uber Technologies Inc. It provides a hassle-free way of querying AWS Athena database with Go standard library. It not only provides basic features of Athena Go SDK, but addresses some SDK's limitation, improves and extends it. Moreover, it also includes advanced features like Athena workgroup and tagging creation, driver read-only mode and so on.

The PDF version of AthenaDriver document is available at :scroll:

Features

Except the basic features provided by Go database/sql like error handling, database pool and reconnection, athenadriver supports the following features out of box:

  • Support multiple AWS authorization methods :link:
  • Full support of Athena Basic Data Types
  • Full support of Athena Advanced Type for queries with Geospatial identifiers, ML and UDFs
  • Full support of ALL Athena Query Statements, including DDL, DML and UTILITY :link:
  • Support newly added INSERT INTO...VALUES
  • Athena workgroup and tagging support including remote workgroup creation :link:
  • Go sql's prepared statement support :link:
  • Go sql's DB.Exec() and db.ExecContext() support :link:
  • Query cancelling support :link:
  • Override default query timeout limits :link:
  • Mask columns with specific values :link:
  • Database missing value handling :link:
  • Read-Only mode - disable database write in driver level :link:
  • Moneywise mode :moneybag: - print out query cost(USD) for each query
  • Query with Athena Query ID(QID) - (the ultimate money saver! :money_with_wings: )
  • Pseudo commands from database/sql interface: get_driver_version, get_query_id, get_query_id_status, stop_query_id, get_workgroup, list_workgroups, update_workgroup, get_cost, get_execution_report etc :link:
  • Builtin logging support with zap :link:
  • Builtin metrics support with tally :link:

athenadriver can extremely simplify your code. Check athenareader out as an example and a convenient tool for your Athena query in command line.

How to set up/install/test athenadriver

Prerequisites - AWS Credentials & S3 Query Result Bucket

To be able to query AWS Athena, you need to have an AWS account at Amazon AWS's website. To give it a shot, a free tier account is enough. You also need to have a pair of AWS access key ID and secret access key. You can get it from AWS Security Credentials section of Identity and Access Management (IAM). If you don't have one, please create it. The following is a screenshot from my temporary free tier account:

How to create AWS credentials

In addition to AWS credentials, you also need an s3 bucket to store query result. Just go to AWS S3 web console page to create one. In the examples below, the s3 bucket I use is s3://myqueryresults/.

In most cases, you need the following 4 prerequisites:

  • S3 Output bucket
  • access key ID
  • secret access key
  • AWS region

For more details on athenadriver's support on AWS credentials & S3 query result bucket, please refer to section Support Multiple AWS Authorization Methods.

Installation

Before Go 1.17, go get can be used to install athenadriver:

go get -u github.com/uber/athenadriver

Starting in Go 1.17, installing executables with go get is deprecated. go install may be used instead.

go install github.com/uber/athenadriver@latest

Tests

We provide unit tests and integration tests in the codebase.

Unit Test

All the unit tests are self-contained and passed even in no-internet environment. Test coverage is 100%.

$ cd $GOPATH/src/github.com/uber/athenadriver/go ✔ /opt/share/go/path/src/github.com/uber/athenadriver [uber|1…12] 21:35 $ go test -coverprofile=coverage.out github.com/uber/athenadriver/go && \ go tool cover -func=coverage.out |grep -v 100.0% ok github.com/uber/athenadriver/go 9.255s coverage: 100.0% of statements

Integration Test

All integration tests are under examples folder. Please make sure all prerequisites are met so that you can run the code on your own machine.

All the code snippets in examples folder are fully tested in our machines. For example, to run some stress and crash test, you can use examples/perf/concurrency.go. Build it first:

$cd $GOPATH/src/github.com/uber/athenadriver $go build examples/perf/concurrency.go

Run it, wait for some output but not all, and unplug your network cable:

$./concurrency > examples/perf/concurrency.output.`date +"%Y-%m-%d-%H-%M-%S"`.log 58,13,53,54,78,96,32,48,40,11,35,31,65,61,1,73,74,22,34,49,80,5,69,37,0,79, 2020/02/09 13:49:29 error [38]RequestError: send request failed caused by: Post https://athena.us-east-1.amazonaws.com/: dial tcp: lookup athena.us-east-1.amazonaws.com: no such host ... 2020/02/09 13:49:29 error [89]RequestError: send request failed caused by: Post https://athena.us-east-1.amazonaws.com/: dial tcp: lookup athena.us-east-1.amazonaws.com: no such host

You can see RequestError is thrown out from the code. The active Athena queries failed because the network is down. Now re-plugin your cable and wait for network coming back, you can see the program automatically reconnects to Athena, and resumes to output data correctly:

72,25,92,98,15,93,41,7,8,90,81,56,66,2,18,84,87,63, 44,45,82,99,86,3,52,76,71,16,39,67,23,12,42,17,4,

How to use athenadriver

athenadriver is very easy to use. What you need to do it to import it in your code and then use the standard Go database/sql as usual.

import athenadriver "github.com/uber/athenadriver/go"

The following are coding examples to demonstrate athenadriver's features and how you should use athenadriver in your Go application. Please be noted the code is for demonstration purpose only, so please follow your own coding style or best practice if necessary.

Get Started - A Simple Query

The following is the simplest example for demonstration purpose. The source code is available at dml_select_simple.go.

package main import ( "database/sql" drv "github.com/uber/athenadriver/go" ) func main() { // Step 1. Set AWS Credential in Driver Config. conf, _ := drv.NewDefaultConfig("s3://myqueryresults/", "us-east-2", "DummyAccessID", "DummySecretAccessKey") // Step 2. Open Connection. db, _ := sql.Open(drv.DriverName, conf.Stringify()) // Step 3. Query and print results var url string _ = db.QueryRow("SELECT url from sampledb.elb_logs limit 1").Scan(&url) println(url) }

To make it work for you, please replace OutputBucket, Region, AccessID and SecretAccessKey with your own values. sampledb is provided by Amazon so you don't have to worry about it.

To Build it:

$ go build examples/query/dml_select_simple.go

Run it and you can see output like:

$ ./dml_select_simple https://www.example.com/articles/553

Support Multiple AWS Authentication Methods

athenadriver uses access keys(Access Key ID and Secret Access Key) to sign programmatic requests to AWS. When if the AWS_SDK_LOAD_CONFIG environment variable was set, athenadriver uses Shared Config, respects AWS CLI Configuration and Credential File Settings and gives it even higher priority over the values set in athenadriver.Config.

Use AWS CLI Config For Authentication

When environment variable AWS_SDK_LOAD_CONFIG is set, it will read aws_access_key_id(AccessID) and aws_secret_access_key(SecretAccessKey) from ~/.aws/credentials, region from ~/.aws/config. For details about ~/.aws/credentials and ~/.aws/config, please check here.

But you still need to specify correct OutputBucket in athenadriver.Config because it is not in the AWS client config.

OutputBucket is critical in Athena. Even if you have a default value set in Athena web console, you must pass one programmatically or you will get error: No output location provided. An output location is required either through the Workgroup result configuration setting or as an API input.

The sample code below enforces AWS_SDK_LOAD_CONFIG is set, so athenadriver's AWS Session will be created from the configuration values from the shared config (~/.aws/config) and shared credentials (~/.aws/credentials) files. Even if we pass all dummy values as parameters in NewDefaultConfig() except OutputBucket, they are overridden by the values in AWS CLI config files, so it doesn't really matter.

// To use AWS CLI's Config for authentication func useAWSCLIConfigForAuth() { os.Setenv("AWS_SDK_LOAD_CONFIG", "1") // 1. Set AWS Credential in Driver Config. conf, err := drv.NewDefaultConfig(secret.OutputBucketProd, drv.DummyRegion, drv.DummyAccessID, drv.DummySecretAccessKey) if err != nil { return } // 2. Open Connection. db, _ := sql.Open(drv.DriverName, conf.Stringify()) // 3. Query and print results var i int _ = db.QueryRow("SELECT 456").Scan(&i) println("with AWS CLI Config:", i) os.Unsetenv("AWS_SDK_LOAD_CONFIG") }

If your AWS CLI setting is valid like mine, this function should output:

with AWS CLI Config: 456

The above authentication method also works for querying Athena in AWS Lambda. In lambda, you don't have to provide access ID, key and region, and you don't need AWS CLI config files either. You just need to specify the correct output bucket. Please check the AWS Lambda Go same code here.

Use athenadriver Config For Authentication

When environment variable AWS_SDK_LOAD_CONFIG is NOT set, you may explicitly define credentials by passing valid (NOT dummy) accessID, secretAccessKey, region, and outputBucket into athenadriver.NewDefaultConfig().

The sample code below ensure AWS_SDK_LOAD_CONFIG is not set, then pass four valid parameters into NewDefaultConfig():

// To use athenadriver's Config for authentication func useAthenaDriverConfigForAuth() { os.Unsetenv("AWS_SDK_LOAD_CONFIG") // 1. Set AWS Credential in Driver Config. conf, err := drv.NewDefaultConfig(secret.OutputBucketDev, secret.Region, secret.AccessID, secret.SecretAccessKey) if err != nil { return } // 2. Open Connection. db, _ := sql.Open(drv.DriverName, conf.Stringify()) // 3. Query and print results var i int _ = db.QueryRow("SELECT 123").Scan(&i) println("with AthenaDriver Config:", i) }

The sample output:

with AthenaDriver Config: 123

The full code is here at examples/auth.go.

Use AWS SDK Default Credentials Resolution for Authentication

If environment variable AWS_SDK_LOAD_CONFIG is NOT set and credentials are not supplied in the athenadriver configuration, the AWS SDK will look up credentials using its default methodology described here: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-credentials.

Region and OutputBucket bucket still need to be explictly defined.

The sample code below ensures AWS_SDK_LOAD_CONFIG is not set, then creates a athenadriver config with OutputBucket and Region values set.

// To use AWS SDK Default Credentials func useAthenaDriverConfigForAuth() { os.Unsetenv("AWS_SDK_LOAD_CONFIG") // 1. Set OutputBucket and Region in Driver Config. conf := drv.NewNoOpsConfig() conf.SetOutputBucket(secret.OutputBucketDev) conf.SetRegion(secret.Region) // 2. Open Connection. db, _ := sql.Open(drv.DriverName, conf.Stringify()) // 3. Query and print results var i int _ = db.QueryRow("SELECT 123").Scan(&i) println("with AthenaDriver Config:", i) }

The sample output:

with AthenaDriver Config: 123

Full Support of All Data Types

As we said, athenadriver supports all Athena data types. In the following sample code, we use an SQL statement to SELECT som simple data of all the advanced types and then print them out.

package main import ( "context" "database/sql" drv "github.com/uber/athenadriver/go" ) func main() { // 1. Set AWS Credential in Driver Config. conf, err := drv.NewDefaultConfig("s3://myqueryresults/", "us-east-2", "DummyAccessID", "DummySecretAccessKey") if err != nil { panic(err) } // 2. Open Connection. dsn := conf.Stringify() db, _ := sql.Open(drv.DriverName, dsn) // 3. Query and print results query := "SELECT JSON '\"Hello Athena\"', " + "ST_POINT(-74.006801, 40.70522), " + "ROW(1, 2.0), INTERVAL '2' DAY, " + "INTERVAL '3' MONTH, " + "TIME '01:02:03.456', " + "TIME '01:02:03.456 America/Los_Angeles', " + "TIMESTAMP '2001-08-22 03:04:05.321 America/Los_Angeles';" rows, err := db.Query(query) if err != nil { panic(err) } defer rows.Close() println(drv.ColsRowsToCSV(rows)) }

Sample output:

"Hello Athena",00 00 00 00 01 01 00 00 00 20 25 76 6d 6f 80

编辑推荐精选

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

下拉加载更多