pudo / dataset

Easy-to-use data handling for SQL data stores with support for implicit table creation, bulk loading, and transactions.
https://dataset.readthedocs.org/
MIT License
4.76k stars 297 forks source link

update with same parameter #341

Closed vladiscripts closed 3 years ago

vladiscripts commented 4 years ago

Is it possible to make update with the same parameter? I want to find all the values ​​"value = 1" in the table and replace them with "value = 2". SQL analog: UPDATE table SET value=2 WHERE value=1. The provided update function works only as a unique search filter, for example, update({'value': 1}, keys = ['value']) does not allow changing the value to 2.

medecau commented 3 years ago

this is an unfortunate outcome of having a delightfully simple API

to solve this, you can iterate over the rows you wish to change and then upsert them

rows = t.find(value=1)

# python < 3.9
updated = ({**row, **dict(value=2)} for row in rows)

# python > 3.9
updated = (row | dict(value=2) for row in rows)

t.upsert_many(updated, ['id'])

if you're feeling brave you can try doing it all in one line

t.upsert(({**row, **dict(value=2)} for row in r.find(value=1)), ['id'])
pudo commented 3 years ago

thanks for the advice, @medecau.