go-ozzo / ozzo-dbx

A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.
MIT License
636 stars 91 forks source link

Fields in embedded struct should always be shadowed by fields in outer struct #37

Closed nkovacs closed 7 years ago

nkovacs commented 7 years ago

Let's say you have a struct like this:

type Foo struct {
    ID   int
    Name string
    Position int
}

But when inserting it into the database, you want to use a subquery for Position. You can do this:

wrapper := struct{
    Foo
    Position dbx.Expression
}{
    Foo: foo,
    Position: dbx.NewExp("(SELECT COALESCE(MAX(f.position), 0)+1 AS position FROM foo )").
}

return db.Model(&wrapper).Insert()

Position has to be after Foo in the struct's definition for this to work. The outer Position should shadow the embedded Foo's Position regardless of the order of the fields.

(Foo probably has to have a TableName method for this to work, the anonymous struct will inherit it).

qiangxue commented 7 years ago

Thanks for reporting the issue!