示例#1
0
func main() {

	flag.Parse()

	go_n1ql.SetPassthroughMode(true)

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

	rows, err := n1ql.Query("SELECT name, type, hobbies  FROM contacts")
	if err != nil {
		log.Fatal("Error %v", err)
	}

	columns, _ := rows.Columns()
	count := len(columns)
	values := make([]interface{}, count)
	valuePtrs := make([]interface{}, count)

	for rows.Next() {

		for i, _ := range columns {
			valuePtrs[i] = &values[i]
		}

		rows.Scan(valuePtrs...)
		log.Printf("======= Printing Row ==========")
		for i, col := range columns {
			var v interface{}
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				v = string(b)
			} else {
				v = val
			}
			log.Println(col, v)
		}
	}
}
示例#2
0
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]))
}
示例#3
0
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)
	}

}
示例#4
0
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")
	}

}