Skip to content

Instantly share code, notes, and snippets.

@mshafiee
Last active November 23, 2016 21:57
Show Gist options
  • Save mshafiee/36531d2a772b7f117aa4304c6edb0c1c to your computer and use it in GitHub Desktop.
Save mshafiee/36531d2a772b7f117aa4304c6edb0c1c to your computer and use it in GitHub Desktop.
/*
Mohammad Shafiee
Parsian Business Accelerator
www.parsian.ac
muhammad.shafiee-at-gmail.com
*/
package data
import (
"fmt"
"github.com/couchbase/gocb"
)
/*
How to use:
n1qlQueryString := `SELECT City, State, Contract FROM default WHERE objType=? AND ARRAY_CONTAINS (Phone, ?);`
var QueryParams []interface{}
QueryParams = append(QueryParams, "ARIACODE")
QueryParams = append(QueryParams, "98912440")
results, err := ExecuteN1qlQuery(n1qlQueryString, QueryParams, Bucket)
if err != nil {
fmt.Println(err.Error())
}
for _, r := range results {
fmt.Println(r.(map[string]interface{})["City"])
fmt.Println(r.(map[string]interface{})["State"])
fmt.Println(r.(map[string]interface{})["Contract"])
fmt.Println(r.(map[string]interface{})["ObjType"])
//
// If wildcard is used, like this: SELECT * FROM default ->
// fmt.Println(r.(map[string]interface{})["default"].(map[string]interface{})["City"])
//
}
*/
func ExecuteN1qlQuery(n1qlQueryString string, queryParams []interface{}, bucket *gocb.Bucket) (interfaces []interface{}, err error) {
n1qlQuery := gocb.NewN1qlQuery(n1qlQueryString)
queryResult, err := bucket.ExecuteN1qlQuery(n1qlQuery, queryParams)
if err != nil {
fmt.Println("N1QL query error: ", err)
return nil, err
}
var results []interface{}
var result interface{}
for queryResult.Next(&result) {
results = append(results, result)
}
if err = queryResult.Close(); err != nil {
fmt.Println("N1ql query error: ", err)
return results, err
}
return results, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment