8000 Easy way to bulk-insert while applying SQL function (e.g. `(a, b)` -> `(a, AES_ENCRYPT(b, 'some_key'))`)? · Issue #1218 · uptrace/bun · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Easy way to bulk-insert while applying SQL function (e.g. (a, b) -> (a, AES_ENCRYPT(b, 'some_key')))? #1218
Open
@your-diary

Description

@your-diary

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
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0