typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
33.46k stars 6.21k forks source link

Make updatedAt timestamp update optional when saving a Entity #10665

Open matthiasfeist opened 3 months ago

matthiasfeist commented 3 months ago

Feature Description

I have a use-case where I want to update the last activity of a user in my database when they do something in my app. I set up a date field that I update every time the users performs an action. Unfortunately, this also sets the "updatedAt" timestamp automatically. I would like to have the option to opt out of the automatic update of the updatedAt timestamp for some actions. In my case: I'd really like to have the updatedAt reflecting actions that are done to the conceptual user model (change email, change password etc).

The Solution

Maybe an extra option that could be passed to the save or update method? Something like:

user.lastActivity = new Date();
await user.save({ skipUpdatedAt:true });

Considered Alternatives

Manually setting the updatedAt timestamp to what I read in the model before:

await User.update(user.id, { lastActivity: new Date(), updatedAt: user.updatedAt });

Additional Context

No response

Relevant Database Driver(s)

Are you willing to resolve this issue by submitting a Pull Request?

Yes, I have the time, but I don't know how to start. I would need guidance.

Hamsajj commented 3 months ago

Hello. Why not use a normal @Column instead of @UpdateDateColumn for the updatedAt column? that way you have control over when to update or not yourself.

You can also use a custom @BeforeUpdate function hook, to update the updatedAt decorated as a @Column based on some arbitrary conditions on every save or update call that's going to update the entity.

matthiasfeist commented 3 months ago

great idea. For some reason I hadn't thought of this myself. thanks :)

stim371 commented 1 week ago

I'd love to see something like this (very similar to Rails' touch: false option).

My scenario is that I want to run large data backfills on my db as I add new features. If I call update or even run low-level queries (connection.query("...")), it updates everything to the same time, confusing customers.

The only way I've found to not change the timestamp is to loop over objects and set their updatedAt explicitly, which is super non-performant.

It'd be a heck of a lot cleaner to allow skipping of the update timestamp field versus requiring anyone that has the use case to rip out the UpdatedDateColumn feature for the <1% of updates that require the behavior.