diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json deleted file mode 100644 index 51e3144..0000000 --- a/Godeps/Godeps.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "ImportPath": "local/instantPillar", - "GoVersion": "go1.12", - "GodepVersion": "v80", - "Deps": [ - { - "ImportPath": "github.com/BrandonRomano/iso8601", - "Comment": "v0.1.0", - "Rev": "2ef8540f216c9c1c6768cbff3cfbbe7b0196c05e" - }, - { - "ImportPath": "github.com/BrandonRomano/wrecker", - "Comment": "v0.1.5", - "Rev": "d37dcbf1a77802e496cddbcc55e28e5ee9583459" - }, - { - "ImportPath": "github.com/a-frony/go-pinterest", - "Comment": "v2.1.1-3-g34cee64", - "Rev": "34cee649b802c88f1008333eb1e78b0bf5aa6a0e" - }, - { - "ImportPath": "github.com/a-frony/go-pinterest/controllers", - "Comment": "v2.1.1-3-g34cee64", - "Rev": "34cee649b802c88f1008333eb1e78b0bf5aa6a0e" - }, - { - "ImportPath": "github.com/a-frony/go-pinterest/models", - "Comment": "v2.1.1-3-g34cee64", - "Rev": "34cee649b802c88f1008333eb1e78b0bf5aa6a0e" - }, - { - "ImportPath": "github.com/go-telegram-bot-api/telegram-bot-api", - "Comment": "v4.6.4-25-gb33efee", - "Rev": "b33efeebc78563cfeddf19563781cffb16aaabdf" - }, - { - "ImportPath": "github.com/jmoiron/sqlx", - "Comment": "v1.2.0-23-gd7d9517", - "Rev": "d7d95172beb5a538ff08c50a6e98aee6e7c41f40" - }, - { - "ImportPath": "github.com/jmoiron/sqlx/reflectx", - "Comment": "v1.2.0-23-gd7d9517", - "Rev": "d7d95172beb5a538ff08c50a6e98aee6e7c41f40" - }, - { - "ImportPath": "github.com/lib/pq", - "Comment": "v1.2.0-12-g931b5ae", - "Rev": "931b5ae4c24e6810c8c82ab4734904de3df1c3dc" - }, - { - "ImportPath": "github.com/lib/pq/oid", - "Comment": "v1.2.0-12-g931b5ae", - "Rev": "931b5ae4c24e6810c8c82ab4734904de3df1c3dc" - }, - { - "ImportPath": "github.com/lib/pq/scram", - "Comment": "v1.2.0-12-g931b5ae", - "Rev": "931b5ae4c24e6810c8c82ab4734904de3df1c3dc" - }, - { - "ImportPath": "github.com/technoweenie/multipartstreamer", - "Comment": "v1.0.1", - "Rev": "a90a01d73ae432e2611d178c18367fbaa13e0154" - } - ] -} diff --git a/Godeps/Readme b/Godeps/Readme deleted file mode 100644 index 4cdaa53..0000000 --- a/Godeps/Readme +++ /dev/null @@ -1,5 +0,0 @@ -This directory tree is generated automatically by godep. - -Please do not edit. - -See https://github.com/tools/godep for more information. diff --git a/config.json b/config.json index ee78232..3884a3b 100644 --- a/config.json +++ b/config.json @@ -1,10 +1,10 @@ { "Language":"en-US", - "TelegramBotToken":"970284242:AAF91MAfEGW0fBJXqFLdpvivhJgY0LOwCMA", - "PinterestToken":"Arczna__ssB-Vs-do2Cv0vHdPRHcFcrDAp9iY_FGM-6LsMDBIQgEQDAAAEWCRjUVoNkArs0AAAAA", - "BotAdmin":"a_frony", - "DBUser":"test_user", - "DBPass":"test_pass", - "DBName":"instant_pillars" + "TelegramBotToken":"", + "PinterestToken":"", + "BotAdmin":"", + "DBUser":"", + "DBPass":"", + "DBName":"" } \ No newline at end of file diff --git a/procfile b/procfile deleted file mode 100644 index aa1926e..0000000 --- a/procfile +++ /dev/null @@ -1 +0,0 @@ -web: frony-go-test \ No newline at end of file diff --git a/vendor/github.com/BrandonRomano/iso8601/LICENSE b/vendor/github.com/BrandonRomano/iso8601/LICENSE deleted file mode 100644 index 5869b24..0000000 --- a/vendor/github.com/BrandonRomano/iso8601/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Joe Shaw - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/BrandonRomano/iso8601/README.md b/vendor/github.com/BrandonRomano/iso8601/README.md deleted file mode 100644 index 1b22912..0000000 --- a/vendor/github.com/BrandonRomano/iso8601/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# iso8601 # - -iso8601 is a simple Go package for encoding `time.Time` in JSON in ISO -8601 format, without subsecond resolution or time zone info. - -```go -package main - -import ( - "encoding/json" - "fmt" - "time" - - "github.com/joeshaw/iso8601" -) - -func main() { - t := time.Now() - - // Standard JSON format - // "2014-03-25T16:15:25.701623113-04:00" - data, _ := json.Marshal(t) - fmt.Println(string(data)) - - // ISO8601 JSON format - // "2014-03-25T16:15:25" - data, _ = json.Marshal(iso8601.Time(t)) - fmt.Println(string(data)) - - // Output after decoding back to go. Note the loss of - // precision and time zone info. - // 2014-03-25 16:15:25 +0000 +0000 - var t2 iso8601.Time - json.Unmarshal(data, &t2) - fmt.Println(t2) -} -``` diff --git a/vendor/github.com/BrandonRomano/iso8601/iso8601.go b/vendor/github.com/BrandonRomano/iso8601/iso8601.go deleted file mode 100644 index 589044b..0000000 --- a/vendor/github.com/BrandonRomano/iso8601/iso8601.go +++ /dev/null @@ -1,76 +0,0 @@ -// The iso8601 package encodes and decodes time.Time in JSON in -// ISO 8601 format, without subsecond resolution or time zone info. -package iso8601 - -import ( - "encoding/json" - "fmt" - "reflect" - "time" -) - -const Format = "2006-01-02T15:04:05" -const jsonFormat = `"` + Format + `"` - -var fixedZone = time.FixedZone("", 0) - -type Time struct { - Time time.Time - Valid bool -} - -// New constructs a new iso8601.Time instance from an existing -// time.Time instance. This causes the nanosecond field to be set to -// 0, and its time zone set to a fixed zone with no offset from UTC -// (but it is *not* UTC itself). -func New(t time.Time) Time { - return Time{ - Time: time.Date( - t.Year(), - t.Month(), - t.Day(), - t.Hour(), - t.Minute(), - t.Second(), - 0, - fixedZone, - ), - Valid: true, - } -} - -func (it Time) MarshalJSON() ([]byte, error) { - if !it.Valid { - return []byte("null"), nil - } - return []byte(time.Time(it.Time).Format(jsonFormat)), nil -} - -func (it *Time) UnmarshalJSON(data []byte) error { - var err error - var v interface{} - if err = json.Unmarshal(data, &v); err != nil { - return err - } - switch x := v.(type) { - case string: - t, err := time.ParseInLocation(jsonFormat, x, fixedZone) - if err == nil { - it = &Time{ - Time: t, - Valid: true, - } - } - case nil: - it.Valid = false - return nil - default: - err = fmt.Errorf("json: cannot unmarshal %v into Go value of type iso8601.Time", reflect.TypeOf(v).Name()) - } - it.Valid = err == nil - return err -} - -func (it Time) String() string { - return time.Time(it.Time).String() -} diff --git a/vendor/github.com/BrandonRomano/wrecker/.gitignore b/vendor/github.com/BrandonRomano/wrecker/.gitignore deleted file mode 100644 index b82648e..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# vim -*.swp - -# go -wrecker -_vendor/* diff --git a/vendor/github.com/BrandonRomano/wrecker/.travis.yml b/vendor/github.com/BrandonRomano/wrecker/.travis.yml deleted file mode 100644 index 5a77c3c..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go -go: - - tip -before_install: - - go get github.com/mattn/gom -script: - - $HOME/gopath/bin/gom install - - cd test; $HOME/gopath/bin/gom test diff --git a/vendor/github.com/BrandonRomano/wrecker/Gomfile b/vendor/github.com/BrandonRomano/wrecker/Gomfile deleted file mode 100644 index 84d70ba..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/Gomfile +++ /dev/null @@ -1,2 +0,0 @@ -gom 'github.com/stretchr/testify' -gom 'github.com/julienschmidt/httprouter' diff --git a/vendor/github.com/BrandonRomano/wrecker/LICENSE.md b/vendor/github.com/BrandonRomano/wrecker/LICENSE.md deleted file mode 100644 index 6a81c89..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Brandon Romano - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/BrandonRomano/wrecker/README.md b/vendor/github.com/BrandonRomano/wrecker/README.md deleted file mode 100644 index 1d643dc..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Wrecker - -Wrecker is a request builder for JSON based APIs, written in Go. - -> Please note that the API is being actively developed, so please expect breaking changes until we post a 1.0 release. If you would like to use wrecker now, we suggest creating a fork and using that. - -[![Build Status](https://travis-ci.org/BrandonRomano/wrecker.svg?branch=master)](https://travis-ci.org/BrandonRomano/wrecker) - -## Fluent Builder - -Without digging too far into anything, here is what your requests will look like with Wrecker: - -```go -wreckerClient.Get("/users"). - URLParam("id", "1"). - Into(&user). // Loads the response into the user struct - Execute() -``` - -## Usage - -### Wrecker Instance - -To get started with Wrecker, you first have to prepare an instance for yourself: - -```go -wreckerClient = &wrecker.Wrecker{ - BaseURL: "http://localhost:5000", - HttpClient: &http.Client{ - Timeout: 10 * time.Second, - }, - DefaultContentType: "application/x-www-form-urlencoded", - RequestInterceptor: func(req *wrecker.Request) error { - req.URLParam("id", "1") - return nil - }, -} -``` - -There are three values you'll have to set - -- `BaseURL`: This is the base URL of the API you will be using -- `HttpClient`: This is an instance of an http.Client. Feel free to tweak this as much as you would like. -- `DefaultContentType`: This is the value of the `Content-Type` header that will be added to every request. This can be overridden at request level, but for convenience you can set a default. -- `RequestInterceptor`: This is an interceptor that can update every request before it gets sent out. This can safely be set to nil if you do not have a need for a request interceptor. - -You're only going to have to do this once, but if you still find it's too verbose or you don't need the flexibility you can do this: - -```go -wreckerClient = wrecker.New("http://localhost:" + os.Getenv("PORT")) -``` - -This way will default the `HttpClient` + `DefaultContentType` to the values set in the first example, and `RequestInterceptor` will be set to nil. - -### Creating Requests - -Let's say that you wanted to hit an endpoint with a response that looked something like this: - -```json -{ - "id": 1, - "user_name": "BrandonRomano", - "location": "Brooklyn, NY" -} -``` - -The first thing you would do is create a model that would represent the response: - -```go -type User struct { - Id int `json:"id"` - UserName string `json:"user_name"` - Location string `json:"location"` -} -``` - -Now that we have our struct and our instance of `Wrecker`, we're ready to actually create the response. - -```go -user := User{} - -response, err := wreckerClient.Get("/users"). - URLParam("id", "1"). - Into(&user). - Execute() - -fmt.Println(strconv.Itoa(user.Id)) // Prints 1 -fmt.Println(user.UserName) // Prints "BrandonRomano" -fmt.Println(user.Location) // Prints "Brooklyn, NY" -``` - -## License - -Wrecker is licensed under [MIT](LICENSE.md) diff --git a/vendor/github.com/BrandonRomano/wrecker/error.go b/vendor/github.com/BrandonRomano/wrecker/error.go deleted file mode 100644 index 12f1167..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/error.go +++ /dev/null @@ -1,10 +0,0 @@ -package wrecker - -type ResponseError struct { - StatusCode int - StatusText string -} - -func (r ResponseError) Error() string { - return r.StatusText -} diff --git a/vendor/github.com/BrandonRomano/wrecker/request.go b/vendor/github.com/BrandonRomano/wrecker/request.go deleted file mode 100644 index a2e1689..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/request.go +++ /dev/null @@ -1,90 +0,0 @@ -package wrecker - -import ( - "errors" - "net/http" - "net/url" -) - -type BasicAuthInfo struct { - Username string - Password string -} - -type Request struct { - HttpVerb string - Endpoint string - Response interface{} - URLParams url.Values - FormParams url.Values - HttpBody interface{} - Headers map[string]string - Cookies []*http.Cookie - BasicAuthInfo *BasicAuthInfo - WreckerClient *Wrecker -} - -func (r *Request) Cookie(cookie *http.Cookie) *Request { - r.Cookies = append(r.Cookies, cookie) - return r -} - -func (r *Request) Header(key, value string) *Request { - r.Headers[key] = value - return r -} - -func (r *Request) URLParam(key, value string) *Request { - r.URLParams.Add(key, value) - return r -} - -func (r *Request) FormParam(key, value string) *Request { - r.FormParams.Add(key, value) - return r -} - -func (r *Request) Body(body interface{}) *Request { - r.HttpBody = body - return r -} - -func (r *Request) SetBasicAuth(username, password string) *Request { - r.BasicAuthInfo = &BasicAuthInfo{ - Username: username, - Password: password, - } - return r -} - -func (r *Request) Into(response interface{}) *Request { - r.Response = response - return r -} - -func (r *Request) Execute() (*http.Response, error) { - // Calling interceptor if we have one - if r.WreckerClient.RequestInterceptor != nil { - r.WreckerClient.RequestInterceptor(r) - } - - // Sending Request - switch r.HttpVerb { - - case GET, POST, PUT, DELETE, PATCH: - return r.WreckerClient.sendRequest(r) - - default: - return nil, errors.New("Must use a valid HTTP verb") - } -} - -func (r *Request) URL() string { - result := r.WreckerClient.BaseURL + r.Endpoint - - if len(r.URLParams) > 0 { - result += "?" + r.URLParams.Encode() - } - - return result -} diff --git a/vendor/github.com/BrandonRomano/wrecker/wrecker.go b/vendor/github.com/BrandonRomano/wrecker/wrecker.go deleted file mode 100644 index e91b9ef..0000000 --- a/vendor/github.com/BrandonRomano/wrecker/wrecker.go +++ /dev/null @@ -1,180 +0,0 @@ -package wrecker - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -type Wrecker struct { - BaseURL string - HttpClient *http.Client - DefaultContentType string - RequestInterceptor func(*Request) error -} - -func New(baseUrl string) *Wrecker { - return &Wrecker{ - BaseURL: baseUrl, - HttpClient: &http.Client{ - Timeout: 10 * time.Second, - }, - DefaultContentType: "application/x-www-form-urlencoded", - RequestInterceptor: nil, - } -} - -const ( - GET = "GET" - POST = "POST" - PUT = "PUT" - PATCH = "PATCH" - DELETE = "DELETE" -) - -func (w *Wrecker) newRequest(httpVerb string, endpoint string) *Request { - return &Request{ - HttpVerb: httpVerb, - Endpoint: endpoint, - URLParams: url.Values{}, - FormParams: url.Values{}, - Headers: make(map[string]string), - WreckerClient: w, - } -} - -func (w *Wrecker) Get(endpoint string) *Request { - return w.newRequest(GET, endpoint) -} - -func (w *Wrecker) Post(endpoint string) *Request { - return w.newRequest(POST, endpoint) -} - -func (w *Wrecker) Put(endpoint string) *Request { - return w.newRequest(PUT, endpoint) -} - -func (w *Wrecker) Patch(endpoint string) *Request { - return w.newRequest(PATCH, endpoint) -} - -func (w *Wrecker) Delete(endpoint string) *Request { - return w.newRequest(DELETE, endpoint) -} - -func (w *Wrecker) sendRequest(r *Request) (*http.Response, error) { - - var contentType string - var bodyReader io.Reader - var err error - - // GET methods don't have an HTTP Body. For all other methods, - // it's time to defined the body content. - if r.HttpVerb != GET { - - bodyReader, contentType, err = w.getRequestBody(r) - - if err != nil { - return nil, err - } - } - - // Create the HTTP client request - clientReq, err := http.NewRequest(r.HttpVerb, r.URL(), bodyReader) - if err != nil { - return nil, err - } - - // Add Basic Auth, if we have it - if r.BasicAuthInfo != nil { - clientReq.SetBasicAuth(r.BasicAuthInfo.Username, r.BasicAuthInfo.Password) - } - - // Set Content-Type for this request - clientReq.Header.Add("Content-Type", contentType) - - // Add headers to clientReq - for key, value := range r.Headers { - clientReq.Header.Add(key, value) - } - - // Add cookies - for _, cookie := range r.Cookies { - clientReq.AddCookie(cookie) - } - - // Executing request - resp, err := w.HttpClient.Do(clientReq) - if err != nil { - return nil, err - } - - // Packing into response, if we have one - if r.Response != nil { - body, err := ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return nil, err - } - err = json.Unmarshal(body, r.Response) - if err != nil { - return resp, err - } - } - - // Handling HTTP Error - if !(resp.StatusCode >= 200 && resp.StatusCode < 300) { - return resp, ResponseError{ - StatusCode: resp.StatusCode, - StatusText: resp.Status, - } - } - - // OK - return resp, nil -} - -func (w *Wrecker) getRequestBody(r *Request) (io.Reader, string, error) { - - // If there's no body, then try form encoding - if r.HttpBody == nil { - - // If there are Form Parameters, then let's use form - return strings.NewReader(r.FormParams.Encode()), "application/x-www-form-urlencoded", nil - - } else { - - // Otherwise, try using a JSON encoded body that was given to us - - var reader io.Reader - var contentType = "application/json" - var err error - - switch r.HttpBody.(type) { - - case io.Reader: - reader = r.HttpBody.(io.Reader) - - case []byte: - reader = bytes.NewReader(r.HttpBody.([]byte)) - - default: - - // try to jsonify it - j, err := json.Marshal(r.HttpBody) - - if err == nil { - reader = bytes.NewReader(j) - } - } - - return reader, contentType, err - } - -} diff --git a/vendor/github.com/a-frony/go-pinterest/.gitignore b/vendor/github.com/a-frony/go-pinterest/.gitignore deleted file mode 100644 index faecb72..0000000 --- a/vendor/github.com/a-frony/go-pinterest/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Vendor files -vendor/* - -# vim -*.swp -*.swo - -# IntelliJ -*.iml -.idea/* - -# Compiled files -pinterest-go-client diff --git a/vendor/github.com/a-frony/go-pinterest/.travis.yml b/vendor/github.com/a-frony/go-pinterest/.travis.yml deleted file mode 100644 index 01c2475..0000000 --- a/vendor/github.com/a-frony/go-pinterest/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - 1.6 - - master -before_install: - - go get github.com/Masterminds/glide -install: - - $HOME/gopath/bin/glide install - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover -script: - - $HOME/gopath/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/a-frony/go-pinterest/LICENSE.md b/vendor/github.com/a-frony/go-pinterest/LICENSE.md deleted file mode 100644 index 1de4a0a..0000000 --- a/vendor/github.com/a-frony/go-pinterest/LICENSE.md +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 a-frony Creative, Brandon Romano - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/a-frony/go-pinterest/README.md b/vendor/github.com/a-frony/go-pinterest/README.md deleted file mode 100644 index ef6a465..0000000 --- a/vendor/github.com/a-frony/go-pinterest/README.md +++ /dev/null @@ -1,382 +0,0 @@ -# Go Pinterest [![Build Status](https://travis-ci.org/a-frony/go-pinterest.svg?branch=master)](https://travis-ci.org/a-frony/go-pinterest) [![Coverage Status](https://coveralls.io/repos/github/a-frony/go-pinterest/badge.svg?branch=master)](https://coveralls.io/github/a-frony/go-pinterest?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/a-frony/go-pinterest)](https://goreportcard.com/report/github.com/a-frony/go-pinterest) - -This is a Go client for the Pinterest API. For more information about the Pinterest API, check out their [getting started](https://developers.pinterest.com/docs/api/overview/) guide. - -## Creating a Client - -To create a simple Pinterest client: - -```go -import( - "github.com/a-frony/go-pinterest" - // Below imports aren't needed immediately, but you'll want these soon after - "github.com/a-frony/go-pinterest/controllers" - "github.com/a-frony/go-pinterest/models" -) - -func main() { - client := pinterest.NewClient() -} -``` - -To create an authenticated Pinterest client you can just chain the `RegisterAccessToken` method: - -```go -import( - "github.com/a-frony/go-pinterest" - // Below imports aren't needed immediately, but you'll want these soon after - "github.com/a-frony/go-pinterest/controllers" - "github.com/a-frony/go-pinterest/models" -) - -func main() { - client := pinterest.NewClient(). - RegisterAccessToken("USERS_ACCESS_TOKEN") -} -``` - -## Calling API Methods - -Calling specific API methods matches 1:1 with the Pinterest API URL schema. - -The best way to illustrate this is with a few examples: - -```go -// Fetch Board info: -// [GET] /v1/boards// -board, err := client.Boards.Fetch("BrandonRRomano/go-pinterest") - -// Unfollow a User: -// [DELETE] /v1/me/following/users// -err := client.Me.Following.Users.Delete("BrandonRRomano") - -// Fetch the Pins on a Board: -// [GET] /v1/boards//pins/ -pins, err := client.Boards.Pins("BrandonRRomano/go-pinterest") -``` - -As you can see, you simply chain through the controllers following the URL in the Pinterest API. If there is a URL with a segment that is a parameter (see Fetch the Pins on a Board in above example), you simply skip that segment in the controller chaining; the parameter will be passed along in the parameters of the method. - -Once you're at the final segment, you can call `Create`, `Fetch`, `Update`, or `Delete`, which will call the API's `POST`, `GET`, `PATCH`, or `DELETE` methods respectively. - -All required parameters to the Pinterest API's methods will be parameters in the method. All optional parameters will be stuffed in an `Optionals` object as the last parameter. - -## Handling Errors - -For all requests made via this library, there is the possibility of the Pinterest API throwing an error. - -When the API does throw an error, this library makes it very easy to handle it. - -If the error came from Pinterest (and not the [http.Client](https://golang.org/pkg/net/http/#Client)) this library wraps it in a custom error, PinterestError: - -```go -type PinterestError struct { - StatusCode int `json:"status_code"` - Message string `json:"message"` -} -``` - -Here's some example usage of this: - -```go -// Fetch a board that doesn't exist -_, err := client.Boards.Fetch("BrandonRRomano/E20450921CE") - -// Check error type -if pinterestError, ok := err.(*models.PinterestError); ok { - if pinterestError.StatusCode == 404 { - // Do something to handle it! - } else { - // something else! - } -} else { - // Was an error thrown by *http.Client! - // Something is probably wrong with your network -} -``` - -## OAuth Endpoints - -### Generate Access Token - -`[POST] /v1/oauth/token` - -```go -accessToken, err := client.OAuth.Token.Create( - "client-id", - "client-secret", - "access-code" -) -``` - -## Boards Endpoints - -### Create a Board - -`[POST] /v1/boards/` - -```go -board, err := client.Boards.Create( - "My Test Board", - &controllers.BoardCreateOptionals{ - Description: "This is a test!", - }, -) -``` - -### Delete a Board - -`[DELETE] /v1/boards//` - -```go -err := client.Boards.Delete("BrandonRRomano/go-pinterest-test") -``` - -### Edit a Board - -`[PATCH] /v1/boards//` - -```go -board, err := client.Boards.Update( - "BrandonRRomano/go-pinterest-test", - &controllers.BoardUpdateOptionals{ - Name: "Some new name", - Description: "Some new description", - }, -) -``` - -### Retrieve information about a Board - -`[GET] /v1/boards//` - -```go -board, err := client.Boards.Fetch("BrandonRRomano/go-pinterest") -``` - -### Retrieve the Pins on a Board - -`[GET] /v1/boards//pins/` - -```go -pins, err := client.Boards.Pins.Fetch( - "BrandonRRomano/go-pinterest", - &controllers.BoardPinsFetchOptionals{ - Cursor: "some-cursor-from-pinterest", - }, -) -``` - -## Me Endpoints - -### Return the logged in user's information - -`[GET] /v1/me/` - -```go -user, err := client.Me.Fetch() -``` - -### Return the logged in user's Boards - -`[GET] /v1/me/boards/` - -```go -boards, err := client.Me.Boards.Fetch() -``` - -### Return Board suggestions for the logged in user - -`[GET] /v1/me/boards/suggested/` - -```go -boards, err := client.Me.Boards.Suggested.Fetch( - &controllers.MeBoardsSuggestedFetchOptionals{ - Count: 10, - Pin: "some-pin-id", - }, -) -``` - -### Return the users that follow the logged in user - -`[GET] /v1/me/followers/` - -```go -users, page, err := client.Me.Followers.Fetch( - &controllers.MeFollowersFetchOptionals{ - Cursor: "some-cursor", - }, -) -``` - -### Get the Boards that the logged in user follows - -`[GET] /v1/me/following/boards/` - -```go -boards, page, err := client.Me.Following.Boards.Fetch( - &controllers.MeFollowingBoardsFetchOptionals{ - Cursor: "some-cursor", - }, -) -``` - -### Follow a Board - -`[POST] /v1/me/following/boards/` - -```go -err := client.Me.Following.Boards.Create("pinterest/pinterest-100-for-2017") -``` - -### Unfollow a Board - -`[DELETE] /v1/me/following/boards//` - -```go -err := client.Me.Following.Boards.Delete("pinterest/pinterest-100-for-2017") -``` - -### Return the Interests the logged in user follows - -`[GET] /v1/me/following/interests/` - -```go -interests, page, err := client.Me.Following.Interests.Fetch( - &controllers.MeFollowingInterestsFetchOptionals{ - Cursor: "some-cursor", - }, -) -``` - -### Return the users that the logged in user follows - -`[GET] /v1/me/following/users/` - -```go -users, page, err := client.Me.Following.Users.Fetch( - &controllers.FollowingUsersControllerFetchOptionals{ - Cursor: "some-cursor", - }, -) -``` - -### Follow a user - -`[POST] /v1/me/following/users/` - -```go -err := client.Me.Following.Users.Create("hhsnopek") -``` - -### Unfollow a user - -`[DELETE] /v1/me/following/users//` - -```go -err := client.Me.Following.Users.Delete("hhsnopek") -``` - -### Return the logged in user's Pins - -`[GET] /v1/me/pins/` - -```go -pins, page, err := client.Me.Pins.Fetch( - &controllers.MePinsFetchOptionals{ - Cursor: "some-cursor", - }, -) -``` - -### Search the logged in user's Boards - -`[GET] /v1/me/search/boards/` - -```go -// Load first page -boards, page, err := client.Me.Search.Boards.Fetch( - "Go Pinterest", - &controllers.MeSearchBoardsFetchOptionals{ - Cursor: "some-cursor", - Limit: 1, - }, -) -``` - -### Search the logged in user's Pins - -`[GET] /v1/me/search/pins/` - -```go -pins, page, err := client.Me.Search.Pins.Fetch( - "Go Gopher", - &controllers.MeSearchPinsFetchOptionals{ - Cursor: "some-cursor", - Limit: 1, - }, -) -``` - -## Pins Endpoints - -### Create a Pin - -`[POST] /v1/pins/` - -```go -pin, err := client.Pins.Create( - "BrandonRRomano/go-pinterest-2", - "This is a cat", - &controllers.PinCreateOptionals{ - Link: "http://www.google.com/", - ImageUrl: "http://i.imgur.com/1olmVpO.jpg", - }, -) -``` - -### Delete a Pin - -`[DELETE] /v1/pins//` - -```go -err := client.Pins.Delete("some-pin-id") -``` - -### Edit a Pin's information - -`[PATCH] /v1/pins//` - -```go -pin, err := client.Pins.Update( - "some-pin-id", - &controllers.PinUpdateOptionals{ - Board: "BrandonRRomano/go-pinterest", - Note: "This is a new cat", - Link: "http://www.facebook.com/", - }, -) -``` - -### Return information about a Pin - -`[GET] /v1/pins//` - -```go -pin, err := client.Pins.Fetch("some-pin-id") -``` - -## Users Endpoints - -### Return a user's information - -`[GET] /v1/users//` - -```go -user, err := client.Users.Fetch("BrandonRRomano") -``` - -## License - -[MIT](LICENSE.md) © a-frony Creative diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/boards_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/boards_controller.go deleted file mode 100644 index b93a34f..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/boards_controller.go +++ /dev/null @@ -1,117 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// BoardsController is the controller that is responsible for all -// /v1/boards/ endpoints in the Pinterest API. -type BoardsController struct { - wreckerClient *wrecker.Wrecker - Pins *BoardsPinsController -} - -// NewBoardsController instantiates a new BoardsController. -func NewBoardsController(wc *wrecker.Wrecker) *BoardsController { - return &BoardsController{ - wreckerClient: wc, - Pins: newBoardsPinsController(wc), - } -} - -// Fetch loads a board from the board_spec (username/board-slug) -// Endpoint: [GET] /v1/boards// -func (bc *BoardsController) Fetch(boardSpec string) (*models.Board, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Board) - httpResp, err := bc.wreckerClient.Get("/boards/"+boardSpec). - URLParam("fields", models.BOARD_FIELDS). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Board), nil -} - -// BoardCreateOptionals is a struct that represents the optional parameters -// that can be passed to the Create endpoint -type BoardCreateOptionals struct { - Description string -} - -// Create makes a new board -// Endpoint: [POST] /v1/boards/ -func (bc *BoardsController) Create(boardName string, optionals *BoardCreateOptionals) (*models.Board, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Board) - httpResp, err := bc.wreckerClient.Post("/boards/"). - URLParam("fields", models.BOARD_FIELDS). - FormParam("name", boardName). - FormParam("description", optionals.Description). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Board), nil -} - -// BoardUpdateOptionals is a struct that represents the optional parameters -// that can be passed to the Update endpoint -type BoardUpdateOptionals struct { - Name string - Description string -} - -// Update updates an existing board -// Endpoint: [PATCH] /v1/boards// -func (bc *BoardsController) Update(boardSpec string, optionals *BoardUpdateOptionals) (*models.Board, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Board) - httpResp, err := bc.wreckerClient.Patch("/boards/"+boardSpec+"/"). - URLParam("fields", models.BOARD_FIELDS). - FormParam("name", optionals.Name). - FormParam("description", optionals.Description). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Board), nil -} - -// Delete deletes an existing board -// Endpoint: [DELETE] /v1/boards// -func (bc *BoardsController) Delete(boardSpec string) error { - // Build + execute request - resp := new(models.Response) - resp.Data = "" - httpResp, err := bc.wreckerClient.Delete("/boards/" + boardSpec + "/"). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/boards_pins_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/boards_pins_controller.go deleted file mode 100644 index d90e267..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/boards_pins_controller.go +++ /dev/null @@ -1,53 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// BoardsPinsController is the controller that is responsible for all -// /v1/boards//pins/ endpoints in the Pinterest API. -type BoardsPinsController struct { - wreckerClient *wrecker.Wrecker -} - -// newBoardsPinsController instantiates a new BoardsPinsController. -func newBoardsPinsController(wc *wrecker.Wrecker) *BoardsPinsController { - return &BoardsPinsController{ - wreckerClient: wc, - } -} - -// BoardsPinsFetchOptionals is a struct that represents the optional parameters -// that can be passed to the Fetch endpoint -type BoardsPinsFetchOptionals struct { - Cursor string - Limit string -} - -// Fetch loads a board from the board_spec (username/board-slug) -// Endpoint: [GET] /v1/boards//pins/ -func (bpc *BoardsPinsController) Fetch(boardSpec string, optionals *BoardsPinsFetchOptionals) (*[]models.Pin, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Pin{} - request := bpc.wreckerClient.Get("/boards/"+boardSpec+"/pins/"). - URLParam("fields", models.PIN_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - if optionals.Limit != "" { - request.URLParam("limit", optionals.Limit) - } - - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Pin), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_controller.go deleted file mode 100644 index 3edbd7c..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_controller.go +++ /dev/null @@ -1,41 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeBoardsController is the controller that is responsible for all -// /v1/me/boards/ endpoints in the Pinterest API. -type MeBoardsController struct { - wreckerClient *wrecker.Wrecker - Suggested *MeBoardsSuggestedController -} - -// newMeBoardsController instantiates a new MeBoardsController -func newMeBoardsController(wc *wrecker.Wrecker) *MeBoardsController { - return &MeBoardsController{ - wreckerClient: wc, - Suggested: newMeBoardsSuggestedController(wc), - } -} - -// Fetch loads the authorized users boards -// Endpoint: [GET] /v1/me/boards/ -func (mbc *MeBoardsController) Fetch() (*[]models.Board, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Board{} - httpResp, err := mbc.wreckerClient.Get("/me/boards/"). - URLParam("fields", models.BOARD_FIELDS). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*[]models.Board), nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_suggested_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_suggested_controller.go deleted file mode 100644 index e465309..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_boards_suggested_controller.go +++ /dev/null @@ -1,53 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" - "strconv" -) - -// MeBoardsSuggestedController is the controller that is responsible for all -// /v1/me/boards/suggested/ endpoints in the Pinterest API. -type MeBoardsSuggestedController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeBoardsSuggestedController instantiates a new MeBoardsSuggestedController -func newMeBoardsSuggestedController(wc *wrecker.Wrecker) *MeBoardsSuggestedController { - return &MeBoardsSuggestedController{ - wreckerClient: wc, - } -} - -// MeBoardsSuggestedFetchOptionals is a struct that represents the optional -// parameters for the Fetch method -type MeBoardsSuggestedFetchOptionals struct { - Count int32 - Pin string -} - -// Fetch loads board suggestions for the logged in user -// Endpoint: [GET] /v1/me/boards/suggested/ -func (mbsc *MeBoardsSuggestedController) Fetch(optionals *MeBoardsSuggestedFetchOptionals) (*[]models.Board, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Board{} - request := mbsc.wreckerClient.Get("/me/boards/suggested/"). - URLParam("fields", models.BOARD_FIELDS). - Into(resp) - if optionals.Count != 0 { - request.URLParam("count", strconv.Itoa(int(optionals.Count))) - } - if optionals.Pin != "" { - request.URLParam("pin", optionals.Pin) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*[]models.Board), nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_controller.go deleted file mode 100644 index 59ada49..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_controller.go +++ /dev/null @@ -1,49 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeController is the controller that is responsible for all -// /v1/me/ endpoints in the Pinterest API. -type MeController struct { - wreckerClient *wrecker.Wrecker - Boards *MeBoardsController - Followers *MeFollowersController - Following *MeFollowingController - Pins *MePinsController - Search *MeSearchController -} - -// NewMeController instantiates a new MeController -func NewMeController(wc *wrecker.Wrecker) *MeController { - return &MeController{ - wreckerClient: wc, - Boards: newMeBoardsController(wc), - Followers: newMeFollowersController(wc), - Following: newMeFollowingController(wc), - Pins: newMePinsController(wc), - Search: newMeSearchController(wc), - } -} - -// Fetch loads the authorized users info -// Endpoint: [GET] /v1/me/ -func (mc *MeController) Fetch() (*models.User, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.User) - httpResp, err := mc.wreckerClient.Get("/me/"). - URLParam("fields", models.USER_FIELDS). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.User), nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_followers_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_followers_controller.go deleted file mode 100644 index af33997..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_followers_controller.go +++ /dev/null @@ -1,48 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeFollowersController is the controller that is responsible for all -// /v1/me/followers/ endpoints in the Pinterest API. -type MeFollowersController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeFollowersController instantiates a new MeFollowersController -func newMeFollowersController(wc *wrecker.Wrecker) *MeFollowersController { - return &MeFollowersController{ - wreckerClient: wc, - } -} - -// MeFollowersFetchOptionals is a struct that represents the optional -// parameters for the Fetch method -type MeFollowersFetchOptionals struct { - Cursor string -} - -// Fetch loads the users that follow the logged in user -// Endpoint: [GET] /v1/me/boards/followers/ -func (mfc *MeFollowersController) Fetch(optionals *MeFollowersFetchOptionals) (*[]models.User, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.User{} - request := mfc.wreckerClient.Get("/me/followers/"). - URLParam("fields", models.USER_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.User), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_boards_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_following_boards_controller.go deleted file mode 100644 index 02d11ba..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_boards_controller.go +++ /dev/null @@ -1,85 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeFollowingBoardsController is the controller that is responsible for all -// /v1/me/following/boards/ endpoints in the Pinterest API. -type MeFollowingBoardsController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeFollowingBoardsController instantiates a new MeFollowingBoardsController -func newMeFollowingBoardsController(wc *wrecker.Wrecker) *MeFollowingBoardsController { - return &MeFollowingBoardsController{ - wreckerClient: wc, - } -} - -// MeFollowingBoardsFetchOptionals is a struct that represents the optional -// parameters for the Fetch method -type MeFollowingBoardsFetchOptionals struct { - Cursor string -} - -// Fetch loads the boards that the authorized user follows -// Endpoint: [GET] /v1/me/following/boards/ -func (mfbc *MeFollowingBoardsController) Fetch(optionals *MeFollowingBoardsFetchOptionals) (*[]models.Board, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Board{} - request := mfbc.wreckerClient.Get("/me/following/boards/"). - URLParam("fields", models.BOARD_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Board), &resp.Page, nil -} - -// Create follows a board for the authorized user -// Endpoint: [POST] /v1/me/following/boards/ -func (mfbc *MeFollowingBoardsController) Create(boardSpec string) error { - // Build + execute request - resp := new(models.Response) - httpResp, err := mfbc.wreckerClient.Post("/me/following/boards/"). - FormParam("board", boardSpec). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} - -// Delete unfollows a board for the authorized user -// Endpoint: [DELETE] /v1/me/following/boards/ -func (mfbc *MeFollowingBoardsController) Delete(boardSpec string) error { - // Build + execute request - resp := new(models.Response) - httpResp, err := mfbc.wreckerClient.Delete("/me/following/boards/" + boardSpec + "/"). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_following_controller.go deleted file mode 100644 index ba28f81..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_controller.go +++ /dev/null @@ -1,24 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" -) - -// MeFollowingController is the controller that is responsible for all -// /v1/me/following/ endpoints in the Pinterest API. -type MeFollowingController struct { - wreckerClient *wrecker.Wrecker - Boards *MeFollowingBoardsController - Interests *MeFollowingInterestsController - Users *MeFollowingUsersController -} - -// newMeFollowingController instantiates a new MeFollowingController -func newMeFollowingController(wc *wrecker.Wrecker) *MeFollowingController { - return &MeFollowingController{ - wreckerClient: wc, - Boards: newMeFollowingBoardsController(wc), - Interests: newMeFollowingInterestsController(wc), - Users: newMeFollowingUsersController(wc), - } -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_interests_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_following_interests_controller.go deleted file mode 100644 index a7c4e8b..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_interests_controller.go +++ /dev/null @@ -1,48 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeFollowingInterestsController is the controller that is responsible for all -// /v1/me/following/interests/ endpoints in the Pinterest API. -type MeFollowingInterestsController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeFollowingInterestsController instantiates a new MeFollowingInterestsController -func newMeFollowingInterestsController(wc *wrecker.Wrecker) *MeFollowingInterestsController { - return &MeFollowingInterestsController{ - wreckerClient: wc, - } -} - -// MeFollowingInterestsFetchOptionals is a struct that represents the optional -// parameters for the Fetch method -type MeFollowingInterestsFetchOptionals struct { - Cursor string -} - -// Fetch loads the authorized users interests -// Endpoint: [GET] /v1/me/following/interests/ -func (mfic *MeFollowingInterestsController) Fetch(optionals *MeFollowingInterestsFetchOptionals) (*[]models.Interest, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Interest{} - request := mfic.wreckerClient.Get("/me/following/interests/"). - URLParam("fields", models.INTEREST_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Interest), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_users_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_following_users_controller.go deleted file mode 100644 index b0a8a15..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_following_users_controller.go +++ /dev/null @@ -1,91 +0,0 @@ -package controllers - -import ( - "strconv" - - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MeFollowingUsersController is the controller that is responsible for all -// /v1/me/following/users/ endpoints in the Pinterest API. -type MeFollowingUsersController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeFollowingUsersController instantiates a new MeFollowingUsersController -func newMeFollowingUsersController(wc *wrecker.Wrecker) *MeFollowingUsersController { - return &MeFollowingUsersController{ - wreckerClient: wc, - } -} - -// FollowingUsersControllerFetchOptionals is a struct that represents the optional -// parameters for the Fetch method -type FollowingUsersControllerFetchOptionals struct { - Cursor string - Limit int -} - -// Fetch loads the users that the authorized user follows -// Endpoint: [GET] /v1/me/following/users/ -func (c *MeFollowingUsersController) Fetch(optionals *FollowingUsersControllerFetchOptionals) (*[]models.User, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.User{} - request := c.wreckerClient.Get("/me/following/users/"). - URLParam("fields", models.USER_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - if optionals.Limit != 0 { - request.URLParam("limit", strconv.Itoa(optionals.Limit)) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.User), &resp.Page, nil -} - -// Create follows a user -// Endpoint: [POST] /v1/me/following/users/ -func (c *MeFollowingUsersController) Create(user string) error { - // Build + execute request - resp := new(models.Response) - httpResp, err := c.wreckerClient.Post("/me/following/users/"). - FormParam("user", user). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} - -// Delete unfollows a user -// Endpoint: [DELETE] /v1/me/following/users/ -func (c *MeFollowingUsersController) Delete(user string) error { - // Build + execute request - resp := new(models.Response) - httpResp, err := c.wreckerClient.Delete("/me/following/users/" + user + "/"). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_pins_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_pins_controller.go deleted file mode 100644 index 7fd8c1c..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_pins_controller.go +++ /dev/null @@ -1,48 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// MePinsController is the controller that is responsible for all -// /v1/me/pins/ endpoints in the Pinterest API. -type MePinsController struct { - wreckerClient *wrecker.Wrecker -} - -// newMePinsController instantiates a new MePinsController -func newMePinsController(wc *wrecker.Wrecker) *MePinsController { - return &MePinsController{ - wreckerClient: wc, - } -} - -// MePinsFetchOptionals is a struct that represents the optional parameters -// that can be passed to the Fetch endpoint -type MePinsFetchOptionals struct { - Cursor string -} - -// Fetch loads all of the logged in user's Pins -// Endpoint: [GET] /v1/me/pins/ -func (mpc *MePinsController) Fetch(optionals *MePinsFetchOptionals) (*[]models.Pin, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Pin{} - request := mpc.wreckerClient.Get("/me/pins/"). - URLParam("fields", models.PIN_FIELDS). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Pin), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_boards_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_search_boards_controller.go deleted file mode 100644 index db027c7..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_boards_controller.go +++ /dev/null @@ -1,54 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" - "strconv" -) - -// MeSearchBoardsController is the controller that is responsible for all -// /v1/me/search/boards/ endpoints in the Pinterest API. -type MeSearchBoardsController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeSearchBoardsController instantiates a new MeSearchBoardsController -func newMeSearchBoardsController(wc *wrecker.Wrecker) *MeSearchBoardsController { - return &MeSearchBoardsController{ - wreckerClient: wc, - } -} - -// MeSearchBoardsFetchOptionals is a struct that represents the optional parameters -// that can be passed to the Fetch endpoint -type MeSearchBoardsFetchOptionals struct { - Cursor string - Limit int -} - -// Fetch searches the logged in user's Boards -// Endpoint: [GET] /v1/me/search/boards/ -func (msbc *MeSearchBoardsController) Fetch(query string, optionals *MeSearchBoardsFetchOptionals) (*[]models.Board, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Board{} - request := msbc.wreckerClient.Get("/me/search/boards/"). - URLParam("fields", models.BOARD_FIELDS). - URLParam("query", query). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - if optionals.Limit != 0 { - request.URLParam("limit", strconv.Itoa(optionals.Limit)) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Board), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_search_controller.go deleted file mode 100644 index 2fd332c..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_controller.go +++ /dev/null @@ -1,22 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" -) - -// MeSearchController is the controller that is responsible for all -// /v1/me/search/ endpoints in the Pinterest API. -type MeSearchController struct { - wreckerClient *wrecker.Wrecker - Boards *MeSearchBoardsController - Pins *MeSearchPinsController -} - -// newMeSearchController instantiates a new MeSearchController -func newMeSearchController(wc *wrecker.Wrecker) *MeSearchController { - return &MeSearchController{ - wreckerClient: wc, - Boards: newMeSearchBoardsController(wc), - Pins: newMeSearchPinsController(wc), - } -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_pins_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/me_search_pins_controller.go deleted file mode 100644 index 2082dda..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/me_search_pins_controller.go +++ /dev/null @@ -1,54 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" - "strconv" -) - -// MeSearchPinsController is the controller that is responsible for all -// /v1/me/search/pins/ endpoints in the Pinterest API. -type MeSearchPinsController struct { - wreckerClient *wrecker.Wrecker -} - -// newMeSearchPinsController instantiates a new MeSearchPinsController -func newMeSearchPinsController(wc *wrecker.Wrecker) *MeSearchPinsController { - return &MeSearchPinsController{ - wreckerClient: wc, - } -} - -// MeSearchPinsFetchOptionals is a struct that represents the optional parameters -// that can be passed to the Fetch endpoint -type MeSearchPinsFetchOptionals struct { - Cursor string - Limit int -} - -// Fetch searches the logged in user's Pins -// Endpoint: [GET] /v1/me/search/pins/ -func (mspc *MeSearchPinsController) Fetch(query string, optionals *MeSearchPinsFetchOptionals) (*[]models.Pin, *models.Page, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = &[]models.Pin{} - request := mspc.wreckerClient.Get("/me/search/pins/"). - URLParam("fields", models.PIN_FIELDS). - URLParam("query", query). - Into(resp) - if optionals.Cursor != "" { - request.URLParam("cursor", optionals.Cursor) - } - if optionals.Limit != 0 { - request.URLParam("limit", strconv.Itoa(optionals.Limit)) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, nil, err - } - - // OK - return resp.Data.(*[]models.Pin), &resp.Page, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/oauth_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/oauth_controller.go deleted file mode 100644 index ec3c972..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/oauth_controller.go +++ /dev/null @@ -1,20 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" -) - -// OAuthController is the controller that is responsible -// for all /v1/oauth endpoints in the Pinterest API. -type OAuthController struct { - wreckerClient *wrecker.Wrecker - Token *OAuthTokenController -} - -// NewOAuthController instantiates a new OAuthController -func NewOAuthController(wc *wrecker.Wrecker) *OAuthController { - return &OAuthController{ - wreckerClient: wc, - Token: newOAuthTokenController(wc), - } -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/oauth_token_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/oauth_token_controller.go deleted file mode 100644 index bb9d65d..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/oauth_token_controller.go +++ /dev/null @@ -1,49 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// OAuthTokenController is the controller that is responsible -// for all /v1/oauth/token endpoints in the Pinterest API. -type OAuthTokenController struct { - wreckerClient *wrecker.Wrecker -} - -// newOAuthTokenController instantiates a new OAuthTokenController -func newOAuthTokenController(wc *wrecker.Wrecker) *OAuthTokenController { - return &OAuthTokenController{ - wreckerClient: wc, - } -} - -// Create generates an access token -// Endpoint: [POST] /v1/oauth/token -func (otc *OAuthTokenController) Create(clientId, clientSecret, accessCode string) (*models.AccessToken, error) { - // Build + execute request - accessToken := new(models.AccessToken) - httpResp, err := otc.wreckerClient.Post("/oauth/token"). - URLParam("grant_type", "authorization_code"). - URLParam("client_id", clientId). - URLParam("client_secret", clientSecret). - URLParam("code", accessCode). - Into(accessToken). - Execute() - - if err != nil { - if _, ok := err.(wrecker.ResponseError); !ok { - return nil, err - } - } - - if !(httpResp.StatusCode >= 200 && httpResp.StatusCode < 300) { - return nil, &models.PinterestError{ - StatusCode: httpResp.StatusCode, - Message: accessToken.Error, - } - } - - // OK - return accessToken, nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/pins_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/pins_controller.go deleted file mode 100644 index 4b935cc..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/pins_controller.go +++ /dev/null @@ -1,144 +0,0 @@ -package controllers - -import ( - "bufio" - "encoding/base64" - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" - "os" -) - -// PinsController is the controller that is responsible for all -// /v1/pins/ endpoints in the Pinterest API. -type PinsController struct { - wreckerClient *wrecker.Wrecker -} - -// NewPinsController instantiates a new PinsController -func NewPinsController(wc *wrecker.Wrecker) *PinsController { - return &PinsController{ - wreckerClient: wc, - } -} - -// Fetch loads a pin from the pin id -// Endpoint: [GET] /v1/pins// -func (pc *PinsController) Fetch(pinId string) (*models.Pin, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Pin) - httpResp, err := pc.wreckerClient.Get("/pins/"+pinId+"/"). - URLParam("fields", models.PIN_FIELDS). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Pin), nil -} - -// PinCreateOptionals is a struct that represents the optional parameters -// that can be passed to the Create endpoint -type PinCreateOptionals struct { - Link string - ImageUrl string - Image *os.File -} - -// Create creates a new pin -// Endpoint: [POST] /v1/pins/ -func (pc *PinsController) Create(boardSpec string, note string, optionals *PinCreateOptionals) (*models.Pin, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Pin) - request := pc.wreckerClient.Post("/pins/"). - URLParam("fields", models.PIN_FIELDS). - FormParam("board", boardSpec). - FormParam("note", note). - Into(resp) - if optionals.Link != "" { - request.FormParam("link", optionals.Link) - } - // Handle Image - if optionals.ImageUrl != "" { - request.FormParam("image_url", optionals.ImageUrl) - } else if fileInfo, err := optionals.Image.Stat(); err == nil { - // Create a new buffer based on file size - var size int64 = fileInfo.Size() - buf := make([]byte, size) - - // Read file content into buffer - fReader := bufio.NewReader(optionals.Image) - fReader.Read(buf) - - // Convert the buffer bytes to base64 string - imageBase64Str := base64.StdEncoding.EncodeToString(buf) - request.FormParam("image_base64", imageBase64Str) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Pin), nil -} - -// PinUpdateOptionals is a struct that represents the optional parameters -// that can be passed to the Update endpoint -type PinUpdateOptionals struct { - Board string - Note string - Link string -} - -// Update updates an existing pin -// Endpoint: [PATCH] /v1/pins// -func (pc *PinsController) Update(pinId string, optionals *PinUpdateOptionals) (*models.Pin, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.Pin) - request := pc.wreckerClient.Patch("/pins/"+pinId+"/"). - URLParam("fields", models.PIN_FIELDS). - Into(resp) - if optionals.Board != "" { - request.FormParam("board", optionals.Board) - } - if optionals.Note != "" { - request.FormParam("note", optionals.Note) - } - if optionals.Link != "" { - request.FormParam("link", optionals.Link) - } - httpResp, err := request.Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.Pin), nil -} - -// Delete deletes an existing pin -// Endpoint: [DELETE] /v1/pins// -func (pc *PinsController) Delete(pinId string) error { - // Execute Request - resp := new(models.Response) - httpResp, err := pc.wreckerClient.Delete("/pins/" + pinId + "/").Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return err - } - - // OK - return nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/controllers/users_controller.go b/vendor/github.com/a-frony/go-pinterest/controllers/users_controller.go deleted file mode 100644 index 56bd7e4..0000000 --- a/vendor/github.com/a-frony/go-pinterest/controllers/users_controller.go +++ /dev/null @@ -1,39 +0,0 @@ -package controllers - -import ( - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/models" -) - -// UsersController is the controller that is responsible for all -// /v1/users/ endpoints in the Pinterest API. -type UsersController struct { - wreckerClient *wrecker.Wrecker -} - -// NewUsersController instantiates a new UsersController. -func NewUsersController(wc *wrecker.Wrecker) *UsersController { - return &UsersController{ - wreckerClient: wc, - } -} - -// Fetch loads a user from their username. -// Endpoint: [GET] /v1/users// -func (uc *UsersController) Fetch(username string) (*models.User, error) { - // Build + execute request - resp := new(models.Response) - resp.Data = new(models.User) - httpResp, err := uc.wreckerClient.Get("/users/"+username+"/"). - URLParam("fields", models.USER_FIELDS). - Into(resp). - Execute() - - // Check Error - if err = models.WrapPinterestError(httpResp, resp, err); err != nil { - return nil, err - } - - // OK - return resp.Data.(*models.User), nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/glide.lock b/vendor/github.com/a-frony/go-pinterest/glide.lock deleted file mode 100644 index e012bb7..0000000 --- a/vendor/github.com/a-frony/go-pinterest/glide.lock +++ /dev/null @@ -1,22 +0,0 @@ -hash: 6799a096754d6da07971b6451883f8ff00ba08dd697aec8b6ac9989b460f6527 -updated: 2017-10-12T14:55:25.756899851-04:00 -imports: -- name: github.com/BrandonRomano/iso8601 - version: 2ef8540f216c9c1c6768cbff3cfbbe7b0196c05e -- name: github.com/BrandonRomano/wrecker - version: b08d8b57181a6d6ae75bdf70f6cd8b57ea3eb755 -testImports: -- name: github.com/davecgh/go-spew - version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 - subpackages: - - spew -- name: github.com/pmezard/go-difflib - version: d8ed2627bdf02c080bf22230dbb337003b7aba2d - subpackages: - - difflib -- name: github.com/stretchr/testify - version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 - subpackages: - - assert - - require - - suite diff --git a/vendor/github.com/a-frony/go-pinterest/glide.yaml b/vendor/github.com/a-frony/go-pinterest/glide.yaml deleted file mode 100644 index 25a7409..0000000 --- a/vendor/github.com/a-frony/go-pinterest/glide.yaml +++ /dev/null @@ -1,17 +0,0 @@ -package: github.com/a-frony/go-pinterest -homepage: https://github.com/a-frony/go-pinterest -license: MIT -owners: -- name: a-frony Creative - email: hello@a-frony.is - homepage: https://a-frony.is -- name: Brandon Romano - email: BrandonRRomano@gmail.com -import: -- package: github.com/BrandonRomano/wrecker - version: v0.1.4 -- package: github.com/BrandonRomano/iso8601 - version: v0.1.0 -testImport: -- package: github.com/stretchr/testify - version: v1.1.4 diff --git a/vendor/github.com/a-frony/go-pinterest/go_pinterest.png b/vendor/github.com/a-frony/go-pinterest/go_pinterest.png deleted file mode 100644 index e9ecbcf..0000000 Binary files a/vendor/github.com/a-frony/go-pinterest/go_pinterest.png and /dev/null differ diff --git a/vendor/github.com/a-frony/go-pinterest/models/access_token.go b/vendor/github.com/a-frony/go-pinterest/models/access_token.go deleted file mode 100644 index 048e73a..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/access_token.go +++ /dev/null @@ -1,11 +0,0 @@ -package models - -// AccessToken is a struct that represents a Access Token -// response from the Pinterest API. -type AccessToken struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - Scope []string `json:"scope"` - ErrorDescription string `json:"error_description"` - Error string `json:"error"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/board.go b/vendor/github.com/a-frony/go-pinterest/models/board.go deleted file mode 100644 index b5aab95..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/board.go +++ /dev/null @@ -1,27 +0,0 @@ -package models - -import ( - "github.com/BrandonRomano/iso8601" -) - -const BOARD_FIELDS = "id,url,reason,counts,created_at,creator,description,image,privacy,name" - -// Board is a struct that represents an individual board -// from the Pinterest API. -type Board struct { - Id string `json:"id"` - Name string `json:"name"` - Url string `json:"url"` - Description string `json:"description"` - Creator Creator `json:"creator"` - CreatedAt iso8601.Time `json:"created_at"` - Counts BoardCounts `json:"counts"` - Image Images `json:"image"` - Privacy string `json:"privacy"` -} - -type BoardCounts struct { - Pins int32 `json:"pins"` - Collaborators int32 `json:"collaborators"` - Followers int32 `json:"followers"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/creator.go b/vendor/github.com/a-frony/go-pinterest/models/creator.go deleted file mode 100644 index 7fce8aa..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/creator.go +++ /dev/null @@ -1,8 +0,0 @@ -package models - -type Creator struct { - Url string `json:"url"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Id string `json:"id"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/images.go b/vendor/github.com/a-frony/go-pinterest/models/images.go deleted file mode 100644 index d68ebc7..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/images.go +++ /dev/null @@ -1,11 +0,0 @@ -package models - -type Images struct { - Size_60x60 Image `json:"60x60"` -} - -type Image struct { - Url string `json:"url"` - Width int32 `json:"width"` - Height int32 `json:"height"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/interest.go b/vendor/github.com/a-frony/go-pinterest/models/interest.go deleted file mode 100644 index 8850af5..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/interest.go +++ /dev/null @@ -1,10 +0,0 @@ -package models - -const INTEREST_FIELDS = "id,name" - -// Interest is a struct that represents an individual interest -// from the Pinterest API. -type Interest struct { - Id string `json:"id"` - Name string `json:"name"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/pin.go b/vendor/github.com/a-frony/go-pinterest/models/pin.go deleted file mode 100644 index 7df452a..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/pin.go +++ /dev/null @@ -1,46 +0,0 @@ -package models - -import "github.com/BrandonRomano/iso8601" - -const PIN_FIELDS = "id,link,note,url,attribution,color,board,counts,created_at,creator,image,media,metadata,original_link" - -type Pin struct { - Id string `json:"id"` - Link string `json:"link"` - Url string `json:"url"` - Creator Creator `json:"creator"` - Board Board `json:"board"` - CreatedAt iso8601.Time `json:"created_at"` - Note string `json:"note"` - Color string `json:"color"` - Counts PinCounts `json:"counts"` - Media Media `json:"json:"media"` - OriginalLink string `json:"original_link"` - Attribution Attribution `json:"attribution"` - Image PinImage `json:"image"` - Metadata PinMetadata `json:"metadata"` -} - -type PinImage struct { - Original Image `json:"original"` -} - -type PinCounts struct { - Likes int32 `json:"likes"` - Comments int32 `json:"comments"` - Repins int32 `json:"repins"` -} - -type Media struct { - Type string `json:"type"` -} - -type Attribution struct { - Title string `json:"title"` - Url string `json:"url"` - ProviderIconUrl string `json:"provider_icon_url"` - AuthorName string `json:"author_name"` - ProviderFaviconUrl string `json:"provider_favicon_url"` - AuthorUrl string `json:"author_url"` - ProviderName string `json:"provider_name"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/pin_metadata.go b/vendor/github.com/a-frony/go-pinterest/models/pin_metadata.go deleted file mode 100644 index d4283e6..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/pin_metadata.go +++ /dev/null @@ -1,96 +0,0 @@ -package models - -import ( - "github.com/BrandonRomano/iso8601" -) - -type PinMetadata struct { - Article Article `json:"article"` - Link Link `json:"link"` - Place Place `json:"place"` - Movie Movie `json:"movie"` - Product Product `json:"product"` -} - -type MetadataPerson struct { - Name string `json:"name"` -} - -// ========== Meta: Article ========== - -type Article struct { - PublishedAt iso8601.Time `json:"published_at"` - Description string `json:"description"` - Name string `json:"name"` - Authors []MetadataPerson `json:"authors"` -} - -// ========== Meta: Link ========== - -type Link struct { - Locale string `json:"locale"` - Title string `json:"title"` - SiteName string `json:"site_name"` - Description string `json:"description"` - Favicon string `json:"favicon"` -} - -// ========== Meta: Place ========== - -type Place struct { - Category string `json:"category"` - Name string `json:"name"` - Locality string `json:"locality"` - Country string `json:"country"` - Region string `json:"region"` - Longitude float32 `json:"longitude"` - SourceUrl string `json:"source_url"` - Street string `json:"street"` - PostalCode string `json:"postal_code"` - Latitude float32 `json:"latitude"` -} - -// ========== Meta: Movie ========== - -type Movie struct { - Rating string `json:"rating"` - Directors []MetadataPerson `json:"directors"` - Actors []MetadataPerson `json:"actors"` - Name string `json:"name"` - PublishedAt iso8601.Time `json:"published_at"` -} - -// ========== Meta: Product ========== - -type Product struct { - Name string `json:"name"` - Offer ProductOffer `json:"offer"` -} - -type ProductOffer struct { - Price string `json:"price"` - InStock bool `json:"in_stock"` -} - -// ========== Meta: Recipe ========== - -type Recipe struct { - Servings RecipeServings `json:"servings"` - Name string `json:"name"` - Ingredients []RecipeCategory `json:"ingredients"` -} - -type RecipeServings struct { - Serves string `json:"serves"` - Summary string `json:"summary"` -} - -type RecipeCategory struct { - Category string `json:"category"` - Ingredients []RecipeIngredient `json:"ingredients"` -} - -type RecipeIngredient struct { - Amount string `json:"amount"` - Name string `json:"name"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/pinterest_error.go b/vendor/github.com/a-frony/go-pinterest/models/pinterest_error.go deleted file mode 100644 index dc472f5..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/pinterest_error.go +++ /dev/null @@ -1,41 +0,0 @@ -package models - -import ( - "encoding/json" - "net/http" - - "github.com/BrandonRomano/wrecker" -) - -// PinterestError is a custom error that is passed for all -// non 200 responses from the API. -type PinterestError struct { - StatusCode int `json:"status_code"` - Message string `json:"message"` - Limit TypeRatelimit -} - -func (e *PinterestError) Error() string { - out, _ := json.Marshal(e) - return "PinterestError: " + string(out) -} - -// WrapPinterestError takes a *http.Response and a Response and returns a -// PinterestError if one should be returned. -func WrapPinterestError(httpResponse *http.Response, bodyResponse *Response, err error) error { - if err != nil { - if _, ok := err.(wrecker.ResponseError); !ok { - return err - } - } - - if !(httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300) { - return &PinterestError{ - StatusCode: httpResponse.StatusCode, - Message: bodyResponse.Message, - Limit: GetRatelimit(httpResponse), - } - } - - return nil -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/rate_limit.go b/vendor/github.com/a-frony/go-pinterest/models/rate_limit.go deleted file mode 100644 index 7d7d24c..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/rate_limit.go +++ /dev/null @@ -1,34 +0,0 @@ -package models - -import ( - "net/http" - "strconv" - "fmt" -) - -type TypeRatelimit struct { - Remaining int - Limit int - Refresh int -} - -func GetLimit(httpResp *http.Response, key string) int { - if val, ok := httpResp.Header[key]; ok { - rateLimit, err := strconv.Atoi(val[0]) - if err != nil { - fmt.Println(err) - return 0 - } - return rateLimit - } - return 0 -} - -func GetRatelimit(httpResp *http.Response) TypeRatelimit { - return TypeRatelimit { - Remaining: GetLimit(httpResp, "X-Ratelimit-Remaining"), - Limit: GetLimit(httpResp, "X-Ratelimit-Limit"), - Refresh: GetLimit(httpResp, "X-Ratelimit-Refresh"), - } -} - diff --git a/vendor/github.com/a-frony/go-pinterest/models/response.go b/vendor/github.com/a-frony/go-pinterest/models/response.go deleted file mode 100644 index 37d58bf..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/response.go +++ /dev/null @@ -1,15 +0,0 @@ -package models - -// Response is the base struct for all responses -// that come back from the Pinterest API. -type Response struct { - Data interface{} `json:"data"` - Message string `json:"message"` - Type string `json:"type"` - Page Page `json:"page"` -} - -type Page struct { - Cursor string `json:"cursor"` - Next string `json:"next"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/models/user.go b/vendor/github.com/a-frony/go-pinterest/models/user.go deleted file mode 100644 index 4a87b1a..0000000 --- a/vendor/github.com/a-frony/go-pinterest/models/user.go +++ /dev/null @@ -1,30 +0,0 @@ -package models - -import ( - "github.com/BrandonRomano/iso8601" -) - -const USER_FIELDS = "first_name,last_name,url,account_type,bio,counts,created_at,id,image,username" - -// User is a struct that represents an individual user -// from the Pinterest API. -type User struct { - Id string `json:"id"` - Username string `json:"username"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Bio string `json:"bio"` - AccountType string `json:"account_type"` - Url string `json:"account_type"` - CreatedAt iso8601.Time `json:"created_at"` - Counts UserCounts `json:"counts"` - Image Images `json:"image"` -} - -type UserCounts struct { - Pins int32 `json:"pins"` - Following int32 `json:"following"` - Followers int32 `json:"followers"` - Boards int32 `json:"boards"` - Likes int32 `json:"likes"` -} diff --git a/vendor/github.com/a-frony/go-pinterest/pinterest.go b/vendor/github.com/a-frony/go-pinterest/pinterest.go deleted file mode 100644 index 69e3166..0000000 --- a/vendor/github.com/a-frony/go-pinterest/pinterest.go +++ /dev/null @@ -1,68 +0,0 @@ -package pinterest - -import ( - "net/http" - "time" - - "github.com/BrandonRomano/wrecker" - "github.com/a-frony/go-pinterest/controllers" -) - -// Client is an API client that connects you with the -// Pinterest API. All API requests will be called through -// an instance of this struct. -// -// Do not instantiate a Client manually, but call the NewClient -// function, which will return you a properly prepared instance. -// -// For more information about the Pinterest API, -// check out https://developers.pinterest.com/ -type Client struct { - OAuth *controllers.OAuthController - Users *controllers.UsersController - Boards *controllers.BoardsController - Pins *controllers.PinsController - Me *controllers.MeController - wreckerClient *wrecker.Wrecker -} - -// NewClient generates a new instance of a Client, which will -// allow you to interact with the Pinterest API. -func NewClient() *Client { - // Build Wrecker client - wc := &wrecker.Wrecker{ - BaseURL: "https://api.pinterest.com/v1", - HttpClient: &http.Client{ - Timeout: 10 * time.Second, - }, - DefaultContentType: "application/json", - RequestInterceptor: nil, - } - - // Build Pinterest client - return &Client{ - wreckerClient: wc, - OAuth: controllers.NewOAuthController(wc), - Users: controllers.NewUsersController(wc), - Boards: controllers.NewBoardsController(wc), - Pins: controllers.NewPinsController(wc), - Me: controllers.NewMeController(wc), - } -} - -// RegisterAccessToken registers an AccessToken on an existing Client. -// All following requests made with the Client will be authorized with -// the specified AccessToken. -func (pc *Client) RegisterAccessToken(accessToken string) *Client { - pc.wreckerClient.RequestInterceptor = func(req *wrecker.Request) error { - req.URLParam("access_token", accessToken) - return nil - } - return pc -} - -// SetHttpClient sets the underlying http.Client that runs all API requests -func (pc *Client) SetHttpClient(client *http.Client) *Client { - pc.wreckerClient.HttpClient = client - return pc -} diff --git a/vendor/github.com/carbocation/go-instagram/AUTHORS b/vendor/github.com/carbocation/go-instagram/AUTHORS deleted file mode 100644 index bb008bb..0000000 --- a/vendor/github.com/carbocation/go-instagram/AUTHORS +++ /dev/null @@ -1,5 +0,0 @@ -Akeda Bagus -Kir Shatrov -Peter DeGroff -Riccardo Volonterio | @Volox on Github -Carbocation | @carbocation on Github \ No newline at end of file diff --git a/vendor/github.com/carbocation/go-instagram/LICENSE.md b/vendor/github.com/carbocation/go-instagram/LICENSE.md deleted file mode 100644 index 17abc87..0000000 --- a/vendor/github.com/carbocation/go-instagram/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2013 The go-instagram AUTHORS. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml deleted file mode 100644 index 5769aa1..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go - -go: - - '1.10' - - '1.11' - - tip diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt deleted file mode 100644 index b1fef93..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Syfaro - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md deleted file mode 100644 index bf341d2..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# Golang bindings for the Telegram Bot API - -[![GoDoc](https://godoc.org/github.com/go-telegram-bot-api/telegram-bot-api?status.svg)](http://godoc.org/github.com/go-telegram-bot-api/telegram-bot-api) -[![Travis](https://travis-ci.org/go-telegram-bot-api/telegram-bot-api.svg)](https://travis-ci.org/go-telegram-bot-api/telegram-bot-api) - -All methods are fairly self explanatory, and reading the godoc page should -explain everything. If something isn't clear, open an issue or submit -a pull request. - -The scope of this project is just to provide a wrapper around the API -without any additional features. There are other projects for creating -something with plugins and command handlers without having to design -all that yourself. - -Join [the development group](https://telegram.me/go_telegram_bot_api) if -you want to ask questions or discuss development. - -## Example - -First, ensure the library is installed and up to date by running -`go get -u github.com/go-telegram-bot-api/telegram-bot-api`. - -This is a very simple bot that just displays any gotten updates, -then replies it to that chat. - -```go -package main - -import ( - "log" - - "github.com/go-telegram-bot-api/telegram-bot-api" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := tgbotapi.NewUpdate(0) - u.Timeout = 60 - - updates, err := bot.GetUpdatesChan(u) - - for update := range updates { - if update.Message == nil { // ignore any non-Message Updates - continue - } - - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID - - bot.Send(msg) - } -} -``` - -There are more examples on the [wiki](https://github.com/go-telegram-bot-api/telegram-bot-api/wiki) -with detailed information on how to do many different kinds of things. -It's a great place to get started on using keyboards, commands, or other -kinds of reply markup. - -If you need to use webhooks (if you wish to run on Google App Engine), -you may use a slightly different method. - -```go -package main - -import ( - "log" - "net/http" - - "github.com/go-telegram-bot-api/telegram-bot-api" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Fatal(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")) - if err != nil { - log.Fatal(err) - } - info, err := bot.GetWebhookInfo() - if err != nil { - log.Fatal(err) - } - if info.LastErrorDate != 0 { - log.Printf("Telegram callback failed: %s", info.LastErrorMessage) - } - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } -} -``` - -If you need, you may generate a self signed certficate, as this requires -HTTPS / TLS. The above example tells Telegram that this is your -certificate and that it should be trusted, even though it is not -properly signed. - - openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes - -Now that [Let's Encrypt](https://letsencrypt.org) is available, -you may wish to generate your free TLS certificate there. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go deleted file mode 100644 index a996790..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go +++ /dev/null @@ -1,976 +0,0 @@ -// Package tgbotapi has functions and types used for interacting with -// the Telegram Bot API. -package tgbotapi - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/technoweenie/multipartstreamer" -) - -// BotAPI allows you to interact with the Telegram Bot API. -type BotAPI struct { - Token string `json:"token"` - Debug bool `json:"debug"` - Buffer int `json:"buffer"` - - Self User `json:"-"` - Client *http.Client `json:"-"` - shutdownChannel chan interface{} - - apiEndpoint string -} - -// NewBotAPI creates a new BotAPI instance. -// -// It requires a token, provided by @BotFather on Telegram. -func NewBotAPI(token string) (*BotAPI, error) { - return NewBotAPIWithClient(token, &http.Client{}) -} - -// NewBotAPIWithClient creates a new BotAPI instance -// and allows you to pass a http.Client. -// -// It requires a token, provided by @BotFather on Telegram. -func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) { - bot := &BotAPI{ - Token: token, - Client: client, - Buffer: 100, - shutdownChannel: make(chan interface{}), - - apiEndpoint: APIEndpoint, - } - - self, err := bot.GetMe() - if err != nil { - return nil, err - } - - bot.Self = self - - return bot, nil -} - -func (b *BotAPI) SetAPIEndpoint(apiEndpoint string) { - b.apiEndpoint = apiEndpoint -} - -// MakeRequest makes a request to a specific endpoint with our token. -func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) { - method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - - resp, err := bot.Client.PostForm(method, params) - if err != nil { - return APIResponse{}, err - } - defer resp.Body.Close() - - var apiResp APIResponse - bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp) - if err != nil { - return apiResp, err - } - - if bot.Debug { - log.Printf("%s resp: %s", endpoint, bytes) - } - - if !apiResp.Ok { - parameters := ResponseParameters{} - if apiResp.Parameters != nil { - parameters = *apiResp.Parameters - } - return apiResp, Error{Code: apiResp.ErrorCode, Message: apiResp.Description, ResponseParameters: parameters} - } - - return apiResp, nil -} - -// decodeAPIResponse decode response and return slice of bytes if debug enabled. -// If debug disabled, just decode http.Response.Body stream to APIResponse struct -// for efficient memory usage -func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) { - if !bot.Debug { - dec := json.NewDecoder(responseBody) - err = dec.Decode(resp) - return - } - - // if debug, read reponse body - data, err := ioutil.ReadAll(responseBody) - if err != nil { - return - } - - err = json.Unmarshal(data, resp) - if err != nil { - return - } - - return data, nil -} - -// makeMessageRequest makes a request to a method that returns a Message. -func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { - resp, err := bot.MakeRequest(endpoint, params) - if err != nil { - return Message{}, err - } - - var message Message - json.Unmarshal(resp.Result, &message) - - bot.debugLog(endpoint, params, message) - - return message, nil -} - -// UploadFile makes a request to the API with a file. -// -// Requires the parameter to hold the file not be in the params. -// File should be a string to a file path, a FileBytes struct, -// a FileReader struct, or a url.URL. -// -// Note that if your FileReader has a size set to -1, it will read -// the file into memory to calculate a size. -func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) { - ms := multipartstreamer.New() - - switch f := file.(type) { - case string: - ms.WriteFields(params) - - fileHandle, err := os.Open(f) - if err != nil { - return APIResponse{}, err - } - defer fileHandle.Close() - - fi, err := os.Stat(f) - if err != nil { - return APIResponse{}, err - } - - ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle) - case FileBytes: - ms.WriteFields(params) - - buf := bytes.NewBuffer(f.Bytes) - ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf) - case FileReader: - ms.WriteFields(params) - - if f.Size != -1 { - ms.WriteReader(fieldname, f.Name, f.Size, f.Reader) - - break - } - - data, err := ioutil.ReadAll(f.Reader) - if err != nil { - return APIResponse{}, err - } - - buf := bytes.NewBuffer(data) - - ms.WriteReader(fieldname, f.Name, int64(len(data)), buf) - case url.URL: - params[fieldname] = f.String() - - ms.WriteFields(params) - default: - return APIResponse{}, errors.New(ErrBadFileType) - } - - method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - - req, err := http.NewRequest("POST", method, nil) - if err != nil { - return APIResponse{}, err - } - - ms.SetupRequest(req) - - res, err := bot.Client.Do(req) - if err != nil { - return APIResponse{}, err - } - defer res.Body.Close() - - bytes, err := ioutil.ReadAll(res.Body) - if err != nil { - return APIResponse{}, err - } - - if bot.Debug { - log.Println(string(bytes)) - } - - var apiResp APIResponse - - err = json.Unmarshal(bytes, &apiResp) - if err != nil { - return APIResponse{}, err - } - - if !apiResp.Ok { - return APIResponse{}, errors.New(apiResp.Description) - } - - return apiResp, nil -} - -// GetFileDirectURL returns direct URL to file -// -// It requires the FileID. -func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { - file, err := bot.GetFile(FileConfig{fileID}) - - if err != nil { - return "", err - } - - return file.Link(bot.Token), nil -} - -// GetMe fetches the currently authenticated bot. -// -// This method is called upon creation to validate the token, -// and so you may get this data from BotAPI.Self without the need for -// another request. -func (bot *BotAPI) GetMe() (User, error) { - resp, err := bot.MakeRequest("getMe", nil) - if err != nil { - return User{}, err - } - - var user User - json.Unmarshal(resp.Result, &user) - - bot.debugLog("getMe", nil, user) - - return user, nil -} - -// IsMessageToMe returns true if message directed to this bot. -// -// It requires the Message. -func (bot *BotAPI) IsMessageToMe(message Message) bool { - return strings.Contains(message.Text, "@"+bot.Self.UserName) -} - -// Send will send a Chattable item to Telegram. -// -// It requires the Chattable to send. -func (bot *BotAPI) Send(c Chattable) (Message, error) { - switch c.(type) { - case Fileable: - return bot.sendFile(c.(Fileable)) - default: - return bot.sendChattable(c) - } -} - -// debugLog checks if the bot is currently running in debug mode, and if -// so will display information about the request and response in the -// debug log. -func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) { - if bot.Debug { - log.Printf("%s req : %+v\n", context, v) - log.Printf("%s resp: %+v\n", context, message) - } -} - -// sendExisting will send a Message with an existing file to Telegram. -func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) { - v, err := config.values() - - if err != nil { - return Message{}, err - } - - message, err := bot.makeMessageRequest(method, v) - if err != nil { - return Message{}, err - } - - return message, nil -} - -// uploadAndSend will send a Message with a new file to Telegram. -func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) { - params, err := config.params() - if err != nil { - return Message{}, err - } - - file := config.getFile() - - resp, err := bot.UploadFile(method, params, config.name(), file) - if err != nil { - return Message{}, err - } - - var message Message - json.Unmarshal(resp.Result, &message) - - bot.debugLog(method, nil, message) - - return message, nil -} - -// sendFile determines if the file is using an existing file or uploading -// a new file, then sends it as needed. -func (bot *BotAPI) sendFile(config Fileable) (Message, error) { - if config.useExistingFile() { - return bot.sendExisting(config.method(), config) - } - - return bot.uploadAndSend(config.method(), config) -} - -// sendChattable sends a Chattable. -func (bot *BotAPI) sendChattable(config Chattable) (Message, error) { - v, err := config.values() - if err != nil { - return Message{}, err - } - - message, err := bot.makeMessageRequest(config.method(), v) - - if err != nil { - return Message{}, err - } - - return message, nil -} - -// GetUserProfilePhotos gets a user's profile photos. -// -// It requires UserID. -// Offset and Limit are optional. -func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) { - v := url.Values{} - v.Add("user_id", strconv.Itoa(config.UserID)) - if config.Offset != 0 { - v.Add("offset", strconv.Itoa(config.Offset)) - } - if config.Limit != 0 { - v.Add("limit", strconv.Itoa(config.Limit)) - } - - resp, err := bot.MakeRequest("getUserProfilePhotos", v) - if err != nil { - return UserProfilePhotos{}, err - } - - var profilePhotos UserProfilePhotos - json.Unmarshal(resp.Result, &profilePhotos) - - bot.debugLog("GetUserProfilePhoto", v, profilePhotos) - - return profilePhotos, nil -} - -// GetFile returns a File which can download a file from Telegram. -// -// Requires FileID. -func (bot *BotAPI) GetFile(config FileConfig) (File, error) { - v := url.Values{} - v.Add("file_id", config.FileID) - - resp, err := bot.MakeRequest("getFile", v) - if err != nil { - return File{}, err - } - - var file File - json.Unmarshal(resp.Result, &file) - - bot.debugLog("GetFile", v, file) - - return file, nil -} - -// GetUpdates fetches updates. -// If a WebHook is set, this will not return any data! -// -// Offset, Limit, and Timeout are optional. -// To avoid stale items, set Offset to one higher than the previous item. -// Set Timeout to a large number to reduce requests so you can get updates -// instantly instead of having to wait between requests. -func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { - v := url.Values{} - if config.Offset != 0 { - v.Add("offset", strconv.Itoa(config.Offset)) - } - if config.Limit > 0 { - v.Add("limit", strconv.Itoa(config.Limit)) - } - if config.Timeout > 0 { - v.Add("timeout", strconv.Itoa(config.Timeout)) - } - - resp, err := bot.MakeRequest("getUpdates", v) - if err != nil { - return []Update{}, err - } - - var updates []Update - json.Unmarshal(resp.Result, &updates) - - bot.debugLog("getUpdates", v, updates) - - return updates, nil -} - -// RemoveWebhook unsets the webhook. -func (bot *BotAPI) RemoveWebhook() (APIResponse, error) { - return bot.MakeRequest("setWebhook", url.Values{}) -} - -// SetWebhook sets a webhook. -// -// If this is set, GetUpdates will not get any data! -// -// If you do not have a legitimate TLS certificate, you need to include -// your self signed certificate with the config. -func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) { - - if config.Certificate == nil { - v := url.Values{} - v.Add("url", config.URL.String()) - if config.MaxConnections != 0 { - v.Add("max_connections", strconv.Itoa(config.MaxConnections)) - } - - return bot.MakeRequest("setWebhook", v) - } - - params := make(map[string]string) - params["url"] = config.URL.String() - if config.MaxConnections != 0 { - params["max_connections"] = strconv.Itoa(config.MaxConnections) - } - - resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate) - if err != nil { - return APIResponse{}, err - } - - return resp, nil -} - -// GetWebhookInfo allows you to fetch information about a webhook and if -// one currently is set, along with pending update count and error messages. -func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { - resp, err := bot.MakeRequest("getWebhookInfo", url.Values{}) - if err != nil { - return WebhookInfo{}, err - } - - var info WebhookInfo - err = json.Unmarshal(resp.Result, &info) - - return info, err -} - -// GetUpdatesChan starts and returns a channel for getting updates. -func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) { - ch := make(chan Update, bot.Buffer) - - go func() { - for { - select { - case <-bot.shutdownChannel: - return - default: - } - - updates, err := bot.GetUpdates(config) - if err != nil { - log.Println(err) - log.Println("Failed to get updates, retrying in 3 seconds...") - time.Sleep(time.Second * 3) - - continue - } - - for _, update := range updates { - if update.UpdateID >= config.Offset { - config.Offset = update.UpdateID + 1 - ch <- update - } - } - } - }() - - return ch, nil -} - -// StopReceivingUpdates stops the go routine which receives updates -func (bot *BotAPI) StopReceivingUpdates() { - if bot.Debug { - log.Println("Stopping the update receiver routine...") - } - close(bot.shutdownChannel) -} - -// ListenForWebhook registers a http handler for a webhook. -func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { - ch := make(chan Update, bot.Buffer) - - http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - bytes, _ := ioutil.ReadAll(r.Body) - r.Body.Close() - - var update Update - json.Unmarshal(bytes, &update) - - ch <- update - }) - - return ch -} - -// AnswerInlineQuery sends a response to an inline query. -// -// Note that you must respond to an inline query within 30 seconds. -func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) { - v := url.Values{} - - v.Add("inline_query_id", config.InlineQueryID) - v.Add("cache_time", strconv.Itoa(config.CacheTime)) - v.Add("is_personal", strconv.FormatBool(config.IsPersonal)) - v.Add("next_offset", config.NextOffset) - data, err := json.Marshal(config.Results) - if err != nil { - return APIResponse{}, err - } - v.Add("results", string(data)) - v.Add("switch_pm_text", config.SwitchPMText) - v.Add("switch_pm_parameter", config.SwitchPMParameter) - - bot.debugLog("answerInlineQuery", v, nil) - - return bot.MakeRequest("answerInlineQuery", v) -} - -// AnswerCallbackQuery sends a response to an inline query callback. -func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) { - v := url.Values{} - - v.Add("callback_query_id", config.CallbackQueryID) - if config.Text != "" { - v.Add("text", config.Text) - } - v.Add("show_alert", strconv.FormatBool(config.ShowAlert)) - if config.URL != "" { - v.Add("url", config.URL) - } - v.Add("cache_time", strconv.Itoa(config.CacheTime)) - - bot.debugLog("answerCallbackQuery", v, nil) - - return bot.MakeRequest("answerCallbackQuery", v) -} - -// KickChatMember kicks a user from a chat. Note that this only will work -// in supergroups, and requires the bot to be an admin. Also note they -// will be unable to rejoin until they are unbanned. -func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - v.Add("user_id", strconv.Itoa(config.UserID)) - - if config.UntilDate != 0 { - v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) - } - - bot.debugLog("kickChatMember", v, nil) - - return bot.MakeRequest("kickChatMember", v) -} - -// LeaveChat makes the bot leave the chat. -func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - - bot.debugLog("leaveChat", v, nil) - - return bot.MakeRequest("leaveChat", v) -} - -// GetChat gets information about a chat. -func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - - resp, err := bot.MakeRequest("getChat", v) - if err != nil { - return Chat{}, err - } - - var chat Chat - err = json.Unmarshal(resp.Result, &chat) - - bot.debugLog("getChat", v, chat) - - return chat, err -} - -// GetChatAdministrators gets a list of administrators in the chat. -// -// If none have been appointed, only the creator will be returned. -// Bots are not shown, even if they are an administrator. -func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - - resp, err := bot.MakeRequest("getChatAdministrators", v) - if err != nil { - return []ChatMember{}, err - } - - var members []ChatMember - err = json.Unmarshal(resp.Result, &members) - - bot.debugLog("getChatAdministrators", v, members) - - return members, err -} - -// GetChatMembersCount gets the number of users in a chat. -func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - - resp, err := bot.MakeRequest("getChatMembersCount", v) - if err != nil { - return -1, err - } - - var count int - err = json.Unmarshal(resp.Result, &count) - - bot.debugLog("getChatMembersCount", v, count) - - return count, err -} - -// GetChatMember gets a specific chat member. -func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - v.Add("user_id", strconv.Itoa(config.UserID)) - - resp, err := bot.MakeRequest("getChatMember", v) - if err != nil { - return ChatMember{}, err - } - - var member ChatMember - err = json.Unmarshal(resp.Result, &member) - - bot.debugLog("getChatMember", v, member) - - return member, err -} - -// UnbanChatMember unbans a user from a chat. Note that this only will work -// in supergroups and channels, and requires the bot to be an admin. -func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { - v := url.Values{} - - if config.SuperGroupUsername != "" { - v.Add("chat_id", config.SuperGroupUsername) - } else if config.ChannelUsername != "" { - v.Add("chat_id", config.ChannelUsername) - } else { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } - v.Add("user_id", strconv.Itoa(config.UserID)) - - bot.debugLog("unbanChatMember", v, nil) - - return bot.MakeRequest("unbanChatMember", v) -} - -// RestrictChatMember to restrict a user in a supergroup. The bot must be an -//administrator in the supergroup for this to work and must have the -//appropriate admin rights. Pass True for all boolean parameters to lift -//restrictions from a user. Returns True on success. -func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { - v := url.Values{} - - if config.SuperGroupUsername != "" { - v.Add("chat_id", config.SuperGroupUsername) - } else if config.ChannelUsername != "" { - v.Add("chat_id", config.ChannelUsername) - } else { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } - v.Add("user_id", strconv.Itoa(config.UserID)) - - if config.CanSendMessages != nil { - v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) - } - if config.CanSendMediaMessages != nil { - v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) - } - if config.CanSendOtherMessages != nil { - v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) - } - if config.CanAddWebPagePreviews != nil { - v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) - } - if config.UntilDate != 0 { - v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) - } - - bot.debugLog("restrictChatMember", v, nil) - - return bot.MakeRequest("restrictChatMember", v) -} - -// PromoteChatMember add admin rights to user -func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { - v := url.Values{} - - if config.SuperGroupUsername != "" { - v.Add("chat_id", config.SuperGroupUsername) - } else if config.ChannelUsername != "" { - v.Add("chat_id", config.ChannelUsername) - } else { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } - v.Add("user_id", strconv.Itoa(config.UserID)) - - if config.CanChangeInfo != nil { - v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) - } - if config.CanPostMessages != nil { - v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) - } - if config.CanEditMessages != nil { - v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) - } - if config.CanDeleteMessages != nil { - v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) - } - if config.CanInviteUsers != nil { - v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) - } - if config.CanRestrictMembers != nil { - v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) - } - if config.CanPinMessages != nil { - v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) - } - if config.CanPromoteMembers != nil { - v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) - } - - bot.debugLog("promoteChatMember", v, nil) - - return bot.MakeRequest("promoteChatMember", v) -} - -// GetGameHighScores allows you to get the high scores for a game. -func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { - v, _ := config.values() - - resp, err := bot.MakeRequest(config.method(), v) - if err != nil { - return []GameHighScore{}, err - } - - var highScores []GameHighScore - err = json.Unmarshal(resp.Result, &highScores) - - return highScores, err -} - -// AnswerShippingQuery allows you to reply to Update with shipping_query parameter. -func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { - v := url.Values{} - - v.Add("shipping_query_id", config.ShippingQueryID) - v.Add("ok", strconv.FormatBool(config.OK)) - if config.OK == true { - data, err := json.Marshal(config.ShippingOptions) - if err != nil { - return APIResponse{}, err - } - v.Add("shipping_options", string(data)) - } else { - v.Add("error_message", config.ErrorMessage) - } - - bot.debugLog("answerShippingQuery", v, nil) - - return bot.MakeRequest("answerShippingQuery", v) -} - -// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query. -func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { - v := url.Values{} - - v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) - v.Add("ok", strconv.FormatBool(config.OK)) - if config.OK != true { - v.Add("error", config.ErrorMessage) - } - - bot.debugLog("answerPreCheckoutQuery", v, nil) - - return bot.MakeRequest("answerPreCheckoutQuery", v) -} - -// DeleteMessage deletes a message in a chat -func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} - -// GetInviteLink get InviteLink for a chat -func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { - v := url.Values{} - - if config.SuperGroupUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.SuperGroupUsername) - } - - resp, err := bot.MakeRequest("exportChatInviteLink", v) - if err != nil { - return "", err - } - - var inviteLink string - err = json.Unmarshal(resp.Result, &inviteLink) - - return inviteLink, err -} - -// PinChatMessage pin message in supergroup -func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} - -// UnpinChatMessage unpin message in supergroup -func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} - -// SetChatTitle change title of chat. -func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} - -// SetChatDescription change description of chat. -func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} - -// SetChatPhoto change photo of chat. -func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { - params, err := config.params() - if err != nil { - return APIResponse{}, err - } - - file := config.getFile() - - return bot.UploadFile(config.method(), params, config.name(), file) -} - -// DeleteChatPhoto delete photo of chat. -func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { - v, err := config.values() - if err != nil { - return APIResponse{}, err - } - - bot.debugLog(config.method(), v, nil) - - return bot.MakeRequest(config.method(), v) -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go deleted file mode 100644 index 181d4e4..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go +++ /dev/null @@ -1,1264 +0,0 @@ -package tgbotapi - -import ( - "encoding/json" - "io" - "net/url" - "strconv" -) - -// Telegram constants -const ( - // APIEndpoint is the endpoint for all API methods, - // with formatting for Sprintf. - APIEndpoint = "https://api.telegram.org/bot%s/%s" - // FileEndpoint is the endpoint for downloading a file from Telegram. - FileEndpoint = "https://api.telegram.org/file/bot%s/%s" -) - -// Constant values for ChatActions -const ( - ChatTyping = "typing" - ChatUploadPhoto = "upload_photo" - ChatRecordVideo = "record_video" - ChatUploadVideo = "upload_video" - ChatRecordAudio = "record_audio" - ChatUploadAudio = "upload_audio" - ChatUploadDocument = "upload_document" - ChatFindLocation = "find_location" -) - -// API errors -const ( - // ErrAPIForbidden happens when a token is bad - ErrAPIForbidden = "forbidden" -) - -// Constant values for ParseMode in MessageConfig -const ( - ModeMarkdown = "Markdown" - ModeHTML = "HTML" -) - -// Library errors -const ( - // ErrBadFileType happens when you pass an unknown type - ErrBadFileType = "bad file type" - ErrBadURL = "bad or empty url" -) - -// Chattable is any config type that can be sent. -type Chattable interface { - values() (url.Values, error) - method() string -} - -// Fileable is any config type that can be sent that includes a file. -type Fileable interface { - Chattable - params() (map[string]string, error) - name() string - getFile() interface{} - useExistingFile() bool -} - -// BaseChat is base type for all chat config types. -type BaseChat struct { - ChatID int64 // required - ChannelUsername string - ReplyToMessageID int - ReplyMarkup interface{} - DisableNotification bool -} - -// values returns url.Values representation of BaseChat -func (chat *BaseChat) values() (url.Values, error) { - v := url.Values{} - if chat.ChannelUsername != "" { - v.Add("chat_id", chat.ChannelUsername) - } else { - v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) - } - - if chat.ReplyToMessageID != 0 { - v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) - } - - if chat.ReplyMarkup != nil { - data, err := json.Marshal(chat.ReplyMarkup) - if err != nil { - return v, err - } - - v.Add("reply_markup", string(data)) - } - - v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) - - return v, nil -} - -// BaseFile is a base type for all file config types. -type BaseFile struct { - BaseChat - File interface{} - FileID string - UseExisting bool - MimeType string - FileSize int -} - -// params returns a map[string]string representation of BaseFile. -func (file BaseFile) params() (map[string]string, error) { - params := make(map[string]string) - - if file.ChannelUsername != "" { - params["chat_id"] = file.ChannelUsername - } else { - params["chat_id"] = strconv.FormatInt(file.ChatID, 10) - } - - if file.ReplyToMessageID != 0 { - params["reply_to_message_id"] = strconv.Itoa(file.ReplyToMessageID) - } - - if file.ReplyMarkup != nil { - data, err := json.Marshal(file.ReplyMarkup) - if err != nil { - return params, err - } - - params["reply_markup"] = string(data) - } - - if file.MimeType != "" { - params["mime_type"] = file.MimeType - } - - if file.FileSize > 0 { - params["file_size"] = strconv.Itoa(file.FileSize) - } - - params["disable_notification"] = strconv.FormatBool(file.DisableNotification) - - return params, nil -} - -// getFile returns the file. -func (file BaseFile) getFile() interface{} { - return file.File -} - -// useExistingFile returns if the BaseFile has already been uploaded. -func (file BaseFile) useExistingFile() bool { - return file.UseExisting -} - -// BaseEdit is base type of all chat edits. -type BaseEdit struct { - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string - ReplyMarkup *InlineKeyboardMarkup -} - -func (edit BaseEdit) values() (url.Values, error) { - v := url.Values{} - - if edit.InlineMessageID == "" { - if edit.ChannelUsername != "" { - v.Add("chat_id", edit.ChannelUsername) - } else { - v.Add("chat_id", strconv.FormatInt(edit.ChatID, 10)) - } - v.Add("message_id", strconv.Itoa(edit.MessageID)) - } else { - v.Add("inline_message_id", edit.InlineMessageID) - } - - if edit.ReplyMarkup != nil { - data, err := json.Marshal(edit.ReplyMarkup) - if err != nil { - return v, err - } - v.Add("reply_markup", string(data)) - } - - return v, nil -} - -// MessageConfig contains information about a SendMessage request. -type MessageConfig struct { - BaseChat - Text string - ParseMode string - DisableWebPagePreview bool -} - -// values returns a url.Values representation of MessageConfig. -func (config MessageConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - v.Add("text", config.Text) - v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - - return v, nil -} - -// method returns Telegram API method name for sending Message. -func (config MessageConfig) method() string { - return "sendMessage" -} - -// ForwardConfig contains information about a ForwardMessage request. -type ForwardConfig struct { - BaseChat - FromChatID int64 // required - FromChannelUsername string - MessageID int // required -} - -// values returns a url.Values representation of ForwardConfig. -func (config ForwardConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) - v.Add("message_id", strconv.Itoa(config.MessageID)) - return v, nil -} - -// method returns Telegram API method name for sending Forward. -func (config ForwardConfig) method() string { - return "forwardMessage" -} - -// PhotoConfig contains information about a SendPhoto request. -type PhotoConfig struct { - BaseFile - Caption string - ParseMode string -} - -// Params returns a map[string]string representation of PhotoConfig. -func (config PhotoConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// Values returns a url.Values representation of PhotoConfig. -func (config PhotoConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// name returns the field name for the Photo. -func (config PhotoConfig) name() string { - return "photo" -} - -// method returns Telegram API method name for sending Photo. -func (config PhotoConfig) method() string { - return "sendPhoto" -} - -// AudioConfig contains information about a SendAudio request. -type AudioConfig struct { - BaseFile - Caption string - ParseMode string - Duration int - Performer string - Title string -} - -// values returns a url.Values representation of AudioConfig. -func (config AudioConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Duration != 0 { - v.Add("duration", strconv.Itoa(config.Duration)) - } - - if config.Performer != "" { - v.Add("performer", config.Performer) - } - if config.Title != "" { - v.Add("title", config.Title) - } - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// params returns a map[string]string representation of AudioConfig. -func (config AudioConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Duration != 0 { - params["duration"] = strconv.Itoa(config.Duration) - } - - if config.Performer != "" { - params["performer"] = config.Performer - } - if config.Title != "" { - params["title"] = config.Title - } - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// name returns the field name for the Audio. -func (config AudioConfig) name() string { - return "audio" -} - -// method returns Telegram API method name for sending Audio. -func (config AudioConfig) method() string { - return "sendAudio" -} - -// DocumentConfig contains information about a SendDocument request. -type DocumentConfig struct { - BaseFile - Caption string - ParseMode string -} - -// values returns a url.Values representation of DocumentConfig. -func (config DocumentConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// params returns a map[string]string representation of DocumentConfig. -func (config DocumentConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// name returns the field name for the Document. -func (config DocumentConfig) name() string { - return "document" -} - -// method returns Telegram API method name for sending Document. -func (config DocumentConfig) method() string { - return "sendDocument" -} - -// StickerConfig contains information about a SendSticker request. -type StickerConfig struct { - BaseFile -} - -// values returns a url.Values representation of StickerConfig. -func (config StickerConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - - return v, nil -} - -// params returns a map[string]string representation of StickerConfig. -func (config StickerConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - return params, nil -} - -// name returns the field name for the Sticker. -func (config StickerConfig) name() string { - return "sticker" -} - -// method returns Telegram API method name for sending Sticker. -func (config StickerConfig) method() string { - return "sendSticker" -} - -// VideoConfig contains information about a SendVideo request. -type VideoConfig struct { - BaseFile - Duration int - Caption string - ParseMode string -} - -// values returns a url.Values representation of VideoConfig. -func (config VideoConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Duration != 0 { - v.Add("duration", strconv.Itoa(config.Duration)) - } - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// params returns a map[string]string representation of VideoConfig. -func (config VideoConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// name returns the field name for the Video. -func (config VideoConfig) name() string { - return "video" -} - -// method returns Telegram API method name for sending Video. -func (config VideoConfig) method() string { - return "sendVideo" -} - -// AnimationConfig contains information about a SendAnimation request. -type AnimationConfig struct { - BaseFile - Duration int - Caption string - ParseMode string -} - -// values returns a url.Values representation of AnimationConfig. -func (config AnimationConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Duration != 0 { - v.Add("duration", strconv.Itoa(config.Duration)) - } - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// params returns a map[string]string representation of AnimationConfig. -func (config AnimationConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// name returns the field name for the Animation. -func (config AnimationConfig) name() string { - return "animation" -} - -// method returns Telegram API method name for sending Animation. -func (config AnimationConfig) method() string { - return "sendAnimation" -} - -// VideoNoteConfig contains information about a SendVideoNote request. -type VideoNoteConfig struct { - BaseFile - Duration int - Length int -} - -// values returns a url.Values representation of VideoNoteConfig. -func (config VideoNoteConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Duration != 0 { - v.Add("duration", strconv.Itoa(config.Duration)) - } - - // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response - if config.Length != 0 { - v.Add("length", strconv.Itoa(config.Length)) - } - - return v, nil -} - -// params returns a map[string]string representation of VideoNoteConfig. -func (config VideoNoteConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Length != 0 { - params["length"] = strconv.Itoa(config.Length) - } - if config.Duration != 0 { - params["duration"] = strconv.Itoa(config.Duration) - } - - return params, nil -} - -// name returns the field name for the VideoNote. -func (config VideoNoteConfig) name() string { - return "video_note" -} - -// method returns Telegram API method name for sending VideoNote. -func (config VideoNoteConfig) method() string { - return "sendVideoNote" -} - -// VoiceConfig contains information about a SendVoice request. -type VoiceConfig struct { - BaseFile - Caption string - ParseMode string - Duration int -} - -// values returns a url.Values representation of VoiceConfig. -func (config VoiceConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add(config.name(), config.FileID) - if config.Duration != 0 { - v.Add("duration", strconv.Itoa(config.Duration)) - } - if config.Caption != "" { - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - } - - return v, nil -} - -// params returns a map[string]string representation of VoiceConfig. -func (config VoiceConfig) params() (map[string]string, error) { - params, _ := config.BaseFile.params() - - if config.Duration != 0 { - params["duration"] = strconv.Itoa(config.Duration) - } - if config.Caption != "" { - params["caption"] = config.Caption - if config.ParseMode != "" { - params["parse_mode"] = config.ParseMode - } - } - - return params, nil -} - -// name returns the field name for the Voice. -func (config VoiceConfig) name() string { - return "voice" -} - -// method returns Telegram API method name for sending Voice. -func (config VoiceConfig) method() string { - return "sendVoice" -} - -// MediaGroupConfig contains information about a sendMediaGroup request. -type MediaGroupConfig struct { - BaseChat - InputMedia []interface{} -} - -func (config MediaGroupConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - data, err := json.Marshal(config.InputMedia) - if err != nil { - return v, err - } - - v.Add("media", string(data)) - - return v, nil -} - -func (config MediaGroupConfig) method() string { - return "sendMediaGroup" -} - -// LocationConfig contains information about a SendLocation request. -type LocationConfig struct { - BaseChat - Latitude float64 // required - Longitude float64 // required -} - -// values returns a url.Values representation of LocationConfig. -func (config LocationConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) - v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) - - return v, nil -} - -// method returns Telegram API method name for sending Location. -func (config LocationConfig) method() string { - return "sendLocation" -} - -// VenueConfig contains information about a SendVenue request. -type VenueConfig struct { - BaseChat - Latitude float64 // required - Longitude float64 // required - Title string // required - Address string // required - FoursquareID string -} - -func (config VenueConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) - v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) - v.Add("title", config.Title) - v.Add("address", config.Address) - if config.FoursquareID != "" { - v.Add("foursquare_id", config.FoursquareID) - } - - return v, nil -} - -func (config VenueConfig) method() string { - return "sendVenue" -} - -// ContactConfig allows you to send a contact. -type ContactConfig struct { - BaseChat - PhoneNumber string - FirstName string - LastName string -} - -func (config ContactConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add("phone_number", config.PhoneNumber) - v.Add("first_name", config.FirstName) - v.Add("last_name", config.LastName) - - return v, nil -} - -func (config ContactConfig) method() string { - return "sendContact" -} - -// GameConfig allows you to send a game. -type GameConfig struct { - BaseChat - GameShortName string -} - -func (config GameConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - - v.Add("game_short_name", config.GameShortName) - - return v, nil -} - -func (config GameConfig) method() string { - return "sendGame" -} - -// SetGameScoreConfig allows you to update the game score in a chat. -type SetGameScoreConfig struct { - UserID int - Score int - Force bool - DisableEditMessage bool - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string -} - -func (config SetGameScoreConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("user_id", strconv.Itoa(config.UserID)) - v.Add("score", strconv.Itoa(config.Score)) - if config.InlineMessageID == "" { - if config.ChannelUsername == "" { - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - } else { - v.Add("chat_id", config.ChannelUsername) - } - v.Add("message_id", strconv.Itoa(config.MessageID)) - } else { - v.Add("inline_message_id", config.InlineMessageID) - } - v.Add("disable_edit_message", strconv.FormatBool(config.DisableEditMessage)) - - return v, nil -} - -func (config SetGameScoreConfig) method() string { - return "setGameScore" -} - -// GetGameHighScoresConfig allows you to fetch the high scores for a game. -type GetGameHighScoresConfig struct { - UserID int - ChatID int - ChannelUsername string - MessageID int - InlineMessageID string -} - -func (config GetGameHighScoresConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("user_id", strconv.Itoa(config.UserID)) - if config.InlineMessageID == "" { - if config.ChannelUsername == "" { - v.Add("chat_id", strconv.Itoa(config.ChatID)) - } else { - v.Add("chat_id", config.ChannelUsername) - } - v.Add("message_id", strconv.Itoa(config.MessageID)) - } else { - v.Add("inline_message_id", config.InlineMessageID) - } - - return v, nil -} - -func (config GetGameHighScoresConfig) method() string { - return "getGameHighScores" -} - -// ChatActionConfig contains information about a SendChatAction request. -type ChatActionConfig struct { - BaseChat - Action string // required -} - -// values returns a url.Values representation of ChatActionConfig. -func (config ChatActionConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - v.Add("action", config.Action) - return v, nil -} - -// method returns Telegram API method name for sending ChatAction. -func (config ChatActionConfig) method() string { - return "sendChatAction" -} - -// EditMessageTextConfig allows you to modify the text in a message. -type EditMessageTextConfig struct { - BaseEdit - Text string - ParseMode string - DisableWebPagePreview bool -} - -func (config EditMessageTextConfig) values() (url.Values, error) { - v, err := config.BaseEdit.values() - if err != nil { - return v, err - } - - v.Add("text", config.Text) - v.Add("parse_mode", config.ParseMode) - v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) - - return v, nil -} - -func (config EditMessageTextConfig) method() string { - return "editMessageText" -} - -// EditMessageCaptionConfig allows you to modify the caption of a message. -type EditMessageCaptionConfig struct { - BaseEdit - Caption string - ParseMode string -} - -func (config EditMessageCaptionConfig) values() (url.Values, error) { - v, _ := config.BaseEdit.values() - - v.Add("caption", config.Caption) - if config.ParseMode != "" { - v.Add("parse_mode", config.ParseMode) - } - - return v, nil -} - -func (config EditMessageCaptionConfig) method() string { - return "editMessageCaption" -} - -// EditMessageReplyMarkupConfig allows you to modify the reply markup -// of a message. -type EditMessageReplyMarkupConfig struct { - BaseEdit -} - -func (config EditMessageReplyMarkupConfig) values() (url.Values, error) { - return config.BaseEdit.values() -} - -func (config EditMessageReplyMarkupConfig) method() string { - return "editMessageReplyMarkup" -} - -// UserProfilePhotosConfig contains information about a -// GetUserProfilePhotos request. -type UserProfilePhotosConfig struct { - UserID int - Offset int - Limit int -} - -// FileConfig has information about a file hosted on Telegram. -type FileConfig struct { - FileID string -} - -// UpdateConfig contains information about a GetUpdates request. -type UpdateConfig struct { - Offset int - Limit int - Timeout int -} - -// WebhookConfig contains information about a SetWebhook request. -type WebhookConfig struct { - URL *url.URL - Certificate interface{} - MaxConnections int -} - -// FileBytes contains information about a set of bytes to upload -// as a File. -type FileBytes struct { - Name string - Bytes []byte -} - -// FileReader contains information about a reader to upload as a File. -// If Size is -1, it will read the entire Reader into memory to -// calculate a Size. -type FileReader struct { - Name string - Reader io.Reader - Size int64 -} - -// InlineConfig contains information on making an InlineQuery response. -type InlineConfig struct { - InlineQueryID string `json:"inline_query_id"` - Results []interface{} `json:"results"` - CacheTime int `json:"cache_time"` - IsPersonal bool `json:"is_personal"` - NextOffset string `json:"next_offset"` - SwitchPMText string `json:"switch_pm_text"` - SwitchPMParameter string `json:"switch_pm_parameter"` -} - -// CallbackConfig contains information on making a CallbackQuery response. -type CallbackConfig struct { - CallbackQueryID string `json:"callback_query_id"` - Text string `json:"text"` - ShowAlert bool `json:"show_alert"` - URL string `json:"url"` - CacheTime int `json:"cache_time"` -} - -// ChatMemberConfig contains information about a user in a chat for use -// with administrative functions such as kicking or unbanning a user. -type ChatMemberConfig struct { - ChatID int64 - SuperGroupUsername string - ChannelUsername string - UserID int -} - -// KickChatMemberConfig contains extra fields to kick user -type KickChatMemberConfig struct { - ChatMemberConfig - UntilDate int64 -} - -// RestrictChatMemberConfig contains fields to restrict members of chat -type RestrictChatMemberConfig struct { - ChatMemberConfig - UntilDate int64 - CanSendMessages *bool - CanSendMediaMessages *bool - CanSendOtherMessages *bool - CanAddWebPagePreviews *bool -} - -// PromoteChatMemberConfig contains fields to promote members of chat -type PromoteChatMemberConfig struct { - ChatMemberConfig - CanChangeInfo *bool - CanPostMessages *bool - CanEditMessages *bool - CanDeleteMessages *bool - CanInviteUsers *bool - CanRestrictMembers *bool - CanPinMessages *bool - CanPromoteMembers *bool -} - -// ChatConfig contains information about getting information on a chat. -type ChatConfig struct { - ChatID int64 - SuperGroupUsername string -} - -// ChatConfigWithUser contains information about getting information on -// a specific user within a chat. -type ChatConfigWithUser struct { - ChatID int64 - SuperGroupUsername string - UserID int -} - -// InvoiceConfig contains information for sendInvoice request. -type InvoiceConfig struct { - BaseChat - Title string // required - Description string // required - Payload string // required - ProviderToken string // required - StartParameter string // required - Currency string // required - Prices *[]LabeledPrice // required - PhotoURL string - PhotoSize int - PhotoWidth int - PhotoHeight int - NeedName bool - NeedPhoneNumber bool - NeedEmail bool - NeedShippingAddress bool - IsFlexible bool -} - -func (config InvoiceConfig) values() (url.Values, error) { - v, err := config.BaseChat.values() - if err != nil { - return v, err - } - v.Add("title", config.Title) - v.Add("description", config.Description) - v.Add("payload", config.Payload) - v.Add("provider_token", config.ProviderToken) - v.Add("start_parameter", config.StartParameter) - v.Add("currency", config.Currency) - data, err := json.Marshal(config.Prices) - if err != nil { - return v, err - } - v.Add("prices", string(data)) - if config.PhotoURL != "" { - v.Add("photo_url", config.PhotoURL) - } - if config.PhotoSize != 0 { - v.Add("photo_size", strconv.Itoa(config.PhotoSize)) - } - if config.PhotoWidth != 0 { - v.Add("photo_width", strconv.Itoa(config.PhotoWidth)) - } - if config.PhotoHeight != 0 { - v.Add("photo_height", strconv.Itoa(config.PhotoHeight)) - } - if config.NeedName != false { - v.Add("need_name", strconv.FormatBool(config.NeedName)) - } - if config.NeedPhoneNumber != false { - v.Add("need_phone_number", strconv.FormatBool(config.NeedPhoneNumber)) - } - if config.NeedEmail != false { - v.Add("need_email", strconv.FormatBool(config.NeedEmail)) - } - if config.NeedShippingAddress != false { - v.Add("need_shipping_address", strconv.FormatBool(config.NeedShippingAddress)) - } - if config.IsFlexible != false { - v.Add("is_flexible", strconv.FormatBool(config.IsFlexible)) - } - - return v, nil -} - -func (config InvoiceConfig) method() string { - return "sendInvoice" -} - -// ShippingConfig contains information for answerShippingQuery request. -type ShippingConfig struct { - ShippingQueryID string // required - OK bool // required - ShippingOptions *[]ShippingOption - ErrorMessage string -} - -// PreCheckoutConfig conatins information for answerPreCheckoutQuery request. -type PreCheckoutConfig struct { - PreCheckoutQueryID string // required - OK bool // required - ErrorMessage string -} - -// DeleteMessageConfig contains information of a message in a chat to delete. -type DeleteMessageConfig struct { - ChatID int64 - MessageID int -} - -func (config DeleteMessageConfig) method() string { - return "deleteMessage" -} - -func (config DeleteMessageConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - v.Add("message_id", strconv.Itoa(config.MessageID)) - - return v, nil -} - -// PinChatMessageConfig contains information of a message in a chat to pin. -type PinChatMessageConfig struct { - ChatID int64 - MessageID int - DisableNotification bool -} - -func (config PinChatMessageConfig) method() string { - return "pinChatMessage" -} - -func (config PinChatMessageConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - v.Add("message_id", strconv.Itoa(config.MessageID)) - v.Add("disable_notification", strconv.FormatBool(config.DisableNotification)) - - return v, nil -} - -// UnpinChatMessageConfig contains information of chat to unpin. -type UnpinChatMessageConfig struct { - ChatID int64 -} - -func (config UnpinChatMessageConfig) method() string { - return "unpinChatMessage" -} - -func (config UnpinChatMessageConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - - return v, nil -} - -// SetChatTitleConfig contains information for change chat title. -type SetChatTitleConfig struct { - ChatID int64 - Title string -} - -func (config SetChatTitleConfig) method() string { - return "setChatTitle" -} - -func (config SetChatTitleConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - v.Add("title", config.Title) - - return v, nil -} - -// SetChatDescriptionConfig contains information for change chat description. -type SetChatDescriptionConfig struct { - ChatID int64 - Description string -} - -func (config SetChatDescriptionConfig) method() string { - return "setChatDescription" -} - -func (config SetChatDescriptionConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - v.Add("description", config.Description) - - return v, nil -} - -// SetChatPhotoConfig contains information for change chat photo -type SetChatPhotoConfig struct { - BaseFile -} - -// name returns the field name for the Photo. -func (config SetChatPhotoConfig) name() string { - return "photo" -} - -// method returns Telegram API method name for sending Photo. -func (config SetChatPhotoConfig) method() string { - return "setChatPhoto" -} - -// DeleteChatPhotoConfig contains information for delete chat photo. -type DeleteChatPhotoConfig struct { - ChatID int64 -} - -func (config DeleteChatPhotoConfig) method() string { - return "deleteChatPhoto" -} - -func (config DeleteChatPhotoConfig) values() (url.Values, error) { - v := url.Values{} - - v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) - - return v, nil -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go deleted file mode 100644 index 3dabe11..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go +++ /dev/null @@ -1,815 +0,0 @@ -package tgbotapi - -import ( - "net/url" -) - -// NewMessage creates a new Message. -// -// chatID is where to send it, text is the message text. -func NewMessage(chatID int64, text string) MessageConfig { - return MessageConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - ReplyToMessageID: 0, - }, - Text: text, - DisableWebPagePreview: false, - } -} - -// NewDeleteMessage creates a request to delete a message. -func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { - return DeleteMessageConfig{ - ChatID: chatID, - MessageID: messageID, - } -} - -// NewMessageToChannel creates a new Message that is sent to a channel -// by username. -// -// username is the username of the channel, text is the message text. -func NewMessageToChannel(username string, text string) MessageConfig { - return MessageConfig{ - BaseChat: BaseChat{ - ChannelUsername: username, - }, - Text: text, - } -} - -// NewForward creates a new forward. -// -// chatID is where to send it, fromChatID is the source chat, -// and messageID is the ID of the original message. -func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { - return ForwardConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, - } -} - -// NewPhotoUpload creates a new photo uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -// -// Note that you must send animated GIFs as a document. -func NewPhotoUpload(chatID int64, file interface{}) PhotoConfig { - return PhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewPhotoShare shares an existing photo. -// You may use this to reshare an existing photo without reuploading it. -// -// chatID is where to send it, fileID is the ID of the file -// already uploaded. -func NewPhotoShare(chatID int64, fileID string) PhotoConfig { - return PhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewAudioUpload creates a new audio uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewAudioUpload(chatID int64, file interface{}) AudioConfig { - return AudioConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewAudioShare shares an existing audio file. -// You may use this to reshare an existing audio file without -// reuploading it. -// -// chatID is where to send it, fileID is the ID of the audio -// already uploaded. -func NewAudioShare(chatID int64, fileID string) AudioConfig { - return AudioConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewDocumentUpload creates a new document uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewDocumentUpload(chatID int64, file interface{}) DocumentConfig { - return DocumentConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewDocumentShare shares an existing document. -// You may use this to reshare an existing document without -// reuploading it. -// -// chatID is where to send it, fileID is the ID of the document -// already uploaded. -func NewDocumentShare(chatID int64, fileID string) DocumentConfig { - return DocumentConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewStickerUpload creates a new sticker uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewStickerUpload(chatID int64, file interface{}) StickerConfig { - return StickerConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewStickerShare shares an existing sticker. -// You may use this to reshare an existing sticker without -// reuploading it. -// -// chatID is where to send it, fileID is the ID of the sticker -// already uploaded. -func NewStickerShare(chatID int64, fileID string) StickerConfig { - return StickerConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewVideoUpload creates a new video uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewVideoUpload(chatID int64, file interface{}) VideoConfig { - return VideoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewVideoShare shares an existing video. -// You may use this to reshare an existing video without reuploading it. -// -// chatID is where to send it, fileID is the ID of the video -// already uploaded. -func NewVideoShare(chatID int64, fileID string) VideoConfig { - return VideoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewAnimationUpload creates a new animation uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewAnimationUpload(chatID int64, file interface{}) AnimationConfig { - return AnimationConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewAnimationShare shares an existing animation. -// You may use this to reshare an existing animation without reuploading it. -// -// chatID is where to send it, fileID is the ID of the animation -// already uploaded. -func NewAnimationShare(chatID int64, fileID string) AnimationConfig { - return AnimationConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewVideoNoteUpload creates a new video note uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewVideoNoteUpload(chatID int64, length int, file interface{}) VideoNoteConfig { - return VideoNoteConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - Length: length, - } -} - -// NewVideoNoteShare shares an existing video. -// You may use this to reshare an existing video without reuploading it. -// -// chatID is where to send it, fileID is the ID of the video -// already uploaded. -func NewVideoNoteShare(chatID int64, length int, fileID string) VideoNoteConfig { - return VideoNoteConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - Length: length, - } -} - -// NewVoiceUpload creates a new voice uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewVoiceUpload(chatID int64, file interface{}) VoiceConfig { - return VoiceConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewVoiceShare shares an existing voice. -// You may use this to reshare an existing voice without reuploading it. -// -// chatID is where to send it, fileID is the ID of the video -// already uploaded. -func NewVoiceShare(chatID int64, fileID string) VoiceConfig { - return VoiceConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} - -// NewMediaGroup creates a new media group. Files should be an array of -// two to ten InputMediaPhoto or InputMediaVideo. -func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { - return MediaGroupConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - InputMedia: files, - } -} - -// NewInputMediaPhoto creates a new InputMediaPhoto. -func NewInputMediaPhoto(media string) InputMediaPhoto { - return InputMediaPhoto{ - Type: "photo", - Media: media, - } -} - -// NewInputMediaVideo creates a new InputMediaVideo. -func NewInputMediaVideo(media string) InputMediaVideo { - return InputMediaVideo{ - Type: "video", - Media: media, - } -} - -// NewContact allows you to send a shared contact. -func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { - return ContactConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - PhoneNumber: phoneNumber, - FirstName: firstName, - } -} - -// NewLocation shares your location. -// -// chatID is where to send it, latitude and longitude are coordinates. -func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig { - return LocationConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewVenue allows you to send a venue and its location. -func NewVenue(chatID int64, title, address string, latitude, longitude float64) VenueConfig { - return VenueConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Title: title, - Address: address, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewChatAction sets a chat action. -// Actions last for 5 seconds, or until your next action. -// -// chatID is where to send it, action should be set via Chat constants. -func NewChatAction(chatID int64, action string) ChatActionConfig { - return ChatActionConfig{ - BaseChat: BaseChat{ChatID: chatID}, - Action: action, - } -} - -// NewUserProfilePhotos gets user profile photos. -// -// userID is the ID of the user you wish to get profile photos from. -func NewUserProfilePhotos(userID int) UserProfilePhotosConfig { - return UserProfilePhotosConfig{ - UserID: userID, - Offset: 0, - Limit: 0, - } -} - -// NewUpdate gets updates since the last Offset. -// -// offset is the last Update ID to include. -// You likely want to set this to the last Update ID plus 1. -func NewUpdate(offset int) UpdateConfig { - return UpdateConfig{ - Offset: offset, - Limit: 0, - Timeout: 0, - } -} - -// NewWebhook creates a new webhook. -// -// link is the url parsable link you wish to get the updates. -func NewWebhook(link string) WebhookConfig { - u, _ := url.Parse(link) - - return WebhookConfig{ - URL: u, - } -} - -// NewWebhookWithCert creates a new webhook with a certificate. -// -// link is the url you wish to get webhooks, -// file contains a string to a file, FileReader, or FileBytes. -func NewWebhookWithCert(link string, file interface{}) WebhookConfig { - u, _ := url.Parse(link) - - return WebhookConfig{ - URL: u, - Certificate: file, - } -} - -// NewInlineQueryResultArticle creates a new inline query article. -func NewInlineQueryResultArticle(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - }, - } -} - -// NewInlineQueryResultArticleMarkdown creates a new inline query article with Markdown parsing. -func NewInlineQueryResultArticleMarkdown(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - ParseMode: "Markdown", - }, - } -} - -// NewInlineQueryResultArticleHTML creates a new inline query article with HTML parsing. -func NewInlineQueryResultArticleHTML(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - ParseMode: "HTML", - }, - } -} - -// NewInlineQueryResultGIF creates a new inline query GIF. -func NewInlineQueryResultGIF(id, url string) InlineQueryResultGIF { - return InlineQueryResultGIF{ - Type: "gif", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedGIF create a new inline query with cached photo. -func NewInlineQueryResultCachedGIF(id, gifID string) InlineQueryResultCachedGIF { - return InlineQueryResultCachedGIF{ - Type: "gif", - ID: id, - GifID: gifID, - } -} - -// NewInlineQueryResultMPEG4GIF creates a new inline query MPEG4 GIF. -func NewInlineQueryResultMPEG4GIF(id, url string) InlineQueryResultMPEG4GIF { - return InlineQueryResultMPEG4GIF{ - Type: "mpeg4_gif", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedPhoto create a new inline query with cached photo. -func NewInlineQueryResultCachedMPEG4GIF(id, MPEG4GifID string) InlineQueryResultCachedMpeg4Gif { - return InlineQueryResultCachedMpeg4Gif{ - Type: "mpeg4_gif", - ID: id, - MGifID: MPEG4GifID, - } -} - -// NewInlineQueryResultPhoto creates a new inline query photo. -func NewInlineQueryResultPhoto(id, url string) InlineQueryResultPhoto { - return InlineQueryResultPhoto{ - Type: "photo", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultPhotoWithThumb creates a new inline query photo. -func NewInlineQueryResultPhotoWithThumb(id, url, thumb string) InlineQueryResultPhoto { - return InlineQueryResultPhoto{ - Type: "photo", - ID: id, - URL: url, - ThumbURL: thumb, - } -} - -// NewInlineQueryResultCachedPhoto create a new inline query with cached photo. -func NewInlineQueryResultCachedPhoto(id, photoID string) InlineQueryResultCachedPhoto { - return InlineQueryResultCachedPhoto{ - Type: "photo", - ID: id, - PhotoID: photoID, - } -} - -// NewInlineQueryResultVideo creates a new inline query video. -func NewInlineQueryResultVideo(id, url string) InlineQueryResultVideo { - return InlineQueryResultVideo{ - Type: "video", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedVideo create a new inline query with cached video. -func NewInlineQueryResultCachedVideo(id, videoID, title string) InlineQueryResultCachedVideo { - return InlineQueryResultCachedVideo{ - Type: "video", - ID: id, - VideoID: videoID, - Title: title, - } -} - -// NewInlineQueryResultAudio creates a new inline query audio. -func NewInlineQueryResultAudio(id, url, title string) InlineQueryResultAudio { - return InlineQueryResultAudio{ - Type: "audio", - ID: id, - URL: url, - Title: title, - } -} - -// NewInlineQueryResultCachedAudio create a new inline query with cached photo. -func NewInlineQueryResultCachedAudio(id, audioID string) InlineQueryResultCachedAudio { - return InlineQueryResultCachedAudio{ - Type: "audio", - ID: id, - AudioID: audioID, - } -} - -// NewInlineQueryResultVoice creates a new inline query voice. -func NewInlineQueryResultVoice(id, url, title string) InlineQueryResultVoice { - return InlineQueryResultVoice{ - Type: "voice", - ID: id, - URL: url, - Title: title, - } -} - -// NewInlineQueryResultCachedVoice create a new inline query with cached photo. -func NewInlineQueryResultCachedVoice(id, voiceID, title string) InlineQueryResultCachedVoice { - return InlineQueryResultCachedVoice{ - Type: "voice", - ID: id, - VoiceID: voiceID, - Title: title, - } -} - -// NewInlineQueryResultDocument creates a new inline query document. -func NewInlineQueryResultDocument(id, url, title, mimeType string) InlineQueryResultDocument { - return InlineQueryResultDocument{ - Type: "document", - ID: id, - URL: url, - Title: title, - MimeType: mimeType, - } -} - -// NewInlineQueryResultCachedDocument create a new inline query with cached photo. -func NewInlineQueryResultCachedDocument(id, documentID, title string) InlineQueryResultCachedDocument { - return InlineQueryResultCachedDocument{ - Type: "document", - ID: id, - DocumentID: documentID, - Title: title, - } -} - -// NewInlineQueryResultLocation creates a new inline query location. -func NewInlineQueryResultLocation(id, title string, latitude, longitude float64) InlineQueryResultLocation { - return InlineQueryResultLocation{ - Type: "location", - ID: id, - Title: title, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewEditMessageText allows you to edit the text of a message. -func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { - return EditMessageTextConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - }, - Text: text, - } -} - -// NewEditMessageCaption allows you to edit the caption of a message. -func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMessageCaptionConfig { - return EditMessageCaptionConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - }, - Caption: caption, - } -} - -// NewEditMessageReplyMarkup allows you to edit the inline -// keyboard markup. -func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup InlineKeyboardMarkup) EditMessageReplyMarkupConfig { - return EditMessageReplyMarkupConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - ReplyMarkup: &replyMarkup, - }, - } -} - -// NewHideKeyboard hides the keyboard, with the option for being selective -// or hiding for everyone. -func NewHideKeyboard(selective bool) ReplyKeyboardHide { - log.Println("NewHideKeyboard is deprecated, please use NewRemoveKeyboard") - - return ReplyKeyboardHide{ - HideKeyboard: true, - Selective: selective, - } -} - -// NewRemoveKeyboard hides the keyboard, with the option for being selective -// or hiding for everyone. -func NewRemoveKeyboard(selective bool) ReplyKeyboardRemove { - return ReplyKeyboardRemove{ - RemoveKeyboard: true, - Selective: selective, - } -} - -// NewKeyboardButton creates a regular keyboard button. -func NewKeyboardButton(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - } -} - -// NewKeyboardButtonContact creates a keyboard button that requests -// user contact information upon click. -func NewKeyboardButtonContact(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - RequestContact: true, - } -} - -// NewKeyboardButtonLocation creates a keyboard button that requests -// user location information upon click. -func NewKeyboardButtonLocation(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - RequestLocation: true, - } -} - -// NewKeyboardButtonRow creates a row of keyboard buttons. -func NewKeyboardButtonRow(buttons ...KeyboardButton) []KeyboardButton { - var row []KeyboardButton - - row = append(row, buttons...) - - return row -} - -// NewReplyKeyboard creates a new regular keyboard with sane defaults. -func NewReplyKeyboard(rows ...[]KeyboardButton) ReplyKeyboardMarkup { - var keyboard [][]KeyboardButton - - keyboard = append(keyboard, rows...) - - return ReplyKeyboardMarkup{ - ResizeKeyboard: true, - Keyboard: keyboard, - } -} - -// NewInlineKeyboardButtonData creates an inline keyboard button with text -// and data for a callback. -func NewInlineKeyboardButtonData(text, data string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - CallbackData: &data, - } -} - -// NewInlineKeyboardButtonURL creates an inline keyboard button with text -// which goes to a URL. -func NewInlineKeyboardButtonURL(text, url string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - URL: &url, - } -} - -// NewInlineKeyboardButtonSwitch creates an inline keyboard button with -// text which allows the user to switch to a chat or return to a chat. -func NewInlineKeyboardButtonSwitch(text, sw string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - SwitchInlineQuery: &sw, - } -} - -// NewInlineKeyboardRow creates an inline keyboard row with buttons. -func NewInlineKeyboardRow(buttons ...InlineKeyboardButton) []InlineKeyboardButton { - var row []InlineKeyboardButton - - row = append(row, buttons...) - - return row -} - -// NewInlineKeyboardMarkup creates a new inline keyboard. -func NewInlineKeyboardMarkup(rows ...[]InlineKeyboardButton) InlineKeyboardMarkup { - var keyboard [][]InlineKeyboardButton - - keyboard = append(keyboard, rows...) - - return InlineKeyboardMarkup{ - InlineKeyboard: keyboard, - } -} - -// NewCallback creates a new callback message. -func NewCallback(id, text string) CallbackConfig { - return CallbackConfig{ - CallbackQueryID: id, - Text: text, - ShowAlert: false, - } -} - -// NewCallbackWithAlert creates a new callback message that alerts -// the user. -func NewCallbackWithAlert(id, text string) CallbackConfig { - return CallbackConfig{ - CallbackQueryID: id, - Text: text, - ShowAlert: true, - } -} - -// NewInvoice creates a new Invoice request to the user. -func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices *[]LabeledPrice) InvoiceConfig { - return InvoiceConfig{ - BaseChat: BaseChat{ChatID: chatID}, - Title: title, - Description: description, - Payload: payload, - ProviderToken: providerToken, - StartParameter: startParameter, - Currency: currency, - Prices: prices} -} - -// NewSetChatPhotoUpload creates a new chat photo uploader. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -// -// Note that you must send animated GIFs as a document. -func NewSetChatPhotoUpload(chatID int64, file interface{}) SetChatPhotoConfig { - return SetChatPhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - UseExisting: false, - }, - } -} - -// NewSetChatPhotoShare shares an existing photo. -// You may use this to reshare an existing photo without reuploading it. -// -// chatID is where to send it, fileID is the ID of the file -// already uploaded. -func NewSetChatPhotoShare(chatID int64, fileID string) SetChatPhotoConfig { - return SetChatPhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - FileID: fileID, - UseExisting: true, - }, - } -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go deleted file mode 100644 index 1872551..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go +++ /dev/null @@ -1,27 +0,0 @@ -package tgbotapi - -import ( - "errors" - stdlog "log" - "os" -) - -// BotLogger is an interface that represents the required methods to log data. -// -// Instead of requiring the standard logger, we can just specify the methods we -// use and allow users to pass anything that implements these. -type BotLogger interface { - Println(v ...interface{}) - Printf(format string, v ...interface{}) -} - -var log BotLogger = stdlog.New(os.Stderr, "", stdlog.LstdFlags) - -// SetLogger specifies the logger that the package should use. -func SetLogger(logger BotLogger) error { - if logger == nil { - return errors.New("logger is nil") - } - log = logger - return nil -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go deleted file mode 100644 index 5f55006..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go +++ /dev/null @@ -1,315 +0,0 @@ -package tgbotapi - -// PassportRequestInfoConfig allows you to request passport info -type PassportRequestInfoConfig struct { - BotID int `json:"bot_id"` - Scope *PassportScope `json:"scope"` - Nonce string `json:"nonce"` - PublicKey string `json:"public_key"` -} - -// PassportScopeElement supports using one or one of several elements. -type PassportScopeElement interface { - ScopeType() string -} - -// PassportScope is the requested scopes of data. -type PassportScope struct { - V int `json:"v"` - Data []PassportScopeElement `json:"data"` -} - -// PassportScopeElementOneOfSeveral allows you to request any one of the -// requested documents. -type PassportScopeElementOneOfSeveral struct { -} - -// ScopeType is the scope type. -func (eo *PassportScopeElementOneOfSeveral) ScopeType() string { - return "one_of" -} - -// PassportScopeElementOne requires the specified element be provided. -type PassportScopeElementOne struct { - Type string `json:"type"` // One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email” - Selfie bool `json:"selfie"` - Translation bool `json:"translation"` - NativeNames bool `json:"native_name"` -} - -// ScopeType is the scope type. -func (eo *PassportScopeElementOne) ScopeType() string { - return "one" -} - -type ( - // PassportData contains information about Telegram Passport data shared with - // the bot by the user. - PassportData struct { - // Array with information about documents and other Telegram Passport - // elements that was shared with the bot - Data []EncryptedPassportElement `json:"data"` - - // Encrypted credentials required to decrypt the data - Credentials *EncryptedCredentials `json:"credentials"` - } - - // PassportFile represents a file uploaded to Telegram Passport. Currently all - // Telegram Passport files are in JPEG format when decrypted and don't exceed - // 10MB. - PassportFile struct { - // Unique identifier for this file - FileID string `json:"file_id"` - - // File size - FileSize int `json:"file_size"` - - // Unix time when the file was uploaded - FileDate int64 `json:"file_date"` - } - - // EncryptedPassportElement contains information about documents or other - // Telegram Passport elements shared with the bot by the user. - EncryptedPassportElement struct { - // Element type. - Type string `json:"type"` - - // Base64-encoded encrypted Telegram Passport element data provided by - // the user, available for "personal_details", "passport", - // "driver_license", "identity_card", "identity_passport" and "address" - // types. Can be decrypted and verified using the accompanying - // EncryptedCredentials. - Data string `json:"data,omitempty"` - - // User's verified phone number, available only for "phone_number" type - PhoneNumber string `json:"phone_number,omitempty"` - - // User's verified email address, available only for "email" type - Email string `json:"email,omitempty"` - - // Array of encrypted files with documents provided by the user, - // available for "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration" and "temporary_registration" types. Files can - // be decrypted and verified using the accompanying EncryptedCredentials. - Files []PassportFile `json:"files,omitempty"` - - // Encrypted file with the front side of the document, provided by the - // user. Available for "passport", "driver_license", "identity_card" and - // "internal_passport". The file can be decrypted and verified using the - // accompanying EncryptedCredentials. - FrontSide *PassportFile `json:"front_side,omitempty"` - - // Encrypted file with the reverse side of the document, provided by the - // user. Available for "driver_license" and "identity_card". The file can - // be decrypted and verified using the accompanying EncryptedCredentials. - ReverseSide *PassportFile `json:"reverse_side,omitempty"` - - // Encrypted file with the selfie of the user holding a document, - // provided by the user; available for "passport", "driver_license", - // "identity_card" and "internal_passport". The file can be decrypted - // and verified using the accompanying EncryptedCredentials. - Selfie *PassportFile `json:"selfie,omitempty"` - } - - // EncryptedCredentials contains data required for decrypting and - // authenticating EncryptedPassportElement. See the Telegram Passport - // Documentation for a complete description of the data decryption and - // authentication processes. - EncryptedCredentials struct { - // Base64-encoded encrypted JSON-serialized data with unique user's - // payload, data hashes and secrets required for EncryptedPassportElement - // decryption and authentication - Data string `json:"data"` - - // Base64-encoded data hash for data authentication - Hash string `json:"hash"` - - // Base64-encoded secret, encrypted with the bot's public RSA key, - // required for data decryption - Secret string `json:"secret"` - } - - // PassportElementError represents an error in the Telegram Passport element - // which was submitted that should be resolved by the user. - PassportElementError interface{} - - // PassportElementErrorDataField represents an issue in one of the data - // fields that was provided by the user. The error is considered resolved - // when the field's value changes. - PassportElementErrorDataField struct { - // Error source, must be data - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the error, one - // of "personal_details", "passport", "driver_license", "identity_card", - // "internal_passport", "address" - Type string `json:"type"` - - // Name of the data field which has the error - FieldName string `json:"field_name"` - - // Base64-encoded data hash - DataHash string `json:"data_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFrontSide represents an issue with the front side of - // a document. The error is considered resolved when the file with the front - // side of the document changes. - PassportElementErrorFrontSide struct { - // Error source, must be front_side - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "passport", "driver_license", "identity_card", "internal_passport" - Type string `json:"type"` - - // Base64-encoded hash of the file with the front side of the document - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorReverseSide represents an issue with the reverse side - // of a document. The error is considered resolved when the file with reverse - // side of the document changes. - PassportElementErrorReverseSide struct { - // Error source, must be reverse_side - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "driver_license", "identity_card" - Type string `json:"type"` - - // Base64-encoded hash of the file with the reverse side of the document - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorSelfie represents an issue with the selfie with a - // document. The error is considered resolved when the file with the selfie - // changes. - PassportElementErrorSelfie struct { - // Error source, must be selfie - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "passport", "driver_license", "identity_card", "internal_passport" - Type string `json:"type"` - - // Base64-encoded hash of the file with the selfie - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFile represents an issue with a document scan. The - // error is considered resolved when the file with the document scan changes. - PassportElementErrorFile struct { - // Error source, must be file - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration", "temporary_registration" - Type string `json:"type"` - - // Base64-encoded file hash - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFiles represents an issue with a list of scans. The - // error is considered resolved when the list of files containing the scans - // changes. - PassportElementErrorFiles struct { - // Error source, must be files - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration", "temporary_registration" - Type string `json:"type"` - - // List of base64-encoded file hashes - FileHashes []string `json:"file_hashes"` - - // Error message - Message string `json:"message"` - } - - // Credentials contains encrypted data. - Credentials struct { - Data SecureData `json:"secure_data"` - // Nonce the same nonce given in the request - Nonce string `json:"nonce"` - } - - // SecureData is a map of the fields and their encrypted values. - SecureData map[string]*SecureValue - // PersonalDetails *SecureValue `json:"personal_details"` - // Passport *SecureValue `json:"passport"` - // InternalPassport *SecureValue `json:"internal_passport"` - // DriverLicense *SecureValue `json:"driver_license"` - // IdentityCard *SecureValue `json:"identity_card"` - // Address *SecureValue `json:"address"` - // UtilityBill *SecureValue `json:"utility_bill"` - // BankStatement *SecureValue `json:"bank_statement"` - // RentalAgreement *SecureValue `json:"rental_agreement"` - // PassportRegistration *SecureValue `json:"passport_registration"` - // TemporaryRegistration *SecureValue `json:"temporary_registration"` - - // SecureValue contains encrypted values for a SecureData item. - SecureValue struct { - Data *DataCredentials `json:"data"` - FrontSide *FileCredentials `json:"front_side"` - ReverseSide *FileCredentials `json:"reverse_side"` - Selfie *FileCredentials `json:"selfie"` - Translation []*FileCredentials `json:"translation"` - Files []*FileCredentials `json:"files"` - } - - // DataCredentials contains information required to decrypt data. - DataCredentials struct { - // DataHash checksum of encrypted data - DataHash string `json:"data_hash"` - // Secret of encrypted data - Secret string `json:"secret"` - } - - // FileCredentials contains information required to decrypt files. - FileCredentials struct { - // FileHash checksum of encrypted data - FileHash string `json:"file_hash"` - // Secret of encrypted data - Secret string `json:"secret"` - } - - // PersonalDetails https://core.telegram.org/passport#personaldetails - PersonalDetails struct { - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - MiddleName string `json:"middle_name"` - BirthDate string `json:"birth_date"` - Gender string `json:"gender"` - CountryCode string `json:"country_code"` - ResidenceCountryCode string `json:"residence_country_code"` - FirstNameNative string `json:"first_name_native"` - LastNameNative string `json:"last_name_native"` - MiddleNameNative string `json:"middle_name_native"` - } - - // IDDocumentData https://core.telegram.org/passport#iddocumentdata - IDDocumentData struct { - DocumentNumber string `json:"document_no"` - ExpiryDate string `json:"expiry_date"` - } -) diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go deleted file mode 100644 index 52cb36c..0000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go +++ /dev/null @@ -1,959 +0,0 @@ -package tgbotapi - -import ( - "encoding/json" - "errors" - "fmt" - "net/url" - "strings" - "time" -) - -// APIResponse is a response from the Telegram API with the result -// stored raw. -type APIResponse struct { - Ok bool `json:"ok"` - Result json.RawMessage `json:"result"` - ErrorCode int `json:"error_code"` - Description string `json:"description"` - Parameters *ResponseParameters `json:"parameters"` -} - -// ResponseParameters are various errors that can be returned in APIResponse. -type ResponseParameters struct { - MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional - RetryAfter int `json:"retry_after"` // optional -} - -// Update is an update response, from GetUpdates. -type Update struct { - UpdateID int `json:"update_id"` - Message *Message `json:"message"` - EditedMessage *Message `json:"edited_message"` - ChannelPost *Message `json:"channel_post"` - EditedChannelPost *Message `json:"edited_channel_post"` - InlineQuery *InlineQuery `json:"inline_query"` - ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result"` - CallbackQuery *CallbackQuery `json:"callback_query"` - ShippingQuery *ShippingQuery `json:"shipping_query"` - PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query"` -} - -// UpdatesChannel is the channel for getting updates. -type UpdatesChannel <-chan Update - -// Clear discards all unprocessed incoming updates. -func (ch UpdatesChannel) Clear() { - for len(ch) != 0 { - <-ch - } -} - -// User is a user on Telegram. -type User struct { - ID int `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` // optional - UserName string `json:"username"` // optional - LanguageCode string `json:"language_code"` // optional - IsBot bool `json:"is_bot"` // optional -} - -// String displays a simple text version of a user. -// -// It is normally a user's username, but falls back to a first/last -// name as available. -func (u *User) String() string { - if u.UserName != "" { - return u.UserName - } - - name := u.FirstName - if u.LastName != "" { - name += " " + u.LastName - } - - return name -} - -// GroupChat is a group chat. -type GroupChat struct { - ID int `json:"id"` - Title string `json:"title"` -} - -// ChatPhoto represents a chat photo. -type ChatPhoto struct { - SmallFileID string `json:"small_file_id"` - BigFileID string `json:"big_file_id"` -} - -// Chat contains information about the place a message was sent. -type Chat struct { - ID int64 `json:"id"` - Type string `json:"type"` - Title string `json:"title"` // optional - UserName string `json:"username"` // optional - FirstName string `json:"first_name"` // optional - LastName string `json:"last_name"` // optional - AllMembersAreAdmins bool `json:"all_members_are_administrators"` // optional - Photo *ChatPhoto `json:"photo"` - Description string `json:"description,omitempty"` // optional - InviteLink string `json:"invite_link,omitempty"` // optional - PinnedMessage *Message `json:"pinned_message"` // optional -} - -// IsPrivate returns if the Chat is a private conversation. -func (c Chat) IsPrivate() bool { - return c.Type == "private" -} - -// IsGroup returns if the Chat is a group. -func (c Chat) IsGroup() bool { - return c.Type == "group" -} - -// IsSuperGroup returns if the Chat is a supergroup. -func (c Chat) IsSuperGroup() bool { - return c.Type == "supergroup" -} - -// IsChannel returns if the Chat is a channel. -func (c Chat) IsChannel() bool { - return c.Type == "channel" -} - -// ChatConfig returns a ChatConfig struct for chat related methods. -func (c Chat) ChatConfig() ChatConfig { - return ChatConfig{ChatID: c.ID} -} - -// Message is returned by almost every request, and contains data about -// almost anything. -type Message struct { - MessageID int `json:"message_id"` - From *User `json:"from"` // optional - Date int `json:"date"` - Chat *Chat `json:"chat"` - ForwardFrom *User `json:"forward_from"` // optional - ForwardFromChat *Chat `json:"forward_from_chat"` // optional - ForwardFromMessageID int `json:"forward_from_message_id"` // optional - ForwardDate int `json:"forward_date"` // optional - ReplyToMessage *Message `json:"reply_to_message"` // optional - EditDate int `json:"edit_date"` // optional - Text string `json:"text"` // optional - Entities *[]MessageEntity `json:"entities"` // optional - CaptionEntities *[]MessageEntity `json:"caption_entities"` // optional - Audio *Audio `json:"audio"` // optional - Document *Document `json:"document"` // optional - Animation *ChatAnimation `json:"animation"` // optional - Game *Game `json:"game"` // optional - Photo *[]PhotoSize `json:"photo"` // optional - Sticker *Sticker `json:"sticker"` // optional - Video *Video `json:"video"` // optional - VideoNote *VideoNote `json:"video_note"` // optional - Voice *Voice `json:"voice"` // optional - Caption string `json:"caption"` // optional - Contact *Contact `json:"contact"` // optional - Location *Location `json:"location"` // optional - Venue *Venue `json:"venue"` // optional - NewChatMembers *[]User `json:"new_chat_members"` // optional - LeftChatMember *User `json:"left_chat_member"` // optional - NewChatTitle string `json:"new_chat_title"` // optional - NewChatPhoto *[]PhotoSize `json:"new_chat_photo"` // optional - DeleteChatPhoto bool `json:"delete_chat_photo"` // optional - GroupChatCreated bool `json:"group_chat_created"` // optional - SuperGroupChatCreated bool `json:"supergroup_chat_created"` // optional - ChannelChatCreated bool `json:"channel_chat_created"` // optional - MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional - MigrateFromChatID int64 `json:"migrate_from_chat_id"` // optional - PinnedMessage *Message `json:"pinned_message"` // optional - Invoice *Invoice `json:"invoice"` // optional - SuccessfulPayment *SuccessfulPayment `json:"successful_payment"` // optional - PassportData *PassportData `json:"passport_data,omitempty"` // optional -} - -// Time converts the message timestamp into a Time. -func (m *Message) Time() time.Time { - return time.Unix(int64(m.Date), 0) -} - -// IsCommand returns true if message starts with a "bot_command" entity. -func (m *Message) IsCommand() bool { - if m.Entities == nil || len(*m.Entities) == 0 { - return false - } - - entity := (*m.Entities)[0] - return entity.Offset == 0 && entity.IsCommand() -} - -// Command checks if the message was a command and if it was, returns the -// command. If the Message was not a command, it returns an empty string. -// -// If the command contains the at name syntax, it is removed. Use -// CommandWithAt() if you do not want that. -func (m *Message) Command() string { - command := m.CommandWithAt() - - if i := strings.Index(command, "@"); i != -1 { - command = command[:i] - } - - return command -} - -// CommandWithAt checks if the message was a command and if it was, returns the -// command. If the Message was not a command, it returns an empty string. -// -// If the command contains the at name syntax, it is not removed. Use Command() -// if you want that. -func (m *Message) CommandWithAt() string { - if !m.IsCommand() { - return "" - } - - // IsCommand() checks that the message begins with a bot_command entity - entity := (*m.Entities)[0] - return m.Text[1:entity.Length] -} - -// CommandArguments checks if the message was a command and if it was, -// returns all text after the command name. If the Message was not a -// command, it returns an empty string. -// -// Note: The first character after the command name is omitted: -// - "/foo bar baz" yields "bar baz", not " bar baz" -// - "/foo-bar baz" yields "bar baz", too -// Even though the latter is not a command conforming to the spec, the API -// marks "/foo" as command entity. -func (m *Message) CommandArguments() string { - if !m.IsCommand() { - return "" - } - - // IsCommand() checks that the message begins with a bot_command entity - entity := (*m.Entities)[0] - if len(m.Text) == entity.Length { - return "" // The command makes up the whole message - } - - return m.Text[entity.Length+1:] -} - -// MessageEntity contains information about data in a Message. -type MessageEntity struct { - Type string `json:"type"` - Offset int `json:"offset"` - Length int `json:"length"` - URL string `json:"url"` // optional - User *User `json:"user"` // optional -} - -// ParseURL attempts to parse a URL contained within a MessageEntity. -func (e MessageEntity) ParseURL() (*url.URL, error) { - if e.URL == "" { - return nil, errors.New(ErrBadURL) - } - - return url.Parse(e.URL) -} - -// IsMention returns true if the type of the message entity is "mention" (@username). -func (e MessageEntity) IsMention() bool { - return e.Type == "mention" -} - -// IsHashtag returns true if the type of the message entity is "hashtag". -func (e MessageEntity) IsHashtag() bool { - return e.Type == "hashtag" -} - -// IsCommand returns true if the type of the message entity is "bot_command". -func (e MessageEntity) IsCommand() bool { - return e.Type == "bot_command" -} - -// IsUrl returns true if the type of the message entity is "url". -func (e MessageEntity) IsUrl() bool { - return e.Type == "url" -} - -// IsEmail returns true if the type of the message entity is "email". -func (e MessageEntity) IsEmail() bool { - return e.Type == "email" -} - -// IsBold returns true if the type of the message entity is "bold" (bold text). -func (e MessageEntity) IsBold() bool { - return e.Type == "bold" -} - -// IsItalic returns true if the type of the message entity is "italic" (italic text). -func (e MessageEntity) IsItalic() bool { - return e.Type == "italic" -} - -// IsCode returns true if the type of the message entity is "code" (monowidth string). -func (e MessageEntity) IsCode() bool { - return e.Type == "code" -} - -// IsPre returns true if the type of the message entity is "pre" (monowidth block). -func (e MessageEntity) IsPre() bool { - return e.Type == "pre" -} - -// IsTextLink returns true if the type of the message entity is "text_link" (clickable text URL). -func (e MessageEntity) IsTextLink() bool { - return e.Type == "text_link" -} - -// PhotoSize contains information about photos. -type PhotoSize struct { - FileID string `json:"file_id"` - Width int `json:"width"` - Height int `json:"height"` - FileSize int `json:"file_size"` // optional -} - -// Audio contains information about audio. -type Audio struct { - FileID string `json:"file_id"` - Duration int `json:"duration"` - Performer string `json:"performer"` // optional - Title string `json:"title"` // optional - MimeType string `json:"mime_type"` // optional - FileSize int `json:"file_size"` // optional -} - -// Document contains information about a document. -type Document struct { - FileID string `json:"file_id"` - Thumbnail *PhotoSize `json:"thumb"` // optional - FileName string `json:"file_name"` // optional - MimeType string `json:"mime_type"` // optional - FileSize int `json:"file_size"` // optional -} - -// Sticker contains information about a sticker. -type Sticker struct { - FileID string `json:"file_id"` - Width int `json:"width"` - Height int `json:"height"` - Thumbnail *PhotoSize `json:"thumb"` // optional - Emoji string `json:"emoji"` // optional - FileSize int `json:"file_size"` // optional - SetName string `json:"set_name"` // optional -} - -// ChatAnimation contains information about an animation. -type ChatAnimation struct { - FileID string `json:"file_id"` - Width int `json:"width"` - Height int `json:"height"` - Duration int `json:"duration"` - Thumbnail *PhotoSize `json:"thumb"` // optional - FileName string `json:"file_name"` // optional - MimeType string `json:"mime_type"` // optional - FileSize int `json:"file_size"` // optional -} - -// Video contains information about a video. -type Video struct { - FileID string `json:"file_id"` - Width int `json:"width"` - Height int `json:"height"` - Duration int `json:"duration"` - Thumbnail *PhotoSize `json:"thumb"` // optional - MimeType string `json:"mime_type"` // optional - FileSize int `json:"file_size"` // optional -} - -// VideoNote contains information about a video. -type VideoNote struct { - FileID string `json:"file_id"` - Length int `json:"length"` - Duration int `json:"duration"` - Thumbnail *PhotoSize `json:"thumb"` // optional - FileSize int `json:"file_size"` // optional -} - -// Voice contains information about a voice. -type Voice struct { - FileID string `json:"file_id"` - Duration int `json:"duration"` - MimeType string `json:"mime_type"` // optional - FileSize int `json:"file_size"` // optional -} - -// Contact contains information about a contact. -// -// Note that LastName and UserID may be empty. -type Contact struct { - PhoneNumber string `json:"phone_number"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` // optional - UserID int `json:"user_id"` // optional -} - -// Location contains information about a place. -type Location struct { - Longitude float64 `json:"longitude"` - Latitude float64 `json:"latitude"` -} - -// Venue contains information about a venue, including its Location. -type Venue struct { - Location Location `json:"location"` - Title string `json:"title"` - Address string `json:"address"` - FoursquareID string `json:"foursquare_id"` // optional -} - -// UserProfilePhotos contains a set of user profile photos. -type UserProfilePhotos struct { - TotalCount int `json:"total_count"` - Photos [][]PhotoSize `json:"photos"` -} - -// File contains information about a file to download from Telegram. -type File struct { - FileID string `json:"file_id"` - FileSize int `json:"file_size"` // optional - FilePath string `json:"file_path"` // optional -} - -// Link returns a full path to the download URL for a File. -// -// It requires the Bot Token to create the link. -func (f *File) Link(token string) string { - return fmt.Sprintf(FileEndpoint, token, f.FilePath) -} - -// ReplyKeyboardMarkup allows the Bot to set a custom keyboard. -type ReplyKeyboardMarkup struct { - Keyboard [][]KeyboardButton `json:"keyboard"` - ResizeKeyboard bool `json:"resize_keyboard"` // optional - OneTimeKeyboard bool `json:"one_time_keyboard"` // optional - Selective bool `json:"selective"` // optional -} - -// KeyboardButton is a button within a custom keyboard. -type KeyboardButton struct { - Text string `json:"text"` - RequestContact bool `json:"request_contact"` - RequestLocation bool `json:"request_location"` -} - -// ReplyKeyboardHide allows the Bot to hide a custom keyboard. -type ReplyKeyboardHide struct { - HideKeyboard bool `json:"hide_keyboard"` - Selective bool `json:"selective"` // optional -} - -// ReplyKeyboardRemove allows the Bot to hide a custom keyboard. -type ReplyKeyboardRemove struct { - RemoveKeyboard bool `json:"remove_keyboard"` - Selective bool `json:"selective"` -} - -// InlineKeyboardMarkup is a custom keyboard presented for an inline bot. -type InlineKeyboardMarkup struct { - InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"` -} - -// InlineKeyboardButton is a button within a custom keyboard for -// inline query responses. -// -// Note that some values are references as even an empty string -// will change behavior. -// -// CallbackGame, if set, MUST be first button in first row. -type InlineKeyboardButton struct { - Text string `json:"text"` - URL *string `json:"url,omitempty"` // optional - CallbackData *string `json:"callback_data,omitempty"` // optional - SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` // optional - SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` // optional - CallbackGame *CallbackGame `json:"callback_game,omitempty"` // optional - Pay bool `json:"pay,omitempty"` // optional -} - -// CallbackQuery is data sent when a keyboard button with callback data -// is clicked. -type CallbackQuery struct { - ID string `json:"id"` - From *User `json:"from"` - Message *Message `json:"message"` // optional - InlineMessageID string `json:"inline_message_id"` // optional - ChatInstance string `json:"chat_instance"` - Data string `json:"data"` // optional - GameShortName string `json:"game_short_name"` // optional -} - -// ForceReply allows the Bot to have users directly reply to it without -// additional interaction. -type ForceReply struct { - ForceReply bool `json:"force_reply"` - Selective bool `json:"selective"` // optional -} - -// ChatMember is information about a member in a chat. -type ChatMember struct { - User *User `json:"user"` - Status string `json:"status"` - UntilDate int64 `json:"until_date,omitempty"` // optional - CanBeEdited bool `json:"can_be_edited,omitempty"` // optional - CanChangeInfo bool `json:"can_change_info,omitempty"` // optional - CanPostMessages bool `json:"can_post_messages,omitempty"` // optional - CanEditMessages bool `json:"can_edit_messages,omitempty"` // optional - CanDeleteMessages bool `json:"can_delete_messages,omitempty"` // optional - CanInviteUsers bool `json:"can_invite_users,omitempty"` // optional - CanRestrictMembers bool `json:"can_restrict_members,omitempty"` // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` // optional - CanPromoteMembers bool `json:"can_promote_members,omitempty"` // optional - CanSendMessages bool `json:"can_send_messages,omitempty"` // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` // optional - CanSendOtherMessages bool `json:"can_send_other_messages,omitempty"` // optional - CanAddWebPagePreviews bool `json:"can_add_web_page_previews,omitempty"` // optional -} - -// IsCreator returns if the ChatMember was the creator of the chat. -func (chat ChatMember) IsCreator() bool { return chat.Status == "creator" } - -// IsAdministrator returns if the ChatMember is a chat administrator. -func (chat ChatMember) IsAdministrator() bool { return chat.Status == "administrator" } - -// IsMember returns if the ChatMember is a current member of the chat. -func (chat ChatMember) IsMember() bool { return chat.Status == "member" } - -// HasLeft returns if the ChatMember left the chat. -func (chat ChatMember) HasLeft() bool { return chat.Status == "left" } - -// WasKicked returns if the ChatMember was kicked from the chat. -func (chat ChatMember) WasKicked() bool { return chat.Status == "kicked" } - -// Game is a game within Telegram. -type Game struct { - Title string `json:"title"` - Description string `json:"description"` - Photo []PhotoSize `json:"photo"` - Text string `json:"text"` - TextEntities []MessageEntity `json:"text_entities"` - Animation Animation `json:"animation"` -} - -// Animation is a GIF animation demonstrating the game. -type Animation struct { - FileID string `json:"file_id"` - Thumb PhotoSize `json:"thumb"` - FileName string `json:"file_name"` - MimeType string `json:"mime_type"` - FileSize int `json:"file_size"` -} - -// GameHighScore is a user's score and position on the leaderboard. -type GameHighScore struct { - Position int `json:"position"` - User User `json:"user"` - Score int `json:"score"` -} - -// CallbackGame is for starting a game in an inline keyboard button. -type CallbackGame struct{} - -// WebhookInfo is information about a currently set webhook. -type WebhookInfo struct { - URL string `json:"url"` - HasCustomCertificate bool `json:"has_custom_certificate"` - PendingUpdateCount int `json:"pending_update_count"` - LastErrorDate int `json:"last_error_date"` // optional - LastErrorMessage string `json:"last_error_message"` // optional -} - -// IsSet returns true if a webhook is currently set. -func (info WebhookInfo) IsSet() bool { - return info.URL != "" -} - -// InputMediaPhoto contains a photo for displaying as part of a media group. -type InputMediaPhoto struct { - Type string `json:"type"` - Media string `json:"media"` - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` -} - -// InputMediaVideo contains a video for displaying as part of a media group. -type InputMediaVideo struct { - Type string `json:"type"` - Media string `json:"media"` - // thumb intentionally missing as it is not currently compatible - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - Width int `json:"width"` - Height int `json:"height"` - Duration int `json:"duration"` - SupportsStreaming bool `json:"supports_streaming"` -} - -// InlineQuery is a Query from Telegram for an inline request. -type InlineQuery struct { - ID string `json:"id"` - From *User `json:"from"` - Location *Location `json:"location"` // optional - Query string `json:"query"` - Offset string `json:"offset"` -} - -// InlineQueryResultArticle is an inline query response article. -type InlineQueryResultArticle struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - Title string `json:"title"` // required - InputMessageContent interface{} `json:"input_message_content,omitempty"` // required - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - URL string `json:"url"` - HideURL bool `json:"hide_url"` - Description string `json:"description"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` -} - -// InlineQueryResultPhoto is an inline query response photo. -type InlineQueryResultPhoto struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"photo_url"` // required - MimeType string `json:"mime_type"` - Width int `json:"photo_width"` - Height int `json:"photo_height"` - ThumbURL string `json:"thumb_url"` - Title string `json:"title"` - Description string `json:"description"` - Caption string `json:"caption"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedPhoto is an inline query response with cached photo. -type InlineQueryResultCachedPhoto struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - PhotoID string `json:"photo_file_id"` // required - Title string `json:"title"` - Description string `json:"description"` - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultGIF is an inline query response GIF. -type InlineQueryResultGIF struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"gif_url"` // required - ThumbURL string `json:"thumb_url"` // required - Width int `json:"gif_width,omitempty"` - Height int `json:"gif_height,omitempty"` - Duration int `json:"gif_duration,omitempty"` - Title string `json:"title,omitempty"` - Caption string `json:"caption,omitempty"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedGIF is an inline query response with cached gif. -type InlineQueryResultCachedGIF struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - GifID string `json:"gif_file_id"` // required - Title string `json:"title"` - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF. -type InlineQueryResultMPEG4GIF struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"mpeg4_url"` // required - Width int `json:"mpeg4_width"` - Height int `json:"mpeg4_height"` - Duration int `json:"mpeg4_duration"` - ThumbURL string `json:"thumb_url"` - Title string `json:"title"` - Caption string `json:"caption"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedMpeg4Gif is an inline query response with cached -// H.264/MPEG-4 AVC video without sound gif. -type InlineQueryResultCachedMpeg4Gif struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - MGifID string `json:"mpeg4_file_id"` // required - Title string `json:"title"` - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultVideo is an inline query response video. -type InlineQueryResultVideo struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"video_url"` // required - MimeType string `json:"mime_type"` // required - ThumbURL string `json:"thumb_url"` - Title string `json:"title"` - Caption string `json:"caption"` - Width int `json:"video_width"` - Height int `json:"video_height"` - Duration int `json:"video_duration"` - Description string `json:"description"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedVideo is an inline query response with cached video. -type InlineQueryResultCachedVideo struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - VideoID string `json:"video_file_id"` // required - Title string `json:"title"` // required - Description string `json:"description"` - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultAudio is an inline query response audio. -type InlineQueryResultAudio struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"audio_url"` // required - Title string `json:"title"` // required - Caption string `json:"caption"` - Performer string `json:"performer"` - Duration int `json:"audio_duration"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedAudio is an inline query response with cached audio. -type InlineQueryResultCachedAudio struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - AudioID string `json:"audio_file_id"` // required - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultVoice is an inline query response voice. -type InlineQueryResultVoice struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - URL string `json:"voice_url"` // required - Title string `json:"title"` // required - Caption string `json:"caption"` - Duration int `json:"voice_duration"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedVoice is an inline query response with cached voice. -type InlineQueryResultCachedVoice struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - VoiceID string `json:"voice_file_id"` // required - Title string `json:"title"` // required - Caption string `json:"caption"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultDocument is an inline query response document. -type InlineQueryResultDocument struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - Title string `json:"title"` // required - Caption string `json:"caption"` - URL string `json:"document_url"` // required - MimeType string `json:"mime_type"` // required - Description string `json:"description"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` -} - -// InlineQueryResultCachedDocument is an inline query response with cached document. -type InlineQueryResultCachedDocument struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - DocumentID string `json:"document_file_id"` // required - Title string `json:"title"` // required - Caption string `json:"caption"` - Description string `json:"description"` - ParseMode string `json:"parse_mode"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultLocation is an inline query response location. -type InlineQueryResultLocation struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - Latitude float64 `json:"latitude"` // required - Longitude float64 `json:"longitude"` // required - Title string `json:"title"` // required - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` -} - -// InlineQueryResultGame is an inline query response game. -type InlineQueryResultGame struct { - Type string `json:"type"` - ID string `json:"id"` - GameShortName string `json:"game_short_name"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` -} - -// ChosenInlineResult is an inline query result chosen by a User -type ChosenInlineResult struct { - ResultID string `json:"result_id"` - From *User `json:"from"` - Location *Location `json:"location"` - InlineMessageID string `json:"inline_message_id"` - Query string `json:"query"` -} - -// InputTextMessageContent contains text for displaying -// as an inline query result. -type InputTextMessageContent struct { - Text string `json:"message_text"` - ParseMode string `json:"parse_mode"` - DisableWebPagePreview bool `json:"disable_web_page_preview"` -} - -// InputLocationMessageContent contains a location for displaying -// as an inline query result. -type InputLocationMessageContent struct { - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` -} - -// InputVenueMessageContent contains a venue for displaying -// as an inline query result. -type InputVenueMessageContent struct { - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` - Title string `json:"title"` - Address string `json:"address"` - FoursquareID string `json:"foursquare_id"` -} - -// InputContactMessageContent contains a contact for displaying -// as an inline query result. -type InputContactMessageContent struct { - PhoneNumber string `json:"phone_number"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` -} - -// Invoice contains basic information about an invoice. -type Invoice struct { - Title string `json:"title"` - Description string `json:"description"` - StartParameter string `json:"start_parameter"` - Currency string `json:"currency"` - TotalAmount int `json:"total_amount"` -} - -// LabeledPrice represents a portion of the price for goods or services. -type LabeledPrice struct { - Label string `json:"label"` - Amount int `json:"amount"` -} - -// ShippingAddress represents a shipping address. -type ShippingAddress struct { - CountryCode string `json:"country_code"` - State string `json:"state"` - City string `json:"city"` - StreetLine1 string `json:"street_line1"` - StreetLine2 string `json:"street_line2"` - PostCode string `json:"post_code"` -} - -// OrderInfo represents information about an order. -type OrderInfo struct { - Name string `json:"name,omitempty"` - PhoneNumber string `json:"phone_number,omitempty"` - Email string `json:"email,omitempty"` - ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` -} - -// ShippingOption represents one shipping option. -type ShippingOption struct { - ID string `json:"id"` - Title string `json:"title"` - Prices *[]LabeledPrice `json:"prices"` -} - -// SuccessfulPayment contains basic information about a successful payment. -type SuccessfulPayment struct { - Currency string `json:"currency"` - TotalAmount int `json:"total_amount"` - InvoicePayload string `json:"invoice_payload"` - ShippingOptionID string `json:"shipping_option_id,omitempty"` - OrderInfo *OrderInfo `json:"order_info,omitempty"` - TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` - ProviderPaymentChargeID string `json:"provider_payment_charge_id"` -} - -// ShippingQuery contains information about an incoming shipping query. -type ShippingQuery struct { - ID string `json:"id"` - From *User `json:"from"` - InvoicePayload string `json:"invoice_payload"` - ShippingAddress *ShippingAddress `json:"shipping_address"` -} - -// PreCheckoutQuery contains information about an incoming pre-checkout query. -type PreCheckoutQuery struct { - ID string `json:"id"` - From *User `json:"from"` - Currency string `json:"currency"` - TotalAmount int `json:"total_amount"` - InvoicePayload string `json:"invoice_payload"` - ShippingOptionID string `json:"shipping_option_id,omitempty"` - OrderInfo *OrderInfo `json:"order_info,omitempty"` -} - -// Error is an error containing extra information returned by the Telegram API. -type Error struct { - Code int - Message string - ResponseParameters -} - -func (e Error) Error() string { - return e.Message -} diff --git a/vendor/github.com/jmoiron/sqlx/.gitignore b/vendor/github.com/jmoiron/sqlx/.gitignore deleted file mode 100644 index 529841c..0000000 --- a/vendor/github.com/jmoiron/sqlx/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -tags -environ diff --git a/vendor/github.com/jmoiron/sqlx/.travis.yml b/vendor/github.com/jmoiron/sqlx/.travis.yml deleted file mode 100644 index d728152..0000000 --- a/vendor/github.com/jmoiron/sqlx/.travis.yml +++ /dev/null @@ -1,27 +0,0 @@ -# vim: ft=yaml sw=2 ts=2 - -language: go - -# enable database services -services: - - mysql - - postgresql - -# create test database -before_install: - - mysql -e 'CREATE DATABASE IF NOT EXISTS sqlxtest;' - - psql -c 'create database sqlxtest;' -U postgres - - go get github.com/mattn/goveralls - - export SQLX_MYSQL_DSN="travis:@/sqlxtest?parseTime=true" - - export SQLX_POSTGRES_DSN="postgres://postgres:@localhost/sqlxtest?sslmode=disable" - - export SQLX_SQLITE_DSN="$HOME/sqlxtest.db" - -# go versions to test -go: - - "1.10.x" - - "1.11.x" - - "1.12.x" - -# run tests w/ coverage -script: - - travis_retry $GOPATH/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/jmoiron/sqlx/LICENSE b/vendor/github.com/jmoiron/sqlx/LICENSE deleted file mode 100644 index 0d31edf..0000000 --- a/vendor/github.com/jmoiron/sqlx/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ - Copyright (c) 2013, Jason Moiron - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following - conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - diff --git a/vendor/github.com/jmoiron/sqlx/README.md b/vendor/github.com/jmoiron/sqlx/README.md deleted file mode 100644 index 6b58616..0000000 --- a/vendor/github.com/jmoiron/sqlx/README.md +++ /dev/null @@ -1,187 +0,0 @@ -# sqlx - -[![Build Status](https://travis-ci.org/jmoiron/sqlx.svg?branch=master)](https://travis-ci.org/jmoiron/sqlx) [![Coverage Status](https://coveralls.io/repos/github/jmoiron/sqlx/badge.svg?branch=master)](https://coveralls.io/github/jmoiron/sqlx?branch=master) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/jmoiron/sqlx) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/jmoiron/sqlx/master/LICENSE) - -sqlx is a library which provides a set of extensions on go's standard -`database/sql` library. The sqlx versions of `sql.DB`, `sql.TX`, `sql.Stmt`, -et al. all leave the underlying interfaces untouched, so that their interfaces -are a superset on the standard ones. This makes it relatively painless to -integrate existing codebases using database/sql with sqlx. - -Major additional concepts are: - -* Marshal rows into structs (with embedded struct support), maps, and slices -* Named parameter support including prepared statements -* `Get` and `Select` to go quickly from query to struct/slice - -In addition to the [godoc API documentation](http://godoc.org/github.com/jmoiron/sqlx), -there is also some [user documentation](http://jmoiron.github.io/sqlx/) that -explains how to use `database/sql` along with sqlx. - -## Recent Changes - -* The [introduction](https://github.com/jmoiron/sqlx/pull/387) of `sql.ColumnType` sets the required minimum Go version to 1.8. - -* sqlx/types.JsonText has been renamed to JSONText to follow Go naming conventions. - -This breaks backwards compatibility, but it's in a way that is trivially fixable -(`s/JsonText/JSONText/g`). The `types` package is both experimental and not in -active development currently. - -* Using Go 1.6 and below with `types.JSONText` and `types.GzippedText` can be _potentially unsafe_, **especially** when used with common auto-scan sqlx idioms like `Select` and `Get`. See [golang bug #13905](https://github.com/golang/go/issues/13905). - -### Backwards Compatibility - -There is no Go1-like promise of absolute stability, but I take the issue seriously -and will maintain the library in a compatible state unless vital bugs prevent me -from doing so. Since [#59](https://github.com/jmoiron/sqlx/issues/59) and -[#60](https://github.com/jmoiron/sqlx/issues/60) necessitated breaking behavior, -a wider API cleanup was done at the time of fixing. It's possible this will happen -in future; if it does, a git tag will be provided for users requiring the old -behavior to continue to use it until such a time as they can migrate. - -## install - - go get github.com/jmoiron/sqlx - -## issues - -Row headers can be ambiguous (`SELECT 1 AS a, 2 AS a`), and the result of -`Columns()` does not fully qualify column names in queries like: - -```sql -SELECT a.id, a.name, b.id, b.name FROM foos AS a JOIN foos AS b ON a.parent = b.id; -``` - -making a struct or map destination ambiguous. Use `AS` in your queries -to give columns distinct names, `rows.Scan` to scan them manually, or -`SliceScan` to get a slice of results. - -## usage - -Below is an example which shows some common use cases for sqlx. Check -[sqlx_test.go](https://github.com/jmoiron/sqlx/blob/master/sqlx_test.go) for more -usage. - - -```go -package main - -import ( - "database/sql" - "fmt" - "log" - - _ "github.com/lib/pq" - "github.com/jmoiron/sqlx" -) - -var schema = ` -CREATE TABLE person ( - first_name text, - last_name text, - email text -); - -CREATE TABLE place ( - country text, - city text NULL, - telcode integer -)` - -type Person struct { - FirstName string `db:"first_name"` - LastName string `db:"last_name"` - Email string -} - -type Place struct { - Country string - City sql.NullString - TelCode int -} - -func main() { - // this Pings the database trying to connect, panics on error - // use sqlx.Open() for sql.Open() semantics - db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable") - if err != nil { - log.Fatalln(err) - } - - // exec the schema or fail; multi-statement Exec behavior varies between - // database drivers; pq will exec them all, sqlite3 won't, ymmv - db.MustExec(schema) - - tx := db.MustBegin() - tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "jmoiron@jmoiron.net") - tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "John", "Doe", "johndoeDNE@gmail.net") - tx.MustExec("INSERT INTO place (country, city, telcode) VALUES ($1, $2, $3)", "United States", "New York", "1") - tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Hong Kong", "852") - tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Singapore", "65") - // Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person - tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"}) - tx.Commit() - - // Query the database, storing results in a []Person (wrapped in []interface{}) - people := []Person{} - db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC") - jason, john := people[0], people[1] - - fmt.Printf("%#v\n%#v", jason, john) - // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"} - // Person{FirstName:"John", LastName:"Doe", Email:"johndoeDNE@gmail.net"} - - // You can also get a single result, a la QueryRow - jason = Person{} - err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason") - fmt.Printf("%#v\n", jason) - // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"} - - // if you have null fields and use SELECT *, you must use sql.Null* in your struct - places := []Place{} - err = db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC") - if err != nil { - fmt.Println(err) - return - } - usa, singsing, honkers := places[0], places[1], places[2] - - fmt.Printf("%#v\n%#v\n%#v\n", usa, singsing, honkers) - // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1} - // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65} - // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852} - - // Loop through rows using only one struct - place := Place{} - rows, err := db.Queryx("SELECT * FROM place") - for rows.Next() { - err := rows.StructScan(&place) - if err != nil { - log.Fatalln(err) - } - fmt.Printf("%#v\n", place) - } - // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1} - // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852} - // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65} - - // Named queries, using `:name` as the bindvar. Automatic bindvar support - // which takes into account the dbtype based on the driverName on sqlx.Open/Connect - _, err = db.NamedExec(`INSERT INTO person (first_name,last_name,email) VALUES (:first,:last,:email)`, - map[string]interface{}{ - "first": "Bin", - "last": "Smuth", - "email": "bensmith@allblacks.nz", - }) - - // Selects Mr. Smith from the database - rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:fn`, map[string]interface{}{"fn": "Bin"}) - - // Named queries can also use structs. Their bind names follow the same rules - // as the name -> db mapping, so struct fields are lowercased and the `db` tag - // is taken into consideration. - rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:first_name`, jason) -} -``` - diff --git a/vendor/github.com/jmoiron/sqlx/bind.go b/vendor/github.com/jmoiron/sqlx/bind.go deleted file mode 100644 index bd8595d..0000000 --- a/vendor/github.com/jmoiron/sqlx/bind.go +++ /dev/null @@ -1,221 +0,0 @@ -package sqlx - -import ( - "bytes" - "database/sql/driver" - "errors" - "reflect" - "strconv" - "strings" - - "github.com/jmoiron/sqlx/reflectx" -) - -// Bindvar types supported by Rebind, BindMap and BindStruct. -const ( - UNKNOWN = iota - QUESTION - DOLLAR - NAMED - AT -) - -// BindType returns the bindtype for a given database given a drivername. -func BindType(driverName string) int { - switch driverName { - case "postgres", "pgx", "pq-timeouts", "cloudsqlpostgres", "ql": - return DOLLAR - case "mysql": - return QUESTION - case "sqlite3": - return QUESTION - case "oci8", "ora", "goracle": - return NAMED - case "sqlserver": - return AT - } - return UNKNOWN -} - -// FIXME: this should be able to be tolerant of escaped ?'s in queries without -// losing much speed, and should be to avoid confusion. - -// Rebind a query from the default bindtype (QUESTION) to the target bindtype. -func Rebind(bindType int, query string) string { - switch bindType { - case QUESTION, UNKNOWN: - return query - } - - // Add space enough for 10 params before we have to allocate - rqb := make([]byte, 0, len(query)+10) - - var i, j int - - for i = strings.Index(query, "?"); i != -1; i = strings.Index(query, "?") { - rqb = append(rqb, query[:i]...) - - switch bindType { - case DOLLAR: - rqb = append(rqb, '$') - case NAMED: - rqb = append(rqb, ':', 'a', 'r', 'g') - case AT: - rqb = append(rqb, '@', 'p') - } - - j++ - rqb = strconv.AppendInt(rqb, int64(j), 10) - - query = query[i+1:] - } - - return string(append(rqb, query...)) -} - -// Experimental implementation of Rebind which uses a bytes.Buffer. The code is -// much simpler and should be more resistant to odd unicode, but it is twice as -// slow. Kept here for benchmarking purposes and to possibly replace Rebind if -// problems arise with its somewhat naive handling of unicode. -func rebindBuff(bindType int, query string) string { - if bindType != DOLLAR { - return query - } - - b := make([]byte, 0, len(query)) - rqb := bytes.NewBuffer(b) - j := 1 - for _, r := range query { - if r == '?' { - rqb.WriteRune('$') - rqb.WriteString(strconv.Itoa(j)) - j++ - } else { - rqb.WriteRune(r) - } - } - - return rqb.String() -} - -// In expands slice values in args, returning the modified query string -// and a new arg list that can be executed by a database. The `query` should -// use the `?` bindVar. The return value uses the `?` bindVar. -func In(query string, args ...interface{}) (string, []interface{}, error) { - // argMeta stores reflect.Value and length for slices and - // the value itself for non-slice arguments - type argMeta struct { - v reflect.Value - i interface{} - length int - } - - var flatArgsCount int - var anySlices bool - - meta := make([]argMeta, len(args)) - - for i, arg := range args { - if a, ok := arg.(driver.Valuer); ok { - var err error - arg, err = a.Value() - if err != nil { - return "", nil, err - } - } - v := reflect.ValueOf(arg) - t := reflectx.Deref(v.Type()) - - // []byte is a driver.Value type so it should not be expanded - if t.Kind() == reflect.Slice && t != reflect.TypeOf([]byte{}) { - meta[i].length = v.Len() - meta[i].v = v - - anySlices = true - flatArgsCount += meta[i].length - - if meta[i].length == 0 { - return "", nil, errors.New("empty slice passed to 'in' query") - } - } else { - meta[i].i = arg - flatArgsCount++ - } - } - - // don't do any parsing if there aren't any slices; note that this means - // some errors that we might have caught below will not be returned. - if !anySlices { - return query, args, nil - } - - newArgs := make([]interface{}, 0, flatArgsCount) - buf := make([]byte, 0, len(query)+len(", ?")*flatArgsCount) - - var arg, offset int - - for i := strings.IndexByte(query[offset:], '?'); i != -1; i = strings.IndexByte(query[offset:], '?') { - if arg >= len(meta) { - // if an argument wasn't passed, lets return an error; this is - // not actually how database/sql Exec/Query works, but since we are - // creating an argument list programmatically, we want to be able - // to catch these programmer errors earlier. - return "", nil, errors.New("number of bindVars exceeds arguments") - } - - argMeta := meta[arg] - arg++ - - // not a slice, continue. - // our questionmark will either be written before the next expansion - // of a slice or after the loop when writing the rest of the query - if argMeta.length == 0 { - offset = offset + i + 1 - newArgs = append(newArgs, argMeta.i) - continue - } - - // write everything up to and including our ? character - buf = append(buf, query[:offset+i+1]...) - - for si := 1; si < argMeta.length; si++ { - buf = append(buf, ", ?"...) - } - - newArgs = appendReflectSlice(newArgs, argMeta.v, argMeta.length) - - // slice the query and reset the offset. this avoids some bookkeeping for - // the write after the loop - query = query[offset+i+1:] - offset = 0 - } - - buf = append(buf, query...) - - if arg < len(meta) { - return "", nil, errors.New("number of bindVars less than number arguments") - } - - return string(buf), newArgs, nil -} - -func appendReflectSlice(args []interface{}, v reflect.Value, vlen int) []interface{} { - switch val := v.Interface().(type) { - case []interface{}: - args = append(args, val...) - case []int: - for i := range val { - args = append(args, val[i]) - } - case []string: - for i := range val { - args = append(args, val[i]) - } - default: - for si := 0; si < vlen; si++ { - args = append(args, v.Index(si).Interface()) - } - } - - return args -} diff --git a/vendor/github.com/jmoiron/sqlx/doc.go b/vendor/github.com/jmoiron/sqlx/doc.go deleted file mode 100644 index e2b4e60..0000000 --- a/vendor/github.com/jmoiron/sqlx/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package sqlx provides general purpose extensions to database/sql. -// -// It is intended to seamlessly wrap database/sql and provide convenience -// methods which are useful in the development of database driven applications. -// None of the underlying database/sql methods are changed. Instead all extended -// behavior is implemented through new methods defined on wrapper types. -// -// Additions include scanning into structs, named query support, rebinding -// queries for different drivers, convenient shorthands for common error handling -// and more. -// -package sqlx diff --git a/vendor/github.com/jmoiron/sqlx/go.mod b/vendor/github.com/jmoiron/sqlx/go.mod deleted file mode 100644 index 66c6756..0000000 --- a/vendor/github.com/jmoiron/sqlx/go.mod +++ /dev/null @@ -1,7 +0,0 @@ -module github.com/jmoiron/sqlx - -require ( - github.com/go-sql-driver/mysql v1.4.0 - github.com/lib/pq v1.0.0 - github.com/mattn/go-sqlite3 v1.9.0 -) diff --git a/vendor/github.com/jmoiron/sqlx/go.sum b/vendor/github.com/jmoiron/sqlx/go.sum deleted file mode 100644 index a3239ad..0000000 --- a/vendor/github.com/jmoiron/sqlx/go.sum +++ /dev/null @@ -1,6 +0,0 @@ -github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk= -github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= -github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4= -github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= diff --git a/vendor/github.com/jmoiron/sqlx/named.go b/vendor/github.com/jmoiron/sqlx/named.go deleted file mode 100644 index a4056de..0000000 --- a/vendor/github.com/jmoiron/sqlx/named.go +++ /dev/null @@ -1,413 +0,0 @@ -package sqlx - -// Named Query Support -// -// * BindMap - bind query bindvars to map/struct args -// * NamedExec, NamedQuery - named query w/ struct or map -// * NamedStmt - a pre-compiled named query which is a prepared statement -// -// Internal Interfaces: -// -// * compileNamedQuery - rebind a named query, returning a query and list of names -// * bindArgs, bindMapArgs, bindAnyArgs - given a list of names, return an arglist -// -import ( - "bytes" - "database/sql" - "errors" - "fmt" - "reflect" - "regexp" - "strconv" - "unicode" - - "github.com/jmoiron/sqlx/reflectx" -) - -// NamedStmt is a prepared statement that executes named queries. Prepare it -// how you would execute a NamedQuery, but pass in a struct or map when executing. -type NamedStmt struct { - Params []string - QueryString string - Stmt *Stmt -} - -// Close closes the named statement. -func (n *NamedStmt) Close() error { - return n.Stmt.Close() -} - -// Exec executes a named statement using the struct passed. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) Exec(arg interface{}) (sql.Result, error) { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return *new(sql.Result), err - } - return n.Stmt.Exec(args...) -} - -// Query executes a named statement using the struct argument, returning rows. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) Query(arg interface{}) (*sql.Rows, error) { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return nil, err - } - return n.Stmt.Query(args...) -} - -// QueryRow executes a named statement against the database. Because sqlx cannot -// create a *sql.Row with an error condition pre-set for binding errors, sqlx -// returns a *sqlx.Row instead. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryRow(arg interface{}) *Row { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return &Row{err: err} - } - return n.Stmt.QueryRowx(args...) -} - -// MustExec execs a NamedStmt, panicing on error -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) MustExec(arg interface{}) sql.Result { - res, err := n.Exec(arg) - if err != nil { - panic(err) - } - return res -} - -// Queryx using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) Queryx(arg interface{}) (*Rows, error) { - r, err := n.Query(arg) - if err != nil { - return nil, err - } - return &Rows{Rows: r, Mapper: n.Stmt.Mapper, unsafe: isUnsafe(n)}, err -} - -// QueryRowx this NamedStmt. Because of limitations with QueryRow, this is -// an alias for QueryRow. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryRowx(arg interface{}) *Row { - return n.QueryRow(arg) -} - -// Select using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) Select(dest interface{}, arg interface{}) error { - rows, err := n.Queryx(arg) - if err != nil { - return err - } - // if something happens here, we want to make sure the rows are Closed - defer rows.Close() - return scanAll(rows, dest, false) -} - -// Get using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) Get(dest interface{}, arg interface{}) error { - r := n.QueryRowx(arg) - return r.scanAny(dest, false) -} - -// Unsafe creates an unsafe version of the NamedStmt -func (n *NamedStmt) Unsafe() *NamedStmt { - r := &NamedStmt{Params: n.Params, Stmt: n.Stmt, QueryString: n.QueryString} - r.Stmt.unsafe = true - return r -} - -// A union interface of preparer and binder, required to be able to prepare -// named statements (as the bindtype must be determined). -type namedPreparer interface { - Preparer - binder -} - -func prepareNamed(p namedPreparer, query string) (*NamedStmt, error) { - bindType := BindType(p.DriverName()) - q, args, err := compileNamedQuery([]byte(query), bindType) - if err != nil { - return nil, err - } - stmt, err := Preparex(p, q) - if err != nil { - return nil, err - } - return &NamedStmt{ - QueryString: q, - Params: args, - Stmt: stmt, - }, nil -} - -func bindAnyArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) { - if maparg, ok := arg.(map[string]interface{}); ok { - return bindMapArgs(names, maparg) - } - return bindArgs(names, arg, m) -} - -// private interface to generate a list of interfaces from a given struct -// type, given a list of names to pull out of the struct. Used by public -// BindStruct interface. -func bindArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) { - arglist := make([]interface{}, 0, len(names)) - - // grab the indirected value of arg - v := reflect.ValueOf(arg) - for v = reflect.ValueOf(arg); v.Kind() == reflect.Ptr; { - v = v.Elem() - } - - err := m.TraversalsByNameFunc(v.Type(), names, func(i int, t []int) error { - if len(t) == 0 { - return fmt.Errorf("could not find name %s in %#v", names[i], arg) - } - - val := reflectx.FieldByIndexesReadOnly(v, t) - arglist = append(arglist, val.Interface()) - - return nil - }) - - return arglist, err -} - -// like bindArgs, but for maps. -func bindMapArgs(names []string, arg map[string]interface{}) ([]interface{}, error) { - arglist := make([]interface{}, 0, len(names)) - - for _, name := range names { - val, ok := arg[name] - if !ok { - return arglist, fmt.Errorf("could not find name %s in %#v", name, arg) - } - arglist = append(arglist, val) - } - return arglist, nil -} - -// bindStruct binds a named parameter query with fields from a struct argument. -// The rules for binding field names to parameter names follow the same -// conventions as for StructScan, including obeying the `db` struct tags. -func bindStruct(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { - bound, names, err := compileNamedQuery([]byte(query), bindType) - if err != nil { - return "", []interface{}{}, err - } - - arglist, err := bindArgs(names, arg, m) - if err != nil { - return "", []interface{}{}, err - } - - return bound, arglist, nil -} - -var valueBracketReg = regexp.MustCompile(`\([^(]*\?+[^)]*\)`) - -func fixBound(bound string, loop int) string { - loc := valueBracketReg.FindStringIndex(bound) - if len(loc) != 2 { - return bound - } - var buffer bytes.Buffer - - buffer.WriteString(bound[0:loc[1]]) - for i := 0; i < loop-1; i++ { - buffer.WriteString(",") - buffer.WriteString(bound[loc[0]:loc[1]]) - } - buffer.WriteString(bound[loc[1]:]) - return buffer.String() -} - -// bindArray binds a named parameter query with fields from an array or slice of -// structs argument. -func bindArray(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { - // do the initial binding with QUESTION; if bindType is not question, - // we can rebind it at the end. - bound, names, err := compileNamedQuery([]byte(query), QUESTION) - if err != nil { - return "", []interface{}{}, err - } - arrayValue := reflect.ValueOf(arg) - arrayLen := arrayValue.Len() - if arrayLen == 0 { - return "", []interface{}{}, fmt.Errorf("length of array is 0: %#v", arg) - } - var arglist []interface{} - for i := 0; i < arrayLen; i++ { - elemArglist, err := bindArgs(names, arrayValue.Index(i).Interface(), m) - if err != nil { - return "", []interface{}{}, err - } - arglist = append(arglist, elemArglist...) - } - if arrayLen > 1 { - bound = fixBound(bound, arrayLen) - } - // adjust binding type if we weren't on question - if bindType != QUESTION { - bound = Rebind(bindType, bound) - } - return bound, arglist, nil -} - -// bindMap binds a named parameter query with a map of arguments. -func bindMap(bindType int, query string, args map[string]interface{}) (string, []interface{}, error) { - bound, names, err := compileNamedQuery([]byte(query), bindType) - if err != nil { - return "", []interface{}{}, err - } - - arglist, err := bindMapArgs(names, args) - return bound, arglist, err -} - -// -- Compilation of Named Queries - -// Allow digits and letters in bind params; additionally runes are -// checked against underscores, meaning that bind params can have be -// alphanumeric with underscores. Mind the difference between unicode -// digits and numbers, where '5' is a digit but '五' is not. -var allowedBindRunes = []*unicode.RangeTable{unicode.Letter, unicode.Digit} - -// FIXME: this function isn't safe for unicode named params, as a failing test -// can testify. This is not a regression but a failure of the original code -// as well. It should be modified to range over runes in a string rather than -// bytes, even though this is less convenient and slower. Hopefully the -// addition of the prepared NamedStmt (which will only do this once) will make -// up for the slightly slower ad-hoc NamedExec/NamedQuery. - -// compile a NamedQuery into an unbound query (using the '?' bindvar) and -// a list of names. -func compileNamedQuery(qs []byte, bindType int) (query string, names []string, err error) { - names = make([]string, 0, 10) - rebound := make([]byte, 0, len(qs)) - - inName := false - last := len(qs) - 1 - currentVar := 1 - name := make([]byte, 0, 10) - - for i, b := range qs { - // a ':' while we're in a name is an error - if b == ':' { - // if this is the second ':' in a '::' escape sequence, append a ':' - if inName && i > 0 && qs[i-1] == ':' { - rebound = append(rebound, ':') - inName = false - continue - } else if inName { - err = errors.New("unexpected `:` while reading named param at " + strconv.Itoa(i)) - return query, names, err - } - inName = true - name = []byte{} - } else if inName && i > 0 && b == '=' && len(name) == 0 { - rebound = append(rebound, ':', '=') - inName = false - continue - // if we're in a name, and this is an allowed character, continue - } else if inName && (unicode.IsOneOf(allowedBindRunes, rune(b)) || b == '_' || b == '.') && i != last { - // append the byte to the name if we are in a name and not on the last byte - name = append(name, b) - // if we're in a name and it's not an allowed character, the name is done - } else if inName { - inName = false - // if this is the final byte of the string and it is part of the name, then - // make sure to add it to the name - if i == last && unicode.IsOneOf(allowedBindRunes, rune(b)) { - name = append(name, b) - } - // add the string representation to the names list - names = append(names, string(name)) - // add a proper bindvar for the bindType - switch bindType { - // oracle only supports named type bind vars even for positional - case NAMED: - rebound = append(rebound, ':') - rebound = append(rebound, name...) - case QUESTION, UNKNOWN: - rebound = append(rebound, '?') - case DOLLAR: - rebound = append(rebound, '$') - for _, b := range strconv.Itoa(currentVar) { - rebound = append(rebound, byte(b)) - } - currentVar++ - case AT: - rebound = append(rebound, '@', 'p') - for _, b := range strconv.Itoa(currentVar) { - rebound = append(rebound, byte(b)) - } - currentVar++ - } - // add this byte to string unless it was not part of the name - if i != last { - rebound = append(rebound, b) - } else if !unicode.IsOneOf(allowedBindRunes, rune(b)) { - rebound = append(rebound, b) - } - } else { - // this is a normal byte and should just go onto the rebound query - rebound = append(rebound, b) - } - } - - return string(rebound), names, err -} - -// BindNamed binds a struct or a map to a query with named parameters. -// DEPRECATED: use sqlx.Named` instead of this, it may be removed in future. -func BindNamed(bindType int, query string, arg interface{}) (string, []interface{}, error) { - return bindNamedMapper(bindType, query, arg, mapper()) -} - -// Named takes a query using named parameters and an argument and -// returns a new query with a list of args that can be executed by -// a database. The return value uses the `?` bindvar. -func Named(query string, arg interface{}) (string, []interface{}, error) { - return bindNamedMapper(QUESTION, query, arg, mapper()) -} - -func bindNamedMapper(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { - if maparg, ok := arg.(map[string]interface{}); ok { - return bindMap(bindType, query, maparg) - } - switch reflect.TypeOf(arg).Kind() { - case reflect.Array, reflect.Slice: - return bindArray(bindType, query, arg, m) - default: - return bindStruct(bindType, query, arg, m) - } -} - -// NamedQuery binds a named query and then runs Query on the result using the -// provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with -// map[string]interface{} types. -func NamedQuery(e Ext, query string, arg interface{}) (*Rows, error) { - q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) - if err != nil { - return nil, err - } - return e.Queryx(q, args...) -} - -// NamedExec uses BindStruct to get a query executable by the driver and -// then runs Exec on the result. Returns an error from the binding -// or the query execution itself. -func NamedExec(e Ext, query string, arg interface{}) (sql.Result, error) { - q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) - if err != nil { - return nil, err - } - return e.Exec(q, args...) -} diff --git a/vendor/github.com/jmoiron/sqlx/named_context.go b/vendor/github.com/jmoiron/sqlx/named_context.go deleted file mode 100644 index 07ad216..0000000 --- a/vendor/github.com/jmoiron/sqlx/named_context.go +++ /dev/null @@ -1,132 +0,0 @@ -// +build go1.8 - -package sqlx - -import ( - "context" - "database/sql" -) - -// A union interface of contextPreparer and binder, required to be able to -// prepare named statements with context (as the bindtype must be determined). -type namedPreparerContext interface { - PreparerContext - binder -} - -func prepareNamedContext(ctx context.Context, p namedPreparerContext, query string) (*NamedStmt, error) { - bindType := BindType(p.DriverName()) - q, args, err := compileNamedQuery([]byte(query), bindType) - if err != nil { - return nil, err - } - stmt, err := PreparexContext(ctx, p, q) - if err != nil { - return nil, err - } - return &NamedStmt{ - QueryString: q, - Params: args, - Stmt: stmt, - }, nil -} - -// ExecContext executes a named statement using the struct passed. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) ExecContext(ctx context.Context, arg interface{}) (sql.Result, error) { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return *new(sql.Result), err - } - return n.Stmt.ExecContext(ctx, args...) -} - -// QueryContext executes a named statement using the struct argument, returning rows. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryContext(ctx context.Context, arg interface{}) (*sql.Rows, error) { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return nil, err - } - return n.Stmt.QueryContext(ctx, args...) -} - -// QueryRowContext executes a named statement against the database. Because sqlx cannot -// create a *sql.Row with an error condition pre-set for binding errors, sqlx -// returns a *sqlx.Row instead. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryRowContext(ctx context.Context, arg interface{}) *Row { - args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) - if err != nil { - return &Row{err: err} - } - return n.Stmt.QueryRowxContext(ctx, args...) -} - -// MustExecContext execs a NamedStmt, panicing on error -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) MustExecContext(ctx context.Context, arg interface{}) sql.Result { - res, err := n.ExecContext(ctx, arg) - if err != nil { - panic(err) - } - return res -} - -// QueryxContext using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryxContext(ctx context.Context, arg interface{}) (*Rows, error) { - r, err := n.QueryContext(ctx, arg) - if err != nil { - return nil, err - } - return &Rows{Rows: r, Mapper: n.Stmt.Mapper, unsafe: isUnsafe(n)}, err -} - -// QueryRowxContext this NamedStmt. Because of limitations with QueryRow, this is -// an alias for QueryRow. -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) QueryRowxContext(ctx context.Context, arg interface{}) *Row { - return n.QueryRowContext(ctx, arg) -} - -// SelectContext using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) SelectContext(ctx context.Context, dest interface{}, arg interface{}) error { - rows, err := n.QueryxContext(ctx, arg) - if err != nil { - return err - } - // if something happens here, we want to make sure the rows are Closed - defer rows.Close() - return scanAll(rows, dest, false) -} - -// GetContext using this NamedStmt -// Any named placeholder parameters are replaced with fields from arg. -func (n *NamedStmt) GetContext(ctx context.Context, dest interface{}, arg interface{}) error { - r := n.QueryRowxContext(ctx, arg) - return r.scanAny(dest, false) -} - -// NamedQueryContext binds a named query and then runs Query on the result using the -// provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with -// map[string]interface{} types. -func NamedQueryContext(ctx context.Context, e ExtContext, query string, arg interface{}) (*Rows, error) { - q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) - if err != nil { - return nil, err - } - return e.QueryxContext(ctx, q, args...) -} - -// NamedExecContext uses BindStruct to get a query executable by the driver and -// then runs Exec on the result. Returns an error from the binding -// or the query execution itself. -func NamedExecContext(ctx context.Context, e ExtContext, query string, arg interface{}) (sql.Result, error) { - q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) - if err != nil { - return nil, err - } - return e.ExecContext(ctx, q, args...) -} diff --git a/vendor/github.com/jmoiron/sqlx/reflectx/README.md b/vendor/github.com/jmoiron/sqlx/reflectx/README.md deleted file mode 100644 index f01d3d1..0000000 --- a/vendor/github.com/jmoiron/sqlx/reflectx/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# reflectx - -The sqlx package has special reflect needs. In particular, it needs to: - -* be able to map a name to a field -* understand embedded structs -* understand mapping names to fields by a particular tag -* user specified name -> field mapping functions - -These behaviors mimic the behaviors by the standard library marshallers and also the -behavior of standard Go accessors. - -The first two are amply taken care of by `Reflect.Value.FieldByName`, and the third is -addressed by `Reflect.Value.FieldByNameFunc`, but these don't quite understand struct -tags in the ways that are vital to most marshallers, and they are slow. - -This reflectx package extends reflect to achieve these goals. diff --git a/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go b/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go deleted file mode 100644 index 458021d..0000000 --- a/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go +++ /dev/null @@ -1,439 +0,0 @@ -// Package reflectx implements extensions to the standard reflect lib suitable -// for implementing marshalling and unmarshalling packages. The main Mapper type -// allows for Go-compatible named attribute access, including accessing embedded -// struct attributes and the ability to use functions and struct tags to -// customize field names. -// -package reflectx - -import ( - "reflect" - "runtime" - "strings" - "sync" -) - -// A FieldInfo is metadata for a struct field. -type FieldInfo struct { - Index []int - Path string - Field reflect.StructField - Zero reflect.Value - Name string - Options map[string]string - Embedded bool - Children []*FieldInfo - Parent *FieldInfo -} - -// A StructMap is an index of field metadata for a struct. -type StructMap struct { - Tree *FieldInfo - Index []*FieldInfo - Paths map[string]*FieldInfo - Names map[string]*FieldInfo -} - -// GetByPath returns a *FieldInfo for a given string path. -func (f StructMap) GetByPath(path string) *FieldInfo { - return f.Paths[path] -} - -// GetByTraversal returns a *FieldInfo for a given integer path. It is -// analogous to reflect.FieldByIndex, but using the cached traversal -// rather than re-executing the reflect machinery each time. -func (f StructMap) GetByTraversal(index []int) *FieldInfo { - if len(index) == 0 { - return nil - } - - tree := f.Tree - for _, i := range index { - if i >= len(tree.Children) || tree.Children[i] == nil { - return nil - } - tree = tree.Children[i] - } - return tree -} - -// Mapper is a general purpose mapper of names to struct fields. A Mapper -// behaves like most marshallers in the standard library, obeying a field tag -// for name mapping but also providing a basic transform function. -type Mapper struct { - cache map[reflect.Type]*StructMap - tagName string - tagMapFunc func(string) string - mapFunc func(string) string - mutex sync.Mutex -} - -// NewMapper returns a new mapper using the tagName as its struct field tag. -// If tagName is the empty string, it is ignored. -func NewMapper(tagName string) *Mapper { - return &Mapper{ - cache: make(map[reflect.Type]*StructMap), - tagName: tagName, - } -} - -// NewMapperTagFunc returns a new mapper which contains a mapper for field names -// AND a mapper for tag values. This is useful for tags like json which can -// have values like "name,omitempty". -func NewMapperTagFunc(tagName string, mapFunc, tagMapFunc func(string) string) *Mapper { - return &Mapper{ - cache: make(map[reflect.Type]*StructMap), - tagName: tagName, - mapFunc: mapFunc, - tagMapFunc: tagMapFunc, - } -} - -// NewMapperFunc returns a new mapper which optionally obeys a field tag and -// a struct field name mapper func given by f. Tags will take precedence, but -// for any other field, the mapped name will be f(field.Name) -func NewMapperFunc(tagName string, f func(string) string) *Mapper { - return &Mapper{ - cache: make(map[reflect.Type]*StructMap), - tagName: tagName, - mapFunc: f, - } -} - -// TypeMap returns a mapping of field strings to int slices representing -// the traversal down the struct to reach the field. -func (m *Mapper) TypeMap(t reflect.Type) *StructMap { - m.mutex.Lock() - mapping, ok := m.cache[t] - if !ok { - mapping = getMapping(t, m.tagName, m.mapFunc, m.tagMapFunc) - m.cache[t] = mapping - } - m.mutex.Unlock() - return mapping -} - -// FieldMap returns the mapper's mapping of field names to reflect values. Panics -// if v's Kind is not Struct, or v is not Indirectable to a struct kind. -func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value { - v = reflect.Indirect(v) - mustBe(v, reflect.Struct) - - r := map[string]reflect.Value{} - tm := m.TypeMap(v.Type()) - for tagName, fi := range tm.Names { - r[tagName] = FieldByIndexes(v, fi.Index) - } - return r -} - -// FieldByName returns a field by its mapped name as a reflect.Value. -// Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. -// Returns zero Value if the name is not found. -func (m *Mapper) FieldByName(v reflect.Value, name string) reflect.Value { - v = reflect.Indirect(v) - mustBe(v, reflect.Struct) - - tm := m.TypeMap(v.Type()) - fi, ok := tm.Names[name] - if !ok { - return v - } - return FieldByIndexes(v, fi.Index) -} - -// FieldsByName returns a slice of values corresponding to the slice of names -// for the value. Panics if v's Kind is not Struct or v is not Indirectable -// to a struct Kind. Returns zero Value for each name not found. -func (m *Mapper) FieldsByName(v reflect.Value, names []string) []reflect.Value { - v = reflect.Indirect(v) - mustBe(v, reflect.Struct) - - tm := m.TypeMap(v.Type()) - vals := make([]reflect.Value, 0, len(names)) - for _, name := range names { - fi, ok := tm.Names[name] - if !ok { - vals = append(vals, *new(reflect.Value)) - } else { - vals = append(vals, FieldByIndexes(v, fi.Index)) - } - } - return vals -} - -// TraversalsByName returns a slice of int slices which represent the struct -// traversals for each mapped name. Panics if t is not a struct or Indirectable -// to a struct. Returns empty int slice for each name not found. -func (m *Mapper) TraversalsByName(t reflect.Type, names []string) [][]int { - r := make([][]int, 0, len(names)) - m.TraversalsByNameFunc(t, names, func(_ int, i []int) error { - if i == nil { - r = append(r, []int{}) - } else { - r = append(r, i) - } - - return nil - }) - return r -} - -// TraversalsByNameFunc traverses the mapped names and calls fn with the index of -// each name and the struct traversal represented by that name. Panics if t is not -// a struct or Indirectable to a struct. Returns the first error returned by fn or nil. -func (m *Mapper) TraversalsByNameFunc(t reflect.Type, names []string, fn func(int, []int) error) error { - t = Deref(t) - mustBe(t, reflect.Struct) - tm := m.TypeMap(t) - for i, name := range names { - fi, ok := tm.Names[name] - if !ok { - if err := fn(i, nil); err != nil { - return err - } - } else { - if err := fn(i, fi.Index); err != nil { - return err - } - } - } - return nil -} - -// FieldByIndexes returns a value for the field given by the struct traversal -// for the given value. -func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value { - for _, i := range indexes { - v = reflect.Indirect(v).Field(i) - // if this is a pointer and it's nil, allocate a new value and set it - if v.Kind() == reflect.Ptr && v.IsNil() { - alloc := reflect.New(Deref(v.Type())) - v.Set(alloc) - } - if v.Kind() == reflect.Map && v.IsNil() { - v.Set(reflect.MakeMap(v.Type())) - } - } - return v -} - -// FieldByIndexesReadOnly returns a value for a particular struct traversal, -// but is not concerned with allocating nil pointers because the value is -// going to be used for reading and not setting. -func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value { - for _, i := range indexes { - v = reflect.Indirect(v).Field(i) - } - return v -} - -// Deref is Indirect for reflect.Types -func Deref(t reflect.Type) reflect.Type { - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t -} - -// -- helpers & utilities -- - -type kinder interface { - Kind() reflect.Kind -} - -// mustBe checks a value against a kind, panicing with a reflect.ValueError -// if the kind isn't that which is required. -func mustBe(v kinder, expected reflect.Kind) { - if k := v.Kind(); k != expected { - panic(&reflect.ValueError{Method: methodName(), Kind: k}) - } -} - -// methodName returns the caller of the function calling methodName -func methodName() string { - pc, _, _, _ := runtime.Caller(2) - f := runtime.FuncForPC(pc) - if f == nil { - return "unknown method" - } - return f.Name() -} - -type typeQueue struct { - t reflect.Type - fi *FieldInfo - pp string // Parent path -} - -// A copying append that creates a new slice each time. -func apnd(is []int, i int) []int { - x := make([]int, len(is)+1) - copy(x, is) - x[len(x)-1] = i - return x -} - -type mapf func(string) string - -// parseName parses the tag and the target name for the given field using -// the tagName (eg 'json' for `json:"foo"` tags), mapFunc for mapping the -// field's name to a target name, and tagMapFunc for mapping the tag to -// a target name. -func parseName(field reflect.StructField, tagName string, mapFunc, tagMapFunc mapf) (tag, fieldName string) { - // first, set the fieldName to the field's name - fieldName = field.Name - // if a mapFunc is set, use that to override the fieldName - if mapFunc != nil { - fieldName = mapFunc(fieldName) - } - - // if there's no tag to look for, return the field name - if tagName == "" { - return "", fieldName - } - - // if this tag is not set using the normal convention in the tag, - // then return the fieldname.. this check is done because according - // to the reflect documentation: - // If the tag does not have the conventional format, - // the value returned by Get is unspecified. - // which doesn't sound great. - if !strings.Contains(string(field.Tag), tagName+":") { - return "", fieldName - } - - // at this point we're fairly sure that we have a tag, so lets pull it out - tag = field.Tag.Get(tagName) - - // if we have a mapper function, call it on the whole tag - // XXX: this is a change from the old version, which pulled out the name - // before the tagMapFunc could be run, but I think this is the right way - if tagMapFunc != nil { - tag = tagMapFunc(tag) - } - - // finally, split the options from the name - parts := strings.Split(tag, ",") - fieldName = parts[0] - - return tag, fieldName -} - -// parseOptions parses options out of a tag string, skipping the name -func parseOptions(tag string) map[string]string { - parts := strings.Split(tag, ",") - options := make(map[string]string, len(parts)) - if len(parts) > 1 { - for _, opt := range parts[1:] { - // short circuit potentially expensive split op - if strings.Contains(opt, "=") { - kv := strings.Split(opt, "=") - options[kv[0]] = kv[1] - continue - } - options[opt] = "" - } - } - return options -} - -// getMapping returns a mapping for the t type, using the tagName, mapFunc and -// tagMapFunc to determine the canonical names of fields. -func getMapping(t reflect.Type, tagName string, mapFunc, tagMapFunc mapf) *StructMap { - m := []*FieldInfo{} - - root := &FieldInfo{} - queue := []typeQueue{} - queue = append(queue, typeQueue{Deref(t), root, ""}) - -QueueLoop: - for len(queue) != 0 { - // pop the first item off of the queue - tq := queue[0] - queue = queue[1:] - - // ignore recursive field - for p := tq.fi.Parent; p != nil; p = p.Parent { - if tq.fi.Field.Type == p.Field.Type { - continue QueueLoop - } - } - - nChildren := 0 - if tq.t.Kind() == reflect.Struct { - nChildren = tq.t.NumField() - } - tq.fi.Children = make([]*FieldInfo, nChildren) - - // iterate through all of its fields - for fieldPos := 0; fieldPos < nChildren; fieldPos++ { - - f := tq.t.Field(fieldPos) - - // parse the tag and the target name using the mapping options for this field - tag, name := parseName(f, tagName, mapFunc, tagMapFunc) - - // if the name is "-", disabled via a tag, skip it - if name == "-" { - continue - } - - fi := FieldInfo{ - Field: f, - Name: name, - Zero: reflect.New(f.Type).Elem(), - Options: parseOptions(tag), - } - - // if the path is empty this path is just the name - if tq.pp == "" { - fi.Path = fi.Name - } else { - fi.Path = tq.pp + "." + fi.Name - } - - // skip unexported fields - if len(f.PkgPath) != 0 && !f.Anonymous { - continue - } - - // bfs search of anonymous embedded structs - if f.Anonymous { - pp := tq.pp - if tag != "" { - pp = fi.Path - } - - fi.Embedded = true - fi.Index = apnd(tq.fi.Index, fieldPos) - nChildren := 0 - ft := Deref(f.Type) - if ft.Kind() == reflect.Struct { - nChildren = ft.NumField() - } - fi.Children = make([]*FieldInfo, nChildren) - queue = append(queue, typeQueue{Deref(f.Type), &fi, pp}) - } else if fi.Zero.Kind() == reflect.Struct || (fi.Zero.Kind() == reflect.Ptr && fi.Zero.Type().Elem().Kind() == reflect.Struct) { - fi.Index = apnd(tq.fi.Index, fieldPos) - fi.Children = make([]*FieldInfo, Deref(f.Type).NumField()) - queue = append(queue, typeQueue{Deref(f.Type), &fi, fi.Path}) - } - - fi.Index = apnd(tq.fi.Index, fieldPos) - fi.Parent = tq.fi - tq.fi.Children[fieldPos] = &fi - m = append(m, &fi) - } - } - - flds := &StructMap{Index: m, Tree: root, Paths: map[string]*FieldInfo{}, Names: map[string]*FieldInfo{}} - for _, fi := range flds.Index { - flds.Paths[fi.Path] = fi - if fi.Name != "" && !fi.Embedded { - flds.Names[fi.Path] = fi - } - } - - return flds -} diff --git a/vendor/github.com/jmoiron/sqlx/sqlx.go b/vendor/github.com/jmoiron/sqlx/sqlx.go deleted file mode 100644 index ce64cbc..0000000 --- a/vendor/github.com/jmoiron/sqlx/sqlx.go +++ /dev/null @@ -1,1045 +0,0 @@ -package sqlx - -import ( - "database/sql" - "database/sql/driver" - "errors" - "fmt" - - "io/ioutil" - "path/filepath" - "reflect" - "strings" - "sync" - - "github.com/jmoiron/sqlx/reflectx" -) - -// Although the NameMapper is convenient, in practice it should not -// be relied on except for application code. If you are writing a library -// that uses sqlx, you should be aware that the name mappings you expect -// can be overridden by your user's application. - -// NameMapper is used to map column names to struct field names. By default, -// it uses strings.ToLower to lowercase struct field names. It can be set -// to whatever you want, but it is encouraged to be set before sqlx is used -// as name-to-field mappings are cached after first use on a type. -var NameMapper = strings.ToLower -var origMapper = reflect.ValueOf(NameMapper) - -// Rather than creating on init, this is created when necessary so that -// importers have time to customize the NameMapper. -var mpr *reflectx.Mapper - -// mprMu protects mpr. -var mprMu sync.Mutex - -// mapper returns a valid mapper using the configured NameMapper func. -func mapper() *reflectx.Mapper { - mprMu.Lock() - defer mprMu.Unlock() - - if mpr == nil { - mpr = reflectx.NewMapperFunc("db", NameMapper) - } else if origMapper != reflect.ValueOf(NameMapper) { - // if NameMapper has changed, create a new mapper - mpr = reflectx.NewMapperFunc("db", NameMapper) - origMapper = reflect.ValueOf(NameMapper) - } - return mpr -} - -// isScannable takes the reflect.Type and the actual dest value and returns -// whether or not it's Scannable. Something is scannable if: -// * it is not a struct -// * it implements sql.Scanner -// * it has no exported fields -func isScannable(t reflect.Type) bool { - if reflect.PtrTo(t).Implements(_scannerInterface) { - return true - } - if t.Kind() != reflect.Struct { - return true - } - - // it's not important that we use the right mapper for this particular object, - // we're only concerned on how many exported fields this struct has - m := mapper() - if len(m.TypeMap(t).Index) == 0 { - return true - } - return false -} - -// ColScanner is an interface used by MapScan and SliceScan -type ColScanner interface { - Columns() ([]string, error) - Scan(dest ...interface{}) error - Err() error -} - -// Queryer is an interface used by Get and Select -type Queryer interface { - Query(query string, args ...interface{}) (*sql.Rows, error) - Queryx(query string, args ...interface{}) (*Rows, error) - QueryRowx(query string, args ...interface{}) *Row -} - -// Execer is an interface used by MustExec and LoadFile -type Execer interface { - Exec(query string, args ...interface{}) (sql.Result, error) -} - -// Binder is an interface for something which can bind queries (Tx, DB) -type binder interface { - DriverName() string - Rebind(string) string - BindNamed(string, interface{}) (string, []interface{}, error) -} - -// Ext is a union interface which can bind, query, and exec, used by -// NamedQuery and NamedExec. -type Ext interface { - binder - Queryer - Execer -} - -// Preparer is an interface used by Preparex. -type Preparer interface { - Prepare(query string) (*sql.Stmt, error) -} - -// determine if any of our extensions are unsafe -func isUnsafe(i interface{}) bool { - switch v := i.(type) { - case Row: - return v.unsafe - case *Row: - return v.unsafe - case Rows: - return v.unsafe - case *Rows: - return v.unsafe - case NamedStmt: - return v.Stmt.unsafe - case *NamedStmt: - return v.Stmt.unsafe - case Stmt: - return v.unsafe - case *Stmt: - return v.unsafe - case qStmt: - return v.unsafe - case *qStmt: - return v.unsafe - case DB: - return v.unsafe - case *DB: - return v.unsafe - case Tx: - return v.unsafe - case *Tx: - return v.unsafe - case sql.Rows, *sql.Rows: - return false - default: - return false - } -} - -func mapperFor(i interface{}) *reflectx.Mapper { - switch i := i.(type) { - case DB: - return i.Mapper - case *DB: - return i.Mapper - case Tx: - return i.Mapper - case *Tx: - return i.Mapper - default: - return mapper() - } -} - -var _scannerInterface = reflect.TypeOf((*sql.Scanner)(nil)).Elem() -var _valuerInterface = reflect.TypeOf((*driver.Valuer)(nil)).Elem() - -// Row is a reimplementation of sql.Row in order to gain access to the underlying -// sql.Rows.Columns() data, necessary for StructScan. -type Row struct { - err error - unsafe bool - rows *sql.Rows - Mapper *reflectx.Mapper -} - -// Scan is a fixed implementation of sql.Row.Scan, which does not discard the -// underlying error from the internal rows object if it exists. -func (r *Row) Scan(dest ...interface{}) error { - if r.err != nil { - return r.err - } - - // TODO(bradfitz): for now we need to defensively clone all - // []byte that the driver returned (not permitting - // *RawBytes in Rows.Scan), since we're about to close - // the Rows in our defer, when we return from this function. - // the contract with the driver.Next(...) interface is that it - // can return slices into read-only temporary memory that's - // only valid until the next Scan/Close. But the TODO is that - // for a lot of drivers, this copy will be unnecessary. We - // should provide an optional interface for drivers to - // implement to say, "don't worry, the []bytes that I return - // from Next will not be modified again." (for instance, if - // they were obtained from the network anyway) But for now we - // don't care. - defer r.rows.Close() - for _, dp := range dest { - if _, ok := dp.(*sql.RawBytes); ok { - return errors.New("sql: RawBytes isn't allowed on Row.Scan") - } - } - - if !r.rows.Next() { - if err := r.rows.Err(); err != nil { - return err - } - return sql.ErrNoRows - } - err := r.rows.Scan(dest...) - if err != nil { - return err - } - // Make sure the query can be processed to completion with no errors. - if err := r.rows.Close(); err != nil { - return err - } - return nil -} - -// Columns returns the underlying sql.Rows.Columns(), or the deferred error usually -// returned by Row.Scan() -func (r *Row) Columns() ([]string, error) { - if r.err != nil { - return []string{}, r.err - } - return r.rows.Columns() -} - -// ColumnTypes returns the underlying sql.Rows.ColumnTypes(), or the deferred error -func (r *Row) ColumnTypes() ([]*sql.ColumnType, error) { - if r.err != nil { - return []*sql.ColumnType{}, r.err - } - return r.rows.ColumnTypes() -} - -// Err returns the error encountered while scanning. -func (r *Row) Err() error { - return r.err -} - -// DB is a wrapper around sql.DB which keeps track of the driverName upon Open, -// used mostly to automatically bind named queries using the right bindvars. -type DB struct { - *sql.DB - driverName string - unsafe bool - Mapper *reflectx.Mapper -} - -// NewDb returns a new sqlx DB wrapper for a pre-existing *sql.DB. The -// driverName of the original database is required for named query support. -func NewDb(db *sql.DB, driverName string) *DB { - return &DB{DB: db, driverName: driverName, Mapper: mapper()} -} - -// DriverName returns the driverName passed to the Open function for this DB. -func (db *DB) DriverName() string { - return db.driverName -} - -// Open is the same as sql.Open, but returns an *sqlx.DB instead. -func Open(driverName, dataSourceName string) (*DB, error) { - db, err := sql.Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - return &DB{DB: db, driverName: driverName, Mapper: mapper()}, err -} - -// MustOpen is the same as sql.Open, but returns an *sqlx.DB instead and panics on error. -func MustOpen(driverName, dataSourceName string) *DB { - db, err := Open(driverName, dataSourceName) - if err != nil { - panic(err) - } - return db -} - -// MapperFunc sets a new mapper for this db using the default sqlx struct tag -// and the provided mapper function. -func (db *DB) MapperFunc(mf func(string) string) { - db.Mapper = reflectx.NewMapperFunc("db", mf) -} - -// Rebind transforms a query from QUESTION to the DB driver's bindvar type. -func (db *DB) Rebind(query string) string { - return Rebind(BindType(db.driverName), query) -} - -// Unsafe returns a version of DB which will silently succeed to scan when -// columns in the SQL result have no fields in the destination struct. -// sqlx.Stmt and sqlx.Tx which are created from this DB will inherit its -// safety behavior. -func (db *DB) Unsafe() *DB { - return &DB{DB: db.DB, driverName: db.driverName, unsafe: true, Mapper: db.Mapper} -} - -// BindNamed binds a query using the DB driver's bindvar type. -func (db *DB) BindNamed(query string, arg interface{}) (string, []interface{}, error) { - return bindNamedMapper(BindType(db.driverName), query, arg, db.Mapper) -} - -// NamedQuery using this DB. -// Any named placeholder parameters are replaced with fields from arg. -func (db *DB) NamedQuery(query string, arg interface{}) (*Rows, error) { - return NamedQuery(db, query, arg) -} - -// NamedExec using this DB. -// Any named placeholder parameters are replaced with fields from arg. -func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error) { - return NamedExec(db, query, arg) -} - -// Select using this DB. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) Select(dest interface{}, query string, args ...interface{}) error { - return Select(db, dest, query, args...) -} - -// Get using this DB. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (db *DB) Get(dest interface{}, query string, args ...interface{}) error { - return Get(db, dest, query, args...) -} - -// MustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead -// of an *sql.Tx. -func (db *DB) MustBegin() *Tx { - tx, err := db.Beginx() - if err != nil { - panic(err) - } - return tx -} - -// Beginx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx. -func (db *DB) Beginx() (*Tx, error) { - tx, err := db.DB.Begin() - if err != nil { - return nil, err - } - return &Tx{Tx: tx, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, err -} - -// Queryx queries the database and returns an *sqlx.Rows. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) Queryx(query string, args ...interface{}) (*Rows, error) { - r, err := db.DB.Query(query, args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err -} - -// QueryRowx queries the database and returns an *sqlx.Row. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) QueryRowx(query string, args ...interface{}) *Row { - rows, err := db.DB.Query(query, args...) - return &Row{rows: rows, err: err, unsafe: db.unsafe, Mapper: db.Mapper} -} - -// MustExec (panic) runs MustExec using this database. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) MustExec(query string, args ...interface{}) sql.Result { - return MustExec(db, query, args...) -} - -// Preparex returns an sqlx.Stmt instead of a sql.Stmt -func (db *DB) Preparex(query string) (*Stmt, error) { - return Preparex(db, query) -} - -// PrepareNamed returns an sqlx.NamedStmt -func (db *DB) PrepareNamed(query string) (*NamedStmt, error) { - return prepareNamed(db, query) -} - -// Tx is an sqlx wrapper around sql.Tx with extra functionality -type Tx struct { - *sql.Tx - driverName string - unsafe bool - Mapper *reflectx.Mapper -} - -// DriverName returns the driverName used by the DB which began this transaction. -func (tx *Tx) DriverName() string { - return tx.driverName -} - -// Rebind a query within a transaction's bindvar type. -func (tx *Tx) Rebind(query string) string { - return Rebind(BindType(tx.driverName), query) -} - -// Unsafe returns a version of Tx which will silently succeed to scan when -// columns in the SQL result have no fields in the destination struct. -func (tx *Tx) Unsafe() *Tx { - return &Tx{Tx: tx.Tx, driverName: tx.driverName, unsafe: true, Mapper: tx.Mapper} -} - -// BindNamed binds a query within a transaction's bindvar type. -func (tx *Tx) BindNamed(query string, arg interface{}) (string, []interface{}, error) { - return bindNamedMapper(BindType(tx.driverName), query, arg, tx.Mapper) -} - -// NamedQuery within a transaction. -// Any named placeholder parameters are replaced with fields from arg. -func (tx *Tx) NamedQuery(query string, arg interface{}) (*Rows, error) { - return NamedQuery(tx, query, arg) -} - -// NamedExec a named query within a transaction. -// Any named placeholder parameters are replaced with fields from arg. -func (tx *Tx) NamedExec(query string, arg interface{}) (sql.Result, error) { - return NamedExec(tx, query, arg) -} - -// Select within a transaction. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) Select(dest interface{}, query string, args ...interface{}) error { - return Select(tx, dest, query, args...) -} - -// Queryx within a transaction. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) Queryx(query string, args ...interface{}) (*Rows, error) { - r, err := tx.Tx.Query(query, args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err -} - -// QueryRowx within a transaction. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) QueryRowx(query string, args ...interface{}) *Row { - rows, err := tx.Tx.Query(query, args...) - return &Row{rows: rows, err: err, unsafe: tx.unsafe, Mapper: tx.Mapper} -} - -// Get within a transaction. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error { - return Get(tx, dest, query, args...) -} - -// MustExec runs MustExec within a transaction. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) MustExec(query string, args ...interface{}) sql.Result { - return MustExec(tx, query, args...) -} - -// Preparex a statement within a transaction. -func (tx *Tx) Preparex(query string) (*Stmt, error) { - return Preparex(tx, query) -} - -// Stmtx returns a version of the prepared statement which runs within a transaction. Provided -// stmt can be either *sql.Stmt or *sqlx.Stmt. -func (tx *Tx) Stmtx(stmt interface{}) *Stmt { - var s *sql.Stmt - switch v := stmt.(type) { - case Stmt: - s = v.Stmt - case *Stmt: - s = v.Stmt - case *sql.Stmt: - s = v - default: - panic(fmt.Sprintf("non-statement type %v passed to Stmtx", reflect.ValueOf(stmt).Type())) - } - return &Stmt{Stmt: tx.Stmt(s), Mapper: tx.Mapper} -} - -// NamedStmt returns a version of the prepared statement which runs within a transaction. -func (tx *Tx) NamedStmt(stmt *NamedStmt) *NamedStmt { - return &NamedStmt{ - QueryString: stmt.QueryString, - Params: stmt.Params, - Stmt: tx.Stmtx(stmt.Stmt), - } -} - -// PrepareNamed returns an sqlx.NamedStmt -func (tx *Tx) PrepareNamed(query string) (*NamedStmt, error) { - return prepareNamed(tx, query) -} - -// Stmt is an sqlx wrapper around sql.Stmt with extra functionality -type Stmt struct { - *sql.Stmt - unsafe bool - Mapper *reflectx.Mapper -} - -// Unsafe returns a version of Stmt which will silently succeed to scan when -// columns in the SQL result have no fields in the destination struct. -func (s *Stmt) Unsafe() *Stmt { - return &Stmt{Stmt: s.Stmt, unsafe: true, Mapper: s.Mapper} -} - -// Select using the prepared statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) Select(dest interface{}, args ...interface{}) error { - return Select(&qStmt{s}, dest, "", args...) -} - -// Get using the prepared statement. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (s *Stmt) Get(dest interface{}, args ...interface{}) error { - return Get(&qStmt{s}, dest, "", args...) -} - -// MustExec (panic) using this statement. Note that the query portion of the error -// output will be blank, as Stmt does not expose its query. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) MustExec(args ...interface{}) sql.Result { - return MustExec(&qStmt{s}, "", args...) -} - -// QueryRowx using this statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) QueryRowx(args ...interface{}) *Row { - qs := &qStmt{s} - return qs.QueryRowx("", args...) -} - -// Queryx using this statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) Queryx(args ...interface{}) (*Rows, error) { - qs := &qStmt{s} - return qs.Queryx("", args...) -} - -// qStmt is an unexposed wrapper which lets you use a Stmt as a Queryer & Execer by -// implementing those interfaces and ignoring the `query` argument. -type qStmt struct{ *Stmt } - -func (q *qStmt) Query(query string, args ...interface{}) (*sql.Rows, error) { - return q.Stmt.Query(args...) -} - -func (q *qStmt) Queryx(query string, args ...interface{}) (*Rows, error) { - r, err := q.Stmt.Query(args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}, err -} - -func (q *qStmt) QueryRowx(query string, args ...interface{}) *Row { - rows, err := q.Stmt.Query(args...) - return &Row{rows: rows, err: err, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper} -} - -func (q *qStmt) Exec(query string, args ...interface{}) (sql.Result, error) { - return q.Stmt.Exec(args...) -} - -// Rows is a wrapper around sql.Rows which caches costly reflect operations -// during a looped StructScan -type Rows struct { - *sql.Rows - unsafe bool - Mapper *reflectx.Mapper - // these fields cache memory use for a rows during iteration w/ structScan - started bool - fields [][]int - values []interface{} -} - -// SliceScan using this Rows. -func (r *Rows) SliceScan() ([]interface{}, error) { - return SliceScan(r) -} - -// MapScan using this Rows. -func (r *Rows) MapScan(dest map[string]interface{}) error { - return MapScan(r, dest) -} - -// StructScan is like sql.Rows.Scan, but scans a single Row into a single Struct. -// Use this and iterate over Rows manually when the memory load of Select() might be -// prohibitive. *Rows.StructScan caches the reflect work of matching up column -// positions to fields to avoid that overhead per scan, which means it is not safe -// to run StructScan on the same Rows instance with different struct types. -func (r *Rows) StructScan(dest interface{}) error { - v := reflect.ValueOf(dest) - - if v.Kind() != reflect.Ptr { - return errors.New("must pass a pointer, not a value, to StructScan destination") - } - - v = v.Elem() - - if !r.started { - columns, err := r.Columns() - if err != nil { - return err - } - m := r.Mapper - - r.fields = m.TraversalsByName(v.Type(), columns) - // if we are not unsafe and are missing fields, return an error - if f, err := missingFields(r.fields); err != nil && !r.unsafe { - return fmt.Errorf("missing destination name %s in %T", columns[f], dest) - } - r.values = make([]interface{}, len(columns)) - r.started = true - } - - err := fieldsByTraversal(v, r.fields, r.values, true) - if err != nil { - return err - } - // scan into the struct field pointers and append to our results - err = r.Scan(r.values...) - if err != nil { - return err - } - return r.Err() -} - -// Connect to a database and verify with a ping. -func Connect(driverName, dataSourceName string) (*DB, error) { - db, err := Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - err = db.Ping() - if err != nil { - db.Close() - return nil, err - } - return db, nil -} - -// MustConnect connects to a database and panics on error. -func MustConnect(driverName, dataSourceName string) *DB { - db, err := Connect(driverName, dataSourceName) - if err != nil { - panic(err) - } - return db -} - -// Preparex prepares a statement. -func Preparex(p Preparer, query string) (*Stmt, error) { - s, err := p.Prepare(query) - if err != nil { - return nil, err - } - return &Stmt{Stmt: s, unsafe: isUnsafe(p), Mapper: mapperFor(p)}, err -} - -// Select executes a query using the provided Queryer, and StructScans each row -// into dest, which must be a slice. If the slice elements are scannable, then -// the result set must have only one column. Otherwise, StructScan is used. -// The *sql.Rows are closed automatically. -// Any placeholder parameters are replaced with supplied args. -func Select(q Queryer, dest interface{}, query string, args ...interface{}) error { - rows, err := q.Queryx(query, args...) - if err != nil { - return err - } - // if something happens here, we want to make sure the rows are Closed - defer rows.Close() - return scanAll(rows, dest, false) -} - -// Get does a QueryRow using the provided Queryer, and scans the resulting row -// to dest. If dest is scannable, the result must only have one column. Otherwise, -// StructScan is used. Get will return sql.ErrNoRows like row.Scan would. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func Get(q Queryer, dest interface{}, query string, args ...interface{}) error { - r := q.QueryRowx(query, args...) - return r.scanAny(dest, false) -} - -// LoadFile exec's every statement in a file (as a single call to Exec). -// LoadFile may return a nil *sql.Result if errors are encountered locating or -// reading the file at path. LoadFile reads the entire file into memory, so it -// is not suitable for loading large data dumps, but can be useful for initializing -// schemas or loading indexes. -// -// FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 -// or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting -// this by requiring something with DriverName() and then attempting to split the -// queries will be difficult to get right, and its current driver-specific behavior -// is deemed at least not complex in its incorrectness. -func LoadFile(e Execer, path string) (*sql.Result, error) { - realpath, err := filepath.Abs(path) - if err != nil { - return nil, err - } - contents, err := ioutil.ReadFile(realpath) - if err != nil { - return nil, err - } - res, err := e.Exec(string(contents)) - return &res, err -} - -// MustExec execs the query using e and panics if there was an error. -// Any placeholder parameters are replaced with supplied args. -func MustExec(e Execer, query string, args ...interface{}) sql.Result { - res, err := e.Exec(query, args...) - if err != nil { - panic(err) - } - return res -} - -// SliceScan using this Rows. -func (r *Row) SliceScan() ([]interface{}, error) { - return SliceScan(r) -} - -// MapScan using this Rows. -func (r *Row) MapScan(dest map[string]interface{}) error { - return MapScan(r, dest) -} - -func (r *Row) scanAny(dest interface{}, structOnly bool) error { - if r.err != nil { - return r.err - } - if r.rows == nil { - r.err = sql.ErrNoRows - return r.err - } - defer r.rows.Close() - - v := reflect.ValueOf(dest) - if v.Kind() != reflect.Ptr { - return errors.New("must pass a pointer, not a value, to StructScan destination") - } - if v.IsNil() { - return errors.New("nil pointer passed to StructScan destination") - } - - base := reflectx.Deref(v.Type()) - scannable := isScannable(base) - - if structOnly && scannable { - return structOnlyError(base) - } - - columns, err := r.Columns() - if err != nil { - return err - } - - if scannable && len(columns) > 1 { - return fmt.Errorf("scannable dest type %s with >1 columns (%d) in result", base.Kind(), len(columns)) - } - - if scannable { - return r.Scan(dest) - } - - m := r.Mapper - - fields := m.TraversalsByName(v.Type(), columns) - // if we are not unsafe and are missing fields, return an error - if f, err := missingFields(fields); err != nil && !r.unsafe { - return fmt.Errorf("missing destination name %s in %T", columns[f], dest) - } - values := make([]interface{}, len(columns)) - - err = fieldsByTraversal(v, fields, values, true) - if err != nil { - return err - } - // scan into the struct field pointers and append to our results - return r.Scan(values...) -} - -// StructScan a single Row into dest. -func (r *Row) StructScan(dest interface{}) error { - return r.scanAny(dest, true) -} - -// SliceScan a row, returning a []interface{} with values similar to MapScan. -// This function is primarily intended for use where the number of columns -// is not known. Because you can pass an []interface{} directly to Scan, -// it's recommended that you do that as it will not have to allocate new -// slices per row. -func SliceScan(r ColScanner) ([]interface{}, error) { - // ignore r.started, since we needn't use reflect for anything. - columns, err := r.Columns() - if err != nil { - return []interface{}{}, err - } - - values := make([]interface{}, len(columns)) - for i := range values { - values[i] = new(interface{}) - } - - err = r.Scan(values...) - - if err != nil { - return values, err - } - - for i := range columns { - values[i] = *(values[i].(*interface{})) - } - - return values, r.Err() -} - -// MapScan scans a single Row into the dest map[string]interface{}. -// Use this to get results for SQL that might not be under your control -// (for instance, if you're building an interface for an SQL server that -// executes SQL from input). Please do not use this as a primary interface! -// This will modify the map sent to it in place, so reuse the same map with -// care. Columns which occur more than once in the result will overwrite -// each other! -func MapScan(r ColScanner, dest map[string]interface{}) error { - // ignore r.started, since we needn't use reflect for anything. - columns, err := r.Columns() - if err != nil { - return err - } - - values := make([]interface{}, len(columns)) - for i := range values { - values[i] = new(interface{}) - } - - err = r.Scan(values...) - if err != nil { - return err - } - - for i, column := range columns { - dest[column] = *(values[i].(*interface{})) - } - - return r.Err() -} - -type rowsi interface { - Close() error - Columns() ([]string, error) - Err() error - Next() bool - Scan(...interface{}) error -} - -// structOnlyError returns an error appropriate for type when a non-scannable -// struct is expected but something else is given -func structOnlyError(t reflect.Type) error { - isStruct := t.Kind() == reflect.Struct - isScanner := reflect.PtrTo(t).Implements(_scannerInterface) - if !isStruct { - return fmt.Errorf("expected %s but got %s", reflect.Struct, t.Kind()) - } - if isScanner { - return fmt.Errorf("structscan expects a struct dest but the provided struct type %s implements scanner", t.Name()) - } - return fmt.Errorf("expected a struct, but struct %s has no exported fields", t.Name()) -} - -// scanAll scans all rows into a destination, which must be a slice of any -// type. If the destination slice type is a Struct, then StructScan will be -// used on each row. If the destination is some other kind of base type, then -// each row must only have one column which can scan into that type. This -// allows you to do something like: -// -// rows, _ := db.Query("select id from people;") -// var ids []int -// scanAll(rows, &ids, false) -// -// and ids will be a list of the id results. I realize that this is a desirable -// interface to expose to users, but for now it will only be exposed via changes -// to `Get` and `Select`. The reason that this has been implemented like this is -// this is the only way to not duplicate reflect work in the new API while -// maintaining backwards compatibility. -func scanAll(rows rowsi, dest interface{}, structOnly bool) error { - var v, vp reflect.Value - - value := reflect.ValueOf(dest) - - // json.Unmarshal returns errors for these - if value.Kind() != reflect.Ptr { - return errors.New("must pass a pointer, not a value, to StructScan destination") - } - if value.IsNil() { - return errors.New("nil pointer passed to StructScan destination") - } - direct := reflect.Indirect(value) - - slice, err := baseType(value.Type(), reflect.Slice) - if err != nil { - return err - } - - isPtr := slice.Elem().Kind() == reflect.Ptr - base := reflectx.Deref(slice.Elem()) - scannable := isScannable(base) - - if structOnly && scannable { - return structOnlyError(base) - } - - columns, err := rows.Columns() - if err != nil { - return err - } - - // if it's a base type make sure it only has 1 column; if not return an error - if scannable && len(columns) > 1 { - return fmt.Errorf("non-struct dest type %s with >1 columns (%d)", base.Kind(), len(columns)) - } - - if !scannable { - var values []interface{} - var m *reflectx.Mapper - - switch rows.(type) { - case *Rows: - m = rows.(*Rows).Mapper - default: - m = mapper() - } - - fields := m.TraversalsByName(base, columns) - // if we are not unsafe and are missing fields, return an error - if f, err := missingFields(fields); err != nil && !isUnsafe(rows) { - return fmt.Errorf("missing destination name %s in %T", columns[f], dest) - } - values = make([]interface{}, len(columns)) - - for rows.Next() { - // create a new struct type (which returns PtrTo) and indirect it - vp = reflect.New(base) - v = reflect.Indirect(vp) - - err = fieldsByTraversal(v, fields, values, true) - if err != nil { - return err - } - - // scan into the struct field pointers and append to our results - err = rows.Scan(values...) - if err != nil { - return err - } - - if isPtr { - direct.Set(reflect.Append(direct, vp)) - } else { - direct.Set(reflect.Append(direct, v)) - } - } - } else { - for rows.Next() { - vp = reflect.New(base) - err = rows.Scan(vp.Interface()) - if err != nil { - return err - } - // append - if isPtr { - direct.Set(reflect.Append(direct, vp)) - } else { - direct.Set(reflect.Append(direct, reflect.Indirect(vp))) - } - } - } - - return rows.Err() -} - -// FIXME: StructScan was the very first bit of API in sqlx, and now unfortunately -// it doesn't really feel like it's named properly. There is an incongruency -// between this and the way that StructScan (which might better be ScanStruct -// anyway) works on a rows object. - -// StructScan all rows from an sql.Rows or an sqlx.Rows into the dest slice. -// StructScan will scan in the entire rows result, so if you do not want to -// allocate structs for the entire result, use Queryx and see sqlx.Rows.StructScan. -// If rows is sqlx.Rows, it will use its mapper, otherwise it will use the default. -func StructScan(rows rowsi, dest interface{}) error { - return scanAll(rows, dest, true) - -} - -// reflect helpers - -func baseType(t reflect.Type, expected reflect.Kind) (reflect.Type, error) { - t = reflectx.Deref(t) - if t.Kind() != expected { - return nil, fmt.Errorf("expected %s but got %s", expected, t.Kind()) - } - return t, nil -} - -// fieldsByName fills a values interface with fields from the passed value based -// on the traversals in int. If ptrs is true, return addresses instead of values. -// We write this instead of using FieldsByName to save allocations and map lookups -// when iterating over many rows. Empty traversals will get an interface pointer. -// Because of the necessity of requesting ptrs or values, it's considered a bit too -// specialized for inclusion in reflectx itself. -func fieldsByTraversal(v reflect.Value, traversals [][]int, values []interface{}, ptrs bool) error { - v = reflect.Indirect(v) - if v.Kind() != reflect.Struct { - return errors.New("argument not a struct") - } - - for i, traversal := range traversals { - if len(traversal) == 0 { - values[i] = new(interface{}) - continue - } - f := reflectx.FieldByIndexes(v, traversal) - if ptrs { - values[i] = f.Addr().Interface() - } else { - values[i] = f.Interface() - } - } - return nil -} - -func missingFields(transversals [][]int) (field int, err error) { - for i, t := range transversals { - if len(t) == 0 { - return i, errors.New("missing field") - } - } - return 0, nil -} diff --git a/vendor/github.com/jmoiron/sqlx/sqlx_context.go b/vendor/github.com/jmoiron/sqlx/sqlx_context.go deleted file mode 100644 index 0603311..0000000 --- a/vendor/github.com/jmoiron/sqlx/sqlx_context.go +++ /dev/null @@ -1,346 +0,0 @@ -// +build go1.8 - -package sqlx - -import ( - "context" - "database/sql" - "fmt" - "io/ioutil" - "path/filepath" - "reflect" -) - -// ConnectContext to a database and verify with a ping. -func ConnectContext(ctx context.Context, driverName, dataSourceName string) (*DB, error) { - db, err := Open(driverName, dataSourceName) - if err != nil { - return db, err - } - err = db.PingContext(ctx) - return db, err -} - -// QueryerContext is an interface used by GetContext and SelectContext -type QueryerContext interface { - QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) - QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) - QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row -} - -// PreparerContext is an interface used by PreparexContext. -type PreparerContext interface { - PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) -} - -// ExecerContext is an interface used by MustExecContext and LoadFileContext -type ExecerContext interface { - ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) -} - -// ExtContext is a union interface which can bind, query, and exec, with Context -// used by NamedQueryContext and NamedExecContext. -type ExtContext interface { - binder - QueryerContext - ExecerContext -} - -// SelectContext executes a query using the provided Queryer, and StructScans -// each row into dest, which must be a slice. If the slice elements are -// scannable, then the result set must have only one column. Otherwise, -// StructScan is used. The *sql.Rows are closed automatically. -// Any placeholder parameters are replaced with supplied args. -func SelectContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error { - rows, err := q.QueryxContext(ctx, query, args...) - if err != nil { - return err - } - // if something happens here, we want to make sure the rows are Closed - defer rows.Close() - return scanAll(rows, dest, false) -} - -// PreparexContext prepares a statement. -// -// The provided context is used for the preparation of the statement, not for -// the execution of the statement. -func PreparexContext(ctx context.Context, p PreparerContext, query string) (*Stmt, error) { - s, err := p.PrepareContext(ctx, query) - if err != nil { - return nil, err - } - return &Stmt{Stmt: s, unsafe: isUnsafe(p), Mapper: mapperFor(p)}, err -} - -// GetContext does a QueryRow using the provided Queryer, and scans the -// resulting row to dest. If dest is scannable, the result must only have one -// column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like -// row.Scan would. Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func GetContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error { - r := q.QueryRowxContext(ctx, query, args...) - return r.scanAny(dest, false) -} - -// LoadFileContext exec's every statement in a file (as a single call to Exec). -// LoadFileContext may return a nil *sql.Result if errors are encountered -// locating or reading the file at path. LoadFile reads the entire file into -// memory, so it is not suitable for loading large data dumps, but can be useful -// for initializing schemas or loading indexes. -// -// FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 -// or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting -// this by requiring something with DriverName() and then attempting to split the -// queries will be difficult to get right, and its current driver-specific behavior -// is deemed at least not complex in its incorrectness. -func LoadFileContext(ctx context.Context, e ExecerContext, path string) (*sql.Result, error) { - realpath, err := filepath.Abs(path) - if err != nil { - return nil, err - } - contents, err := ioutil.ReadFile(realpath) - if err != nil { - return nil, err - } - res, err := e.ExecContext(ctx, string(contents)) - return &res, err -} - -// MustExecContext execs the query using e and panics if there was an error. -// Any placeholder parameters are replaced with supplied args. -func MustExecContext(ctx context.Context, e ExecerContext, query string, args ...interface{}) sql.Result { - res, err := e.ExecContext(ctx, query, args...) - if err != nil { - panic(err) - } - return res -} - -// PrepareNamedContext returns an sqlx.NamedStmt -func (db *DB) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error) { - return prepareNamedContext(ctx, db, query) -} - -// NamedQueryContext using this DB. -// Any named placeholder parameters are replaced with fields from arg. -func (db *DB) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error) { - return NamedQueryContext(ctx, db, query, arg) -} - -// NamedExecContext using this DB. -// Any named placeholder parameters are replaced with fields from arg. -func (db *DB) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { - return NamedExecContext(ctx, db, query, arg) -} - -// SelectContext using this DB. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { - return SelectContext(ctx, db, dest, query, args...) -} - -// GetContext using this DB. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (db *DB) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { - return GetContext(ctx, db, dest, query, args...) -} - -// PreparexContext returns an sqlx.Stmt instead of a sql.Stmt. -// -// The provided context is used for the preparation of the statement, not for -// the execution of the statement. -func (db *DB) PreparexContext(ctx context.Context, query string) (*Stmt, error) { - return PreparexContext(ctx, db, query) -} - -// QueryxContext queries the database and returns an *sqlx.Rows. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { - r, err := db.DB.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err -} - -// QueryRowxContext queries the database and returns an *sqlx.Row. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { - rows, err := db.DB.QueryContext(ctx, query, args...) - return &Row{rows: rows, err: err, unsafe: db.unsafe, Mapper: db.Mapper} -} - -// MustBeginTx starts a transaction, and panics on error. Returns an *sqlx.Tx instead -// of an *sql.Tx. -// -// The provided context is used until the transaction is committed or rolled -// back. If the context is canceled, the sql package will roll back the -// transaction. Tx.Commit will return an error if the context provided to -// MustBeginContext is canceled. -func (db *DB) MustBeginTx(ctx context.Context, opts *sql.TxOptions) *Tx { - tx, err := db.BeginTxx(ctx, opts) - if err != nil { - panic(err) - } - return tx -} - -// MustExecContext (panic) runs MustExec using this database. -// Any placeholder parameters are replaced with supplied args. -func (db *DB) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result { - return MustExecContext(ctx, db, query, args...) -} - -// BeginTxx begins a transaction and returns an *sqlx.Tx instead of an -// *sql.Tx. -// -// The provided context is used until the transaction is committed or rolled -// back. If the context is canceled, the sql package will roll back the -// transaction. Tx.Commit will return an error if the context provided to -// BeginxContext is canceled. -func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { - tx, err := db.DB.BeginTx(ctx, opts) - if err != nil { - return nil, err - } - return &Tx{Tx: tx, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, err -} - -// StmtxContext returns a version of the prepared statement which runs within a -// transaction. Provided stmt can be either *sql.Stmt or *sqlx.Stmt. -func (tx *Tx) StmtxContext(ctx context.Context, stmt interface{}) *Stmt { - var s *sql.Stmt - switch v := stmt.(type) { - case Stmt: - s = v.Stmt - case *Stmt: - s = v.Stmt - case *sql.Stmt: - s = v - default: - panic(fmt.Sprintf("non-statement type %v passed to Stmtx", reflect.ValueOf(stmt).Type())) - } - return &Stmt{Stmt: tx.StmtContext(ctx, s), Mapper: tx.Mapper} -} - -// NamedStmtContext returns a version of the prepared statement which runs -// within a transaction. -func (tx *Tx) NamedStmtContext(ctx context.Context, stmt *NamedStmt) *NamedStmt { - return &NamedStmt{ - QueryString: stmt.QueryString, - Params: stmt.Params, - Stmt: tx.StmtxContext(ctx, stmt.Stmt), - } -} - -// PreparexContext returns an sqlx.Stmt instead of a sql.Stmt. -// -// The provided context is used for the preparation of the statement, not for -// the execution of the statement. -func (tx *Tx) PreparexContext(ctx context.Context, query string) (*Stmt, error) { - return PreparexContext(ctx, tx, query) -} - -// PrepareNamedContext returns an sqlx.NamedStmt -func (tx *Tx) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error) { - return prepareNamedContext(ctx, tx, query) -} - -// MustExecContext runs MustExecContext within a transaction. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result { - return MustExecContext(ctx, tx, query, args...) -} - -// QueryxContext within a transaction and context. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { - r, err := tx.Tx.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err -} - -// SelectContext within a transaction and context. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { - return SelectContext(ctx, tx, dest, query, args...) -} - -// GetContext within a transaction and context. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (tx *Tx) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { - return GetContext(ctx, tx, dest, query, args...) -} - -// QueryRowxContext within a transaction and context. -// Any placeholder parameters are replaced with supplied args. -func (tx *Tx) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { - rows, err := tx.Tx.QueryContext(ctx, query, args...) - return &Row{rows: rows, err: err, unsafe: tx.unsafe, Mapper: tx.Mapper} -} - -// NamedExecContext using this Tx. -// Any named placeholder parameters are replaced with fields from arg. -func (tx *Tx) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { - return NamedExecContext(ctx, tx, query, arg) -} - -// SelectContext using the prepared statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) SelectContext(ctx context.Context, dest interface{}, args ...interface{}) error { - return SelectContext(ctx, &qStmt{s}, dest, "", args...) -} - -// GetContext using the prepared statement. -// Any placeholder parameters are replaced with supplied args. -// An error is returned if the result set is empty. -func (s *Stmt) GetContext(ctx context.Context, dest interface{}, args ...interface{}) error { - return GetContext(ctx, &qStmt{s}, dest, "", args...) -} - -// MustExecContext (panic) using this statement. Note that the query portion of -// the error output will be blank, as Stmt does not expose its query. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) MustExecContext(ctx context.Context, args ...interface{}) sql.Result { - return MustExecContext(ctx, &qStmt{s}, "", args...) -} - -// QueryRowxContext using this statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) QueryRowxContext(ctx context.Context, args ...interface{}) *Row { - qs := &qStmt{s} - return qs.QueryRowxContext(ctx, "", args...) -} - -// QueryxContext using this statement. -// Any placeholder parameters are replaced with supplied args. -func (s *Stmt) QueryxContext(ctx context.Context, args ...interface{}) (*Rows, error) { - qs := &qStmt{s} - return qs.QueryxContext(ctx, "", args...) -} - -func (q *qStmt) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { - return q.Stmt.QueryContext(ctx, args...) -} - -func (q *qStmt) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { - r, err := q.Stmt.QueryContext(ctx, args...) - if err != nil { - return nil, err - } - return &Rows{Rows: r, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}, err -} - -func (q *qStmt) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { - rows, err := q.Stmt.QueryContext(ctx, args...) - return &Row{rows: rows, err: err, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper} -} - -func (q *qStmt) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { - return q.Stmt.ExecContext(ctx, args...) -} diff --git a/vendor/github.com/lib/pq/.gitignore b/vendor/github.com/lib/pq/.gitignore deleted file mode 100644 index 0f1d00e..0000000 --- a/vendor/github.com/lib/pq/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.db -*.test -*~ -*.swp diff --git a/vendor/github.com/lib/pq/.travis.sh b/vendor/github.com/lib/pq/.travis.sh deleted file mode 100755 index ebf4470..0000000 --- a/vendor/github.com/lib/pq/.travis.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/bin/bash - -set -eu - -client_configure() { - sudo chmod 600 $PQSSLCERTTEST_PATH/postgresql.key -} - -pgdg_repository() { - local sourcelist='sources.list.d/postgresql.list' - - curl -sS 'https://www.postgresql.org/media/keys/ACCC4CF8.asc' | sudo apt-key add - - echo deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main $PGVERSION | sudo tee "/etc/apt/$sourcelist" - sudo apt-get -o Dir::Etc::sourcelist="$sourcelist" -o Dir::Etc::sourceparts='-' -o APT::Get::List-Cleanup='0' update -} - -postgresql_configure() { - sudo tee /etc/postgresql/$PGVERSION/main/pg_hba.conf > /dev/null <<-config - local all all trust - hostnossl all pqgossltest 127.0.0.1/32 reject - hostnossl all pqgosslcert 127.0.0.1/32 reject - hostssl all pqgossltest 127.0.0.1/32 trust - hostssl all pqgosslcert 127.0.0.1/32 cert - host all all 127.0.0.1/32 trust - hostnossl all pqgossltest ::1/128 reject - hostnossl all pqgosslcert ::1/128 reject - hostssl all pqgossltest ::1/128 trust - hostssl all pqgosslcert ::1/128 cert - host all all ::1/128 trust - config - - xargs sudo install -o postgres -g postgres -m 600 -t /var/lib/postgresql/$PGVERSION/main/ <<-certificates - certs/root.crt - certs/server.crt - certs/server.key - certificates - - sort -VCu <<-versions || - $PGVERSION - 9.2 - versions - sudo tee -a /etc/postgresql/$PGVERSION/main/postgresql.conf > /dev/null <<-config - ssl_ca_file = 'root.crt' - ssl_cert_file = 'server.crt' - ssl_key_file = 'server.key' - config - - echo 127.0.0.1 postgres | sudo tee -a /etc/hosts > /dev/null - - sudo service postgresql restart -} - -postgresql_install() { - xargs sudo apt-get -y -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::='--force-confnew' install <<-packages - postgresql-$PGVERSION - postgresql-server-dev-$PGVERSION - postgresql-contrib-$PGVERSION - packages -} - -postgresql_uninstall() { - sudo service postgresql stop - xargs sudo apt-get -y --purge remove <<-packages - libpq-dev - libpq5 - postgresql - postgresql-client-common - postgresql-common - packages - sudo rm -rf /var/lib/postgresql -} - -$1 diff --git a/vendor/github.com/lib/pq/.travis.yml b/vendor/github.com/lib/pq/.travis.yml deleted file mode 100644 index 8396f5d..0000000 --- a/vendor/github.com/lib/pq/.travis.yml +++ /dev/null @@ -1,44 +0,0 @@ -language: go - -go: - - 1.11.x - - 1.12.x - - master - -sudo: true - -env: - global: - - PGUSER=postgres - - PQGOSSLTESTS=1 - - PQSSLCERTTEST_PATH=$PWD/certs - - PGHOST=127.0.0.1 - matrix: - - PGVERSION=10 - - PGVERSION=9.6 - - PGVERSION=9.5 - - PGVERSION=9.4 - -before_install: - - ./.travis.sh postgresql_uninstall - - ./.travis.sh pgdg_repository - - ./.travis.sh postgresql_install - - ./.travis.sh postgresql_configure - - ./.travis.sh client_configure - - go get golang.org/x/tools/cmd/goimports - - go get golang.org/x/lint/golint - - GO111MODULE=on go get honnef.co/go/tools/cmd/staticcheck@2019.2.1 - -before_script: - - createdb pqgotest - - createuser -DRS pqgossltest - - createuser -DRS pqgosslcert - -script: - - > - goimports -d -e $(find -name '*.go') | awk '{ print } END { exit NR == 0 ? 0 : 1 }' - - go vet ./... - - staticcheck -go 1.11 ./... - - golint ./... - - PQTEST_BINARY_PARAMETERS=no go test -race -v ./... - - PQTEST_BINARY_PARAMETERS=yes go test -race -v ./... diff --git a/vendor/github.com/lib/pq/CONTRIBUTING.md b/vendor/github.com/lib/pq/CONTRIBUTING.md deleted file mode 100644 index 84c937f..0000000 --- a/vendor/github.com/lib/pq/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -## Contributing to pq - -`pq` has a backlog of pull requests, but contributions are still very -much welcome. You can help with patch review, submitting bug reports, -or adding new functionality. There is no formal style guide, but -please conform to the style of existing code and general Go formatting -conventions when submitting patches. - -### Patch review - -Help review existing open pull requests by commenting on the code or -proposed functionality. - -### Bug reports - -We appreciate any bug reports, but especially ones with self-contained -(doesn't depend on code outside of pq), minimal (can't be simplified -further) test cases. It's especially helpful if you can submit a pull -request with just the failing test case (you'll probably want to -pattern it after the tests in -[conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go). - -### New functionality - -There are a number of pending patches for new functionality, so -additional feature patches will take a while to merge. Still, patches -are generally reviewed based on usefulness and complexity in addition -to time-in-queue, so if you have a knockout idea, take a shot. Feel -free to open an issue discussion your proposed patch beforehand. diff --git a/vendor/github.com/lib/pq/LICENSE.md b/vendor/github.com/lib/pq/LICENSE.md deleted file mode 100644 index 5773904..0000000 --- a/vendor/github.com/lib/pq/LICENSE.md +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2011-2013, 'pq' Contributors -Portions Copyright (C) 2011 Blake Mizerany - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/lib/pq/README.md b/vendor/github.com/lib/pq/README.md deleted file mode 100644 index 385fe73..0000000 --- a/vendor/github.com/lib/pq/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# pq - A pure Go postgres driver for Go's database/sql package - -[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://godoc.org/github.com/lib/pq) -[![Build Status](https://travis-ci.org/lib/pq.svg?branch=master)](https://travis-ci.org/lib/pq) - -## Install - - go get github.com/lib/pq - -## Docs - -For detailed documentation and basic usage examples, please see the package -documentation at . - -## Tests - -`go test` is used for testing. See [TESTS.md](TESTS.md) for more details. - -## Features - -* SSL -* Handles bad connections for `database/sql` -* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`) -* Scan binary blobs correctly (i.e. `bytea`) -* Package for `hstore` support -* COPY FROM support -* pq.ParseURL for converting urls to connection strings for sql.Open. -* Many libpq compatible environment variables -* Unix socket support -* Notifications: `LISTEN`/`NOTIFY` -* pgpass support - -## Future / Things you can help with - -* Better COPY FROM / COPY TO (see discussion in #181) - -## Thank you (alphabetical) - -Some of these contributors are from the original library `bmizerany/pq.go` whose -code still exists in here. - -* Andy Balholm (andybalholm) -* Ben Berkert (benburkert) -* Benjamin Heatwole (bheatwole) -* Bill Mill (llimllib) -* Bjørn Madsen (aeons) -* Blake Gentry (bgentry) -* Brad Fitzpatrick (bradfitz) -* Charlie Melbye (cmelbye) -* Chris Bandy (cbandy) -* Chris Gilling (cgilling) -* Chris Walsh (cwds) -* Dan Sosedoff (sosedoff) -* Daniel Farina (fdr) -* Eric Chlebek (echlebek) -* Eric Garrido (minusnine) -* Eric Urban (hydrogen18) -* Everyone at The Go Team -* Evan Shaw (edsrzf) -* Ewan Chou (coocood) -* Fazal Majid (fazalmajid) -* Federico Romero (federomero) -* Fumin (fumin) -* Gary Burd (garyburd) -* Heroku (heroku) -* James Pozdena (jpoz) -* Jason McVetta (jmcvetta) -* Jeremy Jay (pbnjay) -* Joakim Sernbrant (serbaut) -* John Gallagher (jgallagher) -* Jonathan Rudenberg (titanous) -* Joël Stemmer (jstemmer) -* Kamil Kisiel (kisielk) -* Kelly Dunn (kellydunn) -* Keith Rarick (kr) -* Kir Shatrov (kirs) -* Lann Martin (lann) -* Maciek Sakrejda (uhoh-itsmaciek) -* Marc Brinkmann (mbr) -* Marko Tiikkaja (johto) -* Matt Newberry (MattNewberry) -* Matt Robenolt (mattrobenolt) -* Martin Olsen (martinolsen) -* Mike Lewis (mikelikespie) -* Nicolas Patry (Narsil) -* Oliver Tonnhofer (olt) -* Patrick Hayes (phayes) -* Paul Hammond (paulhammond) -* Ryan Smith (ryandotsmith) -* Samuel Stauffer (samuel) -* Timothée Peignier (cyberdelia) -* Travis Cline (tmc) -* TruongSinh Tran-Nguyen (truongsinh) -* Yaismel Miranda (ympons) -* notedit (notedit) diff --git a/vendor/github.com/lib/pq/TESTS.md b/vendor/github.com/lib/pq/TESTS.md deleted file mode 100644 index f050211..0000000 --- a/vendor/github.com/lib/pq/TESTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# Tests - -## Running Tests - -`go test` is used for testing. A running PostgreSQL -server is required, with the ability to log in. The -database to connect to test with is "pqgotest," on -"localhost" but these can be overridden using [environment -variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html). - -Example: - - PGHOST=/run/postgresql go test - -## Benchmarks - -A benchmark suite can be run as part of the tests: - - go test -bench . - -## Example setup (Docker) - -Run a postgres container: - -``` -docker run --expose 5432:5432 postgres -``` - -Run tests: - -``` -PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test -``` diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go deleted file mode 100644 index e4933e2..0000000 --- a/vendor/github.com/lib/pq/array.go +++ /dev/null @@ -1,756 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql" - "database/sql/driver" - "encoding/hex" - "fmt" - "reflect" - "strconv" - "strings" -) - -var typeByteSlice = reflect.TypeOf([]byte{}) -var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() -var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() - -// Array returns the optimal driver.Valuer and sql.Scanner for an array or -// slice of any dimension. -// -// For example: -// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401})) -// -// var x []sql.NullInt64 -// db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x)) -// -// Scanning multi-dimensional arrays is not supported. Arrays where the lower -// bound is not one (such as `[0:0]={1}') are not supported. -func Array(a interface{}) interface { - driver.Valuer - sql.Scanner -} { - switch a := a.(type) { - case []bool: - return (*BoolArray)(&a) - case []float64: - return (*Float64Array)(&a) - case []int64: - return (*Int64Array)(&a) - case []string: - return (*StringArray)(&a) - - case *[]bool: - return (*BoolArray)(a) - case *[]float64: - return (*Float64Array)(a) - case *[]int64: - return (*Int64Array)(a) - case *[]string: - return (*StringArray)(a) - } - - return GenericArray{a} -} - -// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner -// to override the array delimiter used by GenericArray. -type ArrayDelimiter interface { - // ArrayDelimiter returns the delimiter character(s) for this element's type. - ArrayDelimiter() string -} - -// BoolArray represents a one-dimensional array of the PostgreSQL boolean type. -type BoolArray []bool - -// Scan implements the sql.Scanner interface. -func (a *BoolArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to BoolArray", src) -} - -func (a *BoolArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "BoolArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(BoolArray, len(elems)) - for i, v := range elems { - if len(v) != 1 { - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - switch v[0] { - case 't': - b[i] = true - case 'f': - b[i] = false - default: - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a BoolArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be exactly two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1+2*n) - - for i := 0; i < n; i++ { - b[2*i] = ',' - if a[i] { - b[1+2*i] = 't' - } else { - b[1+2*i] = 'f' - } - } - - b[0] = '{' - b[2*n] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type. -type ByteaArray [][]byte - -// Scan implements the sql.Scanner interface. -func (a *ByteaArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to ByteaArray", src) -} - -func (a *ByteaArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "ByteaArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(ByteaArray, len(elems)) - for i, v := range elems { - b[i], err = parseBytea(v) - if err != nil { - return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error()) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. It uses the "hex" format which -// is only supported on PostgreSQL 9.0 or newer. -func (a ByteaArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // 3*N bytes of hex formatting, and N-1 bytes of delimiters. - size := 1 + 6*n - for _, x := range a { - size += hex.EncodedLen(len(x)) - } - - b := make([]byte, size) - - for i, s := 0, b; i < n; i++ { - o := copy(s, `,"\\x`) - o += hex.Encode(s[o:], a[i]) - s[o] = '"' - s = s[o+1:] - } - - b[0] = '{' - b[size-1] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// Float64Array represents a one-dimensional array of the PostgreSQL double -// precision type. -type Float64Array []float64 - -// Scan implements the sql.Scanner interface. -func (a *Float64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Float64Array", src) -} - -func (a *Float64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Float64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Float64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseFloat(string(v), 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Float64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendFloat(b, a[0], 'f', -1, 64) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendFloat(b, a[i], 'f', -1, 64) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// GenericArray implements the driver.Valuer and sql.Scanner interfaces for -// an array or slice of any dimension. -type GenericArray struct{ A interface{} } - -func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { - var assign func([]byte, reflect.Value) error - var del = "," - - // TODO calculate the assign function for other types - // TODO repeat this section on the element type of arrays or slices (multidimensional) - { - if reflect.PtrTo(rt).Implements(typeSQLScanner) { - // dest is always addressable because it is an element of a slice. - assign = func(src []byte, dest reflect.Value) (err error) { - ss := dest.Addr().Interface().(sql.Scanner) - if src == nil { - err = ss.Scan(nil) - } else { - err = ss.Scan(src) - } - return - } - goto FoundType - } - - assign = func([]byte, reflect.Value) error { - return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt) - } - } - -FoundType: - - if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - return rt, assign, del -} - -// Scan implements the sql.Scanner interface. -func (a GenericArray) Scan(src interface{}) error { - dpv := reflect.ValueOf(a.A) - switch { - case dpv.Kind() != reflect.Ptr: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - case dpv.IsNil(): - return fmt.Errorf("pq: destination %T is nil", a.A) - } - - dv := dpv.Elem() - switch dv.Kind() { - case reflect.Slice: - case reflect.Array: - default: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - } - - switch src := src.(type) { - case []byte: - return a.scanBytes(src, dv) - case string: - return a.scanBytes([]byte(src), dv) - case nil: - if dv.Kind() == reflect.Slice { - dv.Set(reflect.Zero(dv.Type())) - return nil - } - } - - return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type()) -} - -func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error { - dtype, assign, del := a.evaluateDestination(dv.Type().Elem()) - dims, elems, err := parseArray(src, []byte(del)) - if err != nil { - return err - } - - // TODO allow multidimensional - - if len(dims) > 1 { - return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented", - strings.Replace(fmt.Sprint(dims), " ", "][", -1)) - } - - // Treat a zero-dimensional array like an array with a single dimension of zero. - if len(dims) == 0 { - dims = append(dims, 0) - } - - for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() { - switch rt.Kind() { - case reflect.Slice: - case reflect.Array: - if rt.Len() != dims[i] { - return fmt.Errorf("pq: cannot convert ARRAY%s to %s", - strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type()) - } - default: - // TODO handle multidimensional - } - } - - values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems)) - for i, e := range elems { - if err := assign(e, values.Index(i)); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - - // TODO handle multidimensional - - switch dv.Kind() { - case reflect.Slice: - dv.Set(values.Slice(0, dims[0])) - case reflect.Array: - for i := 0; i < dims[0]; i++ { - dv.Index(i).Set(values.Index(i)) - } - } - - return nil -} - -// Value implements the driver.Valuer interface. -func (a GenericArray) Value() (driver.Value, error) { - if a.A == nil { - return nil, nil - } - - rv := reflect.ValueOf(a.A) - - switch rv.Kind() { - case reflect.Slice: - if rv.IsNil() { - return nil, nil - } - case reflect.Array: - default: - return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A) - } - - if n := rv.Len(); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 0, 1+2*n) - - b, _, err := appendArray(b, rv, n) - return string(b), err - } - - return "{}", nil -} - -// Int64Array represents a one-dimensional array of the PostgreSQL integer types. -type Int64Array []int64 - -// Scan implements the sql.Scanner interface. -func (a *Int64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Int64Array", src) -} - -func (a *Int64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Int64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Int64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Int64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendInt(b, a[0], 10) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendInt(b, a[i], 10) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// StringArray represents a one-dimensional array of the PostgreSQL character types. -type StringArray []string - -// Scan implements the sql.Scanner interface. -func (a *StringArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to StringArray", src) -} - -func (a *StringArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "StringArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(StringArray, len(elems)) - for i, v := range elems { - if b[i] = string(v); v == nil { - return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a StringArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+3*n) - b[0] = '{' - - b = appendArrayQuotedBytes(b, []byte(a[0])) - for i := 1; i < n; i++ { - b = append(b, ',') - b = appendArrayQuotedBytes(b, []byte(a[i])) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// appendArray appends rv to the buffer, returning the extended buffer and -// the delimiter used between elements. -// -// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice. -func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) { - var del string - var err error - - b = append(b, '{') - - if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil { - return b, del, err - } - - for i := 1; i < n; i++ { - b = append(b, del...) - if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil { - return b, del, err - } - } - - return append(b, '}'), del, nil -} - -// appendArrayElement appends rv to the buffer, returning the extended buffer -// and the delimiter to use before the next element. -// -// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted -// using driver.DefaultParameterConverter and the resulting []byte or string -// is double-quoted. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { - if k := rv.Kind(); k == reflect.Array || k == reflect.Slice { - if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) { - if n := rv.Len(); n > 0 { - return appendArray(b, rv, n) - } - - return b, "", nil - } - } - - var del = "," - var err error - var iv interface{} = rv.Interface() - - if ad, ok := iv.(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil { - return b, del, err - } - - switch v := iv.(type) { - case nil: - return append(b, "NULL"...), del, nil - case []byte: - return appendArrayQuotedBytes(b, v), del, nil - case string: - return appendArrayQuotedBytes(b, []byte(v)), del, nil - } - - b, err = appendValue(b, iv) - return b, del, err -} - -func appendArrayQuotedBytes(b, v []byte) []byte { - b = append(b, '"') - for { - i := bytes.IndexAny(v, `"\`) - if i < 0 { - b = append(b, v...) - break - } - if i > 0 { - b = append(b, v[:i]...) - } - b = append(b, '\\', v[i]) - v = v[i+1:] - } - return append(b, '"') -} - -func appendValue(b []byte, v driver.Value) ([]byte, error) { - return append(b, encode(nil, v, 0)...), nil -} - -// parseArray extracts the dimensions and elements of an array represented in -// text format. Only representations emitted by the backend are supported. -// Notably, whitespace around brackets and delimiters is significant, and NULL -// is case-sensitive. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) { - var depth, i int - - if len(src) < 1 || src[0] != '{' { - return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0) - } - -Open: - for i < len(src) { - switch src[i] { - case '{': - depth++ - i++ - case '}': - elems = make([][]byte, 0) - goto Close - default: - break Open - } - } - dims = make([]int, i) - -Element: - for i < len(src) { - switch src[i] { - case '{': - if depth == len(dims) { - break Element - } - depth++ - dims[depth-1] = 0 - i++ - case '"': - var elem = []byte{} - var escape bool - for i++; i < len(src); i++ { - if escape { - elem = append(elem, src[i]) - escape = false - } else { - switch src[i] { - default: - elem = append(elem, src[i]) - case '\\': - escape = true - case '"': - elems = append(elems, elem) - i++ - break Element - } - } - } - default: - for start := i; i < len(src); i++ { - if bytes.HasPrefix(src[i:], del) || src[i] == '}' { - elem := src[start:i] - if len(elem) == 0 { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - if bytes.Equal(elem, []byte("NULL")) { - elem = nil - } - elems = append(elems, elem) - break Element - } - } - } - } - - for i < len(src) { - if bytes.HasPrefix(src[i:], del) && depth > 0 { - dims[depth-1]++ - i += len(del) - goto Element - } else if src[i] == '}' && depth > 0 { - dims[depth-1]++ - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - -Close: - for i < len(src) { - if src[i] == '}' && depth > 0 { - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - if depth > 0 { - err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i) - } - if err == nil { - for _, d := range dims { - if (len(elems) % d) != 0 { - err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions") - } - } - } - return -} - -func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) { - dims, elems, err := parseArray(src, del) - if err != nil { - return nil, err - } - if len(dims) > 1 { - return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ) - } - return elems, err -} diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go deleted file mode 100644 index 4b0a0a8..0000000 --- a/vendor/github.com/lib/pq/buf.go +++ /dev/null @@ -1,91 +0,0 @@ -package pq - -import ( - "bytes" - "encoding/binary" - - "github.com/lib/pq/oid" -) - -type readBuf []byte - -func (b *readBuf) int32() (n int) { - n = int(int32(binary.BigEndian.Uint32(*b))) - *b = (*b)[4:] - return -} - -func (b *readBuf) oid() (n oid.Oid) { - n = oid.Oid(binary.BigEndian.Uint32(*b)) - *b = (*b)[4:] - return -} - -// N.B: this is actually an unsigned 16-bit integer, unlike int32 -func (b *readBuf) int16() (n int) { - n = int(binary.BigEndian.Uint16(*b)) - *b = (*b)[2:] - return -} - -func (b *readBuf) string() string { - i := bytes.IndexByte(*b, 0) - if i < 0 { - errorf("invalid message format; expected string terminator") - } - s := (*b)[:i] - *b = (*b)[i+1:] - return string(s) -} - -func (b *readBuf) next(n int) (v []byte) { - v = (*b)[:n] - *b = (*b)[n:] - return -} - -func (b *readBuf) byte() byte { - return b.next(1)[0] -} - -type writeBuf struct { - buf []byte - pos int -} - -func (b *writeBuf) int32(n int) { - x := make([]byte, 4) - binary.BigEndian.PutUint32(x, uint32(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) int16(n int) { - x := make([]byte, 2) - binary.BigEndian.PutUint16(x, uint16(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) string(s string) { - b.buf = append(append(b.buf, s...), '\000') -} - -func (b *writeBuf) byte(c byte) { - b.buf = append(b.buf, c) -} - -func (b *writeBuf) bytes(v []byte) { - b.buf = append(b.buf, v...) -} - -func (b *writeBuf) wrap() []byte { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - return b.buf -} - -func (b *writeBuf) next(c byte) { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - b.pos = len(b.buf) + 1 - b.buf = append(b.buf, c, 0, 0, 0, 0) -} diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go deleted file mode 100644 index 55152b1..0000000 --- a/vendor/github.com/lib/pq/conn.go +++ /dev/null @@ -1,1923 +0,0 @@ -package pq - -import ( - "bufio" - "context" - "crypto/md5" - "crypto/sha256" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "os" - "os/user" - "path" - "path/filepath" - "strconv" - "strings" - "time" - "unicode" - - "github.com/lib/pq/oid" - "github.com/lib/pq/scram" -) - -// Common error types -var ( - ErrNotSupported = errors.New("pq: Unsupported command") - ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") - ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") - ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less") - ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly") - - errUnexpectedReady = errors.New("unexpected ReadyForQuery") - errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") - errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") -) - -// Driver is the Postgres database driver. -type Driver struct{} - -// Open opens a new connection to the database. name is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func (d *Driver) Open(name string) (driver.Conn, error) { - return Open(name) -} - -func init() { - sql.Register("postgres", &Driver{}) -} - -type parameterStatus struct { - // server version in the same format as server_version_num, or 0 if - // unavailable - serverVersion int - - // the current location based on the TimeZone value of the session, if - // available - currentLocation *time.Location -} - -type transactionStatus byte - -const ( - txnStatusIdle transactionStatus = 'I' - txnStatusIdleInTransaction transactionStatus = 'T' - txnStatusInFailedTransaction transactionStatus = 'E' -) - -func (s transactionStatus) String() string { - switch s { - case txnStatusIdle: - return "idle" - case txnStatusIdleInTransaction: - return "idle in transaction" - case txnStatusInFailedTransaction: - return "in a failed transaction" - default: - errorf("unknown transactionStatus %d", s) - } - - panic("not reached") -} - -// Dialer is the dialer interface. It can be used to obtain more control over -// how pq creates network connections. -type Dialer interface { - Dial(network, address string) (net.Conn, error) - DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) -} - -// DialerContext is the context-aware dialer interface. -type DialerContext interface { - DialContext(ctx context.Context, network, address string) (net.Conn, error) -} - -type defaultDialer struct { - d net.Dialer -} - -func (d defaultDialer) Dial(network, address string) (net.Conn, error) { - return d.d.Dial(network, address) -} -func (d defaultDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - return d.DialContext(ctx, network, address) -} -func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { - return d.d.DialContext(ctx, network, address) -} - -type conn struct { - c net.Conn - buf *bufio.Reader - namei int - scratch [512]byte - txnStatus transactionStatus - txnFinish func() - - // Save connection arguments to use during CancelRequest. - dialer Dialer - opts values - - // Cancellation key data for use with CancelRequest messages. - processID int - secretKey int - - parameterStatus parameterStatus - - saveMessageType byte - saveMessageBuffer []byte - - // If true, this connection is bad and all public-facing functions should - // return ErrBadConn. - bad bool - - // If set, this connection should never use the binary format when - // receiving query results from prepared statements. Only provided for - // debugging. - disablePreparedBinaryResult bool - - // Whether to always send []byte parameters over as binary. Enables single - // round-trip mode for non-prepared Query calls. - binaryParameters bool - - // If true this connection is in the middle of a COPY - inCopy bool -} - -// Handle driver-side settings in parsed connection string. -func (cn *conn) handleDriverSettings(o values) (err error) { - boolSetting := func(key string, val *bool) error { - if value, ok := o[key]; ok { - if value == "yes" { - *val = true - } else if value == "no" { - *val = false - } else { - return fmt.Errorf("unrecognized value %q for %s", value, key) - } - } - return nil - } - - err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult) - if err != nil { - return err - } - return boolSetting("binary_parameters", &cn.binaryParameters) -} - -func (cn *conn) handlePgpass(o values) { - // if a password was supplied, do not process .pgpass - if _, ok := o["password"]; ok { - return - } - filename := os.Getenv("PGPASSFILE") - if filename == "" { - // XXX this code doesn't work on Windows where the default filename is - // XXX %APPDATA%\postgresql\pgpass.conf - // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 - userHome := os.Getenv("HOME") - if userHome == "" { - user, err := user.Current() - if err != nil { - return - } - userHome = user.HomeDir - } - filename = filepath.Join(userHome, ".pgpass") - } - fileinfo, err := os.Stat(filename) - if err != nil { - return - } - mode := fileinfo.Mode() - if mode&(0x77) != 0 { - // XXX should warn about incorrect .pgpass permissions as psql does - return - } - file, err := os.Open(filename) - if err != nil { - return - } - defer file.Close() - scanner := bufio.NewScanner(io.Reader(file)) - hostname := o["host"] - ntw, _ := network(o) - port := o["port"] - db := o["dbname"] - username := o["user"] - // From: https://github.com/tg/pgpass/blob/master/reader.go - getFields := func(s string) []string { - fs := make([]string, 0, 5) - f := make([]rune, 0, len(s)) - - var esc bool - for _, c := range s { - switch { - case esc: - f = append(f, c) - esc = false - case c == '\\': - esc = true - case c == ':': - fs = append(fs, string(f)) - f = f[:0] - default: - f = append(f, c) - } - } - return append(fs, string(f)) - } - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 || line[0] == '#' { - continue - } - split := getFields(line) - if len(split) != 5 { - continue - } - if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) { - o["password"] = split[4] - return - } - } -} - -func (cn *conn) writeBuf(b byte) *writeBuf { - cn.scratch[0] = b - return &writeBuf{ - buf: cn.scratch[:5], - pos: 1, - } -} - -// Open opens a new connection to the database. dsn is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func Open(dsn string) (_ driver.Conn, err error) { - return DialOpen(defaultDialer{}, dsn) -} - -// DialOpen opens a new connection to the database using a dialer. -func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error) { - c, err := NewConnector(dsn) - if err != nil { - return nil, err - } - c.dialer = d - return c.open(context.Background()) -} - -func (c *Connector) open(ctx context.Context) (cn *conn, err error) { - // Handle any panics during connection initialization. Note that we - // specifically do *not* want to use errRecover(), as that would turn any - // connection errors into ErrBadConns, hiding the real error message from - // the user. - defer errRecoverNoErrBadConn(&err) - - o := c.opts - - cn = &conn{ - opts: o, - dialer: c.dialer, - } - err = cn.handleDriverSettings(o) - if err != nil { - return nil, err - } - cn.handlePgpass(o) - - cn.c, err = dial(ctx, c.dialer, o) - if err != nil { - return nil, err - } - - err = cn.ssl(o) - if err != nil { - if cn.c != nil { - cn.c.Close() - } - return nil, err - } - - // cn.startup panics on error. Make sure we don't leak cn.c. - panicking := true - defer func() { - if panicking { - cn.c.Close() - } - }() - - cn.buf = bufio.NewReader(cn.c) - cn.startup(o) - - // reset the deadline, in case one was set (see dial) - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - err = cn.c.SetDeadline(time.Time{}) - } - panicking = false - return cn, err -} - -func dial(ctx context.Context, d Dialer, o values) (net.Conn, error) { - network, address := network(o) - // SSL is not necessary or supported over UNIX domain sockets - if network == "unix" { - o["sslmode"] = "disable" - } - - // Zero or not specified means wait indefinitely. - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - seconds, err := strconv.ParseInt(timeout, 10, 0) - if err != nil { - return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) - } - duration := time.Duration(seconds) * time.Second - - // connect_timeout should apply to the entire connection establishment - // procedure, so we both use a timeout for the TCP connection - // establishment and set a deadline for doing the initial handshake. - // The deadline is then reset after startup() is done. - deadline := time.Now().Add(duration) - var conn net.Conn - if dctx, ok := d.(DialerContext); ok { - ctx, cancel := context.WithTimeout(ctx, duration) - defer cancel() - conn, err = dctx.DialContext(ctx, network, address) - } else { - conn, err = d.DialTimeout(network, address, duration) - } - if err != nil { - return nil, err - } - err = conn.SetDeadline(deadline) - return conn, err - } - if dctx, ok := d.(DialerContext); ok { - return dctx.DialContext(ctx, network, address) - } - return d.Dial(network, address) -} - -func network(o values) (string, string) { - host := o["host"] - - if strings.HasPrefix(host, "/") { - sockPath := path.Join(host, ".s.PGSQL."+o["port"]) - return "unix", sockPath - } - - return "tcp", net.JoinHostPort(host, o["port"]) -} - -type values map[string]string - -// scanner implements a tokenizer for libpq-style option strings. -type scanner struct { - s []rune - i int -} - -// newScanner returns a new scanner initialized with the option string s. -func newScanner(s string) *scanner { - return &scanner{[]rune(s), 0} -} - -// Next returns the next rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) Next() (rune, bool) { - if s.i >= len(s.s) { - return 0, false - } - r := s.s[s.i] - s.i++ - return r, true -} - -// SkipSpaces returns the next non-whitespace rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) SkipSpaces() (rune, bool) { - r, ok := s.Next() - for unicode.IsSpace(r) && ok { - r, ok = s.Next() - } - return r, ok -} - -// parseOpts parses the options from name and adds them to the values. -// -// The parsing code is based on conninfo_parse from libpq's fe-connect.c -func parseOpts(name string, o values) error { - s := newScanner(name) - - for { - var ( - keyRunes, valRunes []rune - r rune - ok bool - ) - - if r, ok = s.SkipSpaces(); !ok { - break - } - - // Scan the key - for !unicode.IsSpace(r) && r != '=' { - keyRunes = append(keyRunes, r) - if r, ok = s.Next(); !ok { - break - } - } - - // Skip any whitespace if we're not at the = yet - if r != '=' { - r, ok = s.SkipSpaces() - } - - // The current character should be = - if r != '=' || !ok { - return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) - } - - // Skip any whitespace after the = - if r, ok = s.SkipSpaces(); !ok { - // If we reach the end here, the last value is just an empty string as per libpq. - o[string(keyRunes)] = "" - break - } - - if r != '\'' { - for !unicode.IsSpace(r) { - if r == '\\' { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`missing character after backslash`) - } - } - valRunes = append(valRunes, r) - - if r, ok = s.Next(); !ok { - break - } - } - } else { - quote: - for { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`unterminated quoted string literal in connection string`) - } - switch r { - case '\'': - break quote - case '\\': - r, _ = s.Next() - fallthrough - default: - valRunes = append(valRunes, r) - } - } - } - - o[string(keyRunes)] = string(valRunes) - } - - return nil -} - -func (cn *conn) isInTransaction() bool { - return cn.txnStatus == txnStatusIdleInTransaction || - cn.txnStatus == txnStatusInFailedTransaction -} - -func (cn *conn) checkIsInTransaction(intxn bool) { - if cn.isInTransaction() != intxn { - cn.bad = true - errorf("unexpected transaction status %v", cn.txnStatus) - } -} - -func (cn *conn) Begin() (_ driver.Tx, err error) { - return cn.begin("") -} - -func (cn *conn) begin(mode string) (_ driver.Tx, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(false) - _, commandTag, err := cn.simpleExec("BEGIN" + mode) - if err != nil { - return nil, err - } - if commandTag != "BEGIN" { - cn.bad = true - return nil, fmt.Errorf("unexpected command tag %s", commandTag) - } - if cn.txnStatus != txnStatusIdleInTransaction { - cn.bad = true - return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) - } - return cn, nil -} - -func (cn *conn) closeTxn() { - if finish := cn.txnFinish; finish != nil { - finish() - } -} - -func (cn *conn) Commit() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(true) - // We don't want the client to think that everything is okay if it tries - // to commit a failed transaction. However, no matter what we return, - // database/sql will release this connection back into the free connection - // pool so we have to abort the current transaction here. Note that you - // would get the same behaviour if you issued a COMMIT in a failed - // transaction, so it's also the least surprising thing to do here. - if cn.txnStatus == txnStatusInFailedTransaction { - if err := cn.rollback(); err != nil { - return err - } - return ErrInFailedTransaction - } - - _, commandTag, err := cn.simpleExec("COMMIT") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "COMMIT" { - cn.bad = true - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) Rollback() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - return cn.rollback() -} - -func (cn *conn) rollback() (err error) { - cn.checkIsInTransaction(true) - _, commandTag, err := cn.simpleExec("ROLLBACK") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "ROLLBACK" { - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) gname() string { - cn.namei++ - return strconv.FormatInt(int64(cn.namei), 10) -} - -func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C': - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - // done - return - case 'E': - err = parseError(r) - case 'I': - res = emptyRows - case 'T', 'D': - // ignore any results - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -func (cn *conn) simpleQuery(q string) (res *rows, err error) { - defer cn.errRecover(&err) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C', 'I': - // We allow queries which don't return any results through Query as - // well as Exec. We still have to give database/sql a rows object - // the user can close, though, to avoid connections from being - // leaked. A "rows" with done=true works fine for that purpose. - if err != nil { - cn.bad = true - errorf("unexpected message %q in simple query execution", t) - } - if res == nil { - res = &rows{ - cn: cn, - } - } - // Set the result and tag to the last command complete if there wasn't a - // query already run. Although queries usually return from here and cede - // control to Next, a query with zero results does not. - if t == 'C' && res.colNames == nil { - res.result, res.tag = cn.parseComplete(r.string()) - } - res.done = true - case 'Z': - cn.processReadyForQuery(r) - // done - return - case 'E': - res = nil - err = parseError(r) - case 'D': - if res == nil { - cn.bad = true - errorf("unexpected DataRow in simple query execution") - } - // the query didn't fail; kick off to Next - cn.saveMessage(t, r) - return - case 'T': - // res might be non-nil here if we received a previous - // CommandComplete, but that's fine; just overwrite it - res = &rows{cn: cn} - res.rowsHeader = parsePortalRowDescribe(r) - - // To work around a bug in QueryRow in Go 1.2 and earlier, wait - // until the first DataRow has been received. - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -type noRows struct{} - -var emptyRows noRows - -var _ driver.Result = noRows{} - -func (noRows) LastInsertId() (int64, error) { - return 0, errNoLastInsertID -} - -func (noRows) RowsAffected() (int64, error) { - return 0, errNoRowsAffected -} - -// Decides which column formats to use for a prepared statement. The input is -// an array of type oids, one element per result column. -func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) { - if len(colTyps) == 0 { - return nil, colFmtDataAllText - } - - colFmts = make([]format, len(colTyps)) - if forceText { - return colFmts, colFmtDataAllText - } - - allBinary := true - allText := true - for i, t := range colTyps { - switch t.OID { - // This is the list of types to use binary mode for when receiving them - // through a prepared statement. If a type appears in this list, it - // must also be implemented in binaryDecode in encode.go. - case oid.T_bytea: - fallthrough - case oid.T_int8: - fallthrough - case oid.T_int4: - fallthrough - case oid.T_int2: - fallthrough - case oid.T_uuid: - colFmts[i] = formatBinary - allText = false - - default: - allBinary = false - } - } - - if allBinary { - return colFmts, colFmtDataAllBinary - } else if allText { - return colFmts, colFmtDataAllText - } else { - colFmtData = make([]byte, 2+len(colFmts)*2) - binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) - for i, v := range colFmts { - binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) - } - return colFmts, colFmtData - } -} - -func (cn *conn) prepareTo(q, stmtName string) *stmt { - st := &stmt{cn: cn, name: stmtName} - - b := cn.writeBuf('P') - b.string(st.name) - b.string(q) - b.int16(0) - - b.next('D') - b.byte('S') - b.string(st.name) - - b.next('S') - cn.send(b) - - cn.readParseResponse() - st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() - st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) - cn.readReadyForQuery() - return st -} - -func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { - s, err := cn.prepareCopyIn(q) - if err == nil { - cn.inCopy = true - } - return s, err - } - return cn.prepareTo(q, cn.gname()), nil -} - -func (cn *conn) Close() (err error) { - // Skip cn.bad return here because we always want to close a connection. - defer cn.errRecover(&err) - - // Ensure that cn.c.Close is always run. Since error handling is done with - // panics and cn.errRecover, the Close must be in a defer. - defer func() { - cerr := cn.c.Close() - if err == nil { - err = cerr - } - }() - - // Don't go through send(); ListenerConn relies on us not scribbling on the - // scratch buffer of this connection. - return cn.sendSimpleMessage('X') -} - -// Implement the "Queryer" interface -func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { - return cn.query(query, args) -} - -func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - if cn.inCopy { - return nil, errCopyInProgress - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleQuery" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - return cn.simpleQuery(query) - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - rows := &rows{cn: cn} - rows.rowsHeader = cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - return rows, nil - } - st := cn.prepareTo(query, "") - st.exec(args) - return &rows{ - cn: cn, - rowsHeader: st.rowsHeader, - }, nil -} - -// Implement the optional "Execer" interface for one-shot queries -func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleExec" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - // ignore commandTag, our caller doesn't care - r, _, err := cn.simpleExec(query) - return r, err - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - res, _, err = cn.readExecuteResponse("Execute") - return res, err - } - // Use the unnamed statement to defer planning until bind - // time, or else value-based selectivity estimates cannot be - // used. - st := cn.prepareTo(query, "") - r, err := st.Exec(args) - if err != nil { - panic(err) - } - return r, err -} - -func (cn *conn) send(m *writeBuf) { - _, err := cn.c.Write(m.wrap()) - if err != nil { - panic(err) - } -} - -func (cn *conn) sendStartupPacket(m *writeBuf) error { - _, err := cn.c.Write((m.wrap())[1:]) - return err -} - -// Send a message of type typ to the server on the other end of cn. The -// message should have no payload. This method does not use the scratch -// buffer. -func (cn *conn) sendSimpleMessage(typ byte) (err error) { - _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) - return err -} - -// saveMessage memorizes a message and its buffer in the conn struct. -// recvMessage will then return these values on the next call to it. This -// method is useful in cases where you have to see what the next message is -// going to be (e.g. to see whether it's an error or not) but you can't handle -// the message yourself. -func (cn *conn) saveMessage(typ byte, buf *readBuf) { - if cn.saveMessageType != 0 { - cn.bad = true - errorf("unexpected saveMessageType %d", cn.saveMessageType) - } - cn.saveMessageType = typ - cn.saveMessageBuffer = *buf -} - -// recvMessage receives any message from the backend, or returns an error if -// a problem occurred while reading the message. -func (cn *conn) recvMessage(r *readBuf) (byte, error) { - // workaround for a QueryRow bug, see exec - if cn.saveMessageType != 0 { - t := cn.saveMessageType - *r = cn.saveMessageBuffer - cn.saveMessageType = 0 - cn.saveMessageBuffer = nil - return t, nil - } - - x := cn.scratch[:5] - _, err := io.ReadFull(cn.buf, x) - if err != nil { - return 0, err - } - - // read the type and length of the message that follows - t := x[0] - n := int(binary.BigEndian.Uint32(x[1:])) - 4 - var y []byte - if n <= len(cn.scratch) { - y = cn.scratch[:n] - } else { - y = make([]byte, n) - } - _, err = io.ReadFull(cn.buf, y) - if err != nil { - return 0, err - } - *r = y - return t, nil -} - -// recv receives a message from the backend, but if an error happened while -// reading the message or the received message was an ErrorResponse, it panics. -// NoticeResponses are ignored. This function should generally be used only -// during the startup sequence. -func (cn *conn) recv() (t byte, r *readBuf) { - for { - var err error - r = &readBuf{} - t, err = cn.recvMessage(r) - if err != nil { - panic(err) - } - switch t { - case 'E': - panic(parseError(r)) - case 'N': - // ignore - default: - return - } - } -} - -// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by -// the caller to avoid an allocation. -func (cn *conn) recv1Buf(r *readBuf) byte { - for { - t, err := cn.recvMessage(r) - if err != nil { - panic(err) - } - - switch t { - case 'A', 'N': - // ignore - case 'S': - cn.processParameterStatus(r) - default: - return t - } - } -} - -// recv1 receives a message from the backend, panicking if an error occurs -// while attempting to read it. All asynchronous messages are ignored, with -// the exception of ErrorResponse. -func (cn *conn) recv1() (t byte, r *readBuf) { - r = &readBuf{} - t = cn.recv1Buf(r) - return t, r -} - -func (cn *conn) ssl(o values) error { - upgrade, err := ssl(o) - if err != nil { - return err - } - - if upgrade == nil { - // Nothing to do - return nil - } - - w := cn.writeBuf(0) - w.int32(80877103) - if err = cn.sendStartupPacket(w); err != nil { - return err - } - - b := cn.scratch[:1] - _, err = io.ReadFull(cn.c, b) - if err != nil { - return err - } - - if b[0] != 'S' { - return ErrSSLNotSupported - } - - cn.c, err = upgrade(cn.c) - return err -} - -// isDriverSetting returns true iff a setting is purely for configuring the -// driver's options and should not be sent to the server in the connection -// startup packet. -func isDriverSetting(key string) bool { - switch key { - case "host", "port": - return true - case "password": - return true - case "sslmode", "sslcert", "sslkey", "sslrootcert": - return true - case "fallback_application_name": - return true - case "connect_timeout": - return true - case "disable_prepared_binary_result": - return true - case "binary_parameters": - return true - - default: - return false - } -} - -func (cn *conn) startup(o values) { - w := cn.writeBuf(0) - w.int32(196608) - // Send the backend the name of the database we want to connect to, and the - // user we want to connect as. Additionally, we send over any run-time - // parameters potentially included in the connection string. If the server - // doesn't recognize any of them, it will reply with an error. - for k, v := range o { - if isDriverSetting(k) { - // skip options which can't be run-time parameters - continue - } - // The protocol requires us to supply the database name as "database" - // instead of "dbname". - if k == "dbname" { - k = "database" - } - w.string(k) - w.string(v) - } - w.string("") - if err := cn.sendStartupPacket(w); err != nil { - panic(err) - } - - for { - t, r := cn.recv() - switch t { - case 'K': - cn.processBackendKeyData(r) - case 'S': - cn.processParameterStatus(r) - case 'R': - cn.auth(r, o) - case 'Z': - cn.processReadyForQuery(r) - return - default: - errorf("unknown response for startup: %q", t) - } - } -} - -func (cn *conn) auth(r *readBuf, o values) { - switch code := r.int32(); code { - case 0: - // OK - case 3: - w := cn.writeBuf('p') - w.string(o["password"]) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - case 5: - s := string(r.next(4)) - w := cn.writeBuf('p') - w.string("md5" + md5s(md5s(o["password"]+o["user"])+s)) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - case 10: - sc := scram.NewClient(sha256.New, o["user"], o["password"]) - sc.Step(nil) - if sc.Err() != nil { - errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) - } - scOut := sc.Out() - - w := cn.writeBuf('p') - w.string("SCRAM-SHA-256") - w.int32(len(scOut)) - w.bytes(scOut) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 11 { - errorf("unexpected authentication response: %q", t) - } - - nextStep := r.next(len(*r)) - sc.Step(nextStep) - if sc.Err() != nil { - errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) - } - - scOut = sc.Out() - w = cn.writeBuf('p') - w.bytes(scOut) - cn.send(w) - - t, r = cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 12 { - errorf("unexpected authentication response: %q", t) - } - - nextStep = r.next(len(*r)) - sc.Step(nextStep) - if sc.Err() != nil { - errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) - } - - default: - errorf("unknown authentication response: %d", code) - } -} - -type format int - -const formatText format = 0 -const formatBinary format = 1 - -// One result-column format code with the value 1 (i.e. all binary). -var colFmtDataAllBinary = []byte{0, 1, 0, 1} - -// No result-column format codes (i.e. all text). -var colFmtDataAllText = []byte{0, 0} - -type stmt struct { - cn *conn - name string - rowsHeader - colFmtData []byte - paramTyps []oid.Oid - closed bool -} - -func (st *stmt) Close() (err error) { - if st.closed { - return nil - } - if st.cn.bad { - return driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - w := st.cn.writeBuf('C') - w.byte('S') - w.string(st.name) - st.cn.send(w) - - st.cn.send(st.cn.writeBuf('S')) - - t, _ := st.cn.recv1() - if t != '3' { - st.cn.bad = true - errorf("unexpected close response: %q", t) - } - st.closed = true - - t, r := st.cn.recv1() - if t != 'Z' { - st.cn.bad = true - errorf("expected ready for query, but got: %q", t) - } - st.cn.processReadyForQuery(r) - - return nil -} - -func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - return &rows{ - cn: st.cn, - rowsHeader: st.rowsHeader, - }, nil -} - -func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - res, _, err = st.cn.readExecuteResponse("simple query") - return res, err -} - -func (st *stmt) exec(v []driver.Value) { - if len(v) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) - } - if len(v) != len(st.paramTyps) { - errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) - } - - cn := st.cn - w := cn.writeBuf('B') - w.byte(0) // unnamed portal - w.string(st.name) - - if cn.binaryParameters { - cn.sendBinaryParameters(w, v) - } else { - w.int16(0) - w.int16(len(v)) - for i, x := range v { - if x == nil { - w.int32(-1) - } else { - b := encode(&cn.parameterStatus, x, st.paramTyps[i]) - w.int32(len(b)) - w.bytes(b) - } - } - } - w.bytes(st.colFmtData) - - w.next('E') - w.byte(0) - w.int32(0) - - w.next('S') - cn.send(w) - - cn.readBindResponse() - cn.postExecuteWorkaround() - -} - -func (st *stmt) NumInput() int { - return len(st.paramTyps) -} - -// parseComplete parses the "command tag" from a CommandComplete message, and -// returns the number of rows affected (if applicable) and a string -// identifying only the command that was executed, e.g. "ALTER TABLE". If the -// command tag could not be parsed, parseComplete panics. -func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { - commandsWithAffectedRows := []string{ - "SELECT ", - // INSERT is handled below - "UPDATE ", - "DELETE ", - "FETCH ", - "MOVE ", - "COPY ", - } - - var affectedRows *string - for _, tag := range commandsWithAffectedRows { - if strings.HasPrefix(commandTag, tag) { - t := commandTag[len(tag):] - affectedRows = &t - commandTag = tag[:len(tag)-1] - break - } - } - // INSERT also includes the oid of the inserted row in its command tag. - // Oids in user tables are deprecated, and the oid is only returned when - // exactly one row is inserted, so it's unlikely to be of value to any - // real-world application and we can ignore it. - if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { - parts := strings.Split(commandTag, " ") - if len(parts) != 3 { - cn.bad = true - errorf("unexpected INSERT command tag %s", commandTag) - } - affectedRows = &parts[len(parts)-1] - commandTag = "INSERT" - } - // There should be no affected rows attached to the tag, just return it - if affectedRows == nil { - return driver.RowsAffected(0), commandTag - } - n, err := strconv.ParseInt(*affectedRows, 10, 64) - if err != nil { - cn.bad = true - errorf("could not parse commandTag: %s", err) - } - return driver.RowsAffected(n), commandTag -} - -type rowsHeader struct { - colNames []string - colTyps []fieldDesc - colFmts []format -} - -type rows struct { - cn *conn - finish func() - rowsHeader - done bool - rb readBuf - result driver.Result - tag string - - next *rowsHeader -} - -func (rs *rows) Close() error { - if finish := rs.finish; finish != nil { - defer finish() - } - // no need to look at cn.bad as Next() will - for { - err := rs.Next(nil) - switch err { - case nil: - case io.EOF: - // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row - // description, used with HasNextResultSet). We need to fetch messages until - // we hit a 'Z', which is done by waiting for done to be set. - if rs.done { - return nil - } - default: - return err - } - } -} - -func (rs *rows) Columns() []string { - return rs.colNames -} - -func (rs *rows) Result() driver.Result { - if rs.result == nil { - return emptyRows - } - return rs.result -} - -func (rs *rows) Tag() string { - return rs.tag -} - -func (rs *rows) Next(dest []driver.Value) (err error) { - if rs.done { - return io.EOF - } - - conn := rs.cn - if conn.bad { - return driver.ErrBadConn - } - defer conn.errRecover(&err) - - for { - t := conn.recv1Buf(&rs.rb) - switch t { - case 'E': - err = parseError(&rs.rb) - case 'C', 'I': - if t == 'C' { - rs.result, rs.tag = conn.parseComplete(rs.rb.string()) - } - continue - case 'Z': - conn.processReadyForQuery(&rs.rb) - rs.done = true - if err != nil { - return err - } - return io.EOF - case 'D': - n := rs.rb.int16() - if err != nil { - conn.bad = true - errorf("unexpected DataRow after error %s", err) - } - if n < len(dest) { - dest = dest[:n] - } - for i := range dest { - l := rs.rb.int32() - if l == -1 { - dest[i] = nil - continue - } - dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) - } - return - case 'T': - next := parsePortalRowDescribe(&rs.rb) - rs.next = &next - return io.EOF - default: - errorf("unexpected message after execute: %q", t) - } - } -} - -func (rs *rows) HasNextResultSet() bool { - hasNext := rs.next != nil && !rs.done - return hasNext -} - -func (rs *rows) NextResultSet() error { - if rs.next == nil { - return io.EOF - } - rs.rowsHeader = *rs.next - rs.next = nil - return nil -} - -// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be -// used as part of an SQL statement. For example: -// -// tblname := "my_table" -// data := "my_data" -// quoted := pq.QuoteIdentifier(tblname) -// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) -// -// Any double quotes in name will be escaped. The quoted identifier will be -// case sensitive when used in a query. If the input string contains a zero -// byte, the result will be truncated immediately before it. -func QuoteIdentifier(name string) string { - end := strings.IndexRune(name, 0) - if end > -1 { - name = name[:end] - } - return `"` + strings.Replace(name, `"`, `""`, -1) + `"` -} - -// QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal -// to DDL and other statements that do not accept parameters) to be used as part -// of an SQL statement. For example: -// -// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z") -// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date)) -// -// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be -// replaced by two backslashes (i.e. "\\") and the C-style escape identifier -// that PostgreSQL provides ('E') will be prepended to the string. -func QuoteLiteral(literal string) string { - // This follows the PostgreSQL internal algorithm for handling quoted literals - // from libpq, which can be found in the "PQEscapeStringInternal" function, - // which is found in the libpq/fe-exec.c source file: - // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c - // - // substitute any single-quotes (') with two single-quotes ('') - literal = strings.Replace(literal, `'`, `''`, -1) - // determine if the string has any backslashes (\) in it. - // if it does, replace any backslashes (\) with two backslashes (\\) - // then, we need to wrap the entire string with a PostgreSQL - // C-style escape. Per how "PQEscapeStringInternal" handles this case, we - // also add a space before the "E" - if strings.Contains(literal, `\`) { - literal = strings.Replace(literal, `\`, `\\`, -1) - literal = ` E'` + literal + `'` - } else { - // otherwise, we can just wrap the literal with a pair of single quotes - literal = `'` + literal + `'` - } - return literal -} - -func md5s(s string) string { - h := md5.New() - h.Write([]byte(s)) - return fmt.Sprintf("%x", h.Sum(nil)) -} - -func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { - // Do one pass over the parameters to see if we're going to send any of - // them over in binary. If we are, create a paramFormats array at the - // same time. - var paramFormats []int - for i, x := range args { - _, ok := x.([]byte) - if ok { - if paramFormats == nil { - paramFormats = make([]int, len(args)) - } - paramFormats[i] = 1 - } - } - if paramFormats == nil { - b.int16(0) - } else { - b.int16(len(paramFormats)) - for _, x := range paramFormats { - b.int16(x) - } - } - - b.int16(len(args)) - for _, x := range args { - if x == nil { - b.int32(-1) - } else { - datum := binaryEncode(&cn.parameterStatus, x) - b.int32(len(datum)) - b.bytes(datum) - } - } -} - -func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { - if len(args) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) - } - - b := cn.writeBuf('P') - b.byte(0) // unnamed statement - b.string(query) - b.int16(0) - - b.next('B') - b.int16(0) // unnamed portal and statement - cn.sendBinaryParameters(b, args) - b.bytes(colFmtDataAllText) - - b.next('D') - b.byte('P') - b.byte(0) // unnamed portal - - b.next('E') - b.byte(0) - b.int32(0) - - b.next('S') - cn.send(b) -} - -func (cn *conn) processParameterStatus(r *readBuf) { - var err error - - param := r.string() - switch param { - case "server_version": - var major1 int - var major2 int - var minor int - _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) - if err == nil { - cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor - } - - case "TimeZone": - cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) - if err != nil { - cn.parameterStatus.currentLocation = nil - } - - default: - // ignore - } -} - -func (cn *conn) processReadyForQuery(r *readBuf) { - cn.txnStatus = transactionStatus(r.byte()) -} - -func (cn *conn) readReadyForQuery() { - t, r := cn.recv1() - switch t { - case 'Z': - cn.processReadyForQuery(r) - return - default: - cn.bad = true - errorf("unexpected message %q; expected ReadyForQuery", t) - } -} - -func (cn *conn) processBackendKeyData(r *readBuf) { - cn.processID = r.int32() - cn.secretKey = r.int32() -} - -func (cn *conn) readParseResponse() { - t, r := cn.recv1() - switch t { - case '1': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Parse response %q", t) - } -} - -func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) { - for { - t, r := cn.recv1() - switch t { - case 't': - nparams := r.int16() - paramTyps = make([]oid.Oid, nparams) - for i := range paramTyps { - paramTyps[i] = r.oid() - } - case 'n': - return paramTyps, nil, nil - case 'T': - colNames, colTyps = parseStatementRowDescribe(r) - return paramTyps, colNames, colTyps - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe statement response %q", t) - } - } -} - -func (cn *conn) readPortalDescribeResponse() rowsHeader { - t, r := cn.recv1() - switch t { - case 'T': - return parsePortalRowDescribe(r) - case 'n': - return rowsHeader{} - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe response %q", t) - } - panic("not reached") -} - -func (cn *conn) readBindResponse() { - t, r := cn.recv1() - switch t { - case '2': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Bind response %q", t) - } -} - -func (cn *conn) postExecuteWorkaround() { - // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores - // any errors from rows.Next, which masks errors that happened during the - // execution of the query. To avoid the problem in common cases, we wait - // here for one more message from the database. If it's not an error the - // query will likely succeed (or perhaps has already, if it's a - // CommandComplete), so we push the message into the conn struct; recv1 - // will return it as the next message for rows.Next or rows.Close. - // However, if it's an error, we wait until ReadyForQuery and then return - // the error to our caller. - for { - t, r := cn.recv1() - switch t { - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - case 'C', 'D', 'I': - // the query didn't fail, but we can't process this message - cn.saveMessage(t, r) - return - default: - cn.bad = true - errorf("unexpected message during extended query execution: %q", t) - } - } -} - -// Only for Exec(), since we ignore the returned data -func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { - for { - t, r := cn.recv1() - switch t { - case 'C': - if err != nil { - cn.bad = true - errorf("unexpected CommandComplete after error %s", err) - } - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - return res, commandTag, err - case 'E': - err = parseError(r) - case 'T', 'D', 'I': - if err != nil { - cn.bad = true - errorf("unexpected %q after error %s", t, err) - } - if t == 'I' { - res = emptyRows - } - // ignore any results - default: - cn.bad = true - errorf("unknown %s response: %q", protocolState, t) - } - } -} - -func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { - n := r.int16() - colNames = make([]string, n) - colTyps = make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - // format code not known when describing a statement; always 0 - r.next(2) - } - return -} - -func parsePortalRowDescribe(r *readBuf) rowsHeader { - n := r.int16() - colNames := make([]string, n) - colFmts := make([]format, n) - colTyps := make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - colFmts[i] = format(r.int16()) - } - return rowsHeader{ - colNames: colNames, - colFmts: colFmts, - colTyps: colTyps, - } -} - -// parseEnviron tries to mimic some of libpq's environment handling -// -// To ease testing, it does not directly reference os.Environ, but is -// designed to accept its output. -// -// Environment-set connection information is intended to have a higher -// precedence than a library default but lower than any explicitly -// passed information (such as in the URL or connection string). -func parseEnviron(env []string) (out map[string]string) { - out = make(map[string]string) - - for _, v := range env { - parts := strings.SplitN(v, "=", 2) - - accrue := func(keyname string) { - out[keyname] = parts[1] - } - unsupported := func() { - panic(fmt.Sprintf("setting %v not supported", parts[0])) - } - - // The order of these is the same as is seen in the - // PostgreSQL 9.1 manual. Unsupported but well-defined - // keys cause a panic; these should be unset prior to - // execution. Options which pq expects to be set to a - // certain value are allowed, but must be set to that - // value if present (they can, of course, be absent). - switch parts[0] { - case "PGHOST": - accrue("host") - case "PGHOSTADDR": - unsupported() - case "PGPORT": - accrue("port") - case "PGDATABASE": - accrue("dbname") - case "PGUSER": - accrue("user") - case "PGPASSWORD": - accrue("password") - case "PGSERVICE", "PGSERVICEFILE", "PGREALM": - unsupported() - case "PGOPTIONS": - accrue("options") - case "PGAPPNAME": - accrue("application_name") - case "PGSSLMODE": - accrue("sslmode") - case "PGSSLCERT": - accrue("sslcert") - case "PGSSLKEY": - accrue("sslkey") - case "PGSSLROOTCERT": - accrue("sslrootcert") - case "PGREQUIRESSL", "PGSSLCRL": - unsupported() - case "PGREQUIREPEER": - unsupported() - case "PGKRBSRVNAME", "PGGSSLIB": - unsupported() - case "PGCONNECT_TIMEOUT": - accrue("connect_timeout") - case "PGCLIENTENCODING": - accrue("client_encoding") - case "PGDATESTYLE": - accrue("datestyle") - case "PGTZ": - accrue("timezone") - case "PGGEQO": - accrue("geqo") - case "PGSYSCONFDIR", "PGLOCALEDIR": - unsupported() - } - } - - return out -} - -// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". -func isUTF8(name string) bool { - // Recognize all sorts of silly things as "UTF-8", like Postgres does - s := strings.Map(alnumLowerASCII, name) - return s == "utf8" || s == "unicode" -} - -func alnumLowerASCII(ch rune) rune { - if 'A' <= ch && ch <= 'Z' { - return ch + ('a' - 'A') - } - if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { - return ch - } - return -1 // discard -} diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go deleted file mode 100644 index 0fdd06a..0000000 --- a/vendor/github.com/lib/pq/conn_go18.go +++ /dev/null @@ -1,149 +0,0 @@ -package pq - -import ( - "context" - "database/sql" - "database/sql/driver" - "fmt" - "io" - "io/ioutil" - "time" -) - -// Implement the "QueryerContext" interface -func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - finish := cn.watchCancel(ctx) - r, err := cn.query(query, list) - if err != nil { - if finish != nil { - finish() - } - return nil, err - } - r.finish = finish - return r, nil -} - -// Implement the "ExecerContext" interface -func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - - if finish := cn.watchCancel(ctx); finish != nil { - defer finish() - } - - return cn.Exec(query, list) -} - -// Implement the "ConnBeginTx" interface -func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - var mode string - - switch sql.IsolationLevel(opts.Isolation) { - case sql.LevelDefault: - // Don't touch mode: use the server's default - case sql.LevelReadUncommitted: - mode = " ISOLATION LEVEL READ UNCOMMITTED" - case sql.LevelReadCommitted: - mode = " ISOLATION LEVEL READ COMMITTED" - case sql.LevelRepeatableRead: - mode = " ISOLATION LEVEL REPEATABLE READ" - case sql.LevelSerializable: - mode = " ISOLATION LEVEL SERIALIZABLE" - default: - return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation) - } - - if opts.ReadOnly { - mode += " READ ONLY" - } else { - mode += " READ WRITE" - } - - tx, err := cn.begin(mode) - if err != nil { - return nil, err - } - cn.txnFinish = cn.watchCancel(ctx) - return tx, nil -} - -func (cn *conn) Ping(ctx context.Context) error { - if finish := cn.watchCancel(ctx); finish != nil { - defer finish() - } - rows, err := cn.simpleQuery("SELECT 'lib/pq ping test';") - if err != nil { - return driver.ErrBadConn // https://golang.org/pkg/database/sql/driver/#Pinger - } - rows.Close() - return nil -} - -func (cn *conn) watchCancel(ctx context.Context) func() { - if done := ctx.Done(); done != nil { - finished := make(chan struct{}) - go func() { - select { - case <-done: - // At this point the function level context is canceled, - // so it must not be used for the additional network - // request to cancel the query. - // Create a new context to pass into the dial. - ctxCancel, cancel := context.WithTimeout(context.Background(), time.Second*10) - defer cancel() - - _ = cn.cancel(ctxCancel) - finished <- struct{}{} - case <-finished: - } - }() - return func() { - select { - case <-finished: - case finished <- struct{}{}: - } - } - } - return nil -} - -func (cn *conn) cancel(ctx context.Context) error { - c, err := dial(ctx, cn.dialer, cn.opts) - if err != nil { - return err - } - defer c.Close() - - { - can := conn{ - c: c, - } - err = can.ssl(cn.opts) - if err != nil { - return err - } - - w := can.writeBuf(0) - w.int32(80877102) // cancel request code - w.int32(cn.processID) - w.int32(cn.secretKey) - - if err := can.sendStartupPacket(w); err != nil { - return err - } - } - - // Read until EOF to ensure that the server received the cancel. - { - _, err := io.Copy(ioutil.Discard, c) - return err - } -} diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go deleted file mode 100644 index 2f8ced6..0000000 --- a/vendor/github.com/lib/pq/connector.go +++ /dev/null @@ -1,110 +0,0 @@ -package pq - -import ( - "context" - "database/sql/driver" - "errors" - "fmt" - "os" - "strings" -) - -// Connector represents a fixed configuration for the pq driver with a given -// name. Connector satisfies the database/sql/driver Connector interface and -// can be used to create any number of DB Conn's via the database/sql OpenDB -// function. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -type Connector struct { - opts values - dialer Dialer -} - -// Connect returns a connection to the database using the fixed configuration -// of this Connector. Context is not used. -func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { - return c.open(ctx) -} - -// Driver returnst the underlying driver of this Connector. -func (c *Connector) Driver() driver.Driver { - return &Driver{} -} - -// NewConnector returns a connector for the pq driver in a fixed configuration -// with the given dsn. The returned connector can be used to create any number -// of equivalent Conn's. The returned connector is intended to be used with -// database/sql.OpenDB. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -func NewConnector(dsn string) (*Connector, error) { - var err error - o := make(values) - - // A number of defaults are applied here, in this order: - // - // * Very low precedence defaults applied in every situation - // * Environment variables - // * Explicitly passed connection information - o["host"] = "localhost" - o["port"] = "5432" - // N.B.: Extra float digits should be set to 3, but that breaks - // Postgres 8.4 and older, where the max is 2. - o["extra_float_digits"] = "2" - for k, v := range parseEnviron(os.Environ()) { - o[k] = v - } - - if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") { - dsn, err = ParseURL(dsn) - if err != nil { - return nil, err - } - } - - if err := parseOpts(dsn, o); err != nil { - return nil, err - } - - // Use the "fallback" application name if necessary - if fallback, ok := o["fallback_application_name"]; ok { - if _, ok := o["application_name"]; !ok { - o["application_name"] = fallback - } - } - - // We can't work with any client_encoding other than UTF-8 currently. - // However, we have historically allowed the user to set it to UTF-8 - // explicitly, and there's no reason to break such programs, so allow that. - // Note that the "options" setting could also set client_encoding, but - // parsing its value is not worth it. Instead, we always explicitly send - // client_encoding as a separate run-time parameter, which should override - // anything set in options. - if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) { - return nil, errors.New("client_encoding must be absent or 'UTF8'") - } - o["client_encoding"] = "UTF8" - // DateStyle needs a similar treatment. - if datestyle, ok := o["datestyle"]; ok { - if datestyle != "ISO, MDY" { - return nil, fmt.Errorf("setting datestyle must be absent or %v; got %v", "ISO, MDY", datestyle) - } - } else { - o["datestyle"] = "ISO, MDY" - } - - // If a user is not provided by any other means, the last - // resort is to use the current operating system provided user - // name. - if _, ok := o["user"]; !ok { - u, err := userCurrent() - if err != nil { - return nil, err - } - o["user"] = u - } - - return &Connector{opts: o, dialer: defaultDialer{}}, nil -} diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go deleted file mode 100644 index 55378d5..0000000 --- a/vendor/github.com/lib/pq/copy.go +++ /dev/null @@ -1,282 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "sync" -) - -var ( - errCopyInClosed = errors.New("pq: copyin statement has already been closed") - errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") - errCopyToNotSupported = errors.New("pq: COPY TO is not supported") - errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") - errCopyInProgress = errors.New("pq: COPY in progress") -) - -// CopyIn creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). The target table should be visible in search_path. -func CopyIn(table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -// CopyInSchema creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). -func CopyInSchema(schema, table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -type copyin struct { - cn *conn - buffer []byte - rowData chan []byte - done chan bool - - closed bool - - sync.Mutex // guards err - err error -} - -const ciBufferSize = 64 * 1024 - -// flush buffer before the buffer is filled up and needs reallocation -const ciBufferFlushSize = 63 * 1024 - -func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) { - if !cn.isInTransaction() { - return nil, errCopyNotSupportedOutsideTxn - } - - ci := ©in{ - cn: cn, - buffer: make([]byte, 0, ciBufferSize), - rowData: make(chan []byte), - done: make(chan bool, 1), - } - // add CopyData identifier + 4 bytes for message length - ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - -awaitCopyInResponse: - for { - t, r := cn.recv1() - switch t { - case 'G': - if r.byte() != 0 { - err = errBinaryCopyNotSupported - break awaitCopyInResponse - } - go ci.resploop() - return ci, nil - case 'H': - err = errCopyToNotSupported - break awaitCopyInResponse - case 'E': - err = parseError(r) - case 'Z': - if err == nil { - ci.setBad() - errorf("unexpected ReadyForQuery in response to COPY") - } - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for copy query: %q", t) - } - } - - // something went wrong, abort COPY before we return - b = cn.writeBuf('f') - b.string(err.Error()) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'c', 'C', 'E': - case 'Z': - // correctly aborted, we're done - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for CopyFail: %q", t) - } - } -} - -func (ci *copyin) flush(buf []byte) { - // set message length (without message identifier) - binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) - - _, err := ci.cn.c.Write(buf) - if err != nil { - panic(err) - } -} - -func (ci *copyin) resploop() { - for { - var r readBuf - t, err := ci.cn.recvMessage(&r) - if err != nil { - ci.setBad() - ci.setError(err) - ci.done <- true - return - } - switch t { - case 'C': - // complete - case 'N': - // NoticeResponse - case 'Z': - ci.cn.processReadyForQuery(&r) - ci.done <- true - return - case 'E': - err := parseError(&r) - ci.setError(err) - default: - ci.setBad() - ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) - ci.done <- true - return - } - } -} - -func (ci *copyin) setBad() { - ci.Lock() - ci.cn.bad = true - ci.Unlock() -} - -func (ci *copyin) isBad() bool { - ci.Lock() - b := ci.cn.bad - ci.Unlock() - return b -} - -func (ci *copyin) isErrorSet() bool { - ci.Lock() - isSet := (ci.err != nil) - ci.Unlock() - return isSet -} - -// setError() sets ci.err if one has not been set already. Caller must not be -// holding ci.Mutex. -func (ci *copyin) setError(err error) { - ci.Lock() - if ci.err == nil { - ci.err = err - } - ci.Unlock() -} - -func (ci *copyin) NumInput() int { - return -1 -} - -func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { - return nil, ErrNotSupported -} - -// Exec inserts values into the COPY stream. The insert is asynchronous -// and Exec can return errors from previous Exec calls to the same -// COPY stmt. -// -// You need to call Exec(nil) to sync the COPY stream and to get any -// errors from pending data, since Stmt.Close() doesn't return errors -// to the user. -func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { - if ci.closed { - return nil, errCopyInClosed - } - - if ci.isBad() { - return nil, driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if ci.isErrorSet() { - return nil, ci.err - } - - if len(v) == 0 { - return driver.RowsAffected(0), ci.Close() - } - - numValues := len(v) - for i, value := range v { - ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value) - if i < numValues-1 { - ci.buffer = append(ci.buffer, '\t') - } - } - - ci.buffer = append(ci.buffer, '\n') - - if len(ci.buffer) > ciBufferFlushSize { - ci.flush(ci.buffer) - // reset buffer, keep bytes for message identifier and length - ci.buffer = ci.buffer[:5] - } - - return driver.RowsAffected(0), nil -} - -func (ci *copyin) Close() (err error) { - if ci.closed { // Don't do anything, we're already closed - return nil - } - ci.closed = true - - if ci.isBad() { - return driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if len(ci.buffer) > 0 { - ci.flush(ci.buffer) - } - // Avoid touching the scratch buffer as resploop could be using it. - err = ci.cn.sendSimpleMessage('c') - if err != nil { - return err - } - - <-ci.done - ci.cn.inCopy = false - - if ci.isErrorSet() { - err = ci.err - return err - } - return nil -} diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go deleted file mode 100644 index 2a60054..0000000 --- a/vendor/github.com/lib/pq/doc.go +++ /dev/null @@ -1,245 +0,0 @@ -/* -Package pq is a pure Go Postgres driver for the database/sql package. - -In most cases clients will use the database/sql package instead of -using this package directly. For example: - - import ( - "database/sql" - - _ "github.com/lib/pq" - ) - - func main() { - connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - if err != nil { - log.Fatal(err) - } - - age := 21 - rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) - … - } - -You can also connect to a database using a URL. For example: - - connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - - -Connection String Parameters - - -Similarly to libpq, when establishing a connection using pq you are expected to -supply a connection string containing zero or more parameters. -A subset of the connection parameters supported by libpq are also supported by pq. -Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem) -directly in the connection string. This is different from libpq, which does not allow -run-time parameters in the connection string, instead requiring you to supply -them in the options parameter. - -For compatibility with libpq, the following special connection parameters are -supported: - - * dbname - The name of the database to connect to - * user - The user to sign in as - * password - The user's password - * host - The host to connect to. Values that start with / are for unix - domain sockets. (default is localhost) - * port - The port to bind to. (default is 5432) - * sslmode - Whether or not to use SSL (default is require, this is not - the default for libpq) - * fallback_application_name - An application_name to fall back to if one isn't provided. - * connect_timeout - Maximum wait for connection, in seconds. Zero or - not specified means wait indefinitely. - * sslcert - Cert file location. The file must contain PEM encoded data. - * sslkey - Key file location. The file must contain PEM encoded data. - * sslrootcert - The location of the root certificate file. The file - must contain PEM encoded data. - -Valid values for sslmode are: - - * disable - No SSL - * require - Always SSL (skip verification) - * verify-ca - Always SSL (verify that the certificate presented by the - server was signed by a trusted CA) - * verify-full - Always SSL (verify that the certification presented by - the server was signed by a trusted CA and the server host name - matches the one in the certificate) - -See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING -for more information about connection string parameters. - -Use single quotes for values that contain whitespace: - - "user=pqgotest password='with spaces'" - -A backslash will escape the next character in values: - - "user=space\ man password='it\'s valid'" - -Note that the connection parameter client_encoding (which sets the -text encoding for the connection) may be set but must be "UTF8", -matching with the same rules as Postgres. It is an error to provide -any other value. - -In addition to the parameters listed above, any run-time parameter that can be -set at backend start time can be set in the connection string. For more -information, see -http://www.postgresql.org/docs/current/static/runtime-config.html. - -Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html -supported by libpq are also supported by pq. If any of the environment -variables not supported by pq are set, pq will panic during connection -establishment. Environment variables have a lower precedence than explicitly -provided connection parameters. - -The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html -is supported, but on Windows PGPASSFILE must be specified explicitly. - - -Queries - - -database/sql does not dictate any specific format for parameter -markers in query strings, and pq uses the Postgres-native ordinal markers, -as shown above. The same marker can be reused for the same parameter: - - rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1 - OR age BETWEEN $2 AND $2 + 3`, "orange", 64) - -pq does not support the LastInsertId() method of the Result type in database/sql. -To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres -RETURNING clause with a standard Query or QueryRow call: - - var userid int - err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age) - VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid) - -For more details on RETURNING, see the Postgres documentation: - - http://www.postgresql.org/docs/current/static/sql-insert.html - http://www.postgresql.org/docs/current/static/sql-update.html - http://www.postgresql.org/docs/current/static/sql-delete.html - -For additional instructions on querying see the documentation for the database/sql package. - - -Data Types - - -Parameters pass through driver.DefaultParameterConverter before they are handled -by this package. When the binary_parameters connection option is enabled, -[]byte values are sent directly to the backend as data in binary format. - -This package returns the following types for values from the PostgreSQL backend: - - - integer types smallint, integer, and bigint are returned as int64 - - floating-point types real and double precision are returned as float64 - - character types char, varchar, and text are returned as string - - temporal types date, time, timetz, timestamp, and timestamptz are - returned as time.Time - - the boolean type is returned as bool - - the bytea type is returned as []byte - -All other types are returned directly from the backend as []byte values in text format. - - -Errors - - -pq may return errors of type *pq.Error which can be interrogated for error details: - - if err, ok := err.(*pq.Error); ok { - fmt.Println("pq error:", err.Code.Name()) - } - -See the pq.Error type for details. - - -Bulk imports - -You can perform bulk imports by preparing a statement returned by pq.CopyIn (or -pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement -handle can then be repeatedly "executed" to copy data into the target table. -After all data has been processed you should call Exec() once with no arguments -to flush all buffered data. Any call to Exec() might return an error which -should be handled appropriately, but because of the internal buffering an error -returned by Exec() might not be related to the data passed in the call that -failed. - -CopyIn uses COPY FROM internally. It is not possible to COPY outside of an -explicit transaction in pq. - -Usage example: - - txn, err := db.Begin() - if err != nil { - log.Fatal(err) - } - - stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age")) - if err != nil { - log.Fatal(err) - } - - for _, user := range users { - _, err = stmt.Exec(user.Name, int64(user.Age)) - if err != nil { - log.Fatal(err) - } - } - - _, err = stmt.Exec() - if err != nil { - log.Fatal(err) - } - - err = stmt.Close() - if err != nil { - log.Fatal(err) - } - - err = txn.Commit() - if err != nil { - log.Fatal(err) - } - - -Notifications - - -PostgreSQL supports a simple publish/subscribe model over database -connections. See http://www.postgresql.org/docs/current/static/sql-notify.html -for more information about the general mechanism. - -To start listening for notifications, you first have to open a new connection -to the database by calling NewListener. This connection can not be used for -anything other than LISTEN / NOTIFY. Calling Listen will open a "notification -channel"; once a notification channel is open, a notification generated on that -channel will effect a send on the Listener.Notify channel. A notification -channel will remain open until Unlisten is called, though connection loss might -result in some notifications being lost. To solve this problem, Listener sends -a nil pointer over the Notify channel any time the connection is re-established -following a connection loss. The application can get information about the -state of the underlying connection by setting an event callback in the call to -NewListener. - -A single Listener can safely be used from concurrent goroutines, which means -that there is often no need to create more than one Listener in your -application. However, a Listener is always connected to a single database, so -you will need to create a new Listener instance for every database you want to -receive notifications in. - -The channel name in both Listen and Unlisten is case sensitive, and can contain -any characters legal in an identifier (see -http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS -for more information). Note that the channel name will be truncated to 63 -bytes by the PostgreSQL server. - -You can find a complete, working example of Listener usage at -https://godoc.org/github.com/lib/pq/example/listen. - -*/ -package pq diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go deleted file mode 100644 index 73cafb8..0000000 --- a/vendor/github.com/lib/pq/encode.go +++ /dev/null @@ -1,602 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "math" - "strconv" - "strings" - "sync" - "time" - - "github.com/lib/pq/oid" -) - -func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte { - switch v := x.(type) { - case []byte: - return v - default: - return encode(parameterStatus, x, oid.T_unknown) - } -} - -func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(nil, v, 10) - case float64: - return strconv.AppendFloat(nil, v, 'f', -1, 64) - case []byte: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, v) - } - - return v - case string: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, []byte(v)) - } - - return []byte(v) - case bool: - return strconv.AppendBool(nil, v) - case time.Time: - return formatTs(v) - - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { - switch f { - case formatBinary: - return binaryDecode(parameterStatus, s, typ) - case formatText: - return textDecode(parameterStatus, s, typ) - default: - panic("not reached") - } -} - -func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_bytea: - return s - case oid.T_int8: - return int64(binary.BigEndian.Uint64(s)) - case oid.T_int4: - return int64(int32(binary.BigEndian.Uint32(s))) - case oid.T_int2: - return int64(int16(binary.BigEndian.Uint16(s))) - case oid.T_uuid: - b, err := decodeUUIDBinary(s) - if err != nil { - panic(err) - } - return b - - default: - errorf("don't know how to decode binary parameter of type %d", uint32(typ)) - } - - panic("not reached") -} - -func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_char, oid.T_varchar, oid.T_text: - return string(s) - case oid.T_bytea: - b, err := parseBytea(s) - if err != nil { - errorf("%s", err) - } - return b - case oid.T_timestamptz: - return parseTs(parameterStatus.currentLocation, string(s)) - case oid.T_timestamp, oid.T_date: - return parseTs(nil, string(s)) - case oid.T_time: - return mustParse("15:04:05", typ, s) - case oid.T_timetz: - return mustParse("15:04:05-07", typ, s) - case oid.T_bool: - return s[0] == 't' - case oid.T_int8, oid.T_int4, oid.T_int2: - i, err := strconv.ParseInt(string(s), 10, 64) - if err != nil { - errorf("%s", err) - } - return i - case oid.T_float4, oid.T_float8: - // We always use 64 bit parsing, regardless of whether the input text is for - // a float4 or float8, because clients expect float64s for all float datatypes - // and returning a 32-bit parsed float64 produces lossy results. - f, err := strconv.ParseFloat(string(s), 64) - if err != nil { - errorf("%s", err) - } - return f - } - - return s -} - -// appendEncodedText encodes item in text format as required by COPY -// and appends to buf -func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(buf, v, 10) - case float64: - return strconv.AppendFloat(buf, v, 'f', -1, 64) - case []byte: - encodedBytea := encodeBytea(parameterStatus.serverVersion, v) - return appendEscapedText(buf, string(encodedBytea)) - case string: - return appendEscapedText(buf, v) - case bool: - return strconv.AppendBool(buf, v) - case time.Time: - return append(buf, formatTs(v)...) - case nil: - return append(buf, "\\N"...) - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func appendEscapedText(buf []byte, text string) []byte { - escapeNeeded := false - startPos := 0 - var c byte - - // check if we need to escape - for i := 0; i < len(text); i++ { - c = text[i] - if c == '\\' || c == '\n' || c == '\r' || c == '\t' { - escapeNeeded = true - startPos = i - break - } - } - if !escapeNeeded { - return append(buf, text...) - } - - // copy till first char to escape, iterate the rest - result := append(buf, text[:startPos]...) - for i := startPos; i < len(text); i++ { - c = text[i] - switch c { - case '\\': - result = append(result, '\\', '\\') - case '\n': - result = append(result, '\\', 'n') - case '\r': - result = append(result, '\\', 'r') - case '\t': - result = append(result, '\\', 't') - default: - result = append(result, c) - } - } - return result -} - -func mustParse(f string, typ oid.Oid, s []byte) time.Time { - str := string(s) - - // check for a 30-minute-offset timezone - if (typ == oid.T_timestamptz || typ == oid.T_timetz) && - str[len(str)-3] == ':' { - f += ":00" - } - t, err := time.Parse(f, str) - if err != nil { - errorf("decode: %s", err) - } - return t -} - -var errInvalidTimestamp = errors.New("invalid timestamp") - -type timestampParser struct { - err error -} - -func (p *timestampParser) expect(str string, char byte, pos int) { - if p.err != nil { - return - } - if pos+1 > len(str) { - p.err = errInvalidTimestamp - return - } - if c := str[pos]; c != char && p.err == nil { - p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c) - } -} - -func (p *timestampParser) mustAtoi(str string, begin int, end int) int { - if p.err != nil { - return 0 - } - if begin < 0 || end < 0 || begin > end || end > len(str) { - p.err = errInvalidTimestamp - return 0 - } - result, err := strconv.Atoi(str[begin:end]) - if err != nil { - if p.err == nil { - p.err = fmt.Errorf("expected number; got '%v'", str) - } - return 0 - } - return result -} - -// The location cache caches the time zones typically used by the client. -type locationCache struct { - cache map[int]*time.Location - lock sync.Mutex -} - -// All connections share the same list of timezones. Benchmarking shows that -// about 5% speed could be gained by putting the cache in the connection and -// losing the mutex, at the cost of a small amount of memory and a somewhat -// significant increase in code complexity. -var globalLocationCache = newLocationCache() - -func newLocationCache() *locationCache { - return &locationCache{cache: make(map[int]*time.Location)} -} - -// Returns the cached timezone for the specified offset, creating and caching -// it if necessary. -func (c *locationCache) getLocation(offset int) *time.Location { - c.lock.Lock() - defer c.lock.Unlock() - - location, ok := c.cache[offset] - if !ok { - location = time.FixedZone("", offset) - c.cache[offset] = location - } - - return location -} - -var infinityTsEnabled = false -var infinityTsNegative time.Time -var infinityTsPositive time.Time - -const ( - infinityTsEnabledAlready = "pq: infinity timestamp enabled already" - infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive" -) - -// EnableInfinityTs controls the handling of Postgres' "-infinity" and -// "infinity" "timestamp"s. -// -// If EnableInfinityTs is not called, "-infinity" and "infinity" will return -// []byte("-infinity") and []byte("infinity") respectively, and potentially -// cause error "sql: Scan error on column index 0: unsupported driver -> Scan -// pair: []uint8 -> *time.Time", when scanning into a time.Time value. -// -// Once EnableInfinityTs has been called, all connections created using this -// driver will decode Postgres' "-infinity" and "infinity" for "timestamp", -// "timestamp with time zone" and "date" types to the predefined minimum and -// maximum times, respectively. When encoding time.Time values, any time which -// equals or precedes the predefined minimum time will be encoded to -// "-infinity". Any values at or past the maximum time will similarly be -// encoded to "infinity". -// -// If EnableInfinityTs is called with negative >= positive, it will panic. -// Calling EnableInfinityTs after a connection has been established results in -// undefined behavior. If EnableInfinityTs is called more than once, it will -// panic. -func EnableInfinityTs(negative time.Time, positive time.Time) { - if infinityTsEnabled { - panic(infinityTsEnabledAlready) - } - if !negative.Before(positive) { - panic(infinityTsNegativeMustBeSmaller) - } - infinityTsEnabled = true - infinityTsNegative = negative - infinityTsPositive = positive -} - -/* - * Testing might want to toggle infinityTsEnabled - */ -func disableInfinityTs() { - infinityTsEnabled = false -} - -// This is a time function specific to the Postgres default DateStyle -// setting ("ISO, MDY"), the only one we currently support. This -// accounts for the discrepancies between the parsing available with -// time.Parse and the Postgres date formatting quirks. -func parseTs(currentLocation *time.Location, str string) interface{} { - switch str { - case "-infinity": - if infinityTsEnabled { - return infinityTsNegative - } - return []byte(str) - case "infinity": - if infinityTsEnabled { - return infinityTsPositive - } - return []byte(str) - } - t, err := ParseTimestamp(currentLocation, str) - if err != nil { - panic(err) - } - return t -} - -// ParseTimestamp parses Postgres' text format. It returns a time.Time in -// currentLocation iff that time's offset agrees with the offset sent from the -// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the -// fixed offset offset provided by the Postgres server. -func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) { - p := timestampParser{} - - monSep := strings.IndexRune(str, '-') - // this is Gregorian year, not ISO Year - // In Gregorian system, the year 1 BC is followed by AD 1 - year := p.mustAtoi(str, 0, monSep) - daySep := monSep + 3 - month := p.mustAtoi(str, monSep+1, daySep) - p.expect(str, '-', daySep) - timeSep := daySep + 3 - day := p.mustAtoi(str, daySep+1, timeSep) - - minLen := monSep + len("01-01") + 1 - - isBC := strings.HasSuffix(str, " BC") - if isBC { - minLen += 3 - } - - var hour, minute, second int - if len(str) > minLen { - p.expect(str, ' ', timeSep) - minSep := timeSep + 3 - p.expect(str, ':', minSep) - hour = p.mustAtoi(str, timeSep+1, minSep) - secSep := minSep + 3 - p.expect(str, ':', secSep) - minute = p.mustAtoi(str, minSep+1, secSep) - secEnd := secSep + 3 - second = p.mustAtoi(str, secSep+1, secEnd) - } - remainderIdx := monSep + len("01-01 00:00:00") + 1 - // Three optional (but ordered) sections follow: the - // fractional seconds, the time zone offset, and the BC - // designation. We set them up here and adjust the other - // offsets if the preceding sections exist. - - nanoSec := 0 - tzOff := 0 - - if remainderIdx < len(str) && str[remainderIdx] == '.' { - fracStart := remainderIdx + 1 - fracOff := strings.IndexAny(str[fracStart:], "-+ ") - if fracOff < 0 { - fracOff = len(str) - fracStart - } - fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff) - nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) - - remainderIdx += fracOff + 1 - } - if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') { - // time zone separator is always '-' or '+' (UTC is +00) - var tzSign int - switch c := str[tzStart]; c { - case '-': - tzSign = -1 - case '+': - tzSign = +1 - default: - return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c) - } - tzHours := p.mustAtoi(str, tzStart+1, tzStart+3) - remainderIdx += 3 - var tzMin, tzSec int - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) - } - var isoYear int - - if isBC { - isoYear = 1 - year - remainderIdx += 3 - } else { - isoYear = year - } - if remainderIdx < len(str) { - return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:]) - } - t := time.Date(isoYear, time.Month(month), day, - hour, minute, second, nanoSec, - globalLocationCache.getLocation(tzOff)) - - if currentLocation != nil { - // Set the location of the returned Time based on the session's - // TimeZone value, but only if the local time zone database agrees with - // the remote database on the offset. - lt := t.In(currentLocation) - _, newOff := lt.Zone() - if newOff == tzOff { - t = lt - } - } - - return t, p.err -} - -// formatTs formats t into a format postgres understands. -func formatTs(t time.Time) []byte { - if infinityTsEnabled { - // t <= -infinity : ! (t > -infinity) - if !t.After(infinityTsNegative) { - return []byte("-infinity") - } - // t >= infinity : ! (!t < infinity) - if !t.Before(infinityTsPositive) { - return []byte("infinity") - } - } - return FormatTimestamp(t) -} - -// FormatTimestamp formats t into Postgres' text format for timestamps. -func FormatTimestamp(t time.Time) []byte { - // Need to send dates before 0001 A.D. with " BC" suffix, instead of the - // minus sign preferred by Go. - // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on - bc := false - if t.Year() <= 0 { - // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" - t = t.AddDate((-t.Year())*2+1, 0, 0) - bc = true - } - b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) - - _, offset := t.Zone() - offset %= 60 - if offset != 0 { - // RFC3339Nano already printed the minus sign - if offset < 0 { - offset = -offset - } - - b = append(b, ':') - if offset < 10 { - b = append(b, '0') - } - b = strconv.AppendInt(b, int64(offset), 10) - } - - if bc { - b = append(b, " BC"...) - } - return b -} - -// Parse a bytea value received from the server. Both "hex" and the legacy -// "escape" format are supported. -func parseBytea(s []byte) (result []byte, err error) { - if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { - // bytea_output = hex - s = s[2:] // trim off leading "\\x" - result = make([]byte, hex.DecodedLen(len(s))) - _, err := hex.Decode(result, s) - if err != nil { - return nil, err - } - } else { - // bytea_output = escape - for len(s) > 0 { - if s[0] == '\\' { - // escaped '\\' - if len(s) >= 2 && s[1] == '\\' { - result = append(result, '\\') - s = s[2:] - continue - } - - // '\\' followed by an octal number - if len(s) < 4 { - return nil, fmt.Errorf("invalid bytea sequence %v", s) - } - r, err := strconv.ParseInt(string(s[1:4]), 8, 9) - if err != nil { - return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) - } - result = append(result, byte(r)) - s = s[4:] - } else { - // We hit an unescaped, raw byte. Try to read in as many as - // possible in one go. - i := bytes.IndexByte(s, '\\') - if i == -1 { - result = append(result, s...) - break - } - result = append(result, s[:i]...) - s = s[i:] - } - } - } - - return result, nil -} - -func encodeBytea(serverVersion int, v []byte) (result []byte) { - if serverVersion >= 90000 { - // Use the hex format if we know that the server supports it - result = make([]byte, 2+hex.EncodedLen(len(v))) - result[0] = '\\' - result[1] = 'x' - hex.Encode(result[2:], v) - } else { - // .. or resort to "escape" - for _, b := range v { - if b == '\\' { - result = append(result, '\\', '\\') - } else if b < 0x20 || b > 0x7e { - result = append(result, []byte(fmt.Sprintf("\\%03o", b))...) - } else { - result = append(result, b) - } - } - } - - return result -} - -// NullTime represents a time.Time that may be null. NullTime implements the -// sql.Scanner interface so it can be used as a scan destination, similar to -// sql.NullString. -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -// Scan implements the Scanner interface. -func (nt *NullTime) Scan(value interface{}) error { - nt.Time, nt.Valid = value.(time.Time) - return nil -} - -// Value implements the driver Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go deleted file mode 100644 index 3d66ba7..0000000 --- a/vendor/github.com/lib/pq/error.go +++ /dev/null @@ -1,515 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "fmt" - "io" - "net" - "runtime" -) - -// Error severities -const ( - Efatal = "FATAL" - Epanic = "PANIC" - Ewarning = "WARNING" - Enotice = "NOTICE" - Edebug = "DEBUG" - Einfo = "INFO" - Elog = "LOG" -) - -// Error represents an error communicating with the server. -// -// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields -type Error struct { - Severity string - Code ErrorCode - Message string - Detail string - Hint string - Position string - InternalPosition string - InternalQuery string - Where string - Schema string - Table string - Column string - DataTypeName string - Constraint string - File string - Line string - Routine string -} - -// ErrorCode is a five-character error code. -type ErrorCode string - -// Name returns a more human friendly rendering of the error code, namely the -// "condition name". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Name() string { - return errorCodeNames[ec] -} - -// ErrorClass is only the class part of an error code. -type ErrorClass string - -// Name returns the condition name of an error class. It is equivalent to the -// condition name of the "standard" error code (i.e. the one having the last -// three characters "000"). -func (ec ErrorClass) Name() string { - return errorCodeNames[ErrorCode(ec+"000")] -} - -// Class returns the error class, e.g. "28". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Class() ErrorClass { - return ErrorClass(ec[0:2]) -} - -// errorCodeNames is a mapping between the five-character error codes and the -// human readable "condition names". It is derived from the list at -// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html -var errorCodeNames = map[ErrorCode]string{ - // Class 00 - Successful Completion - "00000": "successful_completion", - // Class 01 - Warning - "01000": "warning", - "0100C": "dynamic_result_sets_returned", - "01008": "implicit_zero_bit_padding", - "01003": "null_value_eliminated_in_set_function", - "01007": "privilege_not_granted", - "01006": "privilege_not_revoked", - "01004": "string_data_right_truncation", - "01P01": "deprecated_feature", - // Class 02 - No Data (this is also a warning class per the SQL standard) - "02000": "no_data", - "02001": "no_additional_dynamic_result_sets_returned", - // Class 03 - SQL Statement Not Yet Complete - "03000": "sql_statement_not_yet_complete", - // Class 08 - Connection Exception - "08000": "connection_exception", - "08003": "connection_does_not_exist", - "08006": "connection_failure", - "08001": "sqlclient_unable_to_establish_sqlconnection", - "08004": "sqlserver_rejected_establishment_of_sqlconnection", - "08007": "transaction_resolution_unknown", - "08P01": "protocol_violation", - // Class 09 - Triggered Action Exception - "09000": "triggered_action_exception", - // Class 0A - Feature Not Supported - "0A000": "feature_not_supported", - // Class 0B - Invalid Transaction Initiation - "0B000": "invalid_transaction_initiation", - // Class 0F - Locator Exception - "0F000": "locator_exception", - "0F001": "invalid_locator_specification", - // Class 0L - Invalid Grantor - "0L000": "invalid_grantor", - "0LP01": "invalid_grant_operation", - // Class 0P - Invalid Role Specification - "0P000": "invalid_role_specification", - // Class 0Z - Diagnostics Exception - "0Z000": "diagnostics_exception", - "0Z002": "stacked_diagnostics_accessed_without_active_handler", - // Class 20 - Case Not Found - "20000": "case_not_found", - // Class 21 - Cardinality Violation - "21000": "cardinality_violation", - // Class 22 - Data Exception - "22000": "data_exception", - "2202E": "array_subscript_error", - "22021": "character_not_in_repertoire", - "22008": "datetime_field_overflow", - "22012": "division_by_zero", - "22005": "error_in_assignment", - "2200B": "escape_character_conflict", - "22022": "indicator_overflow", - "22015": "interval_field_overflow", - "2201E": "invalid_argument_for_logarithm", - "22014": "invalid_argument_for_ntile_function", - "22016": "invalid_argument_for_nth_value_function", - "2201F": "invalid_argument_for_power_function", - "2201G": "invalid_argument_for_width_bucket_function", - "22018": "invalid_character_value_for_cast", - "22007": "invalid_datetime_format", - "22019": "invalid_escape_character", - "2200D": "invalid_escape_octet", - "22025": "invalid_escape_sequence", - "22P06": "nonstandard_use_of_escape_character", - "22010": "invalid_indicator_parameter_value", - "22023": "invalid_parameter_value", - "2201B": "invalid_regular_expression", - "2201W": "invalid_row_count_in_limit_clause", - "2201X": "invalid_row_count_in_result_offset_clause", - "22009": "invalid_time_zone_displacement_value", - "2200C": "invalid_use_of_escape_character", - "2200G": "most_specific_type_mismatch", - "22004": "null_value_not_allowed", - "22002": "null_value_no_indicator_parameter", - "22003": "numeric_value_out_of_range", - "2200H": "sequence_generator_limit_exceeded", - "22026": "string_data_length_mismatch", - "22001": "string_data_right_truncation", - "22011": "substring_error", - "22027": "trim_error", - "22024": "unterminated_c_string", - "2200F": "zero_length_character_string", - "22P01": "floating_point_exception", - "22P02": "invalid_text_representation", - "22P03": "invalid_binary_representation", - "22P04": "bad_copy_file_format", - "22P05": "untranslatable_character", - "2200L": "not_an_xml_document", - "2200M": "invalid_xml_document", - "2200N": "invalid_xml_content", - "2200S": "invalid_xml_comment", - "2200T": "invalid_xml_processing_instruction", - // Class 23 - Integrity Constraint Violation - "23000": "integrity_constraint_violation", - "23001": "restrict_violation", - "23502": "not_null_violation", - "23503": "foreign_key_violation", - "23505": "unique_violation", - "23514": "check_violation", - "23P01": "exclusion_violation", - // Class 24 - Invalid Cursor State - "24000": "invalid_cursor_state", - // Class 25 - Invalid Transaction State - "25000": "invalid_transaction_state", - "25001": "active_sql_transaction", - "25002": "branch_transaction_already_active", - "25008": "held_cursor_requires_same_isolation_level", - "25003": "inappropriate_access_mode_for_branch_transaction", - "25004": "inappropriate_isolation_level_for_branch_transaction", - "25005": "no_active_sql_transaction_for_branch_transaction", - "25006": "read_only_sql_transaction", - "25007": "schema_and_data_statement_mixing_not_supported", - "25P01": "no_active_sql_transaction", - "25P02": "in_failed_sql_transaction", - // Class 26 - Invalid SQL Statement Name - "26000": "invalid_sql_statement_name", - // Class 27 - Triggered Data Change Violation - "27000": "triggered_data_change_violation", - // Class 28 - Invalid Authorization Specification - "28000": "invalid_authorization_specification", - "28P01": "invalid_password", - // Class 2B - Dependent Privilege Descriptors Still Exist - "2B000": "dependent_privilege_descriptors_still_exist", - "2BP01": "dependent_objects_still_exist", - // Class 2D - Invalid Transaction Termination - "2D000": "invalid_transaction_termination", - // Class 2F - SQL Routine Exception - "2F000": "sql_routine_exception", - "2F005": "function_executed_no_return_statement", - "2F002": "modifying_sql_data_not_permitted", - "2F003": "prohibited_sql_statement_attempted", - "2F004": "reading_sql_data_not_permitted", - // Class 34 - Invalid Cursor Name - "34000": "invalid_cursor_name", - // Class 38 - External Routine Exception - "38000": "external_routine_exception", - "38001": "containing_sql_not_permitted", - "38002": "modifying_sql_data_not_permitted", - "38003": "prohibited_sql_statement_attempted", - "38004": "reading_sql_data_not_permitted", - // Class 39 - External Routine Invocation Exception - "39000": "external_routine_invocation_exception", - "39001": "invalid_sqlstate_returned", - "39004": "null_value_not_allowed", - "39P01": "trigger_protocol_violated", - "39P02": "srf_protocol_violated", - // Class 3B - Savepoint Exception - "3B000": "savepoint_exception", - "3B001": "invalid_savepoint_specification", - // Class 3D - Invalid Catalog Name - "3D000": "invalid_catalog_name", - // Class 3F - Invalid Schema Name - "3F000": "invalid_schema_name", - // Class 40 - Transaction Rollback - "40000": "transaction_rollback", - "40002": "transaction_integrity_constraint_violation", - "40001": "serialization_failure", - "40003": "statement_completion_unknown", - "40P01": "deadlock_detected", - // Class 42 - Syntax Error or Access Rule Violation - "42000": "syntax_error_or_access_rule_violation", - "42601": "syntax_error", - "42501": "insufficient_privilege", - "42846": "cannot_coerce", - "42803": "grouping_error", - "42P20": "windowing_error", - "42P19": "invalid_recursion", - "42830": "invalid_foreign_key", - "42602": "invalid_name", - "42622": "name_too_long", - "42939": "reserved_name", - "42804": "datatype_mismatch", - "42P18": "indeterminate_datatype", - "42P21": "collation_mismatch", - "42P22": "indeterminate_collation", - "42809": "wrong_object_type", - "42703": "undefined_column", - "42883": "undefined_function", - "42P01": "undefined_table", - "42P02": "undefined_parameter", - "42704": "undefined_object", - "42701": "duplicate_column", - "42P03": "duplicate_cursor", - "42P04": "duplicate_database", - "42723": "duplicate_function", - "42P05": "duplicate_prepared_statement", - "42P06": "duplicate_schema", - "42P07": "duplicate_table", - "42712": "duplicate_alias", - "42710": "duplicate_object", - "42702": "ambiguous_column", - "42725": "ambiguous_function", - "42P08": "ambiguous_parameter", - "42P09": "ambiguous_alias", - "42P10": "invalid_column_reference", - "42611": "invalid_column_definition", - "42P11": "invalid_cursor_definition", - "42P12": "invalid_database_definition", - "42P13": "invalid_function_definition", - "42P14": "invalid_prepared_statement_definition", - "42P15": "invalid_schema_definition", - "42P16": "invalid_table_definition", - "42P17": "invalid_object_definition", - // Class 44 - WITH CHECK OPTION Violation - "44000": "with_check_option_violation", - // Class 53 - Insufficient Resources - "53000": "insufficient_resources", - "53100": "disk_full", - "53200": "out_of_memory", - "53300": "too_many_connections", - "53400": "configuration_limit_exceeded", - // Class 54 - Program Limit Exceeded - "54000": "program_limit_exceeded", - "54001": "statement_too_complex", - "54011": "too_many_columns", - "54023": "too_many_arguments", - // Class 55 - Object Not In Prerequisite State - "55000": "object_not_in_prerequisite_state", - "55006": "object_in_use", - "55P02": "cant_change_runtime_param", - "55P03": "lock_not_available", - // Class 57 - Operator Intervention - "57000": "operator_intervention", - "57014": "query_canceled", - "57P01": "admin_shutdown", - "57P02": "crash_shutdown", - "57P03": "cannot_connect_now", - "57P04": "database_dropped", - // Class 58 - System Error (errors external to PostgreSQL itself) - "58000": "system_error", - "58030": "io_error", - "58P01": "undefined_file", - "58P02": "duplicate_file", - // Class F0 - Configuration File Error - "F0000": "config_file_error", - "F0001": "lock_file_exists", - // Class HV - Foreign Data Wrapper Error (SQL/MED) - "HV000": "fdw_error", - "HV005": "fdw_column_name_not_found", - "HV002": "fdw_dynamic_parameter_value_needed", - "HV010": "fdw_function_sequence_error", - "HV021": "fdw_inconsistent_descriptor_information", - "HV024": "fdw_invalid_attribute_value", - "HV007": "fdw_invalid_column_name", - "HV008": "fdw_invalid_column_number", - "HV004": "fdw_invalid_data_type", - "HV006": "fdw_invalid_data_type_descriptors", - "HV091": "fdw_invalid_descriptor_field_identifier", - "HV00B": "fdw_invalid_handle", - "HV00C": "fdw_invalid_option_index", - "HV00D": "fdw_invalid_option_name", - "HV090": "fdw_invalid_string_length_or_buffer_length", - "HV00A": "fdw_invalid_string_format", - "HV009": "fdw_invalid_use_of_null_pointer", - "HV014": "fdw_too_many_handles", - "HV001": "fdw_out_of_memory", - "HV00P": "fdw_no_schemas", - "HV00J": "fdw_option_name_not_found", - "HV00K": "fdw_reply_handle", - "HV00Q": "fdw_schema_not_found", - "HV00R": "fdw_table_not_found", - "HV00L": "fdw_unable_to_create_execution", - "HV00M": "fdw_unable_to_create_reply", - "HV00N": "fdw_unable_to_establish_connection", - // Class P0 - PL/pgSQL Error - "P0000": "plpgsql_error", - "P0001": "raise_exception", - "P0002": "no_data_found", - "P0003": "too_many_rows", - // Class XX - Internal Error - "XX000": "internal_error", - "XX001": "data_corrupted", - "XX002": "index_corrupted", -} - -func parseError(r *readBuf) *Error { - err := new(Error) - for t := r.byte(); t != 0; t = r.byte() { - msg := r.string() - switch t { - case 'S': - err.Severity = msg - case 'C': - err.Code = ErrorCode(msg) - case 'M': - err.Message = msg - case 'D': - err.Detail = msg - case 'H': - err.Hint = msg - case 'P': - err.Position = msg - case 'p': - err.InternalPosition = msg - case 'q': - err.InternalQuery = msg - case 'W': - err.Where = msg - case 's': - err.Schema = msg - case 't': - err.Table = msg - case 'c': - err.Column = msg - case 'd': - err.DataTypeName = msg - case 'n': - err.Constraint = msg - case 'F': - err.File = msg - case 'L': - err.Line = msg - case 'R': - err.Routine = msg - } - } - return err -} - -// Fatal returns true if the Error Severity is fatal. -func (err *Error) Fatal() bool { - return err.Severity == Efatal -} - -// Get implements the legacy PGError interface. New code should use the fields -// of the Error struct directly. -func (err *Error) Get(k byte) (v string) { - switch k { - case 'S': - return err.Severity - case 'C': - return string(err.Code) - case 'M': - return err.Message - case 'D': - return err.Detail - case 'H': - return err.Hint - case 'P': - return err.Position - case 'p': - return err.InternalPosition - case 'q': - return err.InternalQuery - case 'W': - return err.Where - case 's': - return err.Schema - case 't': - return err.Table - case 'c': - return err.Column - case 'd': - return err.DataTypeName - case 'n': - return err.Constraint - case 'F': - return err.File - case 'L': - return err.Line - case 'R': - return err.Routine - } - return "" -} - -func (err Error) Error() string { - return "pq: " + err.Message -} - -// PGError is an interface used by previous versions of pq. It is provided -// only to support legacy code. New code should use the Error type. -type PGError interface { - Error() string - Fatal() bool - Get(k byte) (v string) -} - -func errorf(s string, args ...interface{}) { - panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) -} - -// TODO(ainar-g) Rename to errorf after removing panics. -func fmterrorf(s string, args ...interface{}) error { - return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)) -} - -func errRecoverNoErrBadConn(err *error) { - e := recover() - if e == nil { - // Do nothing - return - } - var ok bool - *err, ok = e.(error) - if !ok { - *err = fmt.Errorf("pq: unexpected error: %#v", e) - } -} - -func (cn *conn) errRecover(err *error) { - e := recover() - switch v := e.(type) { - case nil: - // Do nothing - case runtime.Error: - cn.bad = true - panic(v) - case *Error: - if v.Fatal() { - *err = driver.ErrBadConn - } else { - *err = v - } - case *net.OpError: - cn.bad = true - *err = v - case error: - if v == io.EOF || v.(error).Error() == "remote error: handshake failure" { - *err = driver.ErrBadConn - } else { - *err = v - } - - default: - cn.bad = true - panic(fmt.Sprintf("unknown error: %#v", e)) - } - - // Any time we return ErrBadConn, we need to remember it since *Tx doesn't - // mark the connection bad in database/sql. - if *err == driver.ErrBadConn { - cn.bad = true - } -} diff --git a/vendor/github.com/lib/pq/go.mod b/vendor/github.com/lib/pq/go.mod deleted file mode 100644 index edf0b34..0000000 --- a/vendor/github.com/lib/pq/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/lib/pq diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go deleted file mode 100644 index 850bb90..0000000 --- a/vendor/github.com/lib/pq/notify.go +++ /dev/null @@ -1,797 +0,0 @@ -package pq - -// Package pq is a pure Go Postgres driver for the database/sql package. -// This module contains support for Postgres LISTEN/NOTIFY. - -import ( - "errors" - "fmt" - "sync" - "sync/atomic" - "time" -) - -// Notification represents a single notification from the database. -type Notification struct { - // Process ID (PID) of the notifying postgres backend. - BePid int - // Name of the channel the notification was sent on. - Channel string - // Payload, or the empty string if unspecified. - Extra string -} - -func recvNotification(r *readBuf) *Notification { - bePid := r.int32() - channel := r.string() - extra := r.string() - - return &Notification{bePid, channel, extra} -} - -const ( - connStateIdle int32 = iota - connStateExpectResponse - connStateExpectReadyForQuery -) - -type message struct { - typ byte - err error -} - -var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") - -// ListenerConn is a low-level interface for waiting for notifications. You -// should use Listener instead. -type ListenerConn struct { - // guards cn and err - connectionLock sync.Mutex - cn *conn - err error - - connState int32 - - // the sending goroutine will be holding this lock - senderLock sync.Mutex - - notificationChan chan<- *Notification - - replyChan chan message -} - -// NewListenerConn creates a new ListenerConn. Use NewListener instead. -func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { - return newDialListenerConn(defaultDialer{}, name, notificationChan) -} - -func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) { - cn, err := DialOpen(d, name) - if err != nil { - return nil, err - } - - l := &ListenerConn{ - cn: cn.(*conn), - notificationChan: c, - connState: connStateIdle, - replyChan: make(chan message, 2), - } - - go l.listenerConnMain() - - return l, nil -} - -// We can only allow one goroutine at a time to be running a query on the -// connection for various reasons, so the goroutine sending on the connection -// must be holding senderLock. -// -// Returns an error if an unrecoverable error has occurred and the ListenerConn -// should be abandoned. -func (l *ListenerConn) acquireSenderLock() error { - // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery - l.senderLock.Lock() - - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - if err != nil { - l.senderLock.Unlock() - return err - } - return nil -} - -func (l *ListenerConn) releaseSenderLock() { - l.senderLock.Unlock() -} - -// setState advances the protocol state to newState. Returns false if moving -// to that state from the current state is not allowed. -func (l *ListenerConn) setState(newState int32) bool { - var expectedState int32 - - switch newState { - case connStateIdle: - expectedState = connStateExpectReadyForQuery - case connStateExpectResponse: - expectedState = connStateIdle - case connStateExpectReadyForQuery: - expectedState = connStateExpectResponse - default: - panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) - } - - return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) -} - -// Main logic is here: receive messages from the postgres backend, forward -// notifications and query replies and keep the internal state in sync with the -// protocol state. Returns when the connection has been lost, is about to go -// away or should be discarded because we couldn't agree on the state with the -// server backend. -func (l *ListenerConn) listenerConnLoop() (err error) { - defer errRecoverNoErrBadConn(&err) - - r := &readBuf{} - for { - t, err := l.cn.recvMessage(r) - if err != nil { - return err - } - - switch t { - case 'A': - // recvNotification copies all the data so we don't need to worry - // about the scratch buffer being overwritten. - l.notificationChan <- recvNotification(r) - - case 'T', 'D': - // only used by tests; ignore - - case 'E': - // We might receive an ErrorResponse even when not in a query; it - // is expected that the server will close the connection after - // that, but we should make sure that the error we display is the - // one from the stray ErrorResponse, not io.ErrUnexpectedEOF. - if !l.setState(connStateExpectReadyForQuery) { - return parseError(r) - } - l.replyChan <- message{t, parseError(r)} - - case 'C', 'I': - if !l.setState(connStateExpectReadyForQuery) { - // protocol out of sync - return fmt.Errorf("unexpected CommandComplete") - } - // ExecSimpleQuery doesn't need to know about this message - - case 'Z': - if !l.setState(connStateIdle) { - // protocol out of sync - return fmt.Errorf("unexpected ReadyForQuery") - } - l.replyChan <- message{t, nil} - - case 'N', 'S': - // ignore - default: - return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) - } - } -} - -// This is the main routine for the goroutine receiving on the database -// connection. Most of the main logic is in listenerConnLoop. -func (l *ListenerConn) listenerConnMain() { - err := l.listenerConnLoop() - - // listenerConnLoop terminated; we're done, but we still have to clean up. - // Make sure nobody tries to start any new queries by making sure the err - // pointer is set. It is important that we do not overwrite its value; a - // connection could be closed by either this goroutine or one sending on - // the connection -- whoever closes the connection is assumed to have the - // more meaningful error message (as the other one will probably get - // net.errClosed), so that goroutine sets the error we expose while the - // other error is discarded. If the connection is lost while two - // goroutines are operating on the socket, it probably doesn't matter which - // error we expose so we don't try to do anything more complex. - l.connectionLock.Lock() - if l.err == nil { - l.err = err - } - l.cn.Close() - l.connectionLock.Unlock() - - // There might be a query in-flight; make sure nobody's waiting for a - // response to it, since there's not going to be one. - close(l.replyChan) - - // let the listener know we're done - close(l.notificationChan) - - // this ListenerConn is done -} - -// Listen sends a LISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Listen(channel string) (bool, error) { - return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) -} - -// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Unlisten(channel string) (bool, error) { - return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) -} - -// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery. -func (l *ListenerConn) UnlistenAll() (bool, error) { - return l.ExecSimpleQuery("UNLISTEN *") -} - -// Ping the remote server to make sure it's alive. Non-nil error means the -// connection has failed and should be abandoned. -func (l *ListenerConn) Ping() error { - sent, err := l.ExecSimpleQuery("") - if !sent { - return err - } - if err != nil { - // shouldn't happen - panic(err) - } - return nil -} - -// Attempt to send a query on the connection. Returns an error if sending the -// query failed, and the caller should initiate closure of this connection. -// The caller must be holding senderLock (see acquireSenderLock and -// releaseSenderLock). -func (l *ListenerConn) sendSimpleQuery(q string) (err error) { - defer errRecoverNoErrBadConn(&err) - - // must set connection state before sending the query - if !l.setState(connStateExpectResponse) { - panic("two queries running at the same time") - } - - // Can't use l.cn.writeBuf here because it uses the scratch buffer which - // might get overwritten by listenerConnLoop. - b := &writeBuf{ - buf: []byte("Q\x00\x00\x00\x00"), - pos: 1, - } - b.string(q) - l.cn.send(b) - - return nil -} - -// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable -// parameters) on the connection. The possible return values are: -// 1) "executed" is true; the query was executed to completion on the -// database server. If the query failed, err will be set to the error -// returned by the database, otherwise err will be nil. -// 2) If "executed" is false, the query could not be executed on the remote -// server. err will be non-nil. -// -// After a call to ExecSimpleQuery has returned an executed=false value, the -// connection has either been closed or will be closed shortly thereafter, and -// all subsequently executed queries will return an error. -func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { - if err = l.acquireSenderLock(); err != nil { - return false, err - } - defer l.releaseSenderLock() - - err = l.sendSimpleQuery(q) - if err != nil { - // We can't know what state the protocol is in, so we need to abandon - // this connection. - l.connectionLock.Lock() - // Set the error pointer if it hasn't been set already; see - // listenerConnMain. - if l.err == nil { - l.err = err - } - l.connectionLock.Unlock() - l.cn.c.Close() - return false, err - } - - // now we just wait for a reply.. - for { - m, ok := <-l.replyChan - if !ok { - // We lost the connection to server, don't bother waiting for a - // a response. err should have been set already. - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - return false, err - } - switch m.typ { - case 'Z': - // sanity check - if m.err != nil { - panic("m.err != nil") - } - // done; err might or might not be set - return true, err - - case 'E': - // sanity check - if m.err == nil { - panic("m.err == nil") - } - // server responded with an error; ReadyForQuery to follow - err = m.err - - default: - return false, fmt.Errorf("unknown response for simple query: %q", m.typ) - } - } -} - -// Close closes the connection. -func (l *ListenerConn) Close() error { - l.connectionLock.Lock() - if l.err != nil { - l.connectionLock.Unlock() - return errListenerConnClosed - } - l.err = errListenerConnClosed - l.connectionLock.Unlock() - // We can't send anything on the connection without holding senderLock. - // Simply close the net.Conn to wake up everyone operating on it. - return l.cn.c.Close() -} - -// Err returns the reason the connection was closed. It is not safe to call -// this function until l.Notify has been closed. -func (l *ListenerConn) Err() error { - return l.err -} - -var errListenerClosed = errors.New("pq: Listener has been closed") - -// ErrChannelAlreadyOpen is returned from Listen when a channel is already -// open. -var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") - -// ErrChannelNotOpen is returned from Unlisten when a channel is not open. -var ErrChannelNotOpen = errors.New("pq: channel is not open") - -// ListenerEventType is an enumeration of listener event types. -type ListenerEventType int - -const ( - // ListenerEventConnected is emitted only when the database connection - // has been initially initialized. The err argument of the callback - // will always be nil. - ListenerEventConnected ListenerEventType = iota - - // ListenerEventDisconnected is emitted after a database connection has - // been lost, either because of an error or because Close has been - // called. The err argument will be set to the reason the database - // connection was lost. - ListenerEventDisconnected - - // ListenerEventReconnected is emitted after a database connection has - // been re-established after connection loss. The err argument of the - // callback will always be nil. After this event has been emitted, a - // nil pq.Notification is sent on the Listener.Notify channel. - ListenerEventReconnected - - // ListenerEventConnectionAttemptFailed is emitted after a connection - // to the database was attempted, but failed. The err argument will be - // set to an error describing why the connection attempt did not - // succeed. - ListenerEventConnectionAttemptFailed -) - -// EventCallbackType is the event callback type. See also ListenerEventType -// constants' documentation. -type EventCallbackType func(event ListenerEventType, err error) - -// Listener provides an interface for listening to notifications from a -// PostgreSQL database. For general usage information, see section -// "Notifications". -// -// Listener can safely be used from concurrently running goroutines. -type Listener struct { - // Channel for receiving notifications from the database. In some cases a - // nil value will be sent. See section "Notifications" above. - Notify chan *Notification - - name string - minReconnectInterval time.Duration - maxReconnectInterval time.Duration - dialer Dialer - eventCallback EventCallbackType - - lock sync.Mutex - isClosed bool - reconnectCond *sync.Cond - cn *ListenerConn - connNotificationChan <-chan *Notification - channels map[string]struct{} -} - -// NewListener creates a new database connection dedicated to LISTEN / NOTIFY. -// -// name should be set to a connection string to be used to establish the -// database connection (see section "Connection String Parameters" above). -// -// minReconnectInterval controls the duration to wait before trying to -// re-establish the database connection after connection loss. After each -// consecutive failure this interval is doubled, until maxReconnectInterval is -// reached. Successfully completing the connection establishment procedure -// resets the interval back to minReconnectInterval. -// -// The last parameter eventCallback can be set to a function which will be -// called by the Listener when the state of the underlying database connection -// changes. This callback will be called by the goroutine which dispatches the -// notifications over the Notify channel, so you should try to avoid doing -// potentially time-consuming operations from the callback. -func NewListener(name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback) -} - -// NewDialListener is like NewListener but it takes a Dialer. -func NewDialListener(d Dialer, - name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - - l := &Listener{ - name: name, - minReconnectInterval: minReconnectInterval, - maxReconnectInterval: maxReconnectInterval, - dialer: d, - eventCallback: eventCallback, - - channels: make(map[string]struct{}), - - Notify: make(chan *Notification, 32), - } - l.reconnectCond = sync.NewCond(&l.lock) - - go l.listenerMain() - - return l -} - -// NotificationChannel returns the notification channel for this listener. -// This is the same channel as Notify, and will not be recreated during the -// life time of the Listener. -func (l *Listener) NotificationChannel() <-chan *Notification { - return l.Notify -} - -// Listen starts listening for notifications on a channel. Calls to this -// function will block until an acknowledgement has been received from the -// server. Note that Listener automatically re-establishes the connection -// after connection loss, so this function may block indefinitely if the -// connection can not be re-established. -// -// Listen will only fail in three conditions: -// 1) The channel is already open. The returned error will be -// ErrChannelAlreadyOpen. -// 2) The query was executed on the remote server, but PostgreSQL returned an -// error message in response to the query. The returned error will be a -// pq.Error containing the information the server supplied. -// 3) Close is called on the Listener before the request could be completed. -// -// The channel name is case-sensitive. -func (l *Listener) Listen(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // The server allows you to issue a LISTEN on a channel which is already - // open, but it seems useful to be able to detect this case to spot for - // mistakes in application logic. If the application genuinely does't - // care, it can check the exported error and ignore it. - _, exists := l.channels[channel] - if exists { - return ErrChannelAlreadyOpen - } - - if l.cn != nil { - // If gotResponse is true but error is set, the query was executed on - // the remote server, but resulted in an error. This should be - // relatively rare, so it's fine if we just pass the error to our - // caller. However, if gotResponse is false, we could not complete the - // query on the remote server and our underlying connection is about - // to go away, so we only add relname to l.channels, and wait for - // resync() to take care of the rest. - gotResponse, err := l.cn.Listen(channel) - if gotResponse && err != nil { - return err - } - } - - l.channels[channel] = struct{}{} - for l.cn == nil { - l.reconnectCond.Wait() - // we let go of the mutex for a while - if l.isClosed { - return errListenerClosed - } - } - - return nil -} - -// Unlisten removes a channel from the Listener's channel list. Returns -// ErrChannelNotOpen if the Listener is not listening on the specified channel. -// Returns immediately with no error if there is no connection. Note that you -// might still get notifications for this channel even after Unlisten has -// returned. -// -// The channel name is case-sensitive. -func (l *Listener) Unlisten(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // Similarly to LISTEN, this is not an error in Postgres, but it seems - // useful to distinguish from the normal conditions. - _, exists := l.channels[channel] - if !exists { - return ErrChannelNotOpen - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.Unlisten(channel) - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - delete(l.channels, channel) - return nil -} - -// UnlistenAll removes all channels from the Listener's channel list. Returns -// immediately with no error if there is no connection. Note that you might -// still get notifications for any of the deleted channels even after -// UnlistenAll has returned. -func (l *Listener) UnlistenAll() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.UnlistenAll() - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - l.channels = make(map[string]struct{}) - return nil -} - -// Ping the remote server to make sure it's alive. Non-nil return value means -// that there is no active connection. -func (l *Listener) Ping() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - if l.cn == nil { - return errors.New("no connection") - } - - return l.cn.Ping() -} - -// Clean up after losing the server connection. Returns l.cn.Err(), which -// should have the reason the connection was lost. -func (l *Listener) disconnectCleanup() error { - l.lock.Lock() - defer l.lock.Unlock() - - // sanity check; can't look at Err() until the channel has been closed - select { - case _, ok := <-l.connNotificationChan: - if ok { - panic("connNotificationChan not closed") - } - default: - panic("connNotificationChan not closed") - } - - err := l.cn.Err() - l.cn.Close() - l.cn = nil - return err -} - -// Synchronize the list of channels we want to be listening on with the server -// after the connection has been established. -func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { - doneChan := make(chan error) - go func(notificationChan <-chan *Notification) { - for channel := range l.channels { - // If we got a response, return that error to our caller as it's - // going to be more descriptive than cn.Err(). - gotResponse, err := cn.Listen(channel) - if gotResponse && err != nil { - doneChan <- err - return - } - - // If we couldn't reach the server, wait for notificationChan to - // close and then return the error message from the connection, as - // per ListenerConn's interface. - if err != nil { - for range notificationChan { - } - doneChan <- cn.Err() - return - } - } - doneChan <- nil - }(notificationChan) - - // Ignore notifications while synchronization is going on to avoid - // deadlocks. We have to send a nil notification over Notify anyway as - // we can't possibly know which notifications (if any) were lost while - // the connection was down, so there's no reason to try and process - // these messages at all. - for { - select { - case _, ok := <-notificationChan: - if !ok { - notificationChan = nil - } - - case err := <-doneChan: - return err - } - } -} - -// caller should NOT be holding l.lock -func (l *Listener) closed() bool { - l.lock.Lock() - defer l.lock.Unlock() - - return l.isClosed -} - -func (l *Listener) connect() error { - notificationChan := make(chan *Notification, 32) - cn, err := newDialListenerConn(l.dialer, l.name, notificationChan) - if err != nil { - return err - } - - l.lock.Lock() - defer l.lock.Unlock() - - err = l.resync(cn, notificationChan) - if err != nil { - cn.Close() - return err - } - - l.cn = cn - l.connNotificationChan = notificationChan - l.reconnectCond.Broadcast() - - return nil -} - -// Close disconnects the Listener from the database and shuts it down. -// Subsequent calls to its methods will return an error. Close returns an -// error if the connection has already been closed. -func (l *Listener) Close() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - l.cn.Close() - } - l.isClosed = true - - // Unblock calls to Listen() - l.reconnectCond.Broadcast() - - return nil -} - -func (l *Listener) emitEvent(event ListenerEventType, err error) { - if l.eventCallback != nil { - l.eventCallback(event, err) - } -} - -// Main logic here: maintain a connection to the server when possible, wait -// for notifications and emit events. -func (l *Listener) listenerConnLoop() { - var nextReconnect time.Time - - reconnectInterval := l.minReconnectInterval - for { - for { - err := l.connect() - if err == nil { - break - } - - if l.closed() { - return - } - l.emitEvent(ListenerEventConnectionAttemptFailed, err) - - time.Sleep(reconnectInterval) - reconnectInterval *= 2 - if reconnectInterval > l.maxReconnectInterval { - reconnectInterval = l.maxReconnectInterval - } - } - - if nextReconnect.IsZero() { - l.emitEvent(ListenerEventConnected, nil) - } else { - l.emitEvent(ListenerEventReconnected, nil) - l.Notify <- nil - } - - reconnectInterval = l.minReconnectInterval - nextReconnect = time.Now().Add(reconnectInterval) - - for { - notification, ok := <-l.connNotificationChan - if !ok { - // lost connection, loop again - break - } - l.Notify <- notification - } - - err := l.disconnectCleanup() - if l.closed() { - return - } - l.emitEvent(ListenerEventDisconnected, err) - - time.Sleep(time.Until(nextReconnect)) - } -} - -func (l *Listener) listenerMain() { - l.listenerConnLoop() - close(l.Notify) -} diff --git a/vendor/github.com/lib/pq/oid/doc.go b/vendor/github.com/lib/pq/oid/doc.go deleted file mode 100644 index caaede2..0000000 --- a/vendor/github.com/lib/pq/oid/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Package oid contains OID constants -// as defined by the Postgres server. -package oid - -// Oid is a Postgres Object ID. -type Oid uint32 diff --git a/vendor/github.com/lib/pq/oid/gen.go b/vendor/github.com/lib/pq/oid/gen.go deleted file mode 100644 index 7c634cd..0000000 --- a/vendor/github.com/lib/pq/oid/gen.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build ignore - -// Generate the table of OID values -// Run with 'go run gen.go'. -package main - -import ( - "database/sql" - "fmt" - "log" - "os" - "os/exec" - "strings" - - _ "github.com/lib/pq" -) - -// OID represent a postgres Object Identifier Type. -type OID struct { - ID int - Type string -} - -// Name returns an upper case version of the oid type. -func (o OID) Name() string { - return strings.ToUpper(o.Type) -} - -func main() { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - db, err := sql.Open("postgres", "") - if err != nil { - log.Fatal(err) - } - rows, err := db.Query(` - SELECT typname, oid - FROM pg_type WHERE oid < 10000 - ORDER BY oid; - `) - if err != nil { - log.Fatal(err) - } - oids := make([]*OID, 0) - for rows.Next() { - var oid OID - if err = rows.Scan(&oid.Type, &oid.ID); err != nil { - log.Fatal(err) - } - oids = append(oids, &oid) - } - if err = rows.Err(); err != nil { - log.Fatal(err) - } - cmd := exec.Command("gofmt") - cmd.Stderr = os.Stderr - w, err := cmd.StdinPipe() - if err != nil { - log.Fatal(err) - } - f, err := os.Create("types.go") - if err != nil { - log.Fatal(err) - } - cmd.Stdout = f - err = cmd.Start() - if err != nil { - log.Fatal(err) - } - fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.") - fmt.Fprintln(w, "\npackage oid") - fmt.Fprintln(w, "const (") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID) - } - fmt.Fprintln(w, ")") - fmt.Fprintln(w, "var TypeName = map[Oid]string{") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name()) - } - fmt.Fprintln(w, "}") - w.Close() - cmd.Wait() -} diff --git a/vendor/github.com/lib/pq/oid/types.go b/vendor/github.com/lib/pq/oid/types.go deleted file mode 100644 index ecc84c2..0000000 --- a/vendor/github.com/lib/pq/oid/types.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by gen.go. DO NOT EDIT. - -package oid - -const ( - T_bool Oid = 16 - T_bytea Oid = 17 - T_char Oid = 18 - T_name Oid = 19 - T_int8 Oid = 20 - T_int2 Oid = 21 - T_int2vector Oid = 22 - T_int4 Oid = 23 - T_regproc Oid = 24 - T_text Oid = 25 - T_oid Oid = 26 - T_tid Oid = 27 - T_xid Oid = 28 - T_cid Oid = 29 - T_oidvector Oid = 30 - T_pg_ddl_command Oid = 32 - T_pg_type Oid = 71 - T_pg_attribute Oid = 75 - T_pg_proc Oid = 81 - T_pg_class Oid = 83 - T_json Oid = 114 - T_xml Oid = 142 - T__xml Oid = 143 - T_pg_node_tree Oid = 194 - T__json Oid = 199 - T_smgr Oid = 210 - T_index_am_handler Oid = 325 - T_point Oid = 600 - T_lseg Oid = 601 - T_path Oid = 602 - T_box Oid = 603 - T_polygon Oid = 604 - T_line Oid = 628 - T__line Oid = 629 - T_cidr Oid = 650 - T__cidr Oid = 651 - T_float4 Oid = 700 - T_float8 Oid = 701 - T_abstime Oid = 702 - T_reltime Oid = 703 - T_tinterval Oid = 704 - T_unknown Oid = 705 - T_circle Oid = 718 - T__circle Oid = 719 - T_money Oid = 790 - T__money Oid = 791 - T_macaddr Oid = 829 - T_inet Oid = 869 - T__bool Oid = 1000 - T__bytea Oid = 1001 - T__char Oid = 1002 - T__name Oid = 1003 - T__int2 Oid = 1005 - T__int2vector Oid = 1006 - T__int4 Oid = 1007 - T__regproc Oid = 1008 - T__text Oid = 1009 - T__tid Oid = 1010 - T__xid Oid = 1011 - T__cid Oid = 1012 - T__oidvector Oid = 1013 - T__bpchar Oid = 1014 - T__varchar Oid = 1015 - T__int8 Oid = 1016 - T__point Oid = 1017 - T__lseg Oid = 1018 - T__path Oid = 1019 - T__box Oid = 1020 - T__float4 Oid = 1021 - T__float8 Oid = 1022 - T__abstime Oid = 1023 - T__reltime Oid = 1024 - T__tinterval Oid = 1025 - T__polygon Oid = 1027 - T__oid Oid = 1028 - T_aclitem Oid = 1033 - T__aclitem Oid = 1034 - T__macaddr Oid = 1040 - T__inet Oid = 1041 - T_bpchar Oid = 1042 - T_varchar Oid = 1043 - T_date Oid = 1082 - T_time Oid = 1083 - T_timestamp Oid = 1114 - T__timestamp Oid = 1115 - T__date Oid = 1182 - T__time Oid = 1183 - T_timestamptz Oid = 1184 - T__timestamptz Oid = 1185 - T_interval Oid = 1186 - T__interval Oid = 1187 - T__numeric Oid = 1231 - T_pg_database Oid = 1248 - T__cstring Oid = 1263 - T_timetz Oid = 1266 - T__timetz Oid = 1270 - T_bit Oid = 1560 - T__bit Oid = 1561 - T_varbit Oid = 1562 - T__varbit Oid = 1563 - T_numeric Oid = 1700 - T_refcursor Oid = 1790 - T__refcursor Oid = 2201 - T_regprocedure Oid = 2202 - T_regoper Oid = 2203 - T_regoperator Oid = 2204 - T_regclass Oid = 2205 - T_regtype Oid = 2206 - T__regprocedure Oid = 2207 - T__regoper Oid = 2208 - T__regoperator Oid = 2209 - T__regclass Oid = 2210 - T__regtype Oid = 2211 - T_record Oid = 2249 - T_cstring Oid = 2275 - T_any Oid = 2276 - T_anyarray Oid = 2277 - T_void Oid = 2278 - T_trigger Oid = 2279 - T_language_handler Oid = 2280 - T_internal Oid = 2281 - T_opaque Oid = 2282 - T_anyelement Oid = 2283 - T__record Oid = 2287 - T_anynonarray Oid = 2776 - T_pg_authid Oid = 2842 - T_pg_auth_members Oid = 2843 - T__txid_snapshot Oid = 2949 - T_uuid Oid = 2950 - T__uuid Oid = 2951 - T_txid_snapshot Oid = 2970 - T_fdw_handler Oid = 3115 - T_pg_lsn Oid = 3220 - T__pg_lsn Oid = 3221 - T_tsm_handler Oid = 3310 - T_anyenum Oid = 3500 - T_tsvector Oid = 3614 - T_tsquery Oid = 3615 - T_gtsvector Oid = 3642 - T__tsvector Oid = 3643 - T__gtsvector Oid = 3644 - T__tsquery Oid = 3645 - T_regconfig Oid = 3734 - T__regconfig Oid = 3735 - T_regdictionary Oid = 3769 - T__regdictionary Oid = 3770 - T_jsonb Oid = 3802 - T__jsonb Oid = 3807 - T_anyrange Oid = 3831 - T_event_trigger Oid = 3838 - T_int4range Oid = 3904 - T__int4range Oid = 3905 - T_numrange Oid = 3906 - T__numrange Oid = 3907 - T_tsrange Oid = 3908 - T__tsrange Oid = 3909 - T_tstzrange Oid = 3910 - T__tstzrange Oid = 3911 - T_daterange Oid = 3912 - T__daterange Oid = 3913 - T_int8range Oid = 3926 - T__int8range Oid = 3927 - T_pg_shseclabel Oid = 4066 - T_regnamespace Oid = 4089 - T__regnamespace Oid = 4090 - T_regrole Oid = 4096 - T__regrole Oid = 4097 -) - -var TypeName = map[Oid]string{ - T_bool: "BOOL", - T_bytea: "BYTEA", - T_char: "CHAR", - T_name: "NAME", - T_int8: "INT8", - T_int2: "INT2", - T_int2vector: "INT2VECTOR", - T_int4: "INT4", - T_regproc: "REGPROC", - T_text: "TEXT", - T_oid: "OID", - T_tid: "TID", - T_xid: "XID", - T_cid: "CID", - T_oidvector: "OIDVECTOR", - T_pg_ddl_command: "PG_DDL_COMMAND", - T_pg_type: "PG_TYPE", - T_pg_attribute: "PG_ATTRIBUTE", - T_pg_proc: "PG_PROC", - T_pg_class: "PG_CLASS", - T_json: "JSON", - T_xml: "XML", - T__xml: "_XML", - T_pg_node_tree: "PG_NODE_TREE", - T__json: "_JSON", - T_smgr: "SMGR", - T_index_am_handler: "INDEX_AM_HANDLER", - T_point: "POINT", - T_lseg: "LSEG", - T_path: "PATH", - T_box: "BOX", - T_polygon: "POLYGON", - T_line: "LINE", - T__line: "_LINE", - T_cidr: "CIDR", - T__cidr: "_CIDR", - T_float4: "FLOAT4", - T_float8: "FLOAT8", - T_abstime: "ABSTIME", - T_reltime: "RELTIME", - T_tinterval: "TINTERVAL", - T_unknown: "UNKNOWN", - T_circle: "CIRCLE", - T__circle: "_CIRCLE", - T_money: "MONEY", - T__money: "_MONEY", - T_macaddr: "MACADDR", - T_inet: "INET", - T__bool: "_BOOL", - T__bytea: "_BYTEA", - T__char: "_CHAR", - T__name: "_NAME", - T__int2: "_INT2", - T__int2vector: "_INT2VECTOR", - T__int4: "_INT4", - T__regproc: "_REGPROC", - T__text: "_TEXT", - T__tid: "_TID", - T__xid: "_XID", - T__cid: "_CID", - T__oidvector: "_OIDVECTOR", - T__bpchar: "_BPCHAR", - T__varchar: "_VARCHAR", - T__int8: "_INT8", - T__point: "_POINT", - T__lseg: "_LSEG", - T__path: "_PATH", - T__box: "_BOX", - T__float4: "_FLOAT4", - T__float8: "_FLOAT8", - T__abstime: "_ABSTIME", - T__reltime: "_RELTIME", - T__tinterval: "_TINTERVAL", - T__polygon: "_POLYGON", - T__oid: "_OID", - T_aclitem: "ACLITEM", - T__aclitem: "_ACLITEM", - T__macaddr: "_MACADDR", - T__inet: "_INET", - T_bpchar: "BPCHAR", - T_varchar: "VARCHAR", - T_date: "DATE", - T_time: "TIME", - T_timestamp: "TIMESTAMP", - T__timestamp: "_TIMESTAMP", - T__date: "_DATE", - T__time: "_TIME", - T_timestamptz: "TIMESTAMPTZ", - T__timestamptz: "_TIMESTAMPTZ", - T_interval: "INTERVAL", - T__interval: "_INTERVAL", - T__numeric: "_NUMERIC", - T_pg_database: "PG_DATABASE", - T__cstring: "_CSTRING", - T_timetz: "TIMETZ", - T__timetz: "_TIMETZ", - T_bit: "BIT", - T__bit: "_BIT", - T_varbit: "VARBIT", - T__varbit: "_VARBIT", - T_numeric: "NUMERIC", - T_refcursor: "REFCURSOR", - T__refcursor: "_REFCURSOR", - T_regprocedure: "REGPROCEDURE", - T_regoper: "REGOPER", - T_regoperator: "REGOPERATOR", - T_regclass: "REGCLASS", - T_regtype: "REGTYPE", - T__regprocedure: "_REGPROCEDURE", - T__regoper: "_REGOPER", - T__regoperator: "_REGOPERATOR", - T__regclass: "_REGCLASS", - T__regtype: "_REGTYPE", - T_record: "RECORD", - T_cstring: "CSTRING", - T_any: "ANY", - T_anyarray: "ANYARRAY", - T_void: "VOID", - T_trigger: "TRIGGER", - T_language_handler: "LANGUAGE_HANDLER", - T_internal: "INTERNAL", - T_opaque: "OPAQUE", - T_anyelement: "ANYELEMENT", - T__record: "_RECORD", - T_anynonarray: "ANYNONARRAY", - T_pg_authid: "PG_AUTHID", - T_pg_auth_members: "PG_AUTH_MEMBERS", - T__txid_snapshot: "_TXID_SNAPSHOT", - T_uuid: "UUID", - T__uuid: "_UUID", - T_txid_snapshot: "TXID_SNAPSHOT", - T_fdw_handler: "FDW_HANDLER", - T_pg_lsn: "PG_LSN", - T__pg_lsn: "_PG_LSN", - T_tsm_handler: "TSM_HANDLER", - T_anyenum: "ANYENUM", - T_tsvector: "TSVECTOR", - T_tsquery: "TSQUERY", - T_gtsvector: "GTSVECTOR", - T__tsvector: "_TSVECTOR", - T__gtsvector: "_GTSVECTOR", - T__tsquery: "_TSQUERY", - T_regconfig: "REGCONFIG", - T__regconfig: "_REGCONFIG", - T_regdictionary: "REGDICTIONARY", - T__regdictionary: "_REGDICTIONARY", - T_jsonb: "JSONB", - T__jsonb: "_JSONB", - T_anyrange: "ANYRANGE", - T_event_trigger: "EVENT_TRIGGER", - T_int4range: "INT4RANGE", - T__int4range: "_INT4RANGE", - T_numrange: "NUMRANGE", - T__numrange: "_NUMRANGE", - T_tsrange: "TSRANGE", - T__tsrange: "_TSRANGE", - T_tstzrange: "TSTZRANGE", - T__tstzrange: "_TSTZRANGE", - T_daterange: "DATERANGE", - T__daterange: "_DATERANGE", - T_int8range: "INT8RANGE", - T__int8range: "_INT8RANGE", - T_pg_shseclabel: "PG_SHSECLABEL", - T_regnamespace: "REGNAMESPACE", - T__regnamespace: "_REGNAMESPACE", - T_regrole: "REGROLE", - T__regrole: "_REGROLE", -} diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go deleted file mode 100644 index c6aa5b9..0000000 --- a/vendor/github.com/lib/pq/rows.go +++ /dev/null @@ -1,93 +0,0 @@ -package pq - -import ( - "math" - "reflect" - "time" - - "github.com/lib/pq/oid" -) - -const headerSize = 4 - -type fieldDesc struct { - // The object ID of the data type. - OID oid.Oid - // The data type size (see pg_type.typlen). - // Note that negative values denote variable-width types. - Len int - // The type modifier (see pg_attribute.atttypmod). - // The meaning of the modifier is type-specific. - Mod int -} - -func (fd fieldDesc) Type() reflect.Type { - switch fd.OID { - case oid.T_int8: - return reflect.TypeOf(int64(0)) - case oid.T_int4: - return reflect.TypeOf(int32(0)) - case oid.T_int2: - return reflect.TypeOf(int16(0)) - case oid.T_varchar, oid.T_text: - return reflect.TypeOf("") - case oid.T_bool: - return reflect.TypeOf(false) - case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz: - return reflect.TypeOf(time.Time{}) - case oid.T_bytea: - return reflect.TypeOf([]byte(nil)) - default: - return reflect.TypeOf(new(interface{})).Elem() - } -} - -func (fd fieldDesc) Name() string { - return oid.TypeName[fd.OID] -} - -func (fd fieldDesc) Length() (length int64, ok bool) { - switch fd.OID { - case oid.T_text, oid.T_bytea: - return math.MaxInt64, true - case oid.T_varchar, oid.T_bpchar: - return int64(fd.Mod - headerSize), true - default: - return 0, false - } -} - -func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) { - switch fd.OID { - case oid.T_numeric, oid.T__numeric: - mod := fd.Mod - headerSize - precision = int64((mod >> 16) & 0xffff) - scale = int64(mod & 0xffff) - return precision, scale, true - default: - return 0, 0, false - } -} - -// ColumnTypeScanType returns the value type that can be used to scan types into. -func (rs *rows) ColumnTypeScanType(index int) reflect.Type { - return rs.colTyps[index].Type() -} - -// ColumnTypeDatabaseTypeName return the database system type name. -func (rs *rows) ColumnTypeDatabaseTypeName(index int) string { - return rs.colTyps[index].Name() -} - -// ColumnTypeLength returns the length of the column type if the column is a -// variable length type. If the column is not a variable length type ok -// should return false. -func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) { - return rs.colTyps[index].Length() -} - -// ColumnTypePrecisionScale should return the precision and scale for decimal -// types. If not applicable, ok should be false. -func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { - return rs.colTyps[index].PrecisionScale() -} diff --git a/vendor/github.com/lib/pq/scram/scram.go b/vendor/github.com/lib/pq/scram/scram.go deleted file mode 100644 index 477216b..0000000 --- a/vendor/github.com/lib/pq/scram/scram.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) 2014 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802. -// -// http://tools.ietf.org/html/rfc5802 -// -package scram - -import ( - "bytes" - "crypto/hmac" - "crypto/rand" - "encoding/base64" - "fmt" - "hash" - "strconv" - "strings" -) - -// Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc). -// -// A Client may be used within a SASL conversation with logic resembling: -// -// var in []byte -// var client = scram.NewClient(sha1.New, user, pass) -// for client.Step(in) { -// out := client.Out() -// // send out to server -// in := serverOut -// } -// if client.Err() != nil { -// // auth failed -// } -// -type Client struct { - newHash func() hash.Hash - - user string - pass string - step int - out bytes.Buffer - err error - - clientNonce []byte - serverNonce []byte - saltedPass []byte - authMsg bytes.Buffer -} - -// NewClient returns a new SCRAM-* client with the provided hash algorithm. -// -// For SCRAM-SHA-256, for example, use: -// -// client := scram.NewClient(sha256.New, user, pass) -// -func NewClient(newHash func() hash.Hash, user, pass string) *Client { - c := &Client{ - newHash: newHash, - user: user, - pass: pass, - } - c.out.Grow(256) - c.authMsg.Grow(256) - return c -} - -// Out returns the data to be sent to the server in the current step. -func (c *Client) Out() []byte { - if c.out.Len() == 0 { - return nil - } - return c.out.Bytes() -} - -// Err returns the error that occurred, or nil if there were no errors. -func (c *Client) Err() error { - return c.err -} - -// SetNonce sets the client nonce to the provided value. -// If not set, the nonce is generated automatically out of crypto/rand on the first step. -func (c *Client) SetNonce(nonce []byte) { - c.clientNonce = nonce -} - -var escaper = strings.NewReplacer("=", "=3D", ",", "=2C") - -// Step processes the incoming data from the server and makes the -// next round of data for the server available via Client.Out. -// Step returns false if there are no errors and more data is -// still expected. -func (c *Client) Step(in []byte) bool { - c.out.Reset() - if c.step > 2 || c.err != nil { - return false - } - c.step++ - switch c.step { - case 1: - c.err = c.step1(in) - case 2: - c.err = c.step2(in) - case 3: - c.err = c.step3(in) - } - return c.step > 2 || c.err != nil -} - -func (c *Client) step1(in []byte) error { - if len(c.clientNonce) == 0 { - const nonceLen = 16 - buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen)) - if _, err := rand.Read(buf[:nonceLen]); err != nil { - return fmt.Errorf("cannot read random SCRAM-SHA-256 nonce from operating system: %v", err) - } - c.clientNonce = buf[nonceLen:] - b64.Encode(c.clientNonce, buf[:nonceLen]) - } - c.authMsg.WriteString("n=") - escaper.WriteString(&c.authMsg, c.user) - c.authMsg.WriteString(",r=") - c.authMsg.Write(c.clientNonce) - - c.out.WriteString("n,,") - c.out.Write(c.authMsg.Bytes()) - return nil -} - -var b64 = base64.StdEncoding - -func (c *Client) step2(in []byte) error { - c.authMsg.WriteByte(',') - c.authMsg.Write(in) - - fields := bytes.Split(in, []byte(",")) - if len(fields) != 3 { - return fmt.Errorf("expected 3 fields in first SCRAM-SHA-256 server message, got %d: %q", len(fields), in) - } - if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 { - return fmt.Errorf("server sent an invalid SCRAM-SHA-256 nonce: %q", fields[0]) - } - if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 { - return fmt.Errorf("server sent an invalid SCRAM-SHA-256 salt: %q", fields[1]) - } - if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 { - return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2]) - } - - c.serverNonce = fields[0][2:] - if !bytes.HasPrefix(c.serverNonce, c.clientNonce) { - return fmt.Errorf("server SCRAM-SHA-256 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce) - } - - salt := make([]byte, b64.DecodedLen(len(fields[1][2:]))) - n, err := b64.Decode(salt, fields[1][2:]) - if err != nil { - return fmt.Errorf("cannot decode SCRAM-SHA-256 salt sent by server: %q", fields[1]) - } - salt = salt[:n] - iterCount, err := strconv.Atoi(string(fields[2][2:])) - if err != nil { - return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2]) - } - c.saltPassword(salt, iterCount) - - c.authMsg.WriteString(",c=biws,r=") - c.authMsg.Write(c.serverNonce) - - c.out.WriteString("c=biws,r=") - c.out.Write(c.serverNonce) - c.out.WriteString(",p=") - c.out.Write(c.clientProof()) - return nil -} - -func (c *Client) step3(in []byte) error { - var isv, ise bool - var fields = bytes.Split(in, []byte(",")) - if len(fields) == 1 { - isv = bytes.HasPrefix(fields[0], []byte("v=")) - ise = bytes.HasPrefix(fields[0], []byte("e=")) - } - if ise { - return fmt.Errorf("SCRAM-SHA-256 authentication error: %s", fields[0][2:]) - } else if !isv { - return fmt.Errorf("unsupported SCRAM-SHA-256 final message from server: %q", in) - } - if !bytes.Equal(c.serverSignature(), fields[0][2:]) { - return fmt.Errorf("cannot authenticate SCRAM-SHA-256 server signature: %q", fields[0][2:]) - } - return nil -} - -func (c *Client) saltPassword(salt []byte, iterCount int) { - mac := hmac.New(c.newHash, []byte(c.pass)) - mac.Write(salt) - mac.Write([]byte{0, 0, 0, 1}) - ui := mac.Sum(nil) - hi := make([]byte, len(ui)) - copy(hi, ui) - for i := 1; i < iterCount; i++ { - mac.Reset() - mac.Write(ui) - mac.Sum(ui[:0]) - for j, b := range ui { - hi[j] ^= b - } - } - c.saltedPass = hi -} - -func (c *Client) clientProof() []byte { - mac := hmac.New(c.newHash, c.saltedPass) - mac.Write([]byte("Client Key")) - clientKey := mac.Sum(nil) - hash := c.newHash() - hash.Write(clientKey) - storedKey := hash.Sum(nil) - mac = hmac.New(c.newHash, storedKey) - mac.Write(c.authMsg.Bytes()) - clientProof := mac.Sum(nil) - for i, b := range clientKey { - clientProof[i] ^= b - } - clientProof64 := make([]byte, b64.EncodedLen(len(clientProof))) - b64.Encode(clientProof64, clientProof) - return clientProof64 -} - -func (c *Client) serverSignature() []byte { - mac := hmac.New(c.newHash, c.saltedPass) - mac.Write([]byte("Server Key")) - serverKey := mac.Sum(nil) - - mac = hmac.New(c.newHash, serverKey) - mac.Write(c.authMsg.Bytes()) - serverSignature := mac.Sum(nil) - - encoded := make([]byte, b64.EncodedLen(len(serverSignature))) - b64.Encode(encoded, serverSignature) - return encoded -} diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go deleted file mode 100644 index d902084..0000000 --- a/vendor/github.com/lib/pq/ssl.go +++ /dev/null @@ -1,175 +0,0 @@ -package pq - -import ( - "crypto/tls" - "crypto/x509" - "io/ioutil" - "net" - "os" - "os/user" - "path/filepath" -) - -// ssl generates a function to upgrade a net.Conn based on the "sslmode" and -// related settings. The function is nil when no upgrade should take place. -func ssl(o values) (func(net.Conn) (net.Conn, error), error) { - verifyCaOnly := false - tlsConf := tls.Config{} - switch mode := o["sslmode"]; mode { - // "require" is the default. - case "", "require": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - - // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: - // - // Note: For backwards compatibility with earlier versions of - // PostgreSQL, if a root CA file exists, the behavior of - // sslmode=require will be the same as that of verify-ca, meaning the - // server certificate is validated against the CA. Relying on this - // behavior is discouraged, and applications that need certificate - // validation should always use verify-ca or verify-full. - if sslrootcert, ok := o["sslrootcert"]; ok { - if _, err := os.Stat(sslrootcert); err == nil { - verifyCaOnly = true - } else { - delete(o, "sslrootcert") - } - } - case "verify-ca": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - verifyCaOnly = true - case "verify-full": - tlsConf.ServerName = o["host"] - case "disable": - return nil, nil - default: - return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) - } - - err := sslClientCertificates(&tlsConf, o) - if err != nil { - return nil, err - } - err = sslCertificateAuthority(&tlsConf, o) - if err != nil { - return nil, err - } - - // Accept renegotiation requests initiated by the backend. - // - // Renegotiation was deprecated then removed from PostgreSQL 9.5, but - // the default configuration of older versions has it enabled. Redshift - // also initiates renegotiations and cannot be reconfigured. - tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient - - return func(conn net.Conn) (net.Conn, error) { - client := tls.Client(conn, &tlsConf) - if verifyCaOnly { - err := sslVerifyCertificateAuthority(client, &tlsConf) - if err != nil { - return nil, err - } - } - return client, nil - }, nil -} - -// sslClientCertificates adds the certificate specified in the "sslcert" and -// "sslkey" settings, or if they aren't set, from the .postgresql directory -// in the user's home directory. The configured files must exist and have -// the correct permissions. -func sslClientCertificates(tlsConf *tls.Config, o values) error { - // user.Current() might fail when cross-compiling. We have to ignore the - // error and continue without home directory defaults, since we wouldn't - // know from where to load them. - user, _ := user.Current() - - // In libpq, the client certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037 - sslcert := o["sslcert"] - if len(sslcert) == 0 && user != nil { - sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045 - if len(sslcert) == 0 { - return nil - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054 - if _, err := os.Stat(sslcert); os.IsNotExist(err) { - return nil - } else if err != nil { - return err - } - - // In libpq, the ssl key is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222 - sslkey := o["sslkey"] - if len(sslkey) == 0 && user != nil { - sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") - } - - if len(sslkey) > 0 { - if err := sslKeyPermissions(sslkey); err != nil { - return err - } - } - - cert, err := tls.LoadX509KeyPair(sslcert, sslkey) - if err != nil { - return err - } - - tlsConf.Certificates = []tls.Certificate{cert} - return nil -} - -// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting. -func sslCertificateAuthority(tlsConf *tls.Config, o values) error { - // In libpq, the root certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951 - if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 { - tlsConf.RootCAs = x509.NewCertPool() - - cert, err := ioutil.ReadFile(sslrootcert) - if err != nil { - return err - } - - if !tlsConf.RootCAs.AppendCertsFromPEM(cert) { - return fmterrorf("couldn't parse pem in sslrootcert") - } - } - - return nil -} - -// sslVerifyCertificateAuthority carries out a TLS handshake to the server and -// verifies the presented certificate against the CA, i.e. the one specified in -// sslrootcert or the system CA if sslrootcert was not specified. -func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error { - err := client.Handshake() - if err != nil { - return err - } - certs := client.ConnectionState().PeerCertificates - opts := x509.VerifyOptions{ - DNSName: client.ConnectionState().ServerName, - Intermediates: x509.NewCertPool(), - Roots: tlsConf.RootCAs, - } - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - _, err = certs[0].Verify(opts) - return err -} diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go deleted file mode 100644 index 3b7c3a2..0000000 --- a/vendor/github.com/lib/pq/ssl_permissions.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package pq - -import "os" - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(sslkey string) error { - info, err := os.Stat(sslkey) - if err != nil { - return err - } - if info.Mode().Perm()&0077 != 0 { - return ErrSSLKeyHasWorldPermissions - } - return nil -} diff --git a/vendor/github.com/lib/pq/ssl_windows.go b/vendor/github.com/lib/pq/ssl_windows.go deleted file mode 100644 index 5d2c763..0000000 --- a/vendor/github.com/lib/pq/ssl_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package pq - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(string) error { return nil } diff --git a/vendor/github.com/lib/pq/url.go b/vendor/github.com/lib/pq/url.go deleted file mode 100644 index f4d8a7c..0000000 --- a/vendor/github.com/lib/pq/url.go +++ /dev/null @@ -1,76 +0,0 @@ -package pq - -import ( - "fmt" - "net" - nurl "net/url" - "sort" - "strings" -) - -// ParseURL no longer needs to be used by clients of this library since supplying a URL as a -// connection string to sql.Open() is now supported: -// -// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full") -// -// It remains exported here for backwards-compatibility. -// -// ParseURL converts a url to a connection string for driver.Open. -// Example: -// -// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full" -// -// converts to: -// -// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full" -// -// A minimal example: -// -// "postgres://" -// -// This will be blank, causing driver.Open to use all of the defaults -func ParseURL(url string) (string, error) { - u, err := nurl.Parse(url) - if err != nil { - return "", err - } - - if u.Scheme != "postgres" && u.Scheme != "postgresql" { - return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) - } - - var kvs []string - escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) - accrue := func(k, v string) { - if v != "" { - kvs = append(kvs, k+"="+escaper.Replace(v)) - } - } - - if u.User != nil { - v := u.User.Username() - accrue("user", v) - - v, _ = u.User.Password() - accrue("password", v) - } - - if host, port, err := net.SplitHostPort(u.Host); err != nil { - accrue("host", u.Host) - } else { - accrue("host", host) - accrue("port", port) - } - - if u.Path != "" { - accrue("dbname", u.Path[1:]) - } - - q := u.Query() - for k := range q { - accrue(k, q.Get(k)) - } - - sort.Strings(kvs) // Makes testing easier (not a performance concern) - return strings.Join(kvs, " "), nil -} diff --git a/vendor/github.com/lib/pq/user_posix.go b/vendor/github.com/lib/pq/user_posix.go deleted file mode 100644 index bf98252..0000000 --- a/vendor/github.com/lib/pq/user_posix.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. - -// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun - -package pq - -import ( - "os" - "os/user" -) - -func userCurrent() (string, error) { - u, err := user.Current() - if err == nil { - return u.Username, nil - } - - name := os.Getenv("USER") - if name != "" { - return name, nil - } - - return "", ErrCouldNotDetectUsername -} diff --git a/vendor/github.com/lib/pq/user_windows.go b/vendor/github.com/lib/pq/user_windows.go deleted file mode 100644 index 2b69126..0000000 --- a/vendor/github.com/lib/pq/user_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. -package pq - -import ( - "path/filepath" - "syscall" -) - -// Perform Windows user name lookup identically to libpq. -// -// The PostgreSQL code makes use of the legacy Win32 function -// GetUserName, and that function has not been imported into stock Go. -// GetUserNameEx is available though, the difference being that a -// wider range of names are available. To get the output to be the -// same as GetUserName, only the base (or last) component of the -// result is returned. -func userCurrent() (string, error) { - pw_name := make([]uint16, 128) - pwname_size := uint32(len(pw_name)) - 1 - err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size) - if err != nil { - return "", ErrCouldNotDetectUsername - } - s := syscall.UTF16ToString(pw_name) - u := filepath.Base(s) - return u, nil -} diff --git a/vendor/github.com/lib/pq/uuid.go b/vendor/github.com/lib/pq/uuid.go deleted file mode 100644 index 9a1b9e0..0000000 --- a/vendor/github.com/lib/pq/uuid.go +++ /dev/null @@ -1,23 +0,0 @@ -package pq - -import ( - "encoding/hex" - "fmt" -) - -// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format. -func decodeUUIDBinary(src []byte) ([]byte, error) { - if len(src) != 16 { - return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src)) - } - - dst := make([]byte, 36) - dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-' - hex.Encode(dst[0:], src[0:4]) - hex.Encode(dst[9:], src[4:6]) - hex.Encode(dst[14:], src[6:8]) - hex.Encode(dst[19:], src[8:10]) - hex.Encode(dst[24:], src[10:16]) - - return dst, nil -} diff --git a/vendor/github.com/technoweenie/multipartstreamer/LICENSE b/vendor/github.com/technoweenie/multipartstreamer/LICENSE deleted file mode 100644 index 20d92fb..0000000 --- a/vendor/github.com/technoweenie/multipartstreamer/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2013-* rick olson - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/technoweenie/multipartstreamer/README.md b/vendor/github.com/technoweenie/multipartstreamer/README.md deleted file mode 100644 index dc1f824..0000000 --- a/vendor/github.com/technoweenie/multipartstreamer/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# multipartstreamer - -Package multipartstreamer helps you encode large files in MIME multipart format -without reading the entire content into memory. It uses io.MultiReader to -combine an inner multipart.Reader with a file handle. - -```go -package main - -import ( - "github.com/technoweenie/multipartstreamer.go" - "net/http" -) - -func main() { - ms := multipartstreamer.New() - - ms.WriteFields(map[string]string{ - "key": "some-key", - "AWSAccessKeyId": "ABCDEF", - "acl": "some-acl", - }) - - // Add any io.Reader to the multipart.Reader. - ms.WriteReader("file", "filename", some_ioReader, size) - - // Shortcut for adding local file. - ms.WriteFile("file", "path/to/file") - - req, _ := http.NewRequest("POST", "someurl", nil) - ms.SetupRequest(req) - - res, _ := http.DefaultClient.Do(req) -} -``` - -One limitation: You can only write a single file. - -## TODO - -* Multiple files? - -## Credits - -Heavily inspired by James - -https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/Zjg5l4nKcQ0 diff --git a/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go b/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go deleted file mode 100644 index 26d8e85..0000000 --- a/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Package multipartstreamer helps you encode large files in MIME multipart format -without reading the entire content into memory. It uses io.MultiReader to -combine an inner multipart.Reader with a file handle. -*/ -package multipartstreamer - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "os" - "path/filepath" -) - -type MultipartStreamer struct { - ContentType string - bodyBuffer *bytes.Buffer - bodyWriter *multipart.Writer - closeBuffer *bytes.Buffer - reader io.Reader - contentLength int64 -} - -// New initializes a new MultipartStreamer. -func New() (m *MultipartStreamer) { - m = &MultipartStreamer{bodyBuffer: new(bytes.Buffer)} - - m.bodyWriter = multipart.NewWriter(m.bodyBuffer) - boundary := m.bodyWriter.Boundary() - m.ContentType = "multipart/form-data; boundary=" + boundary - - closeBoundary := fmt.Sprintf("\r\n--%s--\r\n", boundary) - m.closeBuffer = bytes.NewBufferString(closeBoundary) - - return -} - -// WriteFields writes multiple form fields to the multipart.Writer. -func (m *MultipartStreamer) WriteFields(fields map[string]string) error { - var err error - - for key, value := range fields { - err = m.bodyWriter.WriteField(key, value) - if err != nil { - return err - } - } - - return nil -} - -// WriteReader adds an io.Reader to get the content of a file. The reader is -// not accessed until the multipart.Reader is copied to some output writer. -func (m *MultipartStreamer) WriteReader(key, filename string, size int64, reader io.Reader) (err error) { - m.reader = reader - m.contentLength = size - - _, err = m.bodyWriter.CreateFormFile(key, filename) - return -} - -// WriteFile is a shortcut for adding a local file as an io.Reader. -func (m *MultipartStreamer) WriteFile(key, filename string) error { - fh, err := os.Open(filename) - if err != nil { - return err - } - - stat, err := fh.Stat() - if err != nil { - return err - } - - return m.WriteReader(key, filepath.Base(filename), stat.Size(), fh) -} - -// SetupRequest sets up the http.Request body, and some crucial HTTP headers. -func (m *MultipartStreamer) SetupRequest(req *http.Request) { - req.Body = m.GetReader() - req.Header.Add("Content-Type", m.ContentType) - req.ContentLength = m.Len() -} - -func (m *MultipartStreamer) Boundary() string { - return m.bodyWriter.Boundary() -} - -// Len calculates the byte size of the multipart content. -func (m *MultipartStreamer) Len() int64 { - return m.contentLength + int64(m.bodyBuffer.Len()) + int64(m.closeBuffer.Len()) -} - -// GetReader gets an io.ReadCloser for passing to an http.Request. -func (m *MultipartStreamer) GetReader() io.ReadCloser { - reader := io.MultiReader(m.bodyBuffer, m.reader, m.closeBuffer) - return ioutil.NopCloser(reader) -}