Masterminds / squirrel

Fluent SQL generation for golang
Other
6.67k stars 458 forks source link

Conditional insert column/value results in invalid SQL #336

Open Southclaws opened 1 year ago

Southclaws commented 1 year ago

I want to conditionally add a value to an insert query but the resulting SQL isn't valid.

    insert := squirrel.Insert("table")

    insert = insert.Columns(
        "id",
        "account_id",
    ).Values(
        id,
        accountID,
    )

    if v, ok := inv.SomeValue.Get(); ok {
        insert = insert.Columns("some_value").Values(v)
    }

results in

INSERT INTO table (id,account_id,some_value) VALUES ($1,$2),($3)

Is this a bug or do I just have to build a mutable slice of both keys and values and wire it up myself?

version github.com/Masterminds/squirrel v1.5.3

lann commented 1 year ago

.Values sets an entire row's values at once, so it cannot do what you're going for here. You might be interested in .SetMap:

https://github.com/Masterminds/squirrel/blob/9b18b54aed2aa831665b8e896cde063d51d921fa/insert_test.go#L76-L87

Note from the docs:

it will reset all previous columns and values