How to fix multiple-value stmt.Query() in single-value context [closed] - postgresql

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am facing the above issue with the code below
stmt, err2 := db.Prepare( "SELECT COUNT(*) FROM xyz WHERE product_id=? and chart_number=?")
rows, err2 := stmt.Query( bidStatusReqVal.ProductId,bidStatusReqVal.ChartNumber).Scan(&count)

Query(...).Scan(...) is not valid because Query returns two values and chaining of calls requires that the previous call returns only one value. Call Scan on the returned rows, or use QueryRow(...).Scan(...) with only err as the return destination.
rows, err := stmt.Query(bidStatusReqVal.ProductId, bidStatusReqVal.ChartNumber)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(&count); err != nil {
return err
}
}
if err := rows.Err(); err != nil {
return err
}
// ...
In cases where the query returns only a single row, e.g. SELECT ... LIMIT 1, or SELECT COUNT(*) ... like in your case, it is much more convenient to use QueryRow.
err := stmt.QueryRow(bidStatusReqVal.ProductId, bidStatusReqVal.ChartNumber).Scan(&count)
if err != nil {
return err
}
// ...

Related

How to update multiple documents in mongodb using Golang [duplicate]

This question already has answers here:
How would I update multiple records based on different key in Mongo in one query?
(1 answer)
MongoDB update array of documents and replace by an array of replacement documents
(1 answer)
Closed last month.
I am trying to update a collection of multiple data in MongoDB using Golang at the same time, instead, it updates only one record, I'm using a for loop to perform this action
My filter code
if len(list_phone) > 1 {
for i := 0; i < len(list_phone); i++ {
update_userPhone, err := helpers.UpdatePhone(list_phone[i]["phone"].(string), list_phone[i]["email"].(string))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"status:":"error", "error": true, "msg": "Something went wrong" }`))
return
}
json.NewEncoder(w).Encode(update_userPhone)
return
}
}
my update function
func UpdatePhone(phone string, email string) (bool, error) {
userCollection, _ := GetDBCollection("users")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
id := email
filter := bson.M{"email": id}
update := bson.M{"$set": bson.M{"phone": phone}}
_, err := userCollection.UpdateOne(ctx, filter, update)
defer cancel()
if err != nil {
return false, err
}
return true, err
}

postgres does not save all data after committing

In my golang project that use gorm as ORM and posgress as database, in some sitution when I begin transaction to
change three tables and commiting, just one of tables changes. two other tables data does not change.
any idea how it might happen?
you can see example below
o := *gorm.DB
tx := o.Begin()
invoice.Number = 1
err := tx.Save(&invoice)
if err != nil {
err2 := tx.RollBack().Error()
return err
}
receipt.Ref = "1331"
err = tx.Save(&receipt)
if err != nil {
err2 := tx.RollBack().Error()
return err
}
payment.status = "succeed"
err = tx.Save(&payment)
if err != nil {
err2 := tx.RollBack().Error()
return err
}
err = tx.Commit()
if err != nil {
err2 := tx.Rollback()
return err
}
Just payment data changed and I'm not getting any error.
Apparently you are mistakenly using save points! In PostgreSQL, we can have nested transactions, that is, defining save points make the transaction split into parts. I am not a Golang programmer and my primary language is not Go, but as I guess the problem is "tx.save" which makes a SavePoint, and does not save the data into database. SavePoints makes a new transaction save point, and thus, the last table commits.
If you are familiar with the Node.js, then any async function callback returns an error as the first argument. In Go, we follow the same norm.
https://medium.com/rungo/error-handling-in-go-f0125de052f0

Unable to create/access database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have been using MongoDB without issues in Python but I am in need to build a client in go now.
I have looked at the documentation and the examples work fine.
But when I try to use my own code, the code execute without errors, but when I inspect the database (via CLI) I see no database, no collection and no data.
I am sure I am doing something wrong, but I am unable to find it in this little testing code.
func main() {
if client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")); err == nil {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
defer client.Disconnect(ctx)
if err = client.Connect(ctx); err == nil {
os.Exit(0)
}
KeysCol := client.Database("yfroot").Collection("KeysCol")
mac, e1 := crypto.GenerateRandomBytes(16)
key, e2 := crypto.GenerateRandomBytes(16)
if e1 != nil || e2 != nil {
fmt.Println("failed crypto generate")
os.Exit(0)
}
testKey := dataformats.DeviceKey{
Mac: string(mac),
Key: key,
}
// ctx, _ = context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
_, err := KeysCol.InsertOne(ctx, testKey)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
} else {
fmt.Println(err)
}
}
Look at this part:
if err = client.Connect(ctx); err == nil {
os.Exit(0)
}
If you are able to connect, that us (err is nil), you are exiting.
You probably meant to do:
if err = client.Connect(ctx); err != nil {
fmt.Println(err)
os.Exit(0)
}

How to insert multiple rows by one query? [duplicate]

This question already has answers here:
How do I insert multiple values into a postgres table at once?
(6 answers)
How to insert multiple data at once
(8 answers)
Closed 3 years ago.
In PostgreSQL I have a pretty simple table where I store information about relationships between users and games. Here is a working function which I use to insert data. As you can see it makes multiple SQL queries to the database which is not elegant I think. What do I need to change to insert multiple rows with one query?
var CreateRelationship = func(responseWriter http.ResponseWriter, request *http.Request) {
userID := mux.Vars(request)["user_id"]
type RequestBody struct {
Games []int `json:"games"`
}
requestBody := RequestBody{}
decoder := json.NewDecoder(request.Body)
if err := decoder.Decode(&requestBody); err != nil {
utils.ResponseWithError(responseWriter, http.StatusBadRequest, err.Error())
return
}
for i := 0; i < len(requestBody.Games); i++ {
if _, err := database.DBSQL.Exec("INSERT INTO users_games_relationship (user_id, game_id) VALUES ($1, $2);", userID, requestBody.Games[i]); err != nil {
utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
return
}
}
utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")
}

Go batch insert Returning ID not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to batch insert some rows and get their ids with golang, this is my attempt in doing so
import (
"database/sql"
"fmt"
_ "github.com/bmizerany/pq"
"log"
)
func main() {
conn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", host, user, password, dbname)
d, err := sql.Open("postgres", conn)
rows, err := d.Query("INSERT INTO MYTABLE(MYCOLUMN) VALUES(1),(2),(3) RETURNING ID")
defer rows.Close()
var ids []int
for rows.Next() {
var id int
scan_err := rows.Scan(&id)
fmt.Println(scan_err)
if scan_err != nil {
log.Fatal(scan_err)
}
ids = append(ids, id)
fmt.Printf("id %d\n", id)
}
}
my problem is ids is always empty even if the values are inserted correctly in the database.
what's interesting is that the following works
var id int
db.QueryRow("INSERT INTO MYTABLE(MYCOLUMN) VALUES(1) RETURNING ID").Scan(&id)
How do solve this?