awql

package module
v0.1.19 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2018 License: MIT Imports: 16 Imported by: 6

README

Awql Database Driver

GoDoc Build Status Code Coverage Go Report Card

AWQL driver for Go's sql package.

Installation

Simple install the package to your $GOPATH with the go tool:

~ $ go get -u github.com/rvflash/awql-driver

Usage

AWQL Driver is an implementation of Go's database/sql/driver interface. You only need to import the driver and can use the full database/sql API then.

Use awql as driverName and a valid DSN as dataSourceName:

import "database/sql"
import _ "github.com/rvflash/awql-driver"

db, err := sql.Open("awql", "AdwordsID:APIVersion|DeveloperToken|AccessToken")

Data Source Name

The Data Source Name has two common formats, the optional parts are marked by squared brackets:

Minimal
AdwordsID|DeveloperToken[|AccessToken]
OAuth credentials
AdwordsID|DeveloperToken[|ClientID|ClientSecret|RefreshToken]

The first part with AdwordsID can contains Adwords API options. A DSN in its fullest form:

AdwordsID[:APIVersion:SupportsZeroImpressions:SkipColumnHeader:UseRawEnumValues]|DeveloperToken[|AccessToken][|ClientID|ClientSecret|RefreshToken]

Alternatively, NewDSN can be used to create a DSN string by filling a struct.

AdwordsID

The client customer ID is the account number of the AdWords client account you want to manage via the API, usually in the form 123-456-7890.

APIVersion
Type:           string
Valid Values:   <version>
Default:        v201809

Version of the Adwords API to use.

SupportsZeroImpressions
Type:           bool
Valid Values:   true, false
Default:        false

If true, report output will include rows where all specified metric fields are zero, provided the requested fields and predicates support zero impressions. If false, report output will not include such rows. Thus, even if this header is false and the Impressions of a row is zero, the row is still returned in case any of the specified metric fields have non-zero values.

SkipColumnHeader
Type:           bool
Valid Values:   true, false
Default:        false

If true, report output will not include a header row containing field names. If false or not specified, report output will include the field names.

UseRawEnumValues
Type:           bool
Valid Values:   true, false
Default:        false

Set to true if you want the returned format to be the actual enum value, for example, "IMAGE_AD" instead of "Image ad". Set to false or omit this header if you want the returned format to be the display value.

DeveloperToken

The developer token identifies your app to the AdWords API. Only approved tokens can connect to the API for production AdWords accounts; pending tokens can connect only to test accounts.

AccessToken

Use to grant connection to Google API

ClientID

Client identifier, used to connect to Adwords with OAuth2.

ClientSecret

Client secret, used to connect to Adwords with OAuth2.

RefreshToken

Because OAuth2 access expires after a limited time, an OAuth2 refresh token is used to automatically renew OAuth2 access.

Examples

Simple Awql query
// Ignores errors for the demo.
query := "SELECT ExternalCustomerId, AccountDescriptiveName FROM ACCOUNT_PERFORMANCE_REPORT"
db, _ := sql.Open("awql", "123-456-7890|dEve1op3er7okeN|ya29.Acc3ss-7ok3n")
stmt, _ := db.Query(query)
for stmt.Next() {
    var id int
    var name string
    stmt.Scan(&id, &name)
    fmt.Printf("%v: %v\n", id, name)
    // Output: 1234567890: Rv
}
Awql query row with arguments
// Ignores errors for the demo.
var name string
query := "SELECT CampaignName FROM CAMPAIGN_PERFORMANCE_REPORT Where CampaignId = ?"
row := db.QueryRow(query, 123456789)
row.Scan(&name)
fmt.Printf("%v\n", name)
// Output: Campaign #19
Advanced sample
// Instantiates a data source name.
dsn := awql.NewDsn("123-456-7890")
dsn.DeveloperToken = "dEve1op3er7okeN"
dsn.ClientID = "1234567890-Aw91.apps.googleusercontent.com"
dsn.ClientSecret = "C13nt5e0r3t"
dsn.RefreshToken = "1/n-R3fr35h70k3n"

// Ignores errors for the demo.
query := "SELECT ConversionTypeName, AllConversions, ConversionValue FROM CRITERIA_PERFORMANCE_REPORT DURING LAST_7_DAYS"
db, _ := sql.Open("awql", dsn.String())
stmt, _ := db.Query(query)
cols, _ := stmt.Columns()
fmt.Printf("%q\n", cols)
// Output: ["Conversion name" "All conv." "Total conv. value"]

// Copy references into the slice
size := len(cols)
vals := make([]string, size)
ints := make([]interface{}, size)
for i := range ints {
    ints[i] = &vals[i]
}
for stmt.Next() {
    stmt.Scan(ints...)
    fmt.Printf("%q\n", vals)
}
// Output:
// ["Transactions (Phone)" "6.0" "362.33"]
// ["Transactions (Web)" "1.0" "89.3"]

Documentation

Index

Constants

View Source
const (
	APIVersion = "v201809"
	DsnSep     = "|"
	DsnOptSep  = ":"
)

Data source name.

Variables

View Source
var (
	ErrQuery        = NewQueryError("missing")
	ErrQueryBinding = NewQueryError("binding not match")
	ErrNoDsn        = NewConnectionError("missing data source")
	ErrNoNetwork    = NewConnectionError("not found")
	ErrBadNetwork   = NewConnectionError("service unavailable")
	ErrBadToken     = NewConnectionError("invalid access token")
	ErrAdwordsID    = NewConnectionError("adwords id")
	ErrDevToken     = NewConnectionError("developer token")
)

Error messages.

Functions

func NewAPIError added in v0.1.10

func NewAPIError(d []byte) error

NewAPIError parses a XML document that represents a download report error. It returns the given message as error.

func NewConnectionError

func NewConnectionError(text string) error

NewConnectionError returns an error of type Connection with the given text.

func NewQueryError

func NewQueryError(text string) error

NewQueryError returns an error of type Internal with the given text.

Types

type APIError added in v0.1.10

type APIError struct {
	Type    string `xml:"ApiError>type"`
	Trigger string `xml:"ApiError>trigger"`
	Field   string `xml:"ApiError>fieldPath"`
}

APIError represents a Google Report Download Error. It voluntary ignores trigger field.

In case of error, Google Adwords API provides more information in a XML response:

<reportDownloadError>
	<ApiError>
		<type>ReportDefinitionError.CUSTOMER_SERVING_TYPE_REPORT_MISMATCH</type>
		<trigger></trigger>
		<fieldPath>selector</fieldPath>
	</ApiError>
</reportDownloadError>

func (*APIError) Error added in v0.1.10

func (e *APIError) Error() string

String returns a representation of the api error.

type Auth

type Auth struct {
	AuthKey
	AuthToken
}

Auth contains all information to deal with an access token via OAuth Google. It implements Stringer interface

func NewAuthByClient

func NewAuthByClient(clientID, clientSecret, refreshToken string) (*Auth, error)

NewAuthByClient returns an Auth struct only based on the client keys.

func NewAuthByToken

func NewAuthByToken(tk string) (*Auth, error)

NewAuthByToken returns an Auth struct only based on the access token.

func (*Auth) IsSet

func (a *Auth) IsSet() bool

IsSet returns true if the auth struct has keys to refresh access token.

func (*Auth) String

func (a *Auth) String() string

String returns a representation of the access token.

func (*Auth) Valid

func (a *Auth) Valid() bool

Valid returns in success is the access token is not expired. The delta in seconds is used to avoid delay expiration of the token.

type AuthKey

type AuthKey struct {
	ClientID,
	ClientSecret,
	RefreshToken string
}

AuthKey represents the keys used to retrieve an access token.

type AuthToken

type AuthToken struct {
	AccessToken,
	TokenType string
	Expiry time.Time
}

AuthToken contains the properties of the Google access token.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a connection to a database and implements driver.Conn.

func (*Conn) Begin

func (c *Conn) Begin() (driver.Tx, error)

Begin is dedicated to start a transaction and awql does not support it.

func (*Conn) Close

func (c *Conn) Close() error

Close marks this connection as no longer in use.

func (*Conn) Prepare

func (c *Conn) Prepare(q string) (driver.Stmt, error)

Prepare returns a prepared statement, bound to this connection.

type ConnectionError

type ConnectionError struct {
	// contains filtered or unexported fields
}

ConnectionError represents an connection error.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error outputs a connection error message.

type Driver

type Driver struct{}

Driver implements all methods to pretend as a sql database driver.

func (*Driver) Open

func (d *Driver) Open(dsn string) (driver.Conn, error)

Open returns a new connection to the database. @see https://github.com/rvflash/awql-driver#data-source-name for how the DSN string is formatted

type Dsn

type Dsn struct {
	AdwordsID, APIVersion,
	DeveloperToken, AccessToken,
	ClientID, ClientSecret,
	RefreshToken string
	SkipColumnHeader,
	SupportsZeroImpressions,
	UseRawEnumValues bool
}

Dsn represents a data source name.

func NewDsn

func NewDsn(id string) *Dsn

NewDsn returns a new instance of Dsn.

func (*Dsn) String

func (d *Dsn) String() (n string)

String outputs the data source name as string. Output: 123-456-7890:v201607:true:false:false|dEve1op3er7okeN|1234567890-c1i3n7iD.com|c1ien753cr37|1/R3Fr35h-70k3n

type Opts

type Opts struct {
	Version string
	SkipReportHeader,
	SkipColumnHeader,
	SkipReportSummary,
	IncludeZeroImpressions,
	UseRawEnumValues bool
}

Opts lists the available Adwords API properties.

func NewOpts

func NewOpts(version string, zero, head, enum bool) *Opts

NewOpts returns a Opts with default options.

type QueryError

type QueryError struct {
	// contains filtered or unexported fields
}

QueryError represents a query error.

func (*QueryError) Error

func (e *QueryError) Error() string

Error outputs a query error message.

type Rows

type Rows struct {
	Position, Size int
	Data           [][]string
}

Rows is an iterator over an executed query's results.

func (*Rows) Close

func (r *Rows) Close() error

Close usual closes the rows iterator.

func (*Rows) Columns

func (r *Rows) Columns() []string

Columns returns the names of the columns.

func (*Rows) Next

func (r *Rows) Next(dest []driver.Value) error

Next is called to populate the next row of data into the provided slice.

type Stmt

type Stmt struct {
	Db       *Conn
	SrcQuery string
}

Stmt is a prepared statement.

func (*Stmt) Bind

func (s *Stmt) Bind(args []driver.Value) error

Bind applies the required argument replacements on the query.

func (*Stmt) Close

func (s *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)

Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.

func (*Stmt) Hash

func (s *Stmt) Hash() (string, error)

Hash returns a hash that represents the statement. Of course, the binding must have already been done to make sense.

func (*Stmt) NumInput

func (s *Stmt) NumInput() int

NumInput returns the number of placeholder parameters.

func (*Stmt) Query

func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)

Query sends request to Google Adwords API and retrieves its content.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL