doug-martin / goqu

SQL builder and query library for golang
http://doug-martin.github.io/goqu/
MIT License
2.39k stars 206 forks source link

CTEs do not inherit dialect of the main dataset #370

Open sgrishanin opened 1 year ago

sgrishanin commented 1 year ago

Describe the bug WithDialect changes the dialect of the receiver dataset, but datasets of CTEs inside it keep the default dialect (unless specified explicitly). The resulting query contains multiple incompatible dialects.

To Reproduce

ds := goqu.
        Select("field_1").
        From("table_1").
        Where(goqu.I("field_2").Eq("2"))

// cte with unspecified dialect
cte := goqu.
        Select("field_3").
        From("table_2").
        Where(goqu.I("field_4").Eq("4"))

ds = ds.With("cte", cte)

ds = ds.WithDialect("postgres") // expected to set dialect for the entire query
ds = ds.Prepared(true)

query, _, _ := ds.ToSQL()
fmt.Println(query) // WITH cte AS (SELECT "field_3" FROM "table_2" WHERE ("field_4" = ?)) SELECT "field_1" FROM "table_1" WHERE ("field_2" = $2)

Expected behavior When the query is being build, I expect it to have a dialect of the main dataset I call .ToSQL() on. I think it should never produce a potentially impossible query.

Dialect:

Additional context Explicitly setting the same dialect on every CTE does the job of course, but it is not obvious and simply cumbersome.

ericleb010 commented 1 year ago

This bit me as well, and the bug that came out of it was very challenging to debug.

iredmail commented 4 months ago

I got panic with same bug, triggered by FromQuery():

sd := db.
    Select(...).
    From(...).
    Where(...)

db.Insert(...).FromQuery(sd).Executor().Exec()

Reported error:

incompatible dialects for INSERT ("default") and SELECT ("default")