-
Notifications
You must be signed in to change notification settings - Fork 2
/
statement.go
197 lines (177 loc) · 4.79 KB
/
statement.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package awql
import (
"database/sql/driver"
"encoding/csv"
"fmt"
"hash/fnv"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
apiURL = "https://adwords.google.com/api/adwords/reportdownload/"
apiFmt = "CSV"
apiTimeout = time.Duration(10 * time.Minute)
)
// Stmt is a prepared statement.
type Stmt struct {
Db *Conn
SrcQuery string
}
// Bind applies the required argument replacements on the query.
func (s *Stmt) Bind(args []driver.Value) error {
if na := s.NumInput(); len(args) < na {
// Number of placements to replace exceeds the number of inputs.
return ErrQueryBinding
}
q := s.SrcQuery
for _, rv := range args {
var v string
switch rv.(type) {
case float64, float32:
// Decimal point
v = fmt.Sprintf("%f", rv)
case int64, int:
// Decimal (base 10)
v = fmt.Sprintf("%d", rv)
case bool:
// TRUE or FALSE
v = strings.ToUpper(fmt.Sprintf("%t", rv))
default:
// Double-quoted string safely escaped
v = fmt.Sprintf("%q", rv)
}
q = strings.Replace(q, "?", v, 1)
}
s.SrcQuery = q
return nil
}
// Close closes the statement.
func (s *Stmt) Close() error {
return nil
}
// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) {
return nil, driver.ErrSkip
}
// Hash returns a hash that represents the statement.
// Of course, the binding must have already been done to make sense.
func (s *Stmt) Hash() (string, error) {
if s.SrcQuery == "" {
return "", ErrQuery
}
h := fnv.New64()
if _, err := h.Write([]byte(strings.ToLower(s.SrcQuery))); err != nil {
return "", err
}
return strconv.FormatUint(h.Sum64(), 10), nil
}
// NumInput returns the number of placeholder parameters.
func (s *Stmt) NumInput() int {
return strings.Count(s.SrcQuery, "?")
}
// Query sends request to Google Adwords API and retrieves its content.
func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {
// Binds all the args on the query
if err := s.Bind(args); err != nil {
return nil, err
}
// Saves response in a file named with the hash64 of the query.
f, err := s.filePath()
if err != nil {
return nil, err
}
// Downloads the report
if err := s.download(f); err != nil {
return nil, err
}
// Parse the CSV report.
d, err := os.Open(f)
if err != nil {
return nil, err
}
defer d.Close()
rs, err := csv.NewReader(d).ReadAll()
if err != nil {
return nil, err
}
// Starts the index to 1 in order to ignore the column header.
var offset int
if !s.Db.opts.SkipColumnHeader {
offset = 1
}
if l := len(rs); l > offset {
return &Rows{Size: l, Data: rs, Position: offset}, nil
}
return &Rows{}, nil
}
// download calls Adwords API and saves response in a file.
func (s *Stmt) download(name string) error {
rq, err := http.NewRequest(
"POST", apiURL+s.Db.opts.Version,
strings.NewReader(url.Values{"__rdquery": {s.SrcQuery}, "__fmt": {apiFmt}}.Encode()),
)
if err != nil {
return err
}
s.Db.client.Timeout = apiTimeout
// @see https://developers.google.com/adwords/api/docs/guides/reporting#request_headers
rq.Header.Add("Content-Type", "application/x-www-form-urlencoded; param=value")
rq.Header.Add("Accept", "*/*")
rq.Header.Add("clientCustomerId", s.Db.adwordsID)
rq.Header.Add("developerToken", s.Db.developerToken)
rq.Header.Add("includeZeroImpressions", strconv.FormatBool(s.Db.opts.IncludeZeroImpressions))
rq.Header.Add("skipColumnHeader", strconv.FormatBool(s.Db.opts.SkipColumnHeader))
rq.Header.Add("skipReportHeader", strconv.FormatBool(s.Db.opts.SkipReportHeader))
rq.Header.Add("skipReportSummary", strconv.FormatBool(s.Db.opts.SkipReportSummary))
rq.Header.Add("useRawEnumValues", strconv.FormatBool(s.Db.opts.UseRawEnumValues))
// Uses access token to fetch report
if s.Db.oAuth != nil {
if err := s.Db.authenticate(); err != nil {
return ErrBadToken
}
rq.Header.Add("Authorization", s.Db.oAuth.String())
}
// Downloads the report
resp, err := s.Db.client.Do(rq)
if err != nil {
return err
}
defer resp.Body.Close()
// Manages response in error
if resp.StatusCode != http.StatusOK {
switch resp.StatusCode {
case 0:
return ErrNoNetwork
case http.StatusBadRequest:
out, _ := ioutil.ReadAll(resp.Body)
return NewAPIError(out)
default:
return ErrBadNetwork
}
}
// Saves response in a file
out, err := os.Create(name)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
// filePath returns the file path to save the response of the query.
// @example /tmp/awql16027257112758723916.csv
func (s *Stmt) filePath() (string, error) {
hash, err := s.Hash()
if err != nil {
return "", nil
}
path := []string{"awql", hash, ".", strings.ToLower(apiFmt)}
return filepath.Join(os.TempDir(), strings.Join(path, "")), nil
}