简体   繁体   中英

How to do Upsert in Vlang

Currently, the ORM for V only supports select , update , and insert . I would like to do a more complicated upsert like this:

INSERT INTO Settings (Key, Value)
VALUES (?0, ?1)
ON CONFLICT(Key)
DO UPDATE
SET Key = ?0,
    Value = ?1;`

But it looks like from the docs there is no exposure for doing an update like this. So, I would need to clean the inserted/updated values myself.

Is there a way to do direct SQL with variables directly? Am I missing something?

Another option I would have would be:

setting := Settings {
    key: key
    value: value
}
sql r.db {
    insert setting into Settings
}
sql r.db {
    update Settings set value = value where key == key
}

Although the above works it isn't very elegant and requires two calls to the DB. Is there a way to do direct queries with arguments?

The vlang Sqlite library (not the Orm) has a method that can execute raw SQL against the db and return raw row data.

You could create your upsert query using the information in this stackoverflow and execute it as a string against the DB.

Something like this maybe (you'll have to test it against your particular database until it works):

r.db.exec("UPDATE Settings SET value = 'value' WHERE id = 2;
INSERT INTO Settings(key, value) SELECT 2, 'value' WHERE changes() = 0;")

Do not use this in production . Unfortunately, the exec function does not santize inputs or pass in parameterized values. This means that you will be vulnerable to sql injection by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM