jmoiron / sqlx

general purpose extensions to golang's database/sql
http://jmoiron.github.io/sqlx/
MIT License
16.3k stars 1.09k forks source link

Behavioural differences between `sql.Named` with query vs `NamedExecContext` cause `UPDATE` error #916

Open koalazub opened 8 months ago

koalazub commented 8 months ago

Tools: |-----| | go 1.21 | | github.com/gorilla/schema v1.2.1 | | github.com/jmoiron/sqlx v1.3.5 |

I'm currently getting an error when using named parameters for my Azure SQL Database.

Contrived, but when performing the following:

    updateQry := `UPDATE tblIdNumber SET
    Cust1 = @Cust1
WHERE IdNumber = @IdNumber 
`

    _, err := d.DB.NamedExecContext(ctx, updateQry, docket)
    if err != nil {
        slog.Error("couldn't update IdNumber", err)
        return err
    }

I get an error:

mssql: Must declare the scalar variable \"@Cust1\"."

Yet when I do:

    updateQry := `UPDATE tblIdNumber SET
    Cust1 = @Cust1
WHERE IdNumber = @IdNumber 

    _, err := d.DB.ExecContext(ctx, updateQry,
        sql.Named("Cust1", Person.Cust1),
    )
    if err != nil {
        slog.Error("couldn't update docket", err)
        return err
    }

It correctly updates the table.

I had the expectation that it removed the need to explicitly state each named parameter but that doesn't seem to be the case in this context. I am pretty new to sqlx, so I'm not sure if I'm missing something here. I did see that there were some fixes to named params in #406 for SQL Server

bwmarrin commented 5 months ago

I am also having this issue. I was hoping to pass a struct to NamedExec() and use @p1, @p2, @p... placeholders however this gives me the same error, Must declare the scalar variable @p1

koalazub commented 5 months ago

I am also having this issue. I was hoping to pass a struct to NamedExec() and use @p1, @p2, @p... placeholders however this gives me the same error, Must declare the scalar variable @p1

Yeah I couldn't figure out a solution for it and just typed each field out unfortunately. Wasn't fun considering the size of the thing