Open
Description
Say I have a list of users each of which is of type User
:
type User struct {
bun.BaseModel `bun:"table:user"`
ID int `bun:"id,pk"`
Name string `bun:"name"`
}
Bulk-inserting them is very easy:
_, err := db.NewInsert().
Model(&users).
Exec(context.TODO())
This executes the following SQL statement for example:
INSERT INTO
user (id, name)
VALUES
(1, 'Mike'),
(2, 'John');
It seems it suddenly becomes very difficult if we want to insert the users NOT as they are but with applying SQL functions on them.
For example, I want to insert them while AES-encrypting their names:
INSERT INTO
user (id, name)
VALUES
(1, AES_ENCRYPT('Mike', 'some_key')),
(2, AES_ENCRYPT('John', 'some_key'));
Is there any easy way to construct such a statement?
I thought the hook definition below would work, but it didn't because only the final call of Value()
was respected, inserting John
twice rather than inserting Mike
and John
once.
func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error {
if insertQuery, ok := query.(*bun.InsertQuery); ok {
insertQuery.Value("name", "AES_ENCRYPT(?, 'some_key')", u.Name)
}
return nil
}
Metadata
Metadata
Assignees
Labels
No labels