go-gorm / playground

GORM Playground (Please Create PR for this project to report issues)
MIT License
89 stars 678 forks source link

demonstrate table alias behavior #614

Open tempoz opened 1 year ago

tempoz commented 1 year ago

Explain your user case and expected results

I would like table aliases to function. Specifically, I want to use db.Clauses(clause.Insert{Table: clause.Table{Name: "Users", Alias: "u"}}).Create(&User{}) and have the resulting SQL statement insert the AS keyword between the table name and the alias in the resulting SQL so that I can use that alias in a later clause.OnConflict with a DoUpdates field, for example:

db.Clauses(
    clause.Insert{Table: clause.Table{Name: "Users", Alias: "u"}},
    clause.OnConflict{
        Where: clause.Where{
            Exprs: []clause.Expression{
                clause.And(
                    gorm.Expr(`u.name <> ?`, user.name),
                    gorm.Expr(`u.name NOT LIKE CONCAT( ?, " AKA %")`, user.name),
                    gorm.Expr(`u.name NOT LIKE CONCAT( "% AKA ", ?)`, user.name),
                    gorm.Expr(`u.name NOT LIKE CONCAT("% AKA ", ? " AKA %")`, user.name),
                ),
            },
        },
        DoUpdates: clause.Assignments(map[string]any{
          "name": gorm.Expr(`CONCAT(u.name, " AKA ", ?)`, user.name),
        }),
    },
).Create(user)

Note that I NEED to be able to specify the table alias (or table name) for this query because in postgres, at least, the row that failed to insert is also available and so the identifier name is ambiguous (see the conflict_action heading on the postgres INSERT docs for more explanation).