コード例 #1
0
ファイル: ping.go プロジェクト: couchbasedeps/go_n1ql
func main() {

	flag.Parse()

	n1ql, err := sql.Open("n1ql", *serverURL)
	if err != nil {
		log.Fatal(err)
		fmt.Println("Error in open")
	}

	err = n1ql.Ping()
	if err != nil {
		fmt.Println("Error in ping")
		log.Fatal(err)

	}

	ac := []byte(`[{"user": "******", "pass": "******"}]`)

	go_n1ql.SetQueryParams("creds", string(ac))
	go_n1ql.SetQueryParams("timeout", "10s")

	rows, err := n1ql.Query("create index idx on `beer-sample`(abv)")

	if err != nil {
		fmt.Println("Error in query. Error", err)
	}

	if err == nil {
		for rows.Next() {
			var row string
			if err := rows.Scan(&row); err != nil {
				log.Fatal(err)
			}
			log.Printf(" Row %v", row)
		}
	}

	rows, err = n1ql.Query("select * from `beer-sample` where abv is not null limit 10")

	if err != nil {
		fmt.Println("Error in query")
		log.Fatal(err)
	}

	for rows.Next() {
		var row string
		if err := rows.Scan(&row); err != nil {
			log.Fatal(err)
		}
		log.Printf(" Row %v", row)
	}

}
コード例 #2
0
ファイル: pop.go プロジェクト: couchbaselabs/go_cbq
func setNewParamPop(name string, paramst *Stack) (int, string) {
	newval, err_code, err_str := paramst.Top()
	if err_code != 0 {
		return err_code, err_str
	}
	var nval string = ""
	if newval.Type() == value.STRING {
		nval = newval.Actual().(string)
	} else {
		nval = ValToStr(newval)
	}

	if name == "creds" {
		// Define credentials as user/pass and convert into
		// JSON object credentials

		var creds Credentials
		creds_ret, err_code, err_str := ToCreds(nval)
		if err_code != 0 {
			return err_code, err_str
		}

		for _, v := range creds_ret {
			creds = append(creds, v)
		}

		ac, err := json.Marshal(creds)
		if err != nil {
			return errors.JSON_MARSHAL, ""
		}
		nval = string(ac)
	}
	go_n1ql.SetQueryParams(name, nval)
	return 0, ""
}
コード例 #3
0
ファイル: push.go プロジェクト: couchbaselabs/go_cbq
/* Push value from the Top of the stack onto the parameter stack.
   This is used by the \PUSH command with no arguments.
*/
func Pushparam_Helper(param map[string]*Stack, isrestp bool, isnamep bool) (int, string) {
	for name, v := range param {
		t, err_code, err_string := v.Top()
		if err_code != 0 {
			return err_code, err_string
		}
		v.Push(t)

		// When passing the query rest api parameter to go_n1ql
		// we need to convert to string only if the value isnt
		// already a string

		if isrestp == true {
			var val string = ""
			if t.Type() == value.STRING {
				val = t.Actual().(string)
			} else {
				val = ValToStr(t)
			}

			if isnamep == true {
				name = "$" + name
			} else {
				//We know it is a query credential
				if name == "creds" {
					// Define credentials as user/pass and convert into
					// JSON object credentials

					var creds Credentials
					creds_ret, err_code, err_str := ToCreds(val)
					if err_code != 0 {
						return err_code, err_str
					}

					for _, v := range creds_ret {
						creds = append(creds, v)
					}

					ac, err := json.Marshal(creds)
					if err != nil {
						return errors.JSON_MARSHAL, ""
					}
					val = string(ac)
				}
			}
			go_n1ql.SetQueryParams(name, val)
		}
	}
	return 0, ""
}
コード例 #4
0
ファイル: common.go プロジェクト: couchbaselabs/go_cbq
func PushOrSet(args []string, pushvalue bool) (int, string) {

	// Check what kind of parameter needs to be set or pushed
	// depending on the pushvalue boolean value.

	if strings.HasPrefix(args[0], "-$") {

		// For Named Parameters
		vble := args[0]
		vble = vble[2:]

		args_str := strings.Join(args[1:], " ")

		err_code, err_str := PushValue_Helper(pushvalue, NamedParam, vble, args_str)
		if err_code != 0 {
			return err_code, err_str
		}
		//Pass the named parameters to the rest api using the SetQueryParams method
		v, err_code, err_str := NamedParam[vble].Top()
		if err_code != 0 {
			return err_code, err_str
		}

		val := ValToStr(v)

		vble = "$" + vble
		go_n1ql.SetQueryParams(vble, val)

	} else if strings.HasPrefix(args[0], "-") {
		// For query parameters

		vble := args[0]
		vble = vble[1:]

		args_str := strings.Join(args[1:], " ")

		err_code, err_str := PushValue_Helper(pushvalue, QueryParam, vble, args_str)

		if err_code != 0 {
			return err_code, err_str
		}

		if vble == "creds" {
			// Define credentials as user/pass and convert into
			//   JSON object credentials

			var creds Credentials
			args_str := strings.Join(args[1:], " ")
			creds_ret, err_code, err_str := ToCreds(args_str)

			if err_code != 0 {
				return err_code, err_str
			}

			for _, v := range creds_ret {
				creds = append(creds, v)
			}

			ac, err := json.Marshal(creds)
			if err != nil {
				return errors.JSON_MARSHAL, ""
			}
			go_n1ql.SetQueryParams("creds", string(ac))

		} else {

			v, err_code, err_str := QueryParam[vble].Top()
			if err_code != 0 {
				return err_code, err_str
			}

			// When passing the query rest api parameter to go_n1ql
			// we need to convert to string only if the value isnt
			// already a string
			var val string = ""
			if v.Type() == value.STRING {
				val = v.Actual().(string)
			} else {
				val = ValToStr(v)
			}

			go_n1ql.SetQueryParams(vble, val)

		}

	} else if strings.HasPrefix(args[0], "$") {

		// For User defined session variables
		vble := args[0]
		vble = vble[1:]

		args_str := strings.Join(args[1:], " ")

		err_code, err_str := PushValue_Helper(pushvalue, UserDefSV, vble, args_str)
		if err_code != 0 {
			return err_code, err_str
		}

	} else {
		// For Predefined session variables

		vble := args[0]

		args_str := strings.Join(args[1:], " ")

		err_code, err_str := PushValue_Helper(pushvalue, PreDefSV, vble, args_str)
		if err_code != 0 {
			return err_code, err_str
		}
	}
	return 0, ""
}
コード例 #5
0
ファイル: shell.go プロジェクト: couchbaselabs/go_cbq
func main() {

	flag.Parse()
	command.W = os.Stdout

	/* Handle options and what they should do */

	// TODO : Readd ...
	//Taken out so as to connect to both cluster and query service
	//using go_n1ql.
	/*
		if strings.HasPrefix(ServerFlag, "http://") == false {
			ServerFlag = "http://" + ServerFlag
		}

		urlRegex := "^(https?://)[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"
		match, _ := regexp.MatchString(urlRegex, ServerFlag)
		if match == false {
			//TODO Isha : Add error code. Throw invalid url error
			fmt.Println("Invalid url please check" + ServerFlag)
		}


		//-engine
		if strings.HasSuffix(ServerFlag, "/") == false {
			ServerFlag = ServerFlag + "/"
		}
	*/

	/* -quiet : Display Message only if flag not specified
	 */
	if !quietFlag && NoQueryService == false {
		s := fmt.Sprintln("Connect to " + ServerFlag + ". Type Ctrl-D to exit.\n")
		_, werr := io.WriteString(command.W, s)
		if werr != nil {
			s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
			command.PrintError(s_err)
		}
	}

	/* -version : Display the version of the shell and then exit.
	 */
	if versionFlag == true {
		dummy := []string{}
		cmd := command.Version{}
		cmd.ExecCommand(dummy)
		os.Exit(0)
	}

	/* -user : Accept Admin credentials. Prompt for password and set
	   the n1ql_creds. Append to creds so that user can also define
	   bucket credentials using -credentials if they need to.
	*/
	var creds command.Credentials

	if userFlag != "" {
		s := fmt.Sprintln("Enter Password: "******"" {
				s_err := command.HandleError(errors.INVALID_PASSWORD, "")
				command.PrintError(s_err)
				os.Exit(1)
			} else {
				creds = append(creds, command.Credential{"user": userFlag, "pass": string(password)})
			}
		} else {
			s_err := command.HandleError(errors.INVALID_PASSWORD, err.Error())
			command.PrintError(s_err)
			os.Exit(1)
		}
	}

	/* -credentials : Accept credentials to pass to the n1ql endpoint.
	   Ensure that the user inputs credentials in the form a:b.
	   It is important to apend these credentials to those given by
	   -user.
	*/
	if userFlag == "" && credsFlag == "" {
		// No credentials exist. This can still be used to connect to
		// un-authenticated servers.
		// Dont output the statement if we are running in single command
		// mode.
		if scriptFlag == "" {
			_, werr := io.WriteString(command.W, "No Input Credentials. In order to connect to a server with authentication, please provide credentials.\n")

			if werr != nil {
				s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
				command.PrintError(s_err)
			}
		}

	} else if credsFlag != "" {

		creds_ret, err_code, err_string := command.ToCreds(credsFlag)
		if err_code != 0 {
			s_err := command.HandleError(err_code, err_string)
			command.PrintError(s_err)
		}
		for _, v := range creds_ret {
			creds = append(creds, v)
		}

	}
	//Append empty credentials. This is used for cases where one of the buckets
	//is a SASL bucket, and we need to access the other unprotected buckets.
	//CBauth works this way.

	//if credsFlag == "" && userFlag != "" {
	creds = append(creds, command.Credential{"user": "", "pass": ""})
	//}

	/* Add the credentials set by -user and -credentials to the
	   go_n1ql creds parameter.
	*/
	if creds != nil {
		ac, err := json.Marshal(creds)
		if err != nil {
			//Error while Marshalling
			s_err := command.HandleError(errors.JSON_MARSHAL, err.Error())
			command.PrintError(s_err)
			os.Exit(1)
		}
		go_n1ql.SetQueryParams("creds", string(ac))
	}

	if scriptFlag != "" {
		go_n1ql.SetPassthroughMode(true)
		err_code, err_str := execute_input(scriptFlag, os.Stdout)
		if err_code != 0 {
			s_err := command.HandleError(err_code, err_str)
			command.PrintError(s_err)
			os.Exit(1)
		}
		os.Exit(0)
	}

	if timeoutFlag != "0ms" {
		go_n1ql.SetQueryParams("timeout", timeoutFlag)
	}

	if inputFlag != "" {
		//Read each line from the file and call execute query

	}

	go_n1ql.SetPassthroughMode(true)
	//fmt.Println("Input arguments, ", os.Args)
	HandleInteractiveMode(filepath.Base(os.Args[0]))
}
コード例 #6
0
ファイル: example.go プロジェクト: couchbasedeps/go_n1ql
func main() {

	flag.Parse()
	n1ql, err := sql.Open("n1ql", *serverURL)
	if err != nil {
		log.Fatal(err)
	}

	err = n1ql.Ping()
	if err != nil {
		log.Fatal(err)
	}

	// Set query parameters
	//os.Setenv("n1ql_timeout", "10s")
	ac := []byte(`[{"user": "******", "pass": "******"}]`)
	//os.Setenv("n1ql_creds", string(ac))

	go_n1ql.SetQueryParams("creds", string(ac))
	go_n1ql.SetQueryParams("timeout", "10s")
	go_n1ql.SetPassthroughMode(true)

	/*
		result, err := n1ql.Exec("Create primary index on `beer-sample`")
		if err != nil {
			log.Fatal(err)
		}
	*/

	rows, err := n1ql.Query("drop primary index on `beer-sample` using view")
	rowsReturned := 0
	if err == nil {
		for rows.Next() {
			var contacts string
			if err := rows.Scan(&contacts); err != nil {
				log.Fatal(err)
			}
			log.Printf(" Row %v", contacts)
			rowsReturned++
		}

		log.Printf("Rows returned %d : \n", rowsReturned)
		if err := rows.Err(); err != nil {
			log.Fatal(err)
		}

		rows.Close()

	}

	rows, err = n1ql.Query("create primary index on `beer-sample` using view")
	if err != nil {
		log.Fatal(err)
	}
	rowsReturned = 0
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts); err != nil {
			log.Fatal(err)
		}
		log.Printf(" Row %v", contacts)
		rowsReturned++
	}

	log.Printf("Rows returned %d : \n", rowsReturned)
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	rows.Close()

	name := "brewery"
	rows, err = n1ql.Query("select * from `beer-sample` where type = ?", name)

	if err != nil {
		log.Fatal(err)
	}
	rowsReturned = 0
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts); err != nil {
			log.Fatal(err)
		}
		rowsReturned++
	}

	log.Printf("Rows returned %d : \n", rowsReturned)
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	stmt, err := n1ql.Prepare("Upsert INTO default values (?,?)")
	if err != nil {
		log.Fatal(err)
	}
	// Map Values need to be marshaled
	value, _ := json.Marshal(map[string]interface{}{"name": "irish", "type": "contact"})

	var rowsAffected int64
	for i := 0; i < 10000; i++ {
		key := fmt.Sprintf("irish%d", i)
		value := make(map[string]interface{})
		value["name"] = key
		value["type"] = "contact"
		valueBytes, _ := json.Marshal(value)
		result, err := stmt.Exec(key, valueBytes)

		if err != nil {
			fmt.Errorf(" Failed here %v", err)
			continue
		}

		ra, err := result.RowsAffected()
		if err != nil {
			log.Fatal(err)
		}
		rowsAffected += ra
	}

	log.Printf("Total Rows Affected %d", rowsAffected)

	stmt.Close()
	_, err = stmt.Exec("test", "this shouldn't work")
	if err == nil {
		log.Fatal("Statement not closed")
	}

	_, err = n1ql.Exec("delete from default  use keys ? ", "irish")
	if err != nil {
		log.Fatal(err)
	}

	keys := make([]string, 0)
	for i := 0; i < 100000; i++ {
		keys = append(keys, fmt.Sprintf("irish%d", i))
	}

	value, _ = json.Marshal(keys)
	_, err = n1ql.Exec("delete from default use keys ?", value)
	if err != nil {
		log.Fatal(err)
	}

}
コード例 #7
0
ファイル: example.go プロジェクト: couchbasedeps/go_n1ql
func main() {

	n1ql, err := sql.Open("n1ql", "http://localhost:8093")
	if err != nil {
		log.Fatal(err)
	}

	err = n1ql.Ping()
	if err != nil {
		log.Fatal(err)
	}

	// Set query parameters
	ac := []byte(`[{"user": "******", "pass": "******"}]`)
	go_n1ql.SetQueryParams("creds", string(ac))
	go_n1ql.SetQueryParams("timeout", "10s")
	go_n1ql.SetQueryParams("scan_consistency", "request_plus")

	rows, err := n1ql.Query("select element (select * from contacts)")

	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned %s : \n", contacts)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	var name string
	rows, err = n1ql.Query("select name,type from contacts")

	if err != nil {
		log.Fatal(err)
	}
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts, &name); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned %s %s: \n", contacts, name)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	// if the following option is set, go_n1ql will return metrics as the last row
	go_n1ql.SetPassthroughMode(true)
	name = "dave"
	rows, err = n1ql.Query("select * from contacts unnest contacts.children where contacts.name = ? and children.age > ?", name, 10)

	if err != nil {
		log.Fatal(err)
	}
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned %s : \n", contacts)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	rows, err = n1ql.Query("select name,type from contacts")

	if err != nil {
		log.Fatal(err)
	}
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts, &name); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned %s %s: \n", contacts, name)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	// explain statement
	rows, err = n1ql.Query("explain select * from contacts")

	if err != nil {
		log.Fatal(err)
	}
	for rows.Next() {
		var contacts string
		if err := rows.Scan(&contacts); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned %s : \n", contacts)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	go_n1ql.SetPassthroughMode(false)

	// prepared statements with positional args

	stmt, err := n1ql.Prepare("select personal_details, shipped_order_history from users_with_orders where doc_type=? and personal_details.age = ?")

	if err != nil {
		log.Fatal(err)
	}

	rows, err = stmt.Query("user_profile", 60)
	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var personal, shipped string
		if err := rows.Scan(&personal, &shipped); err != nil {
			log.Fatal(err)
		}
		log.Printf("Row returned personal_details: %s shipped_order_history %s : \n", personal, shipped)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	rows.Close()

	// Exec examples
	result, err := n1ql.Exec("Upsert INTO contacts values (\"irish\",{\"name\":\"irish\", \"type\":\"contact\"})")
	if err != nil {
		log.Fatal(err)
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Rows affected %d", rowsAffected)

	stmt, err = n1ql.Prepare("Upsert INTO contacts values (?,?)")
	if err != nil {
		log.Fatal(err)
	}

	// Map Values need to be marshaled
	value, _ := json.Marshal(map[string]interface{}{"name": "irish", "type": "contact"})
	result, err = stmt.Exec("irish4", value)
	if err != nil {
		log.Fatal(err)
	}

	rowsAffected, err = result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Rows affected %d", rowsAffected)

	for i := 0; i < 20; i++ {
		key := fmt.Sprintf("irish%d", i)
		result, err = stmt.Exec(key, value)
		if err != nil {
			log.Fatal(err)
		}

		ra, err := result.RowsAffected()
		if err != nil {
			log.Fatal(err)
		}
		rowsAffected += ra
	}

	log.Printf("Total Rows Affected %d", rowsAffected)

	stmt.Close()
	result, err = stmt.Exec("test", "this shouldn't work")
	if err == nil {
		log.Fatal("Statement not closed")
	}

	result, err = n1ql.Exec("delete from contacts use keys ? ", "irish")
	if err != nil {
		log.Fatal(err)
	}

	keys := make([]string, 0)
	for i := 0; i < 20; i++ {
		keys = append(keys, fmt.Sprintf("irish%d", i))
	}

	value, _ = json.Marshal(keys)
	result, err = n1ql.Exec("delete from contacts use keys ?", value)
	if err != nil {
		log.Fatal(err)
	}

	go_n1ql.UnsetQueryParams("scan_consistency")
	result, err = n1ql.Exec("delete from contacts use keys ?", value)
	if err != nil {
		log.Fatal(err)
	}

	go_n1ql.UnsetQueryParams("scan_consistency")

	// error expected
	go_n1ql.SetQueryParams("scan_consistency", "rubbish_plus")
	result, err = n1ql.Exec("delete from contacts use keys ?", value)
	if err == nil {
		log.Fatal("Error expected")
	}

}