GET golang syntax error with optional parameters

Asked

Viewed 58 times

1

I am trying to filter my records based on a "Name parameter"

I did this Handler Function:

func GetFuncionaries(w http.ResponseWriter, r *http.Request) {
    var f model.Funcionary
    var t util.App
    var d db.DB
    err := d.Connection()
    db := d.DB
    defer db.Close()

    Id, _ := strconv.Atoi(r.FormValue("Id"))
    Name:= r.FormValue("Name")

    f.Id = int64(Id)
    f.Name = Name

    funcionaries, err := f.GetFuncionaries(db)
    if err != nil {
            log.Printf("[handler/GetFuncionaries-  Error: %s", err.Error())
            t.ResponseWithError(w, http.StatusInternalServerError, err.Error(), "")
        }
        return
    }
    t.ResponseWithJSON(w, http.StatusOK, funcionaries, 0, 0)
}

And that’s my role model:

func (f *Funcionary) GetFuncionaries(db *sql.DB) ([]Funcionary, error) {
    var values []interface{}
    var where []string

    if f.Name != "" {
        where = append(where, "Name= ?")
        values = append(values, f.Name)
    }


    rows, err := db.Query(`SELECT Id, Data, Role, Name
                    FROM funcionaries
                    WHERE 1=1 `+strings.Join(where, " AND "), values...)
    if err != nil {
        return nil, err
    }

    funcionaries:= []Funcionary{}
    defer rows.Close()
    for rows.Next() {
        var funcionary Funcionary
        if err = rows.Scan(&funcionario.Id, &funcionario.Name, &Others...); err != nil {
            return nil, err
        }
        funcionaries = append(funcionaries, funcionary)
    }
    return funcionaries, nil
}

But when I make a request at Postman:

http://localhost:8000/api/funcies? Name=a

I get:

You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'Name= ? ' at line 3",

I’m forgetting one thing?

  • You have already run the query "at hand" and is functional?

1 answer

1


This is one of the flaws in the design of the database/sql package, as it leaves the implementation of the bind variables, which does not allow to be generic. What you need to remember is that each driver can change this symbol, today what I know is that mysql is used ? , for postgresql it uses $1, oracle do not remember, but it seems that it is equal to postgresql. See the manual/documentation of the database driver you are using.

There is a discussion about this: https://groups.google.com/forum/#! topic/golang-Nuts/p-Qpmneatdi

At the end of the discussion a person gives a suggestion able to get around this problem, although it is not a beautiful thing to see, resolves, hehehe.

:)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.