Drizzle's New $onUpdate Function
Drizzle just added a new $onUpdate
function in v0.30.5.
The $onUpdate
function is a new feature in Drizzle that allows database fields to update automatically under certain conditions.
This feature is designed to make data management more efficient and reduce the need for manual updates.
How Does It Work?
Let's look at a practical example to understand how $onUpdate
works. Imagine you're managing a website with user profiles, and you want to keep track of when users last updated their profiles and how often they do so.
Before $onUpdate
, you might have needed to write extra code to update these fields every time a user made a change. With $onUpdate
, Drizzle does this automatically for you. Here's how you might set it up:
- Login Count: A field that increments by one every time a user logs in.
- Last Login: A field that updates to the current timestamp whenever the user logs in.
Using the $onUpdate
function, you tell Drizzle to automatically adjust these values based on user activity without writing additional code for each update.
Here's a snippet to illustrate how $onUpdate
can be applied:
const userActivity = pgTable('user_activity', { userId: serial('user_id').primaryKey(), loginCount: integer('login_count').default(sql`0`).$onUpdateFn(() => sql`login_count + 1`), lastLogin: timestamp('last_login').$onUpdate(() => new Date()), });
In this example, loginCount
and lastLogin
are set to update automatically, showcasing $onUpdate
in action.
Why I'm happy about the addition:
- Saves Time: Automating updates means you spend less time writing and maintaining code.
- Increases Accuracy: Since updates are automatic, there's less room for error.
- Simplifies Data Management: Keeping your database current becomes much easier, enhancing overall functionality.