electrodb icon indicating copy to clipboard operation
electrodb copied to clipboard

Bug: apply `default` on upsert only for new items

Open zirkelc opened this issue 1 year ago • 2 comments

Describe the bug A clear and concise description of what the bug is.

The default value or function will always be applied on upsert(), even if the item already exists. This will potentially override existing values.

ElectroDB Version Specify the version of ElectroDB you are using (e.g. 1.8.4) latest

ElectroDB Playground Link Playground

Entity/Service Definitions See playground

Expected behavior A clear and concise description of what you expected to happen.

If the item is new, the default values should be applied. This is like create. If the item already exists, the default values should not be applied. This is like update. Am I understanding upsert correctly?

There are two cases to consider:

  1. does the item exist?
    • yes: do not overwrite field with default value
    • no: create new item with default values
  2. does the field on the item exist?
    • yes: do not overwrite field with default value
    • no: do not overwrite field with default value

I think 2) could be fixed by using field = if_not_exists(field, field_default_value). This should update the field only if it doesn't exist. However, I'm not sure if/how 1) could be fixed. If it's not fixable, maybe it could be added to the docs that upsert differs from update in that it always applies default values.

zirkelc avatar Jul 16 '24 10:07 zirkelc

Hi @zirkelc 👋

This is an improvement that has been considered (I thought there might have been an existing issue for this?), and it is an ideal state. I remember looking into implementing this and finding that it would required a non-trivial refactor of some parts of the library to know if a value was provided vs set via "default". Here is how you can ensure the value is not overridden by a default, it's not as ideal as the library handling it under the hood but it does prevent the issue bring up.

I'd like to keep this ticket open so I can prioritize it in my backlog, which is deeper than I'd like right now. Thank you for reporting this!

tywalch avatar Jul 20 '24 16:07 tywalch

Thanks for getting back on this! Sure, let's keep it open and let me know if I can help or test anything!

zirkelc avatar Jul 21 '24 06:07 zirkelc